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

55 lines
1.2 KiB
Go

package context
import (
"fmt"
"io"
"os"
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/completion"
"github.com/docker/cli/cli/context/store"
"github.com/spf13/cobra"
)
func newImportCommand(dockerCli command.Cli) *cobra.Command {
cmd := &cobra.Command{
Use: "import CONTEXT FILE|-",
Short: "Import a context from a tar or zip file",
Args: cli.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
return RunImport(dockerCli, args[0], args[1])
},
// TODO(thaJeztah): this should also include "-"
ValidArgsFunction: completion.FileNames,
}
return cmd
}
// RunImport imports a Docker context
func RunImport(dockerCli command.Cli, name string, source string) error {
if err := checkContextNameForCreation(dockerCli.ContextStore(), name); err != nil {
return err
}
var reader io.Reader
if source == "-" {
reader = dockerCli.In()
} else {
f, err := os.Open(source)
if err != nil {
return err
}
defer f.Close()
reader = f
}
if err := store.Import(name, dockerCli.ContextStore(), reader); err != nil {
return err
}
_, _ = fmt.Fprintln(dockerCli.Out(), name)
_, _ = fmt.Fprintf(dockerCli.Err(), "Successfully imported context %q\n", name)
return nil
}