Skip to content

Commit 093d9ae

Browse files
committed
Add support for parsing multiple config files
1 parent f5f45af commit 093d9ae

File tree

3 files changed

+45
-11
lines changed

3 files changed

+45
-11
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# smartpricer/flag
22

3+
- Add support for multiple config files (separated by colon `:`)
34
- Add support for yaml-like config file format
45
- Change config file to support environment variable-style flag names
56

extras_test.go

+29
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,35 @@ func TestDefaultConfigFlagnameYAML(t *testing.T) {
200200
}
201201
}
202202

203+
func TestDefaultConfigFlagnameMultiple(t *testing.T) {
204+
f := NewFlagSet("test", ContinueOnError)
205+
206+
f.Bool("bool", false, "bool value")
207+
f.Bool("bool2", false, "bool2 value")
208+
f.Int("int", 0, "int value")
209+
f.Int64("int64", 0, "int64 value")
210+
f.Uint("uint", 0, "uint value")
211+
f.Uint64("uint64", 0, "uint64 value")
212+
stringFlag := f.String("string", "0", "string value")
213+
f.String("string2", "0", "string value")
214+
f.String("string3-env-like", "0", "string value")
215+
f.Float64("float64", 0, "float64 value")
216+
f.Duration("duration", 5*time.Second, "time.Duration value")
217+
218+
f.String(DefaultConfigFlagname, "./testdata/test.yml:./testdata/test.conf", "config path")
219+
220+
if err := os.Unsetenv("STRING"); err != nil {
221+
t.Error(err)
222+
}
223+
224+
if err := f.Parse([]string{}); err != nil {
225+
t.Error("parse failed; ", err)
226+
}
227+
228+
if *stringFlag != "helloYAML" {
229+
t.Error("string flag should be `hello`, is", *stringFlag)
230+
}
231+
}
203232

204233
func TestDefaultConfigFlagnameMissingFile(t *testing.T) {
205234
f := NewFlagSet("test", ContinueOnError)

flag.go

+15-11
Original file line numberDiff line numberDiff line change
@@ -1225,19 +1225,23 @@ func (f *FlagSet) parseExtras() error {
12251225
cFile = cf.Value.String()
12261226
}
12271227
if cFile != "" {
1228-
if err := f.ParseFile(cFile); err != nil {
1229-
switch f.errorHandling {
1230-
case ContinueOnError:
1231-
return err
1232-
case ExitOnError:
1233-
if err == ErrHelp {
1234-
os.Exit(0)
1228+
singleFiles := strings.Split(cFile, ":")
1229+
1230+
for _, singleFile := range singleFiles {
1231+
if err := f.ParseFile(singleFile); err != nil {
1232+
switch f.errorHandling {
1233+
case ContinueOnError:
1234+
return err
1235+
case ExitOnError:
1236+
if err == ErrHelp {
1237+
os.Exit(0)
1238+
}
1239+
os.Exit(2)
1240+
case PanicOnError:
1241+
panic(err)
12351242
}
1236-
os.Exit(2)
1237-
case PanicOnError:
1238-
panic(err)
1243+
return err
12391244
}
1240-
return err
12411245
}
12421246
}
12431247
// /* jnovack/flag END */

0 commit comments

Comments
 (0)