Skip to content

Filter root command completion on condition #2262

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
moshe5745 opened this issue Mar 24, 2025 · 11 comments
Open

Filter root command completion on condition #2262

moshe5745 opened this issue Mar 24, 2025 · 11 comments

Comments

@moshe5745
Copy link

I have an init command in my tool.
I want to do some logical checks on the directory where the command was executed
And if it meets specific criteria to show the completion of all the commands and if not to show only the init command.

Is there a way to do it with Cobra today?

I tried to use ValidArgsFunc on the root command but I see it's not been triggered.

@moshe5745
Copy link
Author

moshe5745 commented Mar 24, 2025

I tried to use ValidArgsFunc on the root command but I see it's not been triggered.

Update. I see now its been triggered.
But the original list of commands is too still there....

So its only added new command

@moshe5745
Copy link
Author

Ok. More updates.

I thought I will leave the completion logic for now and use the PersistentPreRunE.
So I added:

PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
			
			if err := util.CheckSomeLogic(); err != nil {
				return fmt.Errorf("%v", err)
			}
			return nil
		},

With this the completions not working. So I guess the PersistentPreRunE is executed on the completion?(TAB)
Buy the way even that I threw the error(and I see it)

It printed the usage of the package. I think its not convenient. I would like to see only my error and that it. Is it possible?

@marckhouzam
Copy link
Collaborator

Is there a way to do it with Cobra today?

Cobra will automatically complete all the available commands.
What you need to do is not to create the other commands of your tool until the conditions are met.
If you don't want to do that all the time, you could only do it when completion is being triggered.

So, you can try in the PersistentPreRun:

  • if cmd.Name() == cobra.ShellCompRequestCmd then check your init logic and if it fails, remove all commands except the init command and the completion command by going through cmd.Root()

If this does not work in the PersistentPreRun (I'm not sure without trying), then you can do something similar before root.Execute() is called, but then you'll have to figure out yourself if the command is __complete or __completeNoDesc

@marckhouzam
Copy link
Collaborator

It printed the usage of the package. I think its not convenient. I would like to see only my error and that it. Is it possible?

Try setting rootCmd.SilenceUsage = true

@moshe5745
Copy link
Author

moshe5745 commented Mar 24, 2025

This one works like a charm:

if err := util.CheckMyInitLogic(); err == nil {
		rootCmd.AddCommand(commands.())
		rootCmd.AddCommand(commands.())
                ...
	} else {
		rootCmd.AddCommand(commands.NewInitCommand())
	}

	if err := rootCmd.Execute(); err != nil {
		os.Exit(1)
	}

This one works. But now when I am trying to execute a legal command that must work after init returns:

~% my_cli_tool some-command
Error: unknown command "some-command" for "my_cli_tool"
Run 'my_cli_tool --help' for usage.

So I guess its not very good UX.

My initial intention was to inform the user to execute the init command before he can use other commands.
Dont know how to tackle this...

@marckhouzam
Copy link
Collaborator

So I guess its not very good UX.

Instead of not creating the commands, you can instead make them hidden, which means they can be invoked and you won't get the error. However, if you run my_cli_tool --help those commands won't be in the help, which I assume is not great either?

So what you should do is

If you don't want to do that all the time, you could only do it when completion is being triggered.

So, the commands will all exist all the time, except when you try to complete them

@moshe5745
Copy link
Author

So what you should do is

If you don't want to do that all the time, you could only do it when completion is being triggered.

So, the commands will all exist all the time, except when you try to complete them

Ok. I am trying to understand.
So you telling that all the commands will always be added.
And I need to add my init logic checker in the completion so I guess its the ValidArgsFunction right?

But the issue I encountered with ValidArgsFunction is that it only adds new completions when I am trying to use it on root command.
So all the commands are still present in the list. Or maybe I didn't get you right?

@marckhouzam
Copy link
Collaborator

Ok. I am trying to understand.

Yeah, it's hard to explain in a comment. But let's try to figure this out.

So you telling that all the commands will always be added.

Except when the command being called is __complete or __completeNoDesc. This command, which can take these two forms, is a hidden command added automatically by Cobra which gets called when you press TAB during shell completion.

So, either in the PersistenPreRun, or if it does not work, before root.Execute is called, you will need to:
1- check if the command is __complete and if so
2- run your init check and if it fails
3- remove all commands (except the __complete one added by cobra).

And I need to add my init logic checker in the completion so I guess its the ValidArgsFunction right?

At that point it is too late because Cobra has already built a list of all existing commands and will suggest them to the user.

@moshe5745
Copy link
Author

So, either in the PersistenPreRun, or if it does not work, before root.Execute is called, you will need to: 1- check if the command is __complete and if so 2- run your init check and if it fails 3- remove all commands (except the __complete one added by cobra).

And I need to add my init logic checker in the completion so I guess its the ValidArgsFunction right?

At that point it is too late because Cobra has already built a list of all existing commands and will suggest them to the user.

Thanks for your help and patience.
Tried to put the logic in PreRun without success.
Now I am trying to put it before the execute. But I cant figure out where I get the current command from?
In the PreRun I got it as function arg.

	if cmd.Name() == cobra.ShellCompRequestCmd {
            ^^^ <<---- How do I get this? 
           // ShellCompRequestCmd is for __complete
           // What is for __completeNoDesc?
		if err := util.CheckRepoContext(); err != nil {
			cmd.Root().RemoveCommand(commands.NewAddRequestCommand())
			cmd.Root().RemoveCommand(commands.NewRequestCommand())
			cmd.Root().RemoveCommand(commands.NewSetEnvCommand())
			cmd.Root().RemoveCommand(commands.NewSetEnvVarCommand())
			cmd.Root().RemoveCommand(commands.NewShowEnvCommand())
		}
	}

	if err := rootCmd.Execute(); err != nil {
		os.Exit(1)
	}

@marckhouzam
Copy link
Collaborator

You’ll have to use os.Args[1:] and cobra.Find()

@marckhouzam
Copy link
Collaborator

Tried to put the logic in PreRun without success.

PreRun won’t work for sure. Try PersistentPreRun, although I’m not sure

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants