From cd0cf8f9a4fd131e9ddb70dee98aa51d82eb4549 Mon Sep 17 00:00:00 2001 From: Neil Macneale IV Date: Tue, 30 May 2023 14:33:44 -0700 Subject: [PATCH] Add ability to drop values from ArgParserResults --- go/libraries/utils/argparser/args_test.go | 45 +++++++++++++++++++++++ go/libraries/utils/argparser/results.go | 17 +++++++++ 2 files changed, 62 insertions(+) diff --git a/go/libraries/utils/argparser/args_test.go b/go/libraries/utils/argparser/args_test.go index 588c27012d..30f1d11591 100644 --- a/go/libraries/utils/argparser/args_test.go +++ b/go/libraries/utils/argparser/args_test.go @@ -280,3 +280,48 @@ func TestValidation(t *testing.T) { t.Error("Arg list issues") } } + +func TestDropValue(t *testing.T) { + ap := NewArgParserWithVariableArgs("test") + + ap.SupportsString("string", "", "string_value", "A string") + ap.SupportsFlag("flag", "", "A flag") + + apr, err := ap.Parse([]string{"--string", "str", "--flag", "1234"}) + if err != nil { + t.Fatal(err.Error()) + } + + newApr1 := apr.DropValue("string") + if apr.Equals(newApr1) { + t.Error("Original value and new value are equal") + } + _, hasVal := newApr1.GetValue("string") + if hasVal { + t.Error("DropValue failed to drop string") + } + _, hasVal = newApr1.GetValue("flag") + if !hasVal { + t.Error("DropValue dropped the wrong value") + } + if newApr1.NArg() != 1 || newApr1.Arg(0) != "1234" { + t.Error("DropValue didn't preserve args") + } + + newApr2 := apr.DropValue("flag") + if apr.Equals(newApr2) { + t.Error("DropValue failed to drop flag") + } + _, hasVal = newApr2.GetValue("string") + if !hasVal { + t.Error("DropValue dropped the wrong value") + } + _, hasVal = newApr2.GetValue("flag") + if hasVal { + t.Error("DropValue failed to drop flag") + } + if newApr2.NArg() != 1 || newApr2.Arg(0) != "1234" { + t.Error("DropValue didn't preserve args") + } + +} diff --git a/go/libraries/utils/argparser/results.go b/go/libraries/utils/argparser/results.go index 9ec12c9f4a..d914c965ed 100644 --- a/go/libraries/utils/argparser/results.go +++ b/go/libraries/utils/argparser/results.go @@ -121,6 +121,23 @@ func (res *ArgParseResults) GetValues(names ...string) map[string]string { return vals } +// DropValue removes the value for the given name from the results. A new ArgParseResults object is returned without the +// names value. If the value is not present in the results then the original results object is returned. +func (res *ArgParseResults) DropValue(name string) *ArgParseResults { + if _, ok := res.options[name]; !ok { + return res + } + + newNamedArgs := make(map[string]string, len(res.options)-1) + for flag, val := range res.options { + if flag != name { + newNamedArgs[flag] = val + } + } + + return &ArgParseResults{newNamedArgs, res.Args, res.parser} +} + func (res *ArgParseResults) MustGetValue(name string) string { val, ok := res.options[name]