cobra icon indicating copy to clipboard operation
cobra copied to clipboard

Question: Avoiding Generation of Example, Short, Long on commands

Open SJrX opened this issue 1 year ago • 2 comments

I have written a utility and the utility itself has several sub-commands that themselves have hundreds of sub-commands, that are generated via meta-data that can allow for very powerful usage and instructions and validation. I recently changed the structure from having a few commands to lots (one per type in meta-data), since it improved usability without rewriting tons of cobra (i.e., the number of arguments is variable in some cases, so I can use a built in validator now instead of coding my own logic).

One challenge I have is that some of the fields, Example, Short, Long are very expensive to generate comparatively and so things like auto-complete resolution, or very simple commands are slow as it generates all the data to populate the "Short", "Example" and "Long" commands.

I was looking for some advice on the best way to avoid these unless necessary. I think the Example and Long are only ever displayed at most once, and Short might only be necessary over one set of descendants. If all these took func() string that would help my performance, but I'm looking for other ideas/solutions and not asking for a breaking API change.

I think for auto complete I could short cut something if it's a completion command.

SJrX avatar Oct 02 '23 19:10 SJrX

Just in case it's not clear, here is an example, I can speed up autocompletion, by doing this in my main method:

if os.Args[1] == "__complete" {
		DisableExpensiveCommandFields = true
}

With this var set, my code that would generate a Long:, Short: and Example: on the commands actually just returns empty, since they shouldn't be used. Although that seems hacky and brittle, and it only makes autocomplete fast. The overhead FYI is about 200 ms, if I can disable those fields it goes down to 5 ms.

It doesn't help with other options (i.e., if/when help is needed, because of a flag, print usage, etc...)

SJrX avatar Oct 02 '23 20:10 SJrX

You could write a PersistentPreRun on your root command and check if the command received is ShellCompRequestCmd.

It’s similar to what you suggest above

marckhouzam avatar Oct 14 '23 14:10 marckhouzam