Skip to content

Commit 72b1559

Browse files
committed
refactor: reworked cli parsing
it is now easier to add a new cli flag. The new implementation automatically adds any flag of the cli.Flag structure which was added to the cli.OPTIONS array to the flag parsing logic. It also supports displaying all added options with their name and description to the help page which can be viewed by running fleck without any arguments.
1 parent 50afa2c commit 72b1559

File tree

2 files changed

+37
-7
lines changed

2 files changed

+37
-7
lines changed

cli/cli.go

Lines changed: 36 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,26 +5,56 @@ import (
55
"fmt"
66
)
77

8+
type Flag struct {
9+
Name string
10+
Default bool
11+
Description string
12+
}
13+
814
type Arguments struct {
9-
ShellMacroEnabled bool
10-
InputFile string
15+
flags map[string]*bool
16+
InputFile string
17+
}
18+
19+
var OPTIONS []Flag = []Flag{
20+
{
21+
"shell-macro-enabled",
22+
false,
23+
"enables the dangerous '@shell{command}' macro, which allows the preprocessor to run any command on your system",
24+
},
1125
}
1226

1327
func ParseCli() Arguments {
14-
shellMacroEnabled := flag.Bool("shell-macro-enabled", false, "enables the @shell{command} macro")
28+
resMap := make(map[string]*bool)
29+
for _, f := range OPTIONS {
30+
resMap[f.Name] = flag.Bool(f.Name, f.Default, f.Description)
31+
}
1532

1633
flag.Parse()
1734
inputFile := flag.Arg(0)
1835

1936
return Arguments{
20-
InputFile: inputFile,
21-
ShellMacroEnabled: *shellMacroEnabled,
37+
InputFile: inputFile,
38+
flags: resMap,
2239
}
2340
}
2441

2542
func PrintShortHelp() {
2643
fmt.Println(`
2744
Usage:
2845
fleck [OPTIONS] file
29-
`)
46+
47+
Options:`)
48+
for _, v := range OPTIONS {
49+
fmt.Printf("\t--%s: %s\n", v.Name, v.Description)
50+
}
51+
fmt.Println("")
52+
}
53+
54+
func GetFlag(a Arguments, name string) bool {
55+
v, ok := a.flags[name]
56+
if !ok {
57+
return false
58+
}
59+
return *v
3060
}

fleck.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ func main() {
1919
os.Exit(1)
2020
}
2121

22-
if ARGUMENTS.ShellMacroEnabled {
22+
if cli.GetFlag(ARGUMENTS, "shell-macro-enabled") {
2323
log.Println("warning: 'shell-macro-enabled' flag specified, this can harm your operating system and make it vulnerable for attack, proceed at your own digression")
2424
}
2525

0 commit comments

Comments
 (0)