Sebastiaan van Stijn 6fd72c6333
context: add shell-completion for context-names
For now, these are not exported and included in the cli/commands/contexts
package; a copy of this also lives in cmd/docker, but we need to find a
good place for these completions, as some of them bring in additional
dependencies.

Commands that accept multiple arguments provide completion, but removing
duplicates:

    docker context inspect<TAB>
    default  desktop-linux  (current)  production  tcd

    docker context inspec default<TAB>
    desktop-linux  (current)  production  tcd

    docker context inspect default tcd<TAB>
    desktop-linux  (current)  production

For "context export", we provide completion for the first argument, after
which file-completion is provided:

    # provides context names completion for the first argument
    docker context export production<TAB>
    default  desktop-linux  (current)  production  tcd

    # then provides completion for filenames
    docker context export desktop-linux<TAB>
    build/           man/                TESTING.md
    cli/             docker.Makefile     go.mod
    ...

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-17 10:32:18 +02:00

58 lines
1.8 KiB
Go

package context
import (
"fmt"
"os"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/context/store"
"github.com/docker/docker/client"
"github.com/spf13/cobra"
)
func newUseCommand(dockerCLI command.Cli) *cobra.Command {
cmd := &cobra.Command{
Use: "use CONTEXT",
Short: "Set the current docker context",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
name := args[0]
return RunUse(dockerCLI, name)
},
ValidArgsFunction: completeContextNames(dockerCLI, 1, false),
}
return cmd
}
// RunUse set the current Docker context
func RunUse(dockerCLI command.Cli, name string) error {
// configValue uses an empty string for "default"
var configValue string
if name != command.DefaultContextName {
if err := store.ValidateContextName(name); err != nil {
return err
}
if _, err := dockerCLI.ContextStore().GetMetadata(name); err != nil {
return err
}
configValue = name
}
dockerConfig := dockerCLI.ConfigFile()
// Avoid updating the config-file if nothing changed. This also prevents
// creating the file and config-directory if the default is used and
// no config-file existed yet.
if dockerConfig.CurrentContext != configValue {
dockerConfig.CurrentContext = configValue
if err := dockerConfig.Save(); err != nil {
return err
}
}
_, _ = fmt.Fprintln(dockerCLI.Out(), name)
_, _ = fmt.Fprintf(dockerCLI.Err(), "Current context is now %q\n", name)
if name != command.DefaultContextName && os.Getenv(client.EnvOverrideHost) != "" {
_, _ = fmt.Fprintf(dockerCLI.Err(), "Warning: %[1]s environment variable overrides the active context. "+
"To use %[2]q, either set the global --context flag, or unset %[1]s environment variable.\n", client.EnvOverrideHost, name)
}
return nil
}