Skip to content
This repository was archived by the owner on Oct 17, 2021. It is now read-only.

Allow passing raw args to commands #5

Merged
merged 1 commit into from
Aug 5, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions command.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ type CommandSpec struct {
// Desc is the description of the command.
// The first line is used as an abbreviated description.
Desc string
// RawArgs indicates that flags should not be parsed, and they should be deferred
// to the command.
RawArgs bool

// Hidden indicates that this command should not show up in it's parent's
// subcommand help.
Expand Down
77 changes: 41 additions & 36 deletions run.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
package cli

import (
"flag"
"os"
"flag"
"os"
)

func appendParent(parent string, add string) string {
if parent == "" {
return add + " "
}
return parent + add + " "
if parent == "" {
return add + " "
}
return parent + add + " "
}

// Run sets up flags, helps, and executes the command with the provided
Expand All @@ -20,38 +20,43 @@ func appendParent(parent string, add string) string {
//
// Use RunRoot if this package is managing the entire CLI.
func Run(cmd Command, args []string, parent string) {
fl := flag.NewFlagSet(parent+""+cmd.Spec().Name, flag.ExitOnError)

if fc, ok := cmd.(FlaggedCommand); ok {
fc.RegisterFlags(fl)
}

fl.Usage = func() {
renderHelp(cmd, fl, os.Stderr)
}
_ = fl.Parse(args)

subcommandArg := fl.Arg(0)

// Route to subcommand.
if pc, ok := cmd.(ParentCommand); ok && subcommandArg != "" {
for _, subcommand := range pc.Subcommands() {
if subcommand.Spec().Name != subcommandArg {
continue
}

Run(
subcommand, fl.Args()[1:],
appendParent(parent, cmd.Spec().Name),
)
return
}
}

cmd.Run(fl)
fl := flag.NewFlagSet(parent+""+cmd.Spec().Name, flag.ExitOnError)

if fc, ok := cmd.(FlaggedCommand); ok {
fc.RegisterFlags(fl)
}

fl.Usage = func() {
renderHelp(cmd, fl, os.Stderr)
}

if cmd.Spec().RawArgs {
// Use `--` to return immediately when parsing the flags.
args = append([]string{"--"}, args...)
}
_ = fl.Parse(args)

subcommandArg := fl.Arg(0)

// Route to subcommand.
if pc, ok := cmd.(ParentCommand); ok && subcommandArg != "" {
for _, subcommand := range pc.Subcommands() {
if subcommand.Spec().Name != subcommandArg {
continue
}

Run(
subcommand, fl.Args()[1:],
appendParent(parent, cmd.Spec().Name),
)
return
}
}

cmd.Run(fl)
}

// RunRoot calls Run with the process's arguments.
func RunRoot(cmd Command) {
Run(cmd, os.Args[1:], "")
Run(cmd, os.Args[1:], "")
}