-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathconfig.go
More file actions
75 lines (64 loc) · 1.72 KB
/
Copy pathconfig.go
File metadata and controls
75 lines (64 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Copyright 2021 Jeffrey M Hodges.
// SPDX-License-Identifier: Apache-2.0
package main
import (
"errors"
"os"
"path/filepath"
"runtime"
"strings"
"github.com/BurntSushi/toml"
)
type config struct {
Home string `toml:"home"`
SSHPreferredHosts []string `toml:"ssh_preferred_hosts"`
}
func loadConfig() (config, error) {
// On macOS, check $HOME/.config/grab/config.toml first before falling
// back to the native Library/Application Support directory.
if runtime.GOOS == "darwin" {
homeDir, err := os.UserHomeDir()
if err != nil {
return config{}, err
}
// Duplicating the appending of grab to the config dir because this is
// the only platform we have a fallback on.
xdgConfig := filepath.Join(homeDir, ".config", "grab", "config.toml")
if _, err := os.Stat(xdgConfig); err == nil {
return loadConfigFrom(filepath.Join(homeDir, ".config"))
}
}
configDir, err := os.UserConfigDir()
if err != nil {
return config{}, err
}
return loadConfigFrom(configDir)
}
func loadConfigFrom(configDir string) (config, error) {
var cfg config
configPath := filepath.Join(configDir, "grab", "config.toml")
data, err := os.ReadFile(configPath)
if err != nil {
if !errors.Is(err, os.ErrNotExist) {
return cfg, err
}
// Missing config file is fine, proceed with defaults.
} else {
if err := toml.Unmarshal(data, &cfg); err != nil {
return cfg, err
}
}
// Env vars override config file values.
if envHome := strings.TrimSpace(os.Getenv("GRAB_HOME")); envHome != "" {
cfg.Home = envHome
}
// Default home to ~/src if still unset.
if cfg.Home == "" {
homeDir, err := os.UserHomeDir()
if err != nil {
return cfg, err
}
cfg.Home = filepath.Join(homeDir, "src")
}
return cfg, nil
}