app-init
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
// ResolveConfigPath finds config.yaml: --config, then next to the exe, then cwd.
|
||||
func ResolveConfigPath(flagPath string) (string, error) {
|
||||
var cands []string
|
||||
if flagPath != "" {
|
||||
cands = append(cands, flagPath)
|
||||
}
|
||||
if exe, err := os.Executable(); err == nil {
|
||||
dir := filepath.Dir(exe)
|
||||
cands = append(cands, filepath.Join(dir, "config.yaml"))
|
||||
cands = append(cands, filepath.Join(dir, "..", "config.yaml"))
|
||||
}
|
||||
cands = append(cands, "config.yaml")
|
||||
seen := map[string]bool{}
|
||||
for _, p := range cands {
|
||||
abs, err := filepath.Abs(p)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
abs = filepath.Clean(abs)
|
||||
if seen[abs] {
|
||||
continue
|
||||
}
|
||||
seen[abs] = true
|
||||
st, err := os.Stat(abs)
|
||||
if err == nil && !st.IsDir() {
|
||||
return abs, nil
|
||||
}
|
||||
}
|
||||
if flagPath == "" {
|
||||
flagPath = "config.yaml"
|
||||
}
|
||||
abs, err := filepath.Abs(flagPath)
|
||||
if err != nil {
|
||||
return flagPath, fmt.Errorf("config not found: %s", flagPath)
|
||||
}
|
||||
return abs, fmt.Errorf("config not found: %s", abs)
|
||||
}
|
||||
|
||||
// ResolvePaths makes LogFile absolute relative to the config file directory.
|
||||
func (c *Config) ResolvePaths() {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
if p, err := filepath.Abs(c.Path); err == nil {
|
||||
c.Path = p
|
||||
}
|
||||
if c.LogFile == "" {
|
||||
c.LogFile = DefaultLogFile
|
||||
}
|
||||
if !filepath.IsAbs(c.LogFile) {
|
||||
c.LogFile = filepath.Join(filepath.Dir(c.Path), c.LogFile)
|
||||
}
|
||||
c.LogFile = filepath.Clean(c.LogFile)
|
||||
}
|
||||
Reference in New Issue
Block a user