Skip to content

Commit

Permalink
refactor: reworked cli parsing
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
xNaCly committed Apr 11, 2023
1 parent 50afa2c commit 72b1559
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 7 deletions.
42 changes: 36 additions & 6 deletions cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,26 +5,56 @@ import (
"fmt"
)

type Flag struct {
Name string
Default bool
Description string
}

type Arguments struct {
ShellMacroEnabled bool
InputFile string
flags map[string]*bool
InputFile string
}

var OPTIONS []Flag = []Flag{
{
"shell-macro-enabled",
false,
"enables the dangerous '@shell{command}' macro, which allows the preprocessor to run any command on your system",
},
}

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

flag.Parse()
inputFile := flag.Arg(0)

return Arguments{
InputFile: inputFile,
ShellMacroEnabled: *shellMacroEnabled,
InputFile: inputFile,
flags: resMap,
}
}

func PrintShortHelp() {
fmt.Println(`
Usage:
fleck [OPTIONS] file
`)
Options:`)
for _, v := range OPTIONS {
fmt.Printf("\t--%s: %s\n", v.Name, v.Description)
}
fmt.Println("")
}

func GetFlag(a Arguments, name string) bool {
v, ok := a.flags[name]
if !ok {
return false
}
return *v
}
2 changes: 1 addition & 1 deletion fleck.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ func main() {
os.Exit(1)
}

if ARGUMENTS.ShellMacroEnabled {
if cli.GetFlag(ARGUMENTS, "shell-macro-enabled") {
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")
}

Expand Down

0 comments on commit 72b1559

Please sign in to comment.