Skip to content

Commit

Permalink
fix: assign value mapped flags
Browse files Browse the repository at this point in the history
  • Loading branch information
natesales committed Aug 25, 2024
1 parent 3ae0d45 commit 6df2868
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
42 changes: 42 additions & 0 deletions cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,3 +196,45 @@ func ParseRRTypes(t []string) (map[uint16]bool, error) {
}
return rrTypes, nil
}

// isBool checks if a flag by a given name is a boolean flag of Flags
func isBool(name string) bool {
v := reflect.ValueOf(Flags{})
vT := v.Type()
for i := 0; i < v.NumField(); i++ {
if vT.Field(i).Tag.Get("short") == name || vT.Field(i).Tag.Get("long") == name {
return vT.Field(i).Type == reflect.TypeOf(true)
}
}
return false
}

// AddEqualSigns adds equal signs between flags and their values, ignoring boolean flags
func AddEqualSigns(args []string) []string {
var newArgs []string
skip := false
for i, arg := range args {
if skip {
skip = false
continue
}

isFlag := arg[0] == '-'
flagName := strings.TrimLeft(arg, "-")

if isFlag && isBool(flagName) { // Standalone boolean flag
newArgs = append(newArgs, arg)
} else if isFlag && !isBool(flagName) { // Flag with mapping
if i+1 < len(args) && args[i+1][0] != '-' { // If the next argument is not a flag
newArgs = append(newArgs, arg+"="+args[i+1])
skip = true
} else { // If the next argument is a flag, add the flag as is
newArgs = append(newArgs, arg)
}
} else { // Positional argument
newArgs = append(newArgs, arg)
}
}

return newArgs
}
1 change: 1 addition & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,7 @@ func parseServer(s string) (string, transport.Type, error) {
// driver is the "main" function for this program that accepts a flag slice for testing
func driver(args []string, out io.Writer) error {
args = cli.SetFalseBooleans(&opts, args)
args = cli.AddEqualSigns(args)
parser := flags.NewParser(&opts, flags.Default)
parser.Usage = `[OPTIONS] [@server] [type...] [name]
Expand Down
10 changes: 10 additions & 0 deletions main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -533,3 +533,13 @@ func TestMainQueryDomainWithRRType(t *testing.T) {
assert.Nil(t, err)
assert.Regexp(t, regexp.MustCompile(`NS.network. .* A .*`), out.String())
}

func TestMainQueryTypeFlag(t *testing.T) {
out, err := run(
"-t", "65",
"cloudflare.com",
"-v",
)
assert.Nil(t, err)
assert.Regexp(t, regexp.MustCompile(`cloudflare.com. .* HTTPS 1 .*`), out.String())
}

0 comments on commit 6df2868

Please sign in to comment.