@@ -8,75 +8,8 @@ import (
88 "regexp"
99 "slices"
1010 "strings"
11-
12- "github.com/pressly/cli/xflag"
1311)
1412
15- // Parse picks the right command and parses its flags from args, but does not run [Command.Exec].
16- // Use Parse with [Run] when you need to do work between parsing and running. For the common case,
17- // call [ParseAndRun].
18- //
19- // Parse returns [flag.ErrHelp] when the user passes -h or --help. You have to print the help
20- // yourself when this happens. [ParseAndRun] does it for you.
21- func Parse (root * Command , args []string ) error {
22- if root == nil {
23- return errors .New ("root command is nil" )
24- }
25- if err := validateCommands (root , nil ); err != nil {
26- return err
27- }
28-
29- // Initialize or update root state. Clear command pointers across the tree first so stale
30- // subcommands from a previous parse do not retain the newly resolved path.
31- state := root .state
32- clearCommandState (root )
33- if state == nil {
34- state = & State {}
35- }
36- root .state = state
37- root .state .Args = nil
38- root .state .Cmd = nil
39- root .state .path = []* Command {root }
40-
41- argsToParse , remainingArgs := splitAtDelimiter (args )
42-
43- current , err := resolveCommandPath (root , argsToParse )
44- if err != nil {
45- return err
46- }
47- root .state .Cmd = current
48- current .Flags .Usage = func () { /* suppress default usage */ }
49-
50- // Check for help flags after resolving the correct command
51- for _ , arg := range argsToParse {
52- if arg == "-h" || arg == "--h" || arg == "-help" || arg == "--help" {
53- return flag .ErrHelp
54- }
55- }
56-
57- combinedFlags := combineFlags (root .state .path )
58-
59- // Let ParseToEnd handle the flag parsing
60- if err := xflag .ParseToEnd (combinedFlags , argsToParse ); err != nil {
61- return fmt .Errorf ("command %q: %w" , getCommandPath (root .state .path ), err )
62- }
63-
64- root .state .Args = collectArgs (root .state .path , combinedFlags .Args (), remainingArgs )
65-
66- if current .Exec == nil && len (current .SubCommands ) > 0 {
67- return UsageErrorf ("subcommand required" )
68- }
69-
70- if err := checkRequiredFlags (root .state .path , combinedFlags ); err != nil {
71- return err
72- }
73-
74- if current .Exec == nil {
75- return fmt .Errorf ("command %q: no exec function defined" , getCommandPath (root .state .path ))
76- }
77- return nil
78- }
79-
8013// splitAtDelimiter splits args at the first "--" delimiter. Returns the args before the delimiter
8114// and any args after it.
8215func splitAtDelimiter (args []string ) (argsToParse , remaining []string ) {
0 commit comments