Skip to content

Commit

Permalink
cmd/cue: avoid loading the current package in cue help
Browse files Browse the repository at this point in the history
Loading a CUE package is necessary for `cue help cmd`,
as the inline comment now explains.

However, it was done for any help invocation,
even for those which did not need to list available `cue cmd` commands
such as `cue help` or `cue -h`.

There's already a regression test for `cue help cmd` showing available
commands in _tools.cue files, which continues to pass.
Other help commands are unaffected in behavior, but are cheaper now.
For example, in our ./internal/ci package which contains CUE commands:

	$ time cue help >/dev/null
	real  0m1.972s
	user  0m3.519s
	sys   0m0.083s

and after the change:

	$ time cue help >/dev/null
	real  0m0.006s
	user  0m0.000s
	sys   0m0.006s

Fixes #2161.

Signed-off-by: Daniel Martí <mvdan@mvdan.cc>
Change-Id: I5cd4942e6874550b9f7b3e51f80cc7ffd54a1cfd
Reviewed-on: https://review.gerrithub.io/c/cue-lang/cue/+/552250
Reviewed-by: Roger Peppe <rogpeppe@gmail.com>
Unity-Result: CUEcueckoo <cueckoo@cuelang.org>
TryBot-Result: CUEcueckoo <cueckoo@cuelang.org>
  • Loading branch information
mvdan committed Apr 5, 2023
1 parent d8c71fa commit 143b102
Showing 1 changed file with 17 additions and 4 deletions.
21 changes: 17 additions & 4 deletions cmd/cue/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"strings"

"github.com/spf13/cobra"
"github.com/spf13/pflag"

"cuelang.org/go/cue"
"cuelang.org/go/cue/cuecontext"
Expand Down Expand Up @@ -279,10 +280,19 @@ func New(args []string) (cmd *Command, err error) {
// "fix": {"fix", nil},
}

// handle help, --help and -h on root 'cue' command
if args[0] == "help" || args[0] == "--help" || args[0] == "-h" {
// Allow errors.
_ = addSubcommands(cmd, sub, args[1:], true)
if args[0] == "help" {
if len(args) >= 2 && sub[args[1]] != nil {
// addSubcommands adds helpful information to each of the help docs,
// for example `cue help cmd` shows the available commands by loading
// `*_tools.cue` files.
//
// Ignore errors, since this is a help command and the extra content
// is an extra that shouldn't prevent help text from being shown.
//
// TODO: `cue cmd -h` does not trigger this, and maybe it should for
// consistency with `cue help cmd`.
_ = addSubcommands(cmd, sub, args[1:], true)
}
return cmd, nil
}

Expand All @@ -294,6 +304,9 @@ func New(args []string) (cmd *Command, err error) {
// it.
err = cmd.cmd.ParseFlags(args)
if err != nil {
if errors.Is(err, pflag.ErrHelp) {
return cmd, nil
}
return nil, err
}

Expand Down

0 comments on commit 143b102

Please sign in to comment.