From 7c12464e7fa6f604220df2c0390109524b02aa88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?lucaxli=28=E9=BB=8E=E5=BE=8B=29?= Date: Mon, 20 Jul 2020 11:32:29 +0800 Subject: [PATCH] fix set flags panic --- go.mod | 3 +++ load.go | 16 ++++++++++++++-- parser/parser.go | 6 ++++++ 3 files changed, 23 insertions(+), 2 deletions(-) create mode 100644 go.mod diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..bca6bdb --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module github.com/spacemonkeygo/flagfile + +go 1.14 diff --git a/load.go b/load.go index 49d354a..ab2abd7 100644 --- a/load.go +++ b/load.go @@ -49,6 +49,14 @@ func mustSet(flag_name, flag_value string) { } } +func trySet(flag_name, flag_value string) error { + err := flag.Set(flag_name, flag_value) + if err != nil { + return err + } + return nil +} + type Option struct { flagfilePath string skipArgs bool @@ -169,8 +177,12 @@ func Load(opts ...Option) { if ignoreUnknowns && flag.Lookup(name) == nil { return } - mustSet(name, value) - set_flags[name] = true + + err := trySet(name, value) + + if err != nil { + set_flags[name] = true + } }) fh.Close() if err != nil { diff --git a/parser/parser.go b/parser/parser.go index 649a5f8..c5f3d32 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -70,7 +70,13 @@ func Parse(in io.Reader, cb func(key, value string)) error { if len(parts) != 2 { return fmt.Errorf("unable to parse flagfile line %d", lineno) } + name := strings.TrimSpace(parts[0]) + // support format like --flag=xx + if len(name) > 2 && name[0:2] == "--" { + name = name[2:] + } + if section != "" { name = section + name }