-
Notifications
You must be signed in to change notification settings - Fork 51
/
user_config.go
78 lines (64 loc) · 2.13 KB
/
user_config.go
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
76
77
78
package app
import (
"io/ioutil"
"os"
"github.com/alecthomas/hcl"
"github.com/alecthomas/kong"
"github.com/cashapp/hermit/errors"
)
const userConfigPath = "~/.hermit.hcl"
var userConfigSchema = func() string {
schema, err := hcl.Schema(&UserConfig{})
if err != nil {
return ""
}
data, err := hcl.MarshalAST(schema)
if err != nil {
return ""
}
return string(data)
}()
// UserConfig is stored in ~/.hermit.hcl
type UserConfig struct {
Prompt string `hcl:"prompt,optional" default:"env" enum:"env,short,none" help:"Modify prompt to include hermit environment (env), just an icon (short) or nothing (none)"`
ShortPrompt bool `hcl:"short-prompt,optional" help:"If true use a short prompt when an environment is activated."`
NoGit bool `hcl:"no-git,optional" help:"If true Hermit will never add/remove files from Git automatically."`
Idea bool `hcl:"idea,optional" help:"If true Hermit will try to add the IntelliJ IDEA plugin automatically."`
}
// LoadUserConfig from disk.
func LoadUserConfig() (UserConfig, error) {
config := UserConfig{}
// always return a valid config on error, with defaults set.
_ = hcl.Unmarshal([]byte{}, &config)
data, err := ioutil.ReadFile(kong.ExpandPath(userConfigPath))
if os.IsNotExist(err) {
return config, nil
} else if err != nil {
return config, errors.WithStack(err)
}
err = hcl.Unmarshal(data, &config)
if err != nil {
return config, errors.WithStack(err)
}
return config, nil
}
// UserConfigResolver is a Kong configuration resolver for the Hermit user configuration file.
func UserConfigResolver(userConfig UserConfig) kong.Resolver {
return &userConfigResolver{userConfig}
}
type userConfigResolver struct{ config UserConfig }
func (u *userConfigResolver) Validate(app *kong.Application) error { return nil }
func (u *userConfigResolver) Resolve(context *kong.Context, parent *kong.Path, flag *kong.Flag) (interface{}, error) {
switch flag.Name {
case "no-git":
return u.config.NoGit, nil
case "prompt":
return u.config.Prompt, nil
case "short-prompt":
return u.config.ShortPrompt, nil
case "idea":
return u.config.Idea, nil
default:
return nil, nil
}
}