Add ability to drop values from ArgParserResults

This commit is contained in:
Neil Macneale IV
2023-05-30 14:33:44 -07:00
parent f122c86949
commit cd0cf8f9a4
2 changed files with 62 additions and 0 deletions

View File

@@ -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")
}
}

View File

@@ -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]