peterbourgon / ff

Flags-first package for configuration
Apache License 2.0
1.37k stars 59 forks source link

Feature request: ability to provide a default config file path #80

Closed nyonson closed 3 years ago

nyonson commented 3 years ago

I would like to provided a default configuration file based on XDG (e.g. ~/.config/APP.config) which could then be overwritten by WithConfigFileFlag if a user prefers a different location. I was surprised to find that with the existing settings WithConfigFile overwrites WithConfigFileFlag, is there a use case for this that I am missing?

peterbourgon commented 3 years ago

WithConfigFile is provided only so there is a way to set a config file without necessarily exposing the parameter as a flag, but that is a very rare circumstance. If you want to provide an e.g. -config-file flag with some default, just define it as a flag with a default value.

var defaultConfigFile string
if d, err := os.UserConfigDir(); err == nil {
    defaultConfigFile = filepath.Join(d, "myctl", "myctl.conf")
}

fs := flag.NewFlagSet("myctl", flag.ExitOnError)
var (
    foo = fs.String("foo", "hello world", "foo flag")
    _   = fs.String("config", defaultConfigFile, "config file")
)
ff.Parse(fs, os.Args[1:], ff.WithConfigFileFlag("config"))
nyonson commented 3 years ago

Ah, I totally misinterpreted how WithConfigFileFlag worked, thanks for the example. I went with your solution.