Skip to content

Commit a10f08a

Browse files
authored
Merge pull request #37 from GGP1/validate_flags
Validate flags before login
2 parents 76c5411 + 924207d commit a10f08a

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

main.go

+31
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package main
22

33
import (
4+
"errors"
45
"fmt"
56
"os"
67
"path/filepath"
@@ -10,12 +11,21 @@ import (
1011
"github.com/GGP1/kure/commands/root"
1112
"github.com/GGP1/kure/config"
1213
"github.com/GGP1/kure/sig"
14+
"github.com/spf13/pflag"
1315

1416
"github.com/awnumar/memguard"
1517
bolt "go.etcd.io/bbolt"
1618
)
1719

1820
func main() {
21+
if err := validateFlags(); err != nil {
22+
if errors.Is(err, pflag.ErrHelp) {
23+
os.Exit(0)
24+
}
25+
fmt.Fprintln(os.Stderr, "error:", err)
26+
os.Exit(1)
27+
}
28+
1929
if err := config.Init(); err != nil {
2030
fmt.Fprintln(os.Stderr, "couldn't initialize the configuration:", err)
2131
os.Exit(1)
@@ -55,3 +65,24 @@ func main() {
5565
db.Close()
5666
memguard.SafeExit(0)
5767
}
68+
69+
// validateFlags looks for the command called and parses its flags. If the flag is `--help`,
70+
// it will print the command's help message and return the error pflag.ErrHelp.
71+
func validateFlags() error {
72+
cmd, args, err := root.NewCmd(nil).Find(os.Args[1:])
73+
if err != nil {
74+
return err
75+
}
76+
77+
if err := cmd.ParseFlags(args); err != nil {
78+
if errors.Is(err, pflag.ErrHelp) {
79+
if err := cmd.Help(); err != nil {
80+
return err
81+
}
82+
return pflag.ErrHelp
83+
}
84+
return err
85+
}
86+
87+
return nil
88+
}

0 commit comments

Comments
 (0)