From 924207d324502680763fa229ab000992b0056e69 Mon Sep 17 00:00:00 2001 From: GGP1 Date: Sun, 28 Jul 2024 14:03:59 -0300 Subject: [PATCH] Validate flags before login --- main.go | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/main.go b/main.go index 04a824c..6a8276a 100644 --- a/main.go +++ b/main.go @@ -1,6 +1,7 @@ package main import ( + "errors" "fmt" "os" "path/filepath" @@ -10,12 +11,21 @@ import ( "github.com/GGP1/kure/commands/root" "github.com/GGP1/kure/config" "github.com/GGP1/kure/sig" + "github.com/spf13/pflag" "github.com/awnumar/memguard" bolt "go.etcd.io/bbolt" ) func main() { + if err := validateFlags(); err != nil { + if errors.Is(err, pflag.ErrHelp) { + os.Exit(0) + } + fmt.Fprintln(os.Stderr, "error:", err) + os.Exit(1) + } + if err := config.Init(); err != nil { fmt.Fprintln(os.Stderr, "couldn't initialize the configuration:", err) os.Exit(1) @@ -55,3 +65,24 @@ func main() { db.Close() memguard.SafeExit(0) } + +// validateFlags looks for the command called and parses its flags. If the flag is `--help`, +// it will print the command's help message and return the error pflag.ErrHelp. +func validateFlags() error { + cmd, args, err := root.NewCmd(nil).Find(os.Args[1:]) + if err != nil { + return err + } + + if err := cmd.ParseFlags(args); err != nil { + if errors.Is(err, pflag.ErrHelp) { + if err := cmd.Help(); err != nil { + return err + } + return pflag.ErrHelp + } + return err + } + + return nil +}