Created
September 4, 2025 01:00
-
-
Save mattmc3/69143c911f7e70cea07667ec40a49cc7 to your computer and use it in GitHub Desktop.
Go expandShortFlags
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// turn -abc5 into -a -b -c5 | |
// ex: | |
// takesValue := map[rune]bool{'c': true} | |
// expandedArgs := expandShortOpts(os.Args[1:], takesValue) | |
func expandShortFlags(args []string, withValue map[rune]bool) []string { | |
var out []string | |
doubledash := false | |
for _, arg := range args { | |
if doubledash { | |
out = append(out, arg) | |
continue | |
} | |
if arg == "--" { | |
out = append(out, arg) | |
doubledash = true | |
continue | |
} | |
if len(arg) > 2 && arg[0] == '-' && arg[1] != '-' { | |
runes := []rune(arg[1:]) | |
for i := 0; i < len(runes); i++ { | |
opt := runes[i] | |
if withValue[opt] { | |
// this option consumes the rest as its value | |
out = append(out, "-"+string(opt), string(runes[i+1:])) | |
break | |
} | |
out = append(out, "-"+string(opt)) | |
} | |
} else { | |
out = append(out, arg) | |
} | |
} | |
return out | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment