spf13 / cobra

A Commander for modern Go CLI interactions
https://cobra.dev
Apache License 2.0
37.59k stars 2.83k forks source link

Completion and sudo #2179

Open apostasie opened 3 weeks ago

apostasie commented 3 weeks ago

Hi,

For nerdctl, we are interested in displaying different completion if called with sudo vs. called directly. (https://github.com/containerd/nerdctl/issues/99 ).

Do you have a recommendation on how to implement this / approach this problem?

I assume we would have to patch: https://github.com/spf13/cobra/blob/v1.8.1/bash_completionsV2.go#L84 to call with sudo if needed.

But then, how do we decide that? Use _complete_as_root to test?

Thanks a lot.

marckhouzam commented 3 weeks ago

First thing to note is that when shell completion is performed it is the completion script for the sudo command that gets called. And apparently that script knows to call the completion of the relevant command. I’d be curious to know what that completion does to eventually invoke the nerctl completion script. If we’re lucky maybe it can help figure out if the invocation is from sudo.

marckhouzam commented 3 weeks ago

it is the completion script for the sudo command that gets called

This is an assumption. Maybe the shell does something special for sudo. Either way I would suggest looking into the shell completion for sudo as a first step.

apostasie commented 3 weeks ago

Yeah, I looked into it.

On Ubuntu 24.04 at least, this is here:

/usr/share/bash-completion/bash_completion (and /usr/share/bash-completion/completions/sudo )

Which is why I was thinking about using _complete_as_root to check.

apostasie commented 3 weeks ago

What I mean is that the following works (as a POC):

    if _complete_as_root; then
      out=$(eval "sudo ${requestComp}" 2>/dev/null)
    else
      out=$(eval "${requestComp}" 2>/dev/null)