diff --git a/Makefile b/Makefile index e6cd68f23cea..8785afc208c7 100644 --- a/Makefile +++ b/Makefile @@ -48,6 +48,7 @@ OCI_RUNTIME ?= "" BASHINSTALLDIR=${PREFIX}/share/bash-completion/completions ZSHINSTALLDIR=${PREFIX}/share/zsh/site-functions +FISHINSTALLDIR=${PREFIX}/share/fish/vendor_completions.d SELINUXOPT ?= $(shell test -x /usr/sbin/selinuxenabled && selinuxenabled && echo -Z) @@ -474,6 +475,15 @@ changelog: ## Generate changelog $(shell cat $(TMPFILE) >> changelog.txt) $(shell rm $(TMPFILE)) +completions: binaries + install ${SELINUXOPT} -d -m 755 completions/{bash,zsh,fish} + ./bin/podman completion bash --no-desc -f completions/bash/podman + ./bin/podman-remote completion bash --no-desc -f completions/bash/podman-remote + ./bin/podman completion zsh -f completions/zsh/_podman + ./bin/podman-remote completion zsh -f completions/zsh/_podman-remote + ./bin/podman completion fish -f completions/fish/podman.fish + ./bin/podman-remote completion fish -f completions/fish/podman-remote.fish + .PHONY: install install: .gopathok install.bin install.remote install.man install.cni install.systemd ## Install binaries to system locations @@ -512,8 +522,13 @@ install.man: docs install.man-nobuild install.completions: install ${SELINUXOPT} -d -m 755 ${DESTDIR}${BASHINSTALLDIR} install ${SELINUXOPT} -m 644 completions/bash/podman ${DESTDIR}${BASHINSTALLDIR} + install ${SELINUXOPT} -m 644 completions/bash/podman-remote ${DESTDIR}${BASHINSTALLDIR} install ${SELINUXOPT} -d -m 755 ${DESTDIR}${ZSHINSTALLDIR} install ${SELINUXOPT} -m 644 completions/zsh/_podman ${DESTDIR}${ZSHINSTALLDIR} + install ${SELINUXOPT} -m 644 completions/zsh/_podman-remote ${DESTDIR}${ZSHINSTALLDIR} + install ${SELINUXOPT} -d -m 755 ${DESTDIR}${FISHINSTALLDIR} + install ${SELINUXOPT} -m 644 completions/fish/podman.fish ${DESTDIR}${FISHINSTALLDIR} + install ${SELINUXOPT} -m 644 completions/fish/podman-remote.fish ${DESTDIR}${FISHINSTALLDIR} .PHONY: install.cni install.cni: @@ -656,9 +671,20 @@ API.md: pkg/varlink/io.podman.varlink $(GO) generate ./docs/... .PHONY: validate.completions -validate.completions: completions/bash/podman +validate.completions: SHELL:=/usr/bin/env bash # Set shell to bash for this target +validate.completions: + # Check that nobody has manually edited the completion scripts + # If this check fails run make completions to restore the correct scripts + diff completions/bash/podman <(./bin/podman completion --no-desc bash) + diff completions/zsh/_podman <(./bin/podman completion zsh) + diff completions/fish/podman.fish <(./bin/podman completion fish) + diff completions/bash/podman-remote <(./bin/podman-remote completion --no-desc bash) + diff completions/zsh/_podman-remote <(./bin/podman-remote completion zsh) + diff completions/fish/podman-remote.fish <(./bin/podman-remote completion fish) + # Check if the files can be loaded by the shell . completions/bash/podman if [ -x /bin/zsh ]; then /bin/zsh completions/zsh/_podman; fi + if [ -x /bin/fish ]; then /bin/fish completions/fish/podman.fish; fi .PHONY: validate validate: gofmt lint .gitvalidation validate.completions man-page-check swagger-check diff --git a/cmd/podman/auto-update.go b/cmd/podman/auto-update.go index 76bff0c705c5..cf806900fdf2 100644 --- a/cmd/podman/auto-update.go +++ b/cmd/podman/auto-update.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/containers/common/pkg/auth" + "github.com/containers/common/pkg/completion" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/containers/podman/v2/pkg/errorhandling" @@ -20,10 +21,11 @@ var ( or similar units that create new containers in order to run the updated images. Please refer to the podman-auto-update(1) man page for details.` autoUpdateCommand = &cobra.Command{ - Use: "auto-update [options]", - Short: "Auto update containers according to their auto-update policy", - Long: autoUpdateDescription, - RunE: autoUpdate, + Use: "auto-update [options]", + Short: "Auto update containers according to their auto-update policy", + Long: autoUpdateDescription, + RunE: autoUpdate, + ValidArgsFunction: completion.AutocompleteNone, Example: `podman auto-update podman auto-update --authfile ~/authfile.json`, } @@ -36,7 +38,10 @@ func init() { }) flags := autoUpdateCommand.Flags() - flags.StringVar(&autoUpdateOptions.Authfile, "authfile", auth.GetDefaultAuthFile(), "Path to the authentication file. Use REGISTRY_AUTH_FILE environment variable to override") + + authfileFlagName := "authfile" + flags.StringVar(&autoUpdateOptions.Authfile, authfileFlagName, auth.GetDefaultAuthFile(), "Path to the authentication file. Use REGISTRY_AUTH_FILE environment variable to override") + _ = autoUpdateCommand.RegisterFlagCompletionFunc(authfileFlagName, completion.AutocompleteDefault) } func autoUpdate(cmd *cobra.Command, args []string) error { diff --git a/cmd/podman/common/completion.go b/cmd/podman/common/completion.go new file mode 100644 index 000000000000..4d66b4e2ba18 --- /dev/null +++ b/cmd/podman/common/completion.go @@ -0,0 +1,638 @@ +package common + +import ( + "bufio" + "os" + "strings" + + "github.com/containers/common/pkg/config" + "github.com/containers/podman/v2/cmd/podman/registry" + "github.com/containers/podman/v2/libpod" + "github.com/containers/podman/v2/libpod/define" + "github.com/containers/podman/v2/pkg/domain/entities" + "github.com/containers/podman/v2/pkg/registries" + systemdGen "github.com/containers/podman/v2/pkg/systemd/generate" + "github.com/spf13/cobra" +) + +var ( + // ChangeCmds is the list of valid Change commands to passed to the Commit call + ChangeCmds = []string{"CMD", "ENTRYPOINT", "ENV", "EXPOSE", "LABEL", "ONBUILD", "STOPSIGNAL", "USER", "VOLUME", "WORKDIR"} + // LogLevels supported by podman + LogLevels = []string{"debug", "info", "warn", "error", "fatal", "panic"} +) + +func getContainers(status string, toComplete string) ([]string, cobra.ShellCompDirective) { + suggestions := []string{} + listOpts := entities.ContainerListOptions{ + Filters: make(map[string][]string), + } + listOpts.All = true + + if status != "all" { + listOpts.Filters = map[string][]string{"status": {status}} + } + + containers, err := registry.ContainerEngine().ContainerList(registry.GetContext(), listOpts) + if err != nil { + cobra.CompErrorln(err.Error()) + return nil, cobra.ShellCompDirectiveError + } + + for _, container := range containers { + // include ids in suggestions if more then 2 chars are typed + if len(toComplete) > 1 { + suggestions = append(suggestions, container.ID[0:12]) + } + // include name in suggestions + suggestions = append(suggestions, container.Names...) + } + return suggestions, cobra.ShellCompDirectiveNoFileComp +} + +func getPods(status string, toComplete string) ([]string, cobra.ShellCompDirective) { + suggestions := []string{} + listOpts := entities.PodPSOptions{ + Filters: make(map[string][]string), + } + + if status != "all" { + listOpts.Filters = map[string][]string{"status": {status}} + } + + pods, err := registry.ContainerEngine().PodPs(registry.GetContext(), listOpts) + if err != nil { + cobra.CompErrorln(err.Error()) + return nil, cobra.ShellCompDirectiveError + } + + for _, pod := range pods { + // include ids in suggestions if more then 2 chars are typed + if len(toComplete) > 1 { + suggestions = append(suggestions, pod.Id[0:12]) + } + // include name in suggestions + suggestions = append(suggestions, pod.Name) + } + return suggestions, cobra.ShellCompDirectiveNoFileComp +} + +func getVolumes() ([]string, cobra.ShellCompDirective) { + suggestions := []string{} + lsOpts := entities.VolumeListOptions{} + + volumes, err := registry.ContainerEngine().VolumeList(registry.GetContext(), lsOpts) + if err != nil { + cobra.CompErrorln(err.Error()) + return nil, cobra.ShellCompDirectiveError + } + + for _, volume := range volumes { + suggestions = append(suggestions, volume.Name) + } + return suggestions, cobra.ShellCompDirectiveNoFileComp +} + +func getImages(toComplete string) ([]string, cobra.ShellCompDirective) { + suggestions := []string{} + listOptions := entities.ImageListOptions{} + + images, err := registry.ImageEngine().List(registry.GetContext(), listOptions) + if err != nil { + cobra.CompErrorln(err.Error()) + return nil, cobra.ShellCompDirectiveError + } + + for _, image := range images { + // FIXME: need ux testing + // discuss when image ids should be completed + // include ids in suggestions if more then 2 chars are typed + if len(toComplete) > 1 { + suggestions = append(suggestions, image.ID[0:12]) + } + for _, repo := range image.RepoTags { + if toComplete == "" { + // suggest only full repo path if no input is given + suggestions = append(suggestions, repo) + } else { + // suggested "registry.fedoraproject.org/f29/httpd:latest" as + // - "registry.fedoraproject.org/f29/httpd:latest" + // - "registry.fedoraproject.org/f29/httpd" + // - "f29/httpd:latest" + // - "f29/httpd" + // - "httpd:latest" + // - "httpd" + paths := strings.Split(repo, "/") + for i := range paths { + suggestionWithTag := strings.Join(paths[i:], "/") + suggestionWithoutTag := strings.SplitN(strings.SplitN(suggestionWithTag, ":", 2)[0], "@", 2)[0] + suggestions = append(suggestions, suggestionWithTag, suggestionWithoutTag) + } + } + } + } + return suggestions, cobra.ShellCompDirectiveNoFileComp +} + +func getRegistries() ([]string, cobra.ShellCompDirective) { + regs, err := registries.GetRegistries() + if err != nil { + cobra.CompErrorln(err.Error()) + return nil, cobra.ShellCompDirectiveError + } + return regs, cobra.ShellCompDirectiveNoFileComp +} + +func getNetworks() ([]string, cobra.ShellCompDirective) { + suggestions := []string{} + networkListOptions := entities.NetworkListOptions{} + + networks, err := registry.ContainerEngine().NetworkList(registry.Context(), networkListOptions) + if err != nil { + cobra.CompErrorln(err.Error()) + return nil, cobra.ShellCompDirectiveError + } + + for _, network := range networks { + suggestions = append(suggestions, network.Name) + } + return suggestions, cobra.ShellCompDirectiveNoFileComp +} + +/* Autocomplete Functions for cobra ValidArgsFunction */ + +// AutocompleteContainers - Autocomplete all container names. +func AutocompleteContainers(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + return getContainers("all", toComplete) +} + +// AutocompleteContainersCreated - Autocomplete only created container names. +func AutocompleteContainersCreated(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + return getContainers("created", toComplete) +} + +// AutocompleteContainersExited - Autocomplete only exited container names. +func AutocompleteContainersExited(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + return getContainers("exited", toComplete) +} + +// AutocompleteContainersPaused - Autocomplete only paused container names. +func AutocompleteContainersPaused(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + return getContainers("paused", toComplete) +} + +// AutocompleteContainersRunning - Autocomplete only running container names. +func AutocompleteContainersRunning(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + return getContainers("running", toComplete) +} + +// AutocompleteContainersStartable - Autocomplete only created and exited container names. +func AutocompleteContainersStartable(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + containersCreated, _ := getContainers("created", toComplete) + containersExited, _ := getContainers("exited", toComplete) + return append(containersCreated, containersExited...), cobra.ShellCompDirectiveNoFileComp +} + +// AutocompletePods - Autocomplete all pod names. +func AutocompletePods(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + return getPods("all", toComplete) +} + +// AutocompletePodsRunning - Autocomplete only running pod names. +func AutocompletePodsRunning(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + return getPods("running", toComplete) +} + +// AutocompleteContainersAndPods - Autocomplete container names and pod names. +func AutocompleteContainersAndPods(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + containers, _ := getContainers("all", toComplete) + pods, _ := getPods("all", toComplete) + return append(containers, pods...), cobra.ShellCompDirectiveNoFileComp +} + +// AutocompleteContainersAndImages - Autocomplete container names and pod names. +func AutocompleteContainersAndImages(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + containers, _ := getContainers("all", toComplete) + images, _ := getImages(toComplete) + return append(containers, images...), cobra.ShellCompDirectiveNoFileComp +} + +// AutocompleteVolumes - Autocomplete volumes. +func AutocompleteVolumes(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + return getVolumes() +} + +// AutocompleteImages - Autocomplete images. +func AutocompleteImages(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + return getImages(toComplete) +} + +// AutocompleteCreateRun - Autocomplete only the fist argument as image and then do file completion. +func AutocompleteCreateRun(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + if len(args) < 1 { + return getImages(toComplete) + } + // TODO: add path completion for files in the image + return nil, cobra.ShellCompDirectiveDefault +} + +// AutocompleteRegistries - Autocomplete registries. +func AutocompleteRegistries(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + return getRegistries() +} + +// AutocompleteNetworks - Autocomplete networks. +func AutocompleteNetworks(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + return getNetworks() +} + +// AutocompleteCpCommand - Autocomplete podman cp command args. +func AutocompleteCpCommand(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + if len(args) < 2 { + containers, _ := getContainers("all", toComplete) + for _, container := range containers { + // TODO: Add path completion for inside the container if possible + if strings.HasPrefix(container, toComplete) { + return containers, cobra.ShellCompDirectiveNoSpace + } + } + // else complete paths + return nil, cobra.ShellCompDirectiveDefault + } + // don't complete more than 2 args + return nil, cobra.ShellCompDirectiveNoFileComp +} + +// AutocompleteSystemConnections - Autocomplete system connections. +func AutocompleteSystemConnections(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + suggestions := []string{} + cfg, err := config.ReadCustomConfig() + if err != nil { + cobra.CompErrorln(err.Error()) + return nil, cobra.ShellCompDirectiveError + } + + for k, v := range cfg.Engine.ServiceDestinations { + // the URI will be show as description in shells like zsh + suggestions = append(suggestions, k+"\t"+v.URI) + } + + return suggestions, cobra.ShellCompDirectiveNoFileComp +} + +/* -------------- Flags ----------------- */ + +// AutocompleteDetachKeys - Autocomplete detach-keys options. +// -> "ctrl-" +func AutocompleteDetachKeys(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + if strings.HasSuffix(toComplete, ",") { + return []string{toComplete + "ctrl-"}, cobra.ShellCompDirectiveNoSpace + } + return []string{"ctrl-"}, cobra.ShellCompDirectiveNoSpace +} + +// AutocompleteChangeInstructions - Autocomplete change instructions options for commit and import. +// -> "CMD", "ENTRYPOINT", "ENV", "EXPOSE", "LABEL", "ONBUILD", "STOPSIGNAL", "USER", "VOLUME", "WORKDIR" +func AutocompleteChangeInstructions(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + return ChangeCmds, cobra.ShellCompDirectiveNoSpace +} + +// AutocompleteImageFormat - Autocomplete image format options. +// -> "oci", "docker" +func AutocompleteImageFormat(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + ImageFormat := []string{"oci", "docker"} + return ImageFormat, cobra.ShellCompDirectiveNoFileComp +} + +// AutocompleteCreateAttach - Autocomplete create --attach options. +// -> "stdin", "stdout", "stderr" +func AutocompleteCreateAttach(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + return []string{"stdin", "stdout", "stderr"}, cobra.ShellCompDirectiveNoFileComp +} + +// AutocompleteNamespace - Autocomplete namespace options. +// -> host,container:[name],ns:[path],private +func AutocompleteNamespace(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + namespacesOptions := []string{"host", "container:", "ns:", "private"} + + switch { + case strings.HasPrefix(toComplete, "container:"): + // Complete containers after colon + containers, _ := getContainers("all", toComplete[10:]) //trim "container:" + + // add "container:" in front of the suggestions + var suggestions []string + for _, container := range containers { + suggestions = append(suggestions, "container:"+container) + } + + return suggestions, cobra.ShellCompDirectiveNoFileComp + + case strings.HasPrefix(toComplete, "ns:"): + // Complete path after colon + return nil, cobra.ShellCompDirectiveDefault + + case strings.HasPrefix(toComplete, "c") || strings.HasPrefix(toComplete, "n"): + // don't insert space for container: and ns: + return []string{"container:", "ns:"}, cobra.ShellCompDirectiveNoSpace + } + return namespacesOptions, cobra.ShellCompDirectiveNoFileComp +} + +// AutocompleteUserNamespace - Autocomplete namespace options. +// -> same as AutocompleteNamespace with "auto", "keep-id" added +func AutocompleteUserNamespace(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + results, directive := AutocompleteNamespace(cmd, args, toComplete) + if directive == cobra.ShellCompDirectiveNoFileComp { + // add the auto and keep-id options + results = append(results, "auto", "keep-id") + } + return results, directive +} + +// AutocompleteCgroupMode - Autocomplete cgroup mode options. +// -> "enabled", "disabled", "no-conmon", "split" +func AutocompleteCgroupMode(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + cgroupModes := []string{"enabled", "disabled", "no-conmon", "split"} + return cgroupModes, cobra.ShellCompDirectiveNoFileComp +} + +// AutocompleteImageVolume - Autocomplete image volume options. +// -> "bind", "tmpfs", "ignore" +func AutocompleteImageVolume(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + imageVolumes := []string{"bind", "tmpfs", "ignore"} + return imageVolumes, cobra.ShellCompDirectiveNoFileComp +} + +// AutocompleteLogDriver - Autocomplete log-driver options. +// -> "journald", "none", "k8s-file" +func AutocompleteLogDriver(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + // don't show json-file + logDrivers := []string{define.JournaldLogging, define.NoLogging, define.KubernetesLogging} + return logDrivers, cobra.ShellCompDirectiveNoFileComp +} + +// AutocompleteLogOpt - Autocomplete log-opt options. +// -> "path=", "tag=" +func AutocompleteLogOpt(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + // FIXME: are these the only one? the man page states these but in the current shell completion they are more options + logOptions := []string{"path=", "tag="} + if strings.HasPrefix(toComplete, "path=") { + return nil, cobra.ShellCompDirectiveDefault + } + return logOptions, cobra.ShellCompDirectiveNoFileComp | cobra.ShellCompDirectiveNoSpace +} + +// AutocompletePullOption - Autocomplete pull options for create and run command. +// -> "always", "missing", "never" +func AutocompletePullOption(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + pullOptions := []string{"always", "missing", "never"} + return pullOptions, cobra.ShellCompDirectiveNoFileComp +} + +// AutocompleteRestartOption - Autocomplete restart options for create and run command. +// -> "always", "no", "on-failure", "unless-stopped" +func AutocompleteRestartOption(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + restartOptions := []string{libpod.RestartPolicyAlways, libpod.RestartPolicyNo, + libpod.RestartPolicyOnFailure, libpod.RestartPolicyUnlessStopped} + return restartOptions, cobra.ShellCompDirectiveNoFileComp +} + +// AutocompleteSecurityOption - Autocomplete security options options. +func AutocompleteSecurityOption(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + SecurityOptions := []string{"apparmor=", "no-new-privileges", "seccomp=", "label="} + switch { + case strings.HasPrefix(toComplete, "apparmor=u"): + // add space after unconfined + return []string{"apparmor=unconfined"}, cobra.ShellCompDirectiveNoFileComp + + case strings.HasPrefix(toComplete, "label=d"): + // add space after disable + return []string{"label=disable"}, cobra.ShellCompDirectiveNoFileComp + + case strings.HasPrefix(toComplete, "label="): + return []string{"label=user:", "label=role:", "label=type:", "label=level:", "label=filetype:", "label=disable"}, + cobra.ShellCompDirectiveNoFileComp | cobra.ShellCompDirectiveNoSpace + + case strings.HasPrefix(toComplete, "seccomp="): + // complete files + return nil, cobra.ShellCompDirectiveDefault + + case strings.HasPrefix(toComplete, "n"): + // add space if no-new-privileges + return []string{"no-new-privileges"}, cobra.ShellCompDirectiveNoFileComp + } + return SecurityOptions, cobra.ShellCompDirectiveNoFileComp | cobra.ShellCompDirectiveNoSpace +} + +// AutocompleteStopSignal - Autocomplete stop signal options. +// -> "SIGHUP", "SIGINT", "SIGKILL", "SIGTERM" +func AutocompleteStopSignal(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + // FIXME: add more/different signals? + stopSignals := []string{"SIGHUP", "SIGINT", "SIGKILL", "SIGTERM"} + return stopSignals, cobra.ShellCompDirectiveNoFileComp +} + +// AutocompleteSystemdFlag - Autocomplete systemd flag options. +// -> "true", "false", "always" +func AutocompleteSystemdFlag(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + systemd := []string{"true", "false", "always"} + return systemd, cobra.ShellCompDirectiveNoFileComp +} + +// AutocompleteUserFlag - Autocomplete user flag based on the names and groups (includes ids after first char) in /etc/passwd and /etc/group files. +// -> user:group +func AutocompleteUserFlag(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + if strings.Contains(toComplete, ":") { + // It would be nice to read the file in the image + // but at this point we don't know the image. + file, err := os.Open("/etc/group") + if err != nil { + return nil, cobra.ShellCompDirectiveError + } + defer file.Close() + + var groups []string + scanner := bufio.NewScanner(file) + user := strings.SplitN(toComplete, ":", 2)[0] + for scanner.Scan() { + entries := strings.SplitN(scanner.Text(), ":", 4) + groups = append(groups, user+":"+entries[0]) + // complete ids after at least one char is given + if len(user)+1 < len(toComplete) { + groups = append(groups, user+":"+entries[2]) + } + } + if err = scanner.Err(); err != nil { + return nil, cobra.ShellCompDirectiveError + } + return groups, cobra.ShellCompDirectiveNoFileComp + } + + // It would be nice to read the file in the image + // but at this point we don't know the image. + file, err := os.Open("/etc/passwd") + if err != nil { + return nil, cobra.ShellCompDirectiveError + } + defer file.Close() + + var users []string + scanner := bufio.NewScanner(file) + for scanner.Scan() { + entries := strings.SplitN(scanner.Text(), ":", 7) + users = append(users, entries[0]+":") + // complete ids after at least one char is given + if len(toComplete) > 0 { + users = append(users, entries[2]+":") + } + } + if err = scanner.Err(); err != nil { + return nil, cobra.ShellCompDirectiveError + } + return users, cobra.ShellCompDirectiveNoSpace +} + +// AutocompleteMountFlag - Autocomplete mount flag options. +// -> "type=bind,", "type=volume,", "type=tmpfs," +func AutocompleteMountFlag(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + types := []string{"type=bind,", "type=volume,", "type=tmpfs,"} + // TODO: Add support for all different options + return types, cobra.ShellCompDirectiveNoSpace +} + +// AutocompleteVolumeFlag - Autocomplete volume flag options. +// -> volumes and paths +func AutocompleteVolumeFlag(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + result := []string{} + volumes, _ := getVolumes() + for _, volume := range volumes { + // If we don't filter on "toComplete", zsh and fish will not do file completion + // even if the prefix typed by the user does not match the returned completions + if strings.HasPrefix(volume, toComplete) { + result = append(result, volume) + } + } + directive := cobra.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveDefault + if strings.Contains(toComplete, ":") { + // add space after second path + directive = cobra.ShellCompDirectiveDefault + } + return result, directive +} + +// AutocompleteJSONFormat - Autocomplete format flag option. +// -> "json" +func AutocompleteJSONFormat(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + return []string{"json"}, cobra.ShellCompDirectiveNoFileComp +} + +// AutocompleteEventFilter - Autocomplete event filter flag options. +// -> "container=", "event=", "image=", "pod=", "volume=", "type=" +func AutocompleteEventFilter(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + filters := []string{"container=", "event=", "image=", "pod=", "volume=", "type="} + return filters, cobra.ShellCompDirectiveNoSpace +} + +// AutocompleteSystemdRestartOptions - Autocomplete systemd restart options. +// -> "no", "on-success", "on-failure", "on-abnormal", "on-watchdog", "on-abort", "always" +func AutocompleteSystemdRestartOptions(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + return systemdGen.RestartPolicies, cobra.ShellCompDirectiveNoFileComp +} + +// AutocompleteTrustType - Autocomplete trust type options. +// -> "signedBy", "accept", "reject" +func AutocompleteTrustType(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + types := []string{"signedBy", "accept", "reject"} + return types, cobra.ShellCompDirectiveNoFileComp +} + +// AutocompleteImageSort - Autocomplete images sort options. +// -> "created", "id", "repository", "size", "tag" +func AutocompleteImageSort(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + sortBy := []string{"created", "id", "repository", "size", "tag"} + return sortBy, cobra.ShellCompDirectiveNoFileComp +} + +// AutocompleteInspectType - Autocomplete inspect type options. +// -> "container", "image", "all" +func AutocompleteInspectType(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + types := []string{"container", "image", "all"} + return types, cobra.ShellCompDirectiveNoFileComp +} + +// AutocompleteManifestFormat - Autocomplete manifest format options. +// -> "oci", "v2s2" +func AutocompleteManifestFormat(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + types := []string{"oci", "v2s2"} + return types, cobra.ShellCompDirectiveNoFileComp +} + +// AutocompleteNetworkDriver - Autocomplete network driver option. +// -> "bridge" +func AutocompleteNetworkDriver(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + drivers := []string{"bridge"} + return drivers, cobra.ShellCompDirectiveNoFileComp +} + +// AutocompletePodShareNamespace - Autocomplete pod create --share flag option. +// -> "ipc", "net", "pid", "user", "uts", "cgroup", "none" +func AutocompletePodShareNamespace(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + namespaces := []string{"ipc", "net", "pid", "user", "uts", "cgroup", "none"} + return namespaces, cobra.ShellCompDirectiveNoFileComp +} + +// AutocompletePodPsSort - Autocomplete images sort options. +// -> "created", "id", "name", "status", "number" +func AutocompletePodPsSort(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + sortBy := []string{"created", "id", "name", "status", "number"} + return sortBy, cobra.ShellCompDirectiveNoFileComp +} + +// AutocompletePsSort - Autocomplete images sort options. +// -> "command", "created", "id", "image", "names", "runningfor", "size", "status" +func AutocompletePsSort(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + sortBy := []string{"command", "created", "id", "image", "names", "runningfor", "size", "status"} + return sortBy, cobra.ShellCompDirectiveNoFileComp +} + +// AutocompleteImageSaveFormat - Autocomplete image save format options. +// -> "oci-archive", "oci-dir", "docker-dir" +func AutocompleteImageSaveFormat(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + formats := []string{"oci-archive", "oci-dir", "docker-dir"} + return formats, cobra.ShellCompDirectiveNoFileComp +} + +// AutocompleteWaitCondition - Autocomplete wait condition options. +// -> "unknown", "configured", "created", "running", "stopped", "paused", "exited", "removing" +func AutocompleteWaitCondition(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + states := []string{"unknown", "configured", "created", "running", "stopped", "paused", "exited", "removing"} + return states, cobra.ShellCompDirectiveNoFileComp +} + +// AutocompleteCgroupManager - Autocomplete cgroup manager options. +// -> "cgroupfs", "systemd" +func AutocompleteCgroupManager(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + types := []string{"cgroupfs", "systemd"} + return types, cobra.ShellCompDirectiveNoFileComp +} + +// AutocompleteEventBackend - Autocomplete event backend options. +// -> "file", "journald", "none" +func AutocompleteEventBackend(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + types := []string{"file", "journald", "none"} + return types, cobra.ShellCompDirectiveNoFileComp +} + +// AutocompleteLogLevel - Autocomplete log level options. +// -> "debug", "info", "warn", "error", "fatal", "panic" +func AutocompleteLogLevel(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + return LogLevels, cobra.ShellCompDirectiveNoFileComp +} + +// AutocompleteSDNotify - Autocomplete sdnotify options. +// -> "container", "conmon", "ignore" +func AutocompleteSDNotify(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + types := []string{"container", "conmon", "ignore"} + return types, cobra.ShellCompDirectiveNoFileComp +} diff --git a/cmd/podman/common/create.go b/cmd/podman/common/create.go index 60f4e526c1f1..ab3a984f08c6 100644 --- a/cmd/podman/common/create.go +++ b/cmd/podman/common/create.go @@ -5,296 +5,457 @@ import ( "os" "github.com/containers/common/pkg/auth" + "github.com/containers/common/pkg/completion" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/libpod/define" - "github.com/spf13/pflag" + "github.com/spf13/cobra" ) const sizeWithUnitFormat = "(format: `[]`, where unit = b (bytes), k (kilobytes), m (megabytes), or g (gigabytes))" var containerConfig = registry.PodmanConfig() -func GetCreateFlags(cf *ContainerCLIOpts) *pflag.FlagSet { - createFlags := pflag.FlagSet{} +func DefineCreateFlags(cmd *cobra.Command, cf *ContainerCLIOpts) { + createFlags := cmd.Flags() + + annotationFlagName := "annotation" createFlags.StringSliceVar( &cf.Annotation, - "annotation", []string{}, + annotationFlagName, []string{}, "Add annotations to container (key:value)", ) + _ = cmd.RegisterFlagCompletionFunc(annotationFlagName, completion.AutocompleteNone) + + attachFlagName := "attach" createFlags.StringSliceVarP( &cf.Attach, - "attach", "a", []string{}, + attachFlagName, "a", []string{}, "Attach to STDIN, STDOUT or STDERR", ) + _ = cmd.RegisterFlagCompletionFunc(attachFlagName, AutocompleteCreateAttach) + + authfileFlagName := "authfile" createFlags.StringVar( &cf.Authfile, - "authfile", auth.GetDefaultAuthFile(), + authfileFlagName, auth.GetDefaultAuthFile(), "Path of the authentication file. Use REGISTRY_AUTH_FILE environment variable to override", ) + _ = cmd.RegisterFlagCompletionFunc(authfileFlagName, completion.AutocompleteDefault) + + blkioWeightFlagName := "blkio-weight" createFlags.StringVar( &cf.BlkIOWeight, - "blkio-weight", "", + blkioWeightFlagName, "", "Block IO weight (relative weight) accepts a weight value between 10 and 1000.", ) + _ = cmd.RegisterFlagCompletionFunc(blkioWeightFlagName, completion.AutocompleteNone) + + blkioWeightDeviceFlagName := "blkio-weight-device" createFlags.StringSliceVar( &cf.BlkIOWeightDevice, - "blkio-weight-device", []string{}, + blkioWeightDeviceFlagName, []string{}, "Block IO weight (relative device weight, format: `DEVICE_NAME:WEIGHT`)", ) + _ = cmd.RegisterFlagCompletionFunc(blkioWeightDeviceFlagName, completion.AutocompleteDefault) + + capAddFlagName := "cap-add" createFlags.StringSliceVar( &cf.CapAdd, - "cap-add", []string{}, + capAddFlagName, []string{}, "Add capabilities to the container", ) + _ = cmd.RegisterFlagCompletionFunc(capAddFlagName, completion.AutocompleteCapabilities) + + capDropFlagName := "cap-drop" createFlags.StringSliceVar( &cf.CapDrop, - "cap-drop", []string{}, + capDropFlagName, []string{}, "Drop capabilities from the container", ) + _ = cmd.RegisterFlagCompletionFunc(capDropFlagName, completion.AutocompleteCapabilities) + + cgroupnsFlagName := "cgroupns" createFlags.String( - "cgroupns", "", + cgroupnsFlagName, "", "cgroup namespace to use", ) + _ = cmd.RegisterFlagCompletionFunc(cgroupnsFlagName, AutocompleteNamespace) + + cgroupsFlagName := "cgroups" createFlags.StringVar( &cf.CGroupsMode, - "cgroups", containerConfig.Cgroups(), + cgroupsFlagName, containerConfig.Cgroups(), `control container cgroup configuration ("enabled"|"disabled"|"no-conmon"|"split")`, ) + _ = cmd.RegisterFlagCompletionFunc(cgroupsFlagName, AutocompleteCgroupMode) + + cgroupParentFlagName := "cgroup-parent" createFlags.StringVar( &cf.CGroupParent, - "cgroup-parent", "", + cgroupParentFlagName, "", "Optional parent cgroup for the container", ) + _ = cmd.RegisterFlagCompletionFunc(cgroupParentFlagName, completion.AutocompleteDefault) + + cidfileFlagName := "cidfile" createFlags.StringVar( &cf.CIDFile, - "cidfile", "", + cidfileFlagName, "", "Write the container ID to the file", ) + _ = cmd.RegisterFlagCompletionFunc(cidfileFlagName, completion.AutocompleteDefault) + + conmonPidfileFlagName := "conmon-pidfile" createFlags.StringVar( &cf.ConmonPIDFile, - "conmon-pidfile", "", + conmonPidfileFlagName, "", "Path to the file that will receive the PID of conmon", ) + _ = cmd.RegisterFlagCompletionFunc(conmonPidfileFlagName, completion.AutocompleteDefault) + + cpuPeriodFlagName := "cpu-period" createFlags.Uint64Var( &cf.CPUPeriod, - "cpu-period", 0, + cpuPeriodFlagName, 0, "Limit the CPU CFS (Completely Fair Scheduler) period", ) + _ = cmd.RegisterFlagCompletionFunc(cpuPeriodFlagName, completion.AutocompleteNone) + + cpuQuotaFlagName := "cpu-quota" createFlags.Int64Var( &cf.CPUQuota, - "cpu-quota", 0, + cpuQuotaFlagName, 0, "Limit the CPU CFS (Completely Fair Scheduler) quota", ) + _ = cmd.RegisterFlagCompletionFunc(cpuQuotaFlagName, completion.AutocompleteNone) + + cpuRtPeriodFlagName := "cpu-rt-period" createFlags.Uint64Var( &cf.CPURTPeriod, - "cpu-rt-period", 0, + cpuRtPeriodFlagName, 0, "Limit the CPU real-time period in microseconds", ) + _ = cmd.RegisterFlagCompletionFunc(cpuRtPeriodFlagName, completion.AutocompleteNone) + + cpuRtRuntimeFlagName := "cpu-rt-runtime" createFlags.Int64Var( &cf.CPURTRuntime, - "cpu-rt-runtime", 0, + cpuRtRuntimeFlagName, 0, "Limit the CPU real-time runtime in microseconds", ) + _ = cmd.RegisterFlagCompletionFunc(cpuRtRuntimeFlagName, completion.AutocompleteNone) + + cpuSharesFlagName := "cpu-shares" createFlags.Uint64Var( &cf.CPUShares, - "cpu-shares", 0, + cpuSharesFlagName, 0, "CPU shares (relative weight)", ) + _ = cmd.RegisterFlagCompletionFunc(cpuSharesFlagName, completion.AutocompleteNone) + + cpusFlagName := "cpus" createFlags.Float64Var( &cf.CPUS, - "cpus", 0, + cpusFlagName, 0, "Number of CPUs. The default is 0.000 which means no limit", ) + _ = cmd.RegisterFlagCompletionFunc(cpusFlagName, completion.AutocompleteNone) + + cpusetCpusFlagName := "cpuset-cpus" createFlags.StringVar( &cf.CPUSetCPUs, - "cpuset-cpus", "", + cpusetCpusFlagName, "", "CPUs in which to allow execution (0-3, 0,1)", ) + _ = cmd.RegisterFlagCompletionFunc(cpusetCpusFlagName, completion.AutocompleteNone) + + cpusetMemsFlagName := "cpuset-mems" createFlags.StringVar( &cf.CPUSetMems, - "cpuset-mems", "", + cpusetMemsFlagName, "", "Memory nodes (MEMs) in which to allow execution (0-3, 0,1). Only effective on NUMA systems.", ) + _ = cmd.RegisterFlagCompletionFunc(cpusetMemsFlagName, completion.AutocompleteNone) + + deviceFlagName := "device" createFlags.StringSliceVar( &cf.Devices, - "device", containerConfig.Devices(), + deviceFlagName, containerConfig.Devices(), fmt.Sprintf("Add a host device to the container"), ) + _ = cmd.RegisterFlagCompletionFunc(deviceFlagName, completion.AutocompleteDefault) + + deviceCgroupRuleFlagName := "device-cgroup-rule" createFlags.StringSliceVar( &cf.DeviceCGroupRule, - "device-cgroup-rule", []string{}, + deviceCgroupRuleFlagName, []string{}, "Add a rule to the cgroup allowed devices list", ) + _ = cmd.RegisterFlagCompletionFunc(deviceCgroupRuleFlagName, completion.AutocompleteNone) + + deviceReadBpsFlagName := "device-read-bps" createFlags.StringSliceVar( &cf.DeviceReadBPs, - "device-read-bps", []string{}, + deviceReadBpsFlagName, []string{}, "Limit read rate (bytes per second) from a device (e.g. --device-read-bps=/dev/sda:1mb)", ) + _ = cmd.RegisterFlagCompletionFunc(deviceReadBpsFlagName, completion.AutocompleteDefault) + + deviceReadIopsFlagName := "device-read-iops" createFlags.StringSliceVar( &cf.DeviceReadIOPs, - "device-read-iops", []string{}, + deviceReadIopsFlagName, []string{}, "Limit read rate (IO per second) from a device (e.g. --device-read-iops=/dev/sda:1000)", ) + _ = cmd.RegisterFlagCompletionFunc(deviceReadIopsFlagName, completion.AutocompleteDefault) + + deviceWriteBpsFlagName := "device-write-bps" createFlags.StringSliceVar( &cf.DeviceWriteBPs, - "device-write-bps", []string{}, + deviceWriteBpsFlagName, []string{}, "Limit write rate (bytes per second) to a device (e.g. --device-write-bps=/dev/sda:1mb)", ) + _ = cmd.RegisterFlagCompletionFunc(deviceWriteBpsFlagName, completion.AutocompleteDefault) + + deviceWriteIopsFlagName := "device-write-iops" createFlags.StringSliceVar( &cf.DeviceWriteIOPs, - "device-write-iops", []string{}, + deviceWriteIopsFlagName, []string{}, "Limit write rate (IO per second) to a device (e.g. --device-write-iops=/dev/sda:1000)", ) + _ = cmd.RegisterFlagCompletionFunc(deviceWriteIopsFlagName, completion.AutocompleteDefault) + createFlags.Bool( "disable-content-trust", false, "This is a Docker specific option and is a NOOP", ) - createFlags.String("entrypoint", "", + + entrypointFlagName := "entrypoint" + createFlags.String(entrypointFlagName, "", "Overwrite the default ENTRYPOINT of the image", ) + _ = cmd.RegisterFlagCompletionFunc(entrypointFlagName, completion.AutocompleteNone) + + envFlagName := "env" createFlags.StringArrayP( - "env", "e", containerConfig.Env(), + envFlagName, "e", containerConfig.Env(), "Set environment variables in container", ) + _ = cmd.RegisterFlagCompletionFunc(envFlagName, completion.AutocompleteNone) + if !registry.IsRemote() { createFlags.BoolVar( &cf.EnvHost, "env-host", false, "Use all current host environment variables in container", ) } + + envFileFlagName := "env-file" createFlags.StringSliceVar( &cf.EnvFile, - "env-file", []string{}, + envFileFlagName, []string{}, "Read in a file of environment variables", ) + _ = cmd.RegisterFlagCompletionFunc(envFileFlagName, completion.AutocompleteDefault) + + exposeFlagName := "expose" createFlags.StringSliceVar( &cf.Expose, - "expose", []string{}, + exposeFlagName, []string{}, "Expose a port or a range of ports", ) + _ = cmd.RegisterFlagCompletionFunc(exposeFlagName, completion.AutocompleteNone) + + gidmapFlagName := "gidmap" createFlags.StringSliceVar( &cf.GIDMap, - "gidmap", []string{}, + gidmapFlagName, []string{}, "GID map to use for the user namespace", ) + _ = cmd.RegisterFlagCompletionFunc(gidmapFlagName, completion.AutocompleteNone) + + groupAddFlagName := "group-add" createFlags.StringSliceVar( &cf.GroupAdd, - "group-add", []string{}, + groupAddFlagName, []string{}, "Add additional groups to join", ) + _ = cmd.RegisterFlagCompletionFunc(groupAddFlagName, completion.AutocompleteNone) + createFlags.Bool( "help", false, "", ) + + healthCmdFlagName := "health-cmd" createFlags.StringVar( &cf.HealthCmd, - "health-cmd", "", + healthCmdFlagName, "", "set a healthcheck command for the container ('none' disables the existing healthcheck)", ) + _ = cmd.RegisterFlagCompletionFunc(healthCmdFlagName, completion.AutocompleteNone) + + healthIntervalFlagName := "health-interval" createFlags.StringVar( &cf.HealthInterval, - "health-interval", DefaultHealthCheckInterval, + healthIntervalFlagName, DefaultHealthCheckInterval, "set an interval for the healthchecks (a value of disable results in no automatic timer setup)", ) + _ = cmd.RegisterFlagCompletionFunc(healthIntervalFlagName, completion.AutocompleteNone) + + healthRetriesFlagName := "health-retries" createFlags.UintVar( &cf.HealthRetries, - "health-retries", DefaultHealthCheckRetries, + healthRetriesFlagName, DefaultHealthCheckRetries, "the number of retries allowed before a healthcheck is considered to be unhealthy", ) + _ = cmd.RegisterFlagCompletionFunc(healthRetriesFlagName, completion.AutocompleteNone) + + healthStartPeriodFlagName := "health-start-period" createFlags.StringVar( &cf.HealthStartPeriod, - "health-start-period", DefaultHealthCheckStartPeriod, + healthStartPeriodFlagName, DefaultHealthCheckStartPeriod, "the initialization time needed for a container to bootstrap", ) + _ = cmd.RegisterFlagCompletionFunc(healthStartPeriodFlagName, completion.AutocompleteNone) + + healthTimeoutFlagName := "health-timeout" createFlags.StringVar( &cf.HealthTimeout, - "health-timeout", DefaultHealthCheckTimeout, + healthTimeoutFlagName, DefaultHealthCheckTimeout, "the maximum time allowed to complete the healthcheck before an interval is considered failed", ) + _ = cmd.RegisterFlagCompletionFunc(healthTimeoutFlagName, completion.AutocompleteNone) + + hostnameFlagName := "hostname" createFlags.StringVarP( &cf.Hostname, - "hostname", "h", "", + hostnameFlagName, "h", "", "Set container hostname", ) + _ = cmd.RegisterFlagCompletionFunc(hostnameFlagName, completion.AutocompleteNone) + createFlags.BoolVar( &cf.HTTPProxy, "http-proxy", true, "Set proxy environment variables in the container based on the host proxy vars", ) + + imageVolumeFlagName := "image-volume" createFlags.StringVar( &cf.ImageVolume, - "image-volume", DefaultImageVolume, + imageVolumeFlagName, DefaultImageVolume, `Tells podman how to handle the builtin image volumes ("bind"|"tmpfs"|"ignore")`, ) + _ = cmd.RegisterFlagCompletionFunc(imageVolumeFlagName, AutocompleteImageVolume) + createFlags.BoolVar( &cf.Init, "init", false, "Run an init binary inside the container that forwards signals and reaps processes", ) + + initPathFlagName := "init-path" createFlags.StringVar( &cf.InitPath, - "init-path", containerConfig.InitPath(), + initPathFlagName, containerConfig.InitPath(), // Do not use the Value field for setting the default value to determine user input (i.e., non-empty string) fmt.Sprintf("Path to the container-init binary"), ) + _ = cmd.RegisterFlagCompletionFunc(initPathFlagName, completion.AutocompleteDefault) + createFlags.BoolVarP( &cf.Interactive, "interactive", "i", false, "Keep STDIN open even if not attached", ) + + ipcFlagName := "ipc" createFlags.String( - "ipc", "", + ipcFlagName, "", "IPC namespace to use", ) + _ = cmd.RegisterFlagCompletionFunc(ipcFlagName, AutocompleteNamespace) + + kernelMemoryFlagName := "kernel-memory" createFlags.StringVar( &cf.KernelMemory, - "kernel-memory", "", + kernelMemoryFlagName, "", "Kernel memory limit "+sizeWithUnitFormat, ) + _ = cmd.RegisterFlagCompletionFunc(kernelMemoryFlagName, completion.AutocompleteNone) + + labelFlagName := "label" createFlags.StringArrayVarP( &cf.Label, - "label", "l", []string{}, + labelFlagName, "l", []string{}, "Set metadata on container", ) + _ = cmd.RegisterFlagCompletionFunc(labelFlagName, completion.AutocompleteNone) + + labelFileFlagName := "label-file" createFlags.StringSliceVar( &cf.LabelFile, - "label-file", []string{}, + labelFileFlagName, []string{}, "Read in a line delimited file of labels", ) + _ = cmd.RegisterFlagCompletionFunc(labelFileFlagName, completion.AutocompleteDefault) + + logDriverFlagName := "log-driver" createFlags.StringVar( &cf.LogDriver, - "log-driver", "", + logDriverFlagName, "", "Logging driver for the container", ) + _ = cmd.RegisterFlagCompletionFunc(logDriverFlagName, AutocompleteLogDriver) + + logOptFlagName := "log-opt" createFlags.StringSliceVar( &cf.LogOptions, - "log-opt", []string{}, + logOptFlagName, []string{}, "Logging driver options", ) + _ = cmd.RegisterFlagCompletionFunc(logOptFlagName, AutocompleteLogOpt) + + memoryFlagName := "memory" createFlags.StringVarP( &cf.Memory, - "memory", "m", "", + memoryFlagName, "m", "", "Memory limit "+sizeWithUnitFormat, ) + _ = cmd.RegisterFlagCompletionFunc(memoryFlagName, completion.AutocompleteNone) + + memoryReservationFlagName := "memory-reservation" createFlags.StringVar( &cf.MemoryReservation, - "memory-reservation", "", + memoryReservationFlagName, "", "Memory soft limit "+sizeWithUnitFormat, ) + _ = cmd.RegisterFlagCompletionFunc(memoryReservationFlagName, completion.AutocompleteNone) + + memorySwapFlagName := "memory-swap" createFlags.StringVar( &cf.MemorySwap, - "memory-swap", "", + memorySwapFlagName, "", "Swap limit equal to memory plus swap: '-1' to enable unlimited swap", ) + _ = cmd.RegisterFlagCompletionFunc(memorySwapFlagName, completion.AutocompleteNone) + + memorySwappinessFlagName := "memory-swappiness" createFlags.Int64Var( &cf.MemorySwappiness, - "memory-swappiness", -1, + memorySwappinessFlagName, -1, "Tune container memory swappiness (0 to 100, or -1 for system default)", ) + _ = cmd.RegisterFlagCompletionFunc(memorySwappinessFlagName, completion.AutocompleteNone) + + nameFlagName := "name" createFlags.StringVar( &cf.Name, - "name", "", + nameFlagName, "", "Assign a name to the container", ) + _ = cmd.RegisterFlagCompletionFunc(nameFlagName, completion.AutocompleteNone) + createFlags.BoolVar( &cf.NoHealthCheck, "no-healthcheck", false, @@ -305,44 +466,69 @@ func GetCreateFlags(cf *ContainerCLIOpts) *pflag.FlagSet { "oom-kill-disable", false, "Disable OOM Killer", ) + + oomScoreAdjFlagName := "oom-score-adj" createFlags.IntVar( &cf.OOMScoreAdj, - "oom-score-adj", 0, + oomScoreAdjFlagName, 0, "Tune the host's OOM preferences (-1000 to 1000)", ) + _ = cmd.RegisterFlagCompletionFunc(oomScoreAdjFlagName, completion.AutocompleteNone) + + overrideArchFlagName := "override-arch" createFlags.StringVar( &cf.OverrideArch, - "override-arch", "", + overrideArchFlagName, "", "use `ARCH` instead of the architecture of the machine for choosing images", ) + _ = cmd.RegisterFlagCompletionFunc(overrideArchFlagName, completion.AutocompleteNone) + + overrideOSFlagName := "override-os" createFlags.StringVar( &cf.OverrideOS, - "override-os", "", + overrideOSFlagName, "", "use `OS` instead of the running OS for choosing images", ) + _ = cmd.RegisterFlagCompletionFunc(overrideOSFlagName, completion.AutocompleteNone) + + overrideVariantFlagName := "override-variant" createFlags.StringVar( &cf.OverrideVariant, - "override-variant", "", + overrideVariantFlagName, "", "Use _VARIANT_ instead of the running architecture variant for choosing images", ) + _ = cmd.RegisterFlagCompletionFunc(overrideVariantFlagName, completion.AutocompleteNone) + + pidFlagName := "pid" createFlags.String( - "pid", "", + pidFlagName, "", "PID namespace to use", ) + _ = cmd.RegisterFlagCompletionFunc(pidFlagName, AutocompleteNamespace) + + pidsLimitFlagName := "pids-limit" createFlags.Int64( - "pids-limit", containerConfig.PidsLimit(), + pidsLimitFlagName, containerConfig.PidsLimit(), "Tune container pids limit (set 0 for unlimited, -1 for server defaults)", ) + _ = cmd.RegisterFlagCompletionFunc(pidsLimitFlagName, completion.AutocompleteNone) + + podFlagName := "pod" createFlags.StringVar( &cf.Pod, - "pod", "", + podFlagName, "", "Run container in an existing pod", ) + _ = cmd.RegisterFlagCompletionFunc(podFlagName, AutocompletePods) + + podIDFileFlagName := "pod-id-file" createFlags.StringVar( &cf.PodIDFile, - "pod-id-file", "", + podIDFileFlagName, "", "Read the pod ID from the file", ) + _ = cmd.RegisterFlagCompletionFunc(podIDFileFlagName, completion.AutocompleteDefault) + createFlags.BoolVar( &cf.Privileged, "privileged", false, @@ -353,11 +539,15 @@ func GetCreateFlags(cf *ContainerCLIOpts) *pflag.FlagSet { "publish-all", "P", false, "Publish all exposed ports to random ports on the host interface", ) + + pullFlagName := "pull" createFlags.StringVar( &cf.Pull, - "pull", containerConfig.Engine.PullPolicy, + pullFlagName, containerConfig.Engine.PullPolicy, `Pull image before creating ("always"|"missing"|"never")`, ) + _ = cmd.RegisterFlagCompletionFunc(pullFlagName, AutocompletePullOption) + createFlags.BoolVarP( &cf.Quiet, "quiet", "q", false, @@ -378,11 +568,15 @@ func GetCreateFlags(cf *ContainerCLIOpts) *pflag.FlagSet { "replace", false, `If a container with the same name exists, replace it`, ) + + restartFlagName := "restart" createFlags.StringVar( &cf.Restart, - "restart", "", + restartFlagName, "", `Restart policy to apply when a container exits ("always"|"no"|"on-failure"|"unless-stopped")`, ) + _ = cmd.RegisterFlagCompletionFunc(restartFlagName, AutocompleteRestartOption) + createFlags.BoolVar( &cf.Rm, "rm", false, @@ -393,20 +587,31 @@ func GetCreateFlags(cf *ContainerCLIOpts) *pflag.FlagSet { "rootfs", false, "The first argument is not an image but the rootfs to the exploded container", ) + + sdnotifyFlagName := "sdnotify" createFlags.StringVar( &cf.SdNotifyMode, - "sdnotify", define.SdNotifyModeContainer, + sdnotifyFlagName, define.SdNotifyModeContainer, `control sd-notify behavior ("container"|"conmon"|"ignore")`, ) + _ = cmd.RegisterFlagCompletionFunc(sdnotifyFlagName, AutocompleteSDNotify) + + securityOptFlagName := "security-opt" createFlags.StringArrayVar( &cf.SecurityOpt, - "security-opt", []string{}, + securityOptFlagName, []string{}, "Security Options", ) + _ = cmd.RegisterFlagCompletionFunc(securityOptFlagName, AutocompleteSecurityOption) + + shmSizeFlagName := "shm-size" createFlags.String( - "shm-size", containerConfig.ShmSize(), + shmSizeFlagName, containerConfig.ShmSize(), "Size of /dev/shm "+sizeWithUnitFormat, ) + _ = cmd.RegisterFlagCompletionFunc(shmSizeFlagName, completion.AutocompleteNone) + + stopSignalFlagName := "stop-signal" createFlags.StringVar( &cf.SignaturePolicy, "signature-policy", "", @@ -414,112 +619,175 @@ func GetCreateFlags(cf *ContainerCLIOpts) *pflag.FlagSet { ) createFlags.StringVar( &cf.StopSignal, - "stop-signal", "", + stopSignalFlagName, "", "Signal to stop a container. Default is SIGTERM", ) + _ = cmd.RegisterFlagCompletionFunc(stopSignalFlagName, AutocompleteStopSignal) + + stopTimeoutFlagName := "stop-timeout" createFlags.UintVar( &cf.StopTimeout, - "stop-timeout", containerConfig.Engine.StopTimeout, + stopTimeoutFlagName, containerConfig.Engine.StopTimeout, "Timeout (in seconds) to stop a container. Default is 10", ) + _ = cmd.RegisterFlagCompletionFunc(stopTimeoutFlagName, completion.AutocompleteNone) + + storageOptFlagName := "storage-opt" createFlags.StringSliceVar( &cf.StoreageOpt, - "storage-opt", []string{}, + storageOptFlagName, []string{}, "Storage driver options per container", ) + //FIXME: What should we suggest here? The flag is not in the man page. + _ = cmd.RegisterFlagCompletionFunc(storageOptFlagName, completion.AutocompleteNone) + + subgidnameFlagName := "subgidname" createFlags.StringVar( &cf.SubUIDName, - "subgidname", "", + subgidnameFlagName, "", "Name of range listed in /etc/subgid for use in user namespace", ) + _ = cmd.RegisterFlagCompletionFunc(subgidnameFlagName, completion.AutocompleteSubgidName) + + subuidnameFlagName := "subuidname" createFlags.StringVar( &cf.SubGIDName, - "subuidname", "", + subuidnameFlagName, "", "Name of range listed in /etc/subuid for use in user namespace", ) + _ = cmd.RegisterFlagCompletionFunc(subuidnameFlagName, completion.AutocompleteSubuidName) + sysctlFlagName := "sysctl" createFlags.StringSliceVar( &cf.Sysctl, - "sysctl", []string{}, + sysctlFlagName, []string{}, "Sysctl options", ) + //TODO: Add function for systctl completion. + _ = cmd.RegisterFlagCompletionFunc(sysctlFlagName, completion.AutocompleteNone) + + systemdFlagName := "systemd" createFlags.StringVar( &cf.Systemd, - "systemd", "true", + systemdFlagName, "true", `Run container in systemd mode ("true"|"false"|"always")`, ) + _ = cmd.RegisterFlagCompletionFunc(systemdFlagName, AutocompleteSystemdFlag) + + tmpfsFlagName := "tmpfs" createFlags.StringArrayVar( &cf.TmpFS, - "tmpfs", []string{}, + tmpfsFlagName, []string{}, "Mount a temporary filesystem (`tmpfs`) into a container", ) + _ = cmd.RegisterFlagCompletionFunc(tmpfsFlagName, completion.AutocompleteDefault) + createFlags.BoolVarP( &cf.TTY, "tty", "t", false, "Allocate a pseudo-TTY for container", ) + + timezonezFlagName := "tz" createFlags.StringVar( &cf.Timezone, - "tz", containerConfig.TZ(), + timezonezFlagName, containerConfig.TZ(), "Set timezone in container", ) + _ = cmd.RegisterFlagCompletionFunc(timezonezFlagName, completion.AutocompleteNone) //TODO: add timezone completion + + umaskFlagName := "umask" createFlags.StringVar( &cf.Umask, - "umask", containerConfig.Umask(), + umaskFlagName, containerConfig.Umask(), "Set umask in container", ) + _ = cmd.RegisterFlagCompletionFunc(umaskFlagName, completion.AutocompleteNone) + + uidmapFlagName := "uidmap" createFlags.StringSliceVar( &cf.UIDMap, - "uidmap", []string{}, + uidmapFlagName, []string{}, "UID map to use for the user namespace", ) + _ = cmd.RegisterFlagCompletionFunc(uidmapFlagName, completion.AutocompleteNone) + + ulimitFlagName := "ulimit" createFlags.StringSliceVar( &cf.Ulimit, - "ulimit", containerConfig.Ulimits(), + ulimitFlagName, containerConfig.Ulimits(), "Ulimit options", ) + _ = cmd.RegisterFlagCompletionFunc(ulimitFlagName, completion.AutocompleteNone) + + userFlagName := "user" createFlags.StringVarP( &cf.User, - "user", "u", "", + userFlagName, "u", "", "Username or UID (format: [:])", ) + _ = cmd.RegisterFlagCompletionFunc(userFlagName, AutocompleteUserFlag) + + usernsFlagName := "userns" createFlags.String( - "userns", os.Getenv("PODMAN_USERNS"), + usernsFlagName, os.Getenv("PODMAN_USERNS"), "User namespace to use", ) + _ = cmd.RegisterFlagCompletionFunc(usernsFlagName, AutocompleteUserNamespace) + + utsFlagName := "uts" createFlags.String( - "uts", "", + utsFlagName, "", "UTS namespace to use", ) + _ = cmd.RegisterFlagCompletionFunc(utsFlagName, AutocompleteNamespace) + + mountFlagName := "mount" createFlags.StringArrayVar( &cf.Mount, - "mount", []string{}, + mountFlagName, []string{}, "Attach a filesystem mount to the container", ) + _ = cmd.RegisterFlagCompletionFunc(mountFlagName, AutocompleteMountFlag) + + volumeFlagName := "volume" createFlags.StringArrayVarP( &cf.Volume, - "volume", "v", containerConfig.Volumes(), + volumeFlagName, "v", containerConfig.Volumes(), "Bind mount a volume into the container", ) + _ = cmd.RegisterFlagCompletionFunc(volumeFlagName, AutocompleteVolumeFlag) + + volumesFromFlagName := "volumes-from" createFlags.StringArrayVar( &cf.VolumesFrom, - "volumes-from", []string{}, + volumesFromFlagName, []string{}, "Mount volumes from the specified container(s)", ) + _ = cmd.RegisterFlagCompletionFunc(volumesFromFlagName, AutocompleteContainers) + + workdirFlagName := "workdir" createFlags.StringVarP( &cf.Workdir, - "workdir", "w", "", + workdirFlagName, "w", "", "Working directory inside the container", ) + _ = cmd.RegisterFlagCompletionFunc(workdirFlagName, completion.AutocompleteDefault) + + seccompPolicyFlagName := "seccomp-policy" createFlags.StringVar( &cf.SeccompPolicy, - "seccomp-policy", "default", + seccompPolicyFlagName, "default", "Policy for selecting a seccomp profile (experimental)", ) + _ = cmd.RegisterFlagCompletionFunc(seccompPolicyFlagName, completion.AutocompleteDefault) + + cgroupConfFlagName := "cgroup-conf" createFlags.StringSliceVar( &cf.CgroupConf, - "cgroup-conf", []string{}, + cgroupConfFlagName, []string{}, "Configure cgroup v2 (key=value)", ) - return &createFlags + _ = cmd.RegisterFlagCompletionFunc(cgroupConfFlagName, completion.AutocompleteNone) + } diff --git a/cmd/podman/common/netflags.go b/cmd/podman/common/netflags.go index 935a5f7b91c0..cae52ccaa485 100644 --- a/cmd/podman/common/netflags.go +++ b/cmd/podman/common/netflags.go @@ -4,58 +4,85 @@ import ( "net" "strings" + "github.com/containers/common/pkg/completion" "github.com/containers/podman/v2/cmd/podman/parse" "github.com/containers/podman/v2/libpod/define" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/containers/podman/v2/pkg/specgen" "github.com/pkg/errors" "github.com/spf13/cobra" - "github.com/spf13/pflag" ) -func GetNetFlags() *pflag.FlagSet { - netFlags := pflag.FlagSet{} +func DefineNetFlags(cmd *cobra.Command) { + netFlags := cmd.Flags() + + addHostFlagName := "add-host" netFlags.StringSlice( - "add-host", []string{}, + addHostFlagName, []string{}, "Add a custom host-to-IP mapping (host:ip) (default [])", ) + _ = cmd.RegisterFlagCompletionFunc(addHostFlagName, completion.AutocompleteNone) + + dnsFlagName := "dns" netFlags.StringSlice( - "dns", containerConfig.DNSServers(), + dnsFlagName, containerConfig.DNSServers(), "Set custom DNS servers", ) + _ = cmd.RegisterFlagCompletionFunc(dnsFlagName, completion.AutocompleteNone) + + dnsOptFlagName := "dns-opt" netFlags.StringSlice( - "dns-opt", containerConfig.DNSOptions(), + dnsOptFlagName, containerConfig.DNSOptions(), "Set custom DNS options", ) + _ = cmd.RegisterFlagCompletionFunc(dnsOptFlagName, completion.AutocompleteNone) + + dnsSearchFlagName := "dns-search" netFlags.StringSlice( - "dns-search", containerConfig.DNSSearches(), + dnsSearchFlagName, containerConfig.DNSSearches(), "Set custom DNS search domains", ) + _ = cmd.RegisterFlagCompletionFunc(dnsSearchFlagName, completion.AutocompleteNone) + + ipFlagName := "ip" netFlags.String( - "ip", "", + ipFlagName, "", "Specify a static IPv4 address for the container", ) + _ = cmd.RegisterFlagCompletionFunc(ipFlagName, completion.AutocompleteNone) + + macAddressFlagName := "mac-address" netFlags.String( - "mac-address", "", + macAddressFlagName, "", "Container MAC address (e.g. 92:d0:c6:0a:29:33)", ) + _ = cmd.RegisterFlagCompletionFunc(macAddressFlagName, completion.AutocompleteNone) + + networkFlagName := "network" netFlags.String( - "network", containerConfig.NetNS(), + networkFlagName, containerConfig.NetNS(), "Connect a container to a network", ) + _ = cmd.RegisterFlagCompletionFunc(networkFlagName, AutocompleteNetworks) + + networkAliasFlagName := "network-alias" netFlags.StringSlice( - "network-alias", []string{}, + networkAliasFlagName, []string{}, "Add network-scoped alias for the container", ) + _ = cmd.RegisterFlagCompletionFunc(networkAliasFlagName, completion.AutocompleteNone) + + publishFlagName := "publish" netFlags.StringSliceP( - "publish", "p", []string{}, + publishFlagName, "p", []string{}, "Publish a container's port, or a range of ports, to the host (default [])", ) + _ = cmd.RegisterFlagCompletionFunc(publishFlagName, completion.AutocompleteNone) + netFlags.Bool( "no-hosts", false, "Do not create /etc/hosts within the container, instead use the version from the image", ) - return &netFlags } func NetFlagsToNetOptions(cmd *cobra.Command) (*entities.NetOptions, error) { diff --git a/cmd/podman/completion/completion.go b/cmd/podman/completion/completion.go new file mode 100644 index 000000000000..ead8d1f05bc9 --- /dev/null +++ b/cmd/podman/completion/completion.go @@ -0,0 +1,93 @@ +package completion + +import ( + "fmt" + "io" + "os" + "strings" + + commonComp "github.com/containers/common/pkg/completion" + "github.com/containers/podman/v2/cmd/podman/registry" + "github.com/containers/podman/v2/pkg/domain/entities" + "github.com/spf13/cobra" +) + +const ( + completionDescription = `Generate shell autocompletions. + Valid arguments are bash, zsh, and fish. + Please refer to the man page to see how you can load these completions.` +) + +var ( + file string + noDesc bool + shells = []string{"bash", "zsh", "fish"} + completionCmd = &cobra.Command{ + Use: fmt.Sprintf("completion [options] {%s}", strings.Join(shells, "|")), + Short: "Generate shell autocompletions", + Long: completionDescription, + ValidArgs: shells, + Args: cobra.ExactValidArgs(1), + RunE: completion, + Example: `podman completion bash + podman completion zsh -f _podman + podman completion fish --no-desc`, + //dont show this command to users + Hidden: true, + } +) + +func init() { + registry.Commands = append(registry.Commands, registry.CliCommand{ + Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, + Command: completionCmd, + }) + flags := completionCmd.Flags() + fileFlagName := "file" + flags.StringVarP(&file, fileFlagName, "f", "", "Output the completion to file rather than stdout.") + _ = completionCmd.RegisterFlagCompletionFunc(fileFlagName, commonComp.AutocompleteDefault) + + flags.BoolVar(&noDesc, "no-desc", false, "Don't include descriptions in the completion output.") +} + +func completion(cmd *cobra.Command, args []string) error { + var w io.Writer + + if file != "" { + file, err := os.Create(file) + if err != nil { + return err + } + defer file.Close() + w = file + } else { + w = os.Stdout + } + + var err error + switch args[0] { + case "bash": + if noDesc { + err = cmd.Root().GenBashCompletion(w) + } else { + err = cmd.Root().GenBashCompletionWithDesc(w) + } + case "zsh": + if noDesc { + err = cmd.Root().GenZshCompletionNoDesc(w) + } else { + err = cmd.Root().GenZshCompletion(w) + } + case "fish": + err = cmd.Root().GenFishCompletion(w, !noDesc) + } + + if err != nil { + return err + } + + _, err = io.WriteString(w, fmt.Sprintf( + "\n# This file is generated with %q; see: podman-completion(1)\n", cmd.CommandPath(), + )) + return err +} diff --git a/cmd/podman/containers/attach.go b/cmd/podman/containers/attach.go index 0db7c22d07e0..f00c5378b92b 100644 --- a/cmd/podman/containers/attach.go +++ b/cmd/podman/containers/attach.go @@ -3,33 +3,35 @@ package containers import ( "os" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/validate" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/pkg/errors" "github.com/spf13/cobra" - "github.com/spf13/pflag" ) var ( attachDescription = "The podman attach command allows you to attach to a running container using the container's ID or name, either to view its ongoing output or to control it interactively." attachCommand = &cobra.Command{ - Use: "attach [options] CONTAINER", - Short: "Attach to a running container", - Long: attachDescription, - RunE: attach, - Args: validate.IDOrLatestArgs, + Use: "attach [options] CONTAINER", + Short: "Attach to a running container", + Long: attachDescription, + RunE: attach, + Args: validate.IDOrLatestArgs, + ValidArgsFunction: common.AutocompleteContainersRunning, Example: `podman attach ctrID podman attach 1234 podman attach --no-stdin foobar`, } containerAttachCommand = &cobra.Command{ - Use: attachCommand.Use, - Short: attachCommand.Short, - Long: attachCommand.Long, - RunE: attachCommand.RunE, - Args: validate.IDOrLatestArgs, + Use: attachCommand.Use, + Short: attachCommand.Short, + Long: attachCommand.Long, + RunE: attachCommand.RunE, + Args: validate.IDOrLatestArgs, + ValidArgsFunction: attachCommand.ValidArgsFunction, Example: `podman container attach ctrID podman container attach 1234 podman container attach --no-stdin foobar`, @@ -40,8 +42,13 @@ var ( attachOpts entities.AttachOptions ) -func attachFlags(flags *pflag.FlagSet) { - flags.StringVar(&attachOpts.DetachKeys, "detach-keys", containerConfig.DetachKeys(), "Select the key sequence for detaching a container. Format is a single character `[a-Z]` or a comma separated sequence of `ctrl-`, where `` is one of: `a-z`, `@`, `^`, `[`, `\\`, `]`, `^` or `_`") +func attachFlags(cmd *cobra.Command) { + flags := cmd.Flags() + + detachKeysFlagName := "detach-keys" + flags.StringVar(&attachOpts.DetachKeys, detachKeysFlagName, containerConfig.DetachKeys(), "Select the key sequence for detaching a container. Format is a single character `[a-Z]` or a comma separated sequence of `ctrl-`, where `` is one of: `a-z`, `@`, `^`, `[`, `\\`, `]`, `^` or `_`") + _ = cmd.RegisterFlagCompletionFunc(detachKeysFlagName, common.AutocompleteDetachKeys) + flags.BoolVar(&attachOpts.NoStdin, "no-stdin", false, "Do not attach STDIN. The default is false") flags.BoolVar(&attachOpts.SigProxy, "sig-proxy", true, "Proxy received signals to the process") } @@ -51,7 +58,7 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: attachCommand, }) - attachFlags(attachCommand.Flags()) + attachFlags(attachCommand) validate.AddLatestFlag(attachCommand, &attachOpts.Latest) registry.Commands = append(registry.Commands, registry.CliCommand{ @@ -59,7 +66,7 @@ func init() { Command: containerAttachCommand, Parent: containerCmd, }) - attachFlags(containerAttachCommand.Flags()) + attachFlags(containerAttachCommand) validate.AddLatestFlag(containerAttachCommand, &attachOpts.Latest) } diff --git a/cmd/podman/containers/checkpoint.go b/cmd/podman/containers/checkpoint.go index 2606f62c57d0..b6dc213487b6 100644 --- a/cmd/podman/containers/checkpoint.go +++ b/cmd/podman/containers/checkpoint.go @@ -4,6 +4,8 @@ import ( "context" "fmt" + "github.com/containers/common/pkg/completion" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" "github.com/containers/podman/v2/cmd/podman/validate" @@ -27,6 +29,7 @@ var ( Args: func(cmd *cobra.Command, args []string) error { return validate.CheckAllLatestAndCIDFile(cmd, args, false, false) }, + ValidArgsFunction: common.AutocompleteContainersRunning, Example: `podman container checkpoint --keep ctrID podman container checkpoint --all podman container checkpoint --leave-running --latest`, @@ -48,7 +51,11 @@ func init() { flags.BoolVarP(&checkpointOptions.LeaveRunning, "leave-running", "R", false, "Leave the container running after writing checkpoint to disk") flags.BoolVar(&checkpointOptions.TCPEstablished, "tcp-established", false, "Checkpoint a container with established TCP connections") flags.BoolVarP(&checkpointOptions.All, "all", "a", false, "Checkpoint all running containers") - flags.StringVarP(&checkpointOptions.Export, "export", "e", "", "Export the checkpoint image to a tar.gz") + + exportFlagName := "export" + flags.StringVarP(&checkpointOptions.Export, exportFlagName, "e", "", "Export the checkpoint image to a tar.gz") + _ = checkpointCommand.RegisterFlagCompletionFunc(exportFlagName, completion.AutocompleteDefault) + flags.BoolVar(&checkpointOptions.IgnoreRootFS, "ignore-rootfs", false, "Do not include root file-system changes when exporting") validate.AddLatestFlag(checkpointCommand, &checkpointOptions.Latest) } diff --git a/cmd/podman/containers/cleanup.go b/cmd/podman/containers/cleanup.go index 54bc64a60db4..593aaad3df49 100644 --- a/cmd/podman/containers/cleanup.go +++ b/cmd/podman/containers/cleanup.go @@ -3,6 +3,8 @@ package containers import ( "fmt" + "github.com/containers/common/pkg/completion" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" "github.com/containers/podman/v2/cmd/podman/validate" @@ -26,6 +28,7 @@ var ( Args: func(cmd *cobra.Command, args []string) error { return validate.CheckAllLatestAndCIDFile(cmd, args, false, false) }, + ValidArgsFunction: common.AutocompleteContainersExited, Example: `podman container cleanup --latest podman container cleanup ctrID1 ctrID2 ctrID3 podman container cleanup --all`, @@ -44,7 +47,11 @@ func init() { }) flags := cleanupCommand.Flags() flags.BoolVarP(&cleanupOptions.All, "all", "a", false, "Cleans up all containers") - flags.StringVar(&cleanupOptions.Exec, "exec", "", "Clean up the given exec session instead of the container") + + execFlagName := "exec" + flags.StringVar(&cleanupOptions.Exec, execFlagName, "", "Clean up the given exec session instead of the container") + _ = cleanupCommand.RegisterFlagCompletionFunc(execFlagName, completion.AutocompleteNone) + flags.BoolVar(&cleanupOptions.Remove, "rm", false, "After cleanup, remove the container entirely") flags.BoolVar(&cleanupOptions.RemoveImage, "rmi", false, "After cleanup, remove the image entirely") validate.AddLatestFlag(cleanupCommand, &cleanupOptions.Latest) diff --git a/cmd/podman/containers/commit.go b/cmd/podman/containers/commit.go index 412dbf7a8f87..c5c7673b27c5 100644 --- a/cmd/podman/containers/commit.go +++ b/cmd/podman/containers/commit.go @@ -7,22 +7,24 @@ import ( "os" "strings" + "github.com/containers/common/pkg/completion" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/pkg/errors" "github.com/spf13/cobra" - "github.com/spf13/pflag" ) var ( commitDescription = `Create an image from a container's changes. Optionally tag the image created, set the author with the --author flag, set the commit message with the --message flag, and make changes to the instructions with the --change flag.` commitCommand = &cobra.Command{ - Use: "commit [options] CONTAINER [IMAGE]", - Short: "Create new image based on the changed container", - Long: commitDescription, - RunE: commit, - Args: cobra.RangeArgs(1, 2), + Use: "commit [options] CONTAINER [IMAGE]", + Short: "Create new image based on the changed container", + Long: commitDescription, + RunE: commit, + Args: cobra.RangeArgs(1, 2), + ValidArgsFunction: common.AutocompleteContainers, Example: `podman commit -q --message "committing container to image" reverent_golick image-committed podman commit -q --author "firstName lastName" reverent_golick image-committed podman commit -q --pause=false containerID image-committed @@ -30,19 +32,17 @@ var ( } containerCommitCommand = &cobra.Command{ - Args: commitCommand.Args, - Use: commitCommand.Use, - Short: commitCommand.Short, - Long: commitCommand.Long, - RunE: commitCommand.RunE, + Args: commitCommand.Args, + Use: commitCommand.Use, + Short: commitCommand.Short, + Long: commitCommand.Long, + RunE: commitCommand.RunE, + ValidArgsFunction: commitCommand.ValidArgsFunction, Example: `podman container commit -q --message "committing container to image" reverent_golick image-committed podman container commit -q --author "firstName lastName" reverent_golick image-committed podman container commit -q --pause=false containerID image-committed podman container commit containerID`, } - - // ChangeCmds is the list of valid Changes commands to passed to the Commit call - ChangeCmds = []string{"CMD", "ENTRYPOINT", "ENV", "EXPOSE", "LABEL", "ONBUILD", "STOPSIGNAL", "USER", "VOLUME", "WORKDIR"} ) var ( @@ -52,12 +52,29 @@ var ( iidFile string ) -func commitFlags(flags *pflag.FlagSet) { - flags.StringArrayVarP(&commitOptions.Changes, "change", "c", []string{}, "Apply the following possible instructions to the created image (default []): "+strings.Join(ChangeCmds, " | ")) - flags.StringVarP(&commitOptions.Format, "format", "f", "oci", "`Format` of the image manifest and metadata") - flags.StringVarP(&iidFile, "iidfile", "", "", "`file` to write the image ID to") - flags.StringVarP(&commitOptions.Message, "message", "m", "", "Set commit message for imported image") - flags.StringVarP(&commitOptions.Author, "author", "a", "", "Set the author for the image committed") +func commitFlags(cmd *cobra.Command) { + flags := cmd.Flags() + + changeFlagName := "change" + flags.StringArrayVarP(&commitOptions.Changes, changeFlagName, "c", []string{}, "Apply the following possible instructions to the created image (default []): "+strings.Join(common.ChangeCmds, " | ")) + _ = cmd.RegisterFlagCompletionFunc(changeFlagName, common.AutocompleteChangeInstructions) + + formatFlagName := "format" + flags.StringVarP(&commitOptions.Format, formatFlagName, "f", "oci", "`Format` of the image manifest and metadata") + _ = cmd.RegisterFlagCompletionFunc(formatFlagName, common.AutocompleteImageFormat) + + iidFileFlagName := "iidfile" + flags.StringVarP(&iidFile, iidFileFlagName, "", "", "`file` to write the image ID to") + _ = cmd.RegisterFlagCompletionFunc(iidFileFlagName, completion.AutocompleteDefault) + + messageFlagName := "message" + flags.StringVarP(&commitOptions.Message, messageFlagName, "m", "", "Set commit message for imported image") + _ = cmd.RegisterFlagCompletionFunc(messageFlagName, completion.AutocompleteNone) + + authorFlagName := "author" + flags.StringVarP(&commitOptions.Author, authorFlagName, "a", "", "Set the author for the image committed") + _ = cmd.RegisterFlagCompletionFunc(authorFlagName, completion.AutocompleteNone) + flags.BoolVarP(&commitOptions.Pause, "pause", "p", false, "Pause container during commit") flags.BoolVarP(&commitOptions.Quiet, "quiet", "q", false, "Suppress output") flags.BoolVar(&commitOptions.IncludeVolumes, "include-volumes", false, "Include container volumes as image volumes") @@ -68,16 +85,14 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: commitCommand, }) - flags := commitCommand.Flags() - commitFlags(flags) + commitFlags(commitCommand) registry.Commands = append(registry.Commands, registry.CliCommand{ Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: containerCommitCommand, Parent: containerCmd, }) - containerCommitFlags := containerCommitCommand.Flags() - commitFlags(containerCommitFlags) + commitFlags(containerCommitCommand) } func commit(cmd *cobra.Command, args []string) error { diff --git a/cmd/podman/containers/cp.go b/cmd/podman/containers/cp.go index 5dfe43ded212..a74ea89d26ad 100644 --- a/cmd/podman/containers/cp.go +++ b/cmd/podman/containers/cp.go @@ -1,13 +1,13 @@ package containers import ( + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/cgroups" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/containers/podman/v2/pkg/rootless" "github.com/sirupsen/logrus" "github.com/spf13/cobra" - "github.com/spf13/pflag" ) var ( @@ -16,21 +16,23 @@ var ( You can copy from the container's file system to the local machine or the reverse, from the local filesystem to the container. If "-" is specified for either the SRC_PATH or DEST_PATH, you can also stream a tar archive from STDIN or to STDOUT. The CONTAINER can be a running or stopped container. The SRC_PATH or DEST_PATH can be a file or directory. ` cpCommand = &cobra.Command{ - Use: "cp [options] SRC_PATH DEST_PATH", - Short: "Copy files/folders between a container and the local filesystem", - Long: cpDescription, - Args: cobra.ExactArgs(2), - RunE: cp, - Example: "podman cp [CONTAINER:]SRC_PATH [CONTAINER:]DEST_PATH", + Use: "cp [options] SRC_PATH DEST_PATH", + Short: "Copy files/folders between a container and the local filesystem", + Long: cpDescription, + Args: cobra.ExactArgs(2), + RunE: cp, + ValidArgsFunction: common.AutocompleteCpCommand, + Example: "podman cp [CONTAINER:]SRC_PATH [CONTAINER:]DEST_PATH", } containerCpCommand = &cobra.Command{ - Use: cpCommand.Use, - Short: cpCommand.Short, - Long: cpCommand.Long, - Args: cpCommand.Args, - RunE: cpCommand.RunE, - Example: "podman container cp [CONTAINER:]SRC_PATH [CONTAINER:]DEST_PATH", + Use: cpCommand.Use, + Short: cpCommand.Short, + Long: cpCommand.Long, + Args: cpCommand.Args, + RunE: cpCommand.RunE, + ValidArgsFunction: cpCommand.ValidArgsFunction, + Example: "podman container cp [CONTAINER:]SRC_PATH [CONTAINER:]DEST_PATH", } ) @@ -38,7 +40,8 @@ var ( cpOpts entities.ContainerCpOptions ) -func cpFlags(flags *pflag.FlagSet) { +func cpFlags(cmd *cobra.Command) { + flags := cmd.Flags() flags.BoolVar(&cpOpts.Extract, "extract", false, "Extract the tar file into the destination directory.") flags.BoolVar(&cpOpts.Pause, "pause", copyPause(), "Pause the container while copying") } @@ -48,16 +51,14 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode}, Command: cpCommand, }) - flags := cpCommand.Flags() - cpFlags(flags) + cpFlags(cpCommand) registry.Commands = append(registry.Commands, registry.CliCommand{ Mode: []entities.EngineMode{entities.ABIMode}, Command: containerCpCommand, Parent: containerCmd, }) - containerCpFlags := containerCpCommand.Flags() - cpFlags(containerCpFlags) + cpFlags(containerCpCommand) } func cp(cmd *cobra.Command, args []string) error { diff --git a/cmd/podman/containers/create.go b/cmd/podman/containers/create.go index b7b2a364fad6..db920554ed63 100644 --- a/cmd/podman/containers/create.go +++ b/cmd/podman/containers/create.go @@ -19,7 +19,6 @@ import ( "github.com/containers/podman/v2/pkg/util" "github.com/pkg/errors" "github.com/spf13/cobra" - "github.com/spf13/pflag" ) var ( @@ -27,22 +26,24 @@ var ( The container ID is then printed to stdout. You can then start it at any time with the podman start command. The container will be created with the initial state 'created'.` createCommand = &cobra.Command{ - Use: "create [options] IMAGE [COMMAND [ARG...]]", - Short: "Create but do not start a container", - Long: createDescription, - RunE: create, - Args: cobra.MinimumNArgs(1), + Use: "create [options] IMAGE [COMMAND [ARG...]]", + Short: "Create but do not start a container", + Long: createDescription, + RunE: create, + Args: cobra.MinimumNArgs(1), + ValidArgsFunction: common.AutocompleteCreateRun, Example: `podman create alpine ls podman create --annotation HELLO=WORLD alpine ls podman create -t -i --name myctr alpine ls`, } containerCreateCommand = &cobra.Command{ - Args: cobra.MinimumNArgs(1), - Use: createCommand.Use, - Short: createCommand.Short, - Long: createCommand.Long, - RunE: createCommand.RunE, + Args: cobra.MinimumNArgs(1), + Use: createCommand.Use, + Short: createCommand.Short, + Long: createCommand.Long, + RunE: createCommand.RunE, + ValidArgsFunction: createCommand.ValidArgsFunction, Example: `podman container create alpine ls podman container create --annotation HELLO=WORLD alpine ls podman container create -t -i --name myctr alpine ls`, @@ -53,10 +54,13 @@ var ( cliVals common.ContainerCLIOpts ) -func createFlags(flags *pflag.FlagSet) { +func createFlags(cmd *cobra.Command) { + flags := cmd.Flags() + flags.SetInterspersed(false) - flags.AddFlagSet(common.GetCreateFlags(&cliVals)) - flags.AddFlagSet(common.GetNetFlags()) + common.DefineCreateFlags(cmd, &cliVals) + common.DefineNetFlags(cmd) + flags.SetNormalizeFunc(utils.AliasFlags) _ = flags.MarkHidden("signature-policy") @@ -70,18 +74,14 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: createCommand, }) - // common.GetCreateFlags(createCommand) - flags := createCommand.Flags() - createFlags(flags) + createFlags(createCommand) registry.Commands = append(registry.Commands, registry.CliCommand{ Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: containerCreateCommand, Parent: containerCmd, }) - - containerCreateFlags := containerCreateCommand.Flags() - createFlags(containerCreateFlags) + createFlags(containerCreateCommand) } func create(cmd *cobra.Command, args []string) error { diff --git a/cmd/podman/containers/diff.go b/cmd/podman/containers/diff.go index caf7e995553c..4533b7159001 100644 --- a/cmd/podman/containers/diff.go +++ b/cmd/podman/containers/diff.go @@ -13,11 +13,12 @@ import ( var ( // podman container _diff_ diffCmd = &cobra.Command{ - Use: "diff [options] CONTAINER", - Args: validate.IDOrLatestArgs, - Short: "Inspect changes to the container's file systems", - Long: `Displays changes to the container filesystem's'. The container will be compared to its parent layer.`, - RunE: diff, + Use: "diff [options] CONTAINER", + Args: validate.IDOrLatestArgs, + Short: "Inspect changes to the container's file systems", + Long: `Displays changes to the container filesystem's'. The container will be compared to its parent layer.`, + RunE: diff, + ValidArgsFunction: common.AutocompleteContainers, Example: `podman container diff myCtr podman container diff -l --format json myCtr`, } @@ -35,7 +36,11 @@ func init() { flags := diffCmd.Flags() flags.BoolVar(&diffOpts.Archive, "archive", true, "Save the diff as a tar archive") _ = flags.MarkHidden("archive") - flags.StringVar(&diffOpts.Format, "format", "", "Change the output format") + + formatFlagName := "format" + flags.StringVar(&diffOpts.Format, formatFlagName, "", "Change the output format") + _ = diffCmd.RegisterFlagCompletionFunc(formatFlagName, common.AutocompleteJSONFormat) + validate.AddLatestFlag(diffCmd, &diffOpts.Latest) } diff --git a/cmd/podman/containers/exec.go b/cmd/podman/containers/exec.go index 88851f6197d3..306bae58ed46 100644 --- a/cmd/podman/containers/exec.go +++ b/cmd/podman/containers/exec.go @@ -5,6 +5,8 @@ import ( "fmt" "os" + "github.com/containers/common/pkg/completion" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/validate" "github.com/containers/podman/v2/libpod/define" @@ -13,7 +15,6 @@ import ( "github.com/containers/podman/v2/pkg/rootless" "github.com/pkg/errors" "github.com/spf13/cobra" - "github.com/spf13/pflag" ) var ( @@ -25,6 +26,7 @@ var ( Long: execDescription, RunE: exec, DisableFlagsInUseLine: true, + ValidArgsFunction: common.AutocompleteContainersRunning, Example: `podman exec -it ctrID ls podman exec -it -w /tmp myCtr pwd podman exec --user root ctrID ls`, @@ -36,6 +38,7 @@ var ( Long: execCommand.Long, RunE: execCommand.RunE, DisableFlagsInUseLine: true, + ValidArgsFunction: execCommand.ValidArgsFunction, Example: `podman container exec -it ctrID ls podman container exec -it -w /tmp myCtr pwd podman container exec --user root ctrID ls`, @@ -48,18 +51,39 @@ var ( execDetach bool ) -func execFlags(flags *pflag.FlagSet) { +func execFlags(cmd *cobra.Command) { + flags := cmd.Flags() + flags.SetInterspersed(false) flags.BoolVarP(&execDetach, "detach", "d", false, "Run the exec session in detached mode (backgrounded)") - flags.StringVar(&execOpts.DetachKeys, "detach-keys", containerConfig.DetachKeys(), "Select the key sequence for detaching a container. Format is a single character [a-Z] or ctrl- where is one of: a-z, @, ^, [, , or _") - flags.StringArrayVarP(&envInput, "env", "e", []string{}, "Set environment variables") - flags.StringSliceVar(&envFile, "env-file", []string{}, "Read in a file of environment variables") + + detachKeysFlagName := "detach-keys" + flags.StringVar(&execOpts.DetachKeys, detachKeysFlagName, containerConfig.DetachKeys(), "Select the key sequence for detaching a container. Format is a single character [a-Z] or ctrl- where is one of: a-z, @, ^, [, , or _") + _ = cmd.RegisterFlagCompletionFunc(detachKeysFlagName, common.AutocompleteDetachKeys) + + envFlagName := "env" + flags.StringArrayVarP(&envInput, envFlagName, "e", []string{}, "Set environment variables") + _ = cmd.RegisterFlagCompletionFunc(envFlagName, completion.AutocompleteNone) + + envFileFlagName := "env-file" + flags.StringSliceVar(&envFile, envFileFlagName, []string{}, "Read in a file of environment variables") + _ = cmd.RegisterFlagCompletionFunc(envFileFlagName, completion.AutocompleteDefault) + flags.BoolVarP(&execOpts.Interactive, "interactive", "i", false, "Keep STDIN open even if not attached") flags.BoolVar(&execOpts.Privileged, "privileged", false, "Give the process extended Linux capabilities inside the container. The default is false") flags.BoolVarP(&execOpts.Tty, "tty", "t", false, "Allocate a pseudo-TTY. The default is false") - flags.StringVarP(&execOpts.User, "user", "u", "", "Sets the username or UID used and optionally the groupname or GID for the specified command") - flags.UintVar(&execOpts.PreserveFDs, "preserve-fds", 0, "Pass N additional file descriptors to the container") - flags.StringVarP(&execOpts.WorkDir, "workdir", "w", "", "Working directory inside the container") + + userFlagName := "user" + flags.StringVarP(&execOpts.User, userFlagName, "u", "", "Sets the username or UID used and optionally the groupname or GID for the specified command") + _ = cmd.RegisterFlagCompletionFunc(userFlagName, common.AutocompleteUserFlag) + + preserveFdsFlagName := "preserve-fds" + flags.UintVar(&execOpts.PreserveFDs, preserveFdsFlagName, 0, "Pass N additional file descriptors to the container") + _ = cmd.RegisterFlagCompletionFunc(preserveFdsFlagName, completion.AutocompleteNone) + + workdirFlagName := "workdir" + flags.StringVarP(&execOpts.WorkDir, workdirFlagName, "w", "", "Working directory inside the container") + _ = cmd.RegisterFlagCompletionFunc(workdirFlagName, completion.AutocompleteDefault) if registry.IsRemote() { _ = flags.MarkHidden("preserve-fds") @@ -71,7 +95,7 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: execCommand, }) - execFlags(execCommand.Flags()) + execFlags(execCommand) validate.AddLatestFlag(execCommand, &execOpts.Latest) registry.Commands = append(registry.Commands, registry.CliCommand{ @@ -79,7 +103,7 @@ func init() { Command: containerExecCommand, Parent: containerCmd, }) - execFlags(containerExecCommand.Flags()) + execFlags(containerExecCommand) validate.AddLatestFlag(containerExecCommand, &execOpts.Latest) } diff --git a/cmd/podman/containers/exists.go b/cmd/podman/containers/exists.go index 70b8af159cbb..607a03023e15 100644 --- a/cmd/podman/containers/exists.go +++ b/cmd/podman/containers/exists.go @@ -3,6 +3,7 @@ package containers import ( "context" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/spf13/cobra" @@ -20,6 +21,7 @@ var ( RunE: exists, Args: cobra.ExactArgs(1), DisableFlagsInUseLine: true, + ValidArgsFunction: common.AutocompleteContainers, } ) diff --git a/cmd/podman/containers/export.go b/cmd/podman/containers/export.go index f5e02d134ba6..fe2da0f3af1d 100644 --- a/cmd/podman/containers/export.go +++ b/cmd/podman/containers/export.go @@ -4,12 +4,13 @@ import ( "context" "os" + "github.com/containers/common/pkg/completion" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/parse" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/pkg/errors" "github.com/spf13/cobra" - "github.com/spf13/pflag" "golang.org/x/crypto/ssh/terminal" ) @@ -18,21 +19,23 @@ var ( " and saves it on the local machine." exportCommand = &cobra.Command{ - Use: "export [options] CONTAINER", - Short: "Export container's filesystem contents as a tar archive", - Long: exportDescription, - RunE: export, - Args: cobra.ExactArgs(1), + Use: "export [options] CONTAINER", + Short: "Export container's filesystem contents as a tar archive", + Long: exportDescription, + RunE: export, + Args: cobra.ExactArgs(1), + ValidArgsFunction: common.AutocompleteContainers, Example: `podman export ctrID > myCtr.tar podman export --output="myCtr.tar" ctrID`, } containerExportCommand = &cobra.Command{ - Args: cobra.ExactArgs(1), - Use: exportCommand.Use, - Short: exportCommand.Short, - Long: exportCommand.Long, - RunE: exportCommand.RunE, + Args: cobra.ExactArgs(1), + Use: exportCommand.Use, + Short: exportCommand.Short, + Long: exportCommand.Long, + RunE: exportCommand.RunE, + ValidArgsFunction: exportCommand.ValidArgsFunction, Example: `podman container export ctrID > myCtr.tar podman container export --output="myCtr.tar" ctrID`, } @@ -42,8 +45,12 @@ var ( exportOpts entities.ContainerExportOptions ) -func exportFlags(flags *pflag.FlagSet) { - flags.StringVarP(&exportOpts.Output, "output", "o", "", "Write to a specified file (default: stdout, which must be redirected)") +func exportFlags(cmd *cobra.Command) { + flags := cmd.Flags() + + outputFlagName := "output" + flags.StringVarP(&exportOpts.Output, outputFlagName, "o", "", "Write to a specified file (default: stdout, which must be redirected)") + _ = cmd.RegisterFlagCompletionFunc(outputFlagName, completion.AutocompleteDefault) } func init() { @@ -51,17 +58,14 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: exportCommand, }) - flags := exportCommand.Flags() - exportFlags(flags) + exportFlags(exportCommand) registry.Commands = append(registry.Commands, registry.CliCommand{ Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: containerExportCommand, Parent: containerCmd, }) - - containerExportFlags := containerExportCommand.Flags() - exportFlags(containerExportFlags) + exportFlags(containerExportCommand) } func export(cmd *cobra.Command, args []string) error { diff --git a/cmd/podman/containers/init.go b/cmd/podman/containers/init.go index 983c0e4e8fa1..99a32bc24ee8 100644 --- a/cmd/podman/containers/init.go +++ b/cmd/podman/containers/init.go @@ -3,6 +3,7 @@ package containers import ( "fmt" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" "github.com/containers/podman/v2/cmd/podman/validate" @@ -22,17 +23,19 @@ var ( Args: func(cmd *cobra.Command, args []string) error { return validate.CheckAllLatestAndCIDFile(cmd, args, false, false) }, + ValidArgsFunction: common.AutocompleteContainersCreated, Example: `podman init --latest podman init 3c45ef19d893 podman init test1`, } containerInitCommand = &cobra.Command{ - Use: initCommand.Use, - Short: initCommand.Short, - Long: initCommand.Long, - RunE: initCommand.RunE, - Args: initCommand.Args, + Use: initCommand.Use, + Short: initCommand.Short, + Long: initCommand.Long, + RunE: initCommand.RunE, + Args: initCommand.Args, + ValidArgsFunction: initCommand.ValidArgsFunction, Example: `podman container init --latest podman container init 3c45ef19d893 podman container init test1`, diff --git a/cmd/podman/containers/inspect.go b/cmd/podman/containers/inspect.go index b4e1feccb0be..e438bca959ae 100644 --- a/cmd/podman/containers/inspect.go +++ b/cmd/podman/containers/inspect.go @@ -1,6 +1,7 @@ package containers import ( + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/inspect" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/validate" @@ -11,10 +12,11 @@ import ( var ( // podman container _inspect_ inspectCmd = &cobra.Command{ - Use: "inspect [options] CONTAINER [CONTAINER...]", - Short: "Display the configuration of a container", - Long: `Displays the low-level information on a container identified by name or ID.`, - RunE: inspectExec, + Use: "inspect [options] CONTAINER [CONTAINER...]", + Short: "Display the configuration of a container", + Long: `Displays the low-level information on a container identified by name or ID.`, + RunE: inspectExec, + ValidArgsFunction: common.AutocompleteContainers, Example: `podman container inspect myCtr podman container inspect -l --format '{{.Id}} {{.Config.Labels}}'`, } @@ -30,7 +32,11 @@ func init() { inspectOpts = new(entities.InspectOptions) flags := inspectCmd.Flags() flags.BoolVarP(&inspectOpts.Size, "size", "s", false, "Display total file size") - flags.StringVarP(&inspectOpts.Format, "format", "f", "json", "Format the output to a Go template or json") + + formatFlagName := "format" + flags.StringVarP(&inspectOpts.Format, formatFlagName, "f", "json", "Format the output to a Go template or json") + _ = inspectCmd.RegisterFlagCompletionFunc(formatFlagName, common.AutocompleteJSONFormat) + validate.AddLatestFlag(inspectCmd, &inspectOpts.Latest) } diff --git a/cmd/podman/containers/kill.go b/cmd/podman/containers/kill.go index 1bb071b6d2c4..4640229a9e8d 100644 --- a/cmd/podman/containers/kill.go +++ b/cmd/podman/containers/kill.go @@ -5,13 +5,13 @@ import ( "errors" "fmt" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" "github.com/containers/podman/v2/cmd/podman/validate" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/containers/podman/v2/pkg/signal" "github.com/spf13/cobra" - "github.com/spf13/pflag" ) var ( @@ -24,6 +24,7 @@ var ( Args: func(cmd *cobra.Command, args []string) error { return validate.CheckAllLatestAndCIDFile(cmd, args, false, false) }, + ValidArgsFunction: common.AutocompleteContainersRunning, Example: `podman kill mywebserver podman kill 860a4b23 podman kill --signal TERM ctrID`, @@ -33,10 +34,11 @@ var ( Args: func(cmd *cobra.Command, args []string) error { return validate.CheckAllLatestAndCIDFile(cmd, args, false, false) }, - Use: killCommand.Use, - Short: killCommand.Short, - Long: killCommand.Long, - RunE: killCommand.RunE, + Use: killCommand.Use, + Short: killCommand.Short, + Long: killCommand.Long, + RunE: killCommand.RunE, + ValidArgsFunction: killCommand.ValidArgsFunction, Example: `podman container kill mywebserver podman container kill 860a4b23 podman container kill --signal TERM ctrID`, @@ -47,9 +49,14 @@ var ( killOptions = entities.KillOptions{} ) -func killFlags(flags *pflag.FlagSet) { +func killFlags(cmd *cobra.Command) { + flags := cmd.Flags() + flags.BoolVarP(&killOptions.All, "all", "a", false, "Signal all running containers") - flags.StringVarP(&killOptions.Signal, "signal", "s", "KILL", "Signal to send to the container") + + signalFlagName := "signal" + flags.StringVarP(&killOptions.Signal, signalFlagName, "s", "KILL", "Signal to send to the container") + _ = cmd.RegisterFlagCompletionFunc(signalFlagName, common.AutocompleteStopSignal) } func init() { @@ -57,7 +64,7 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: killCommand, }) - killFlags(killCommand.Flags()) + killFlags(killCommand) validate.AddLatestFlag(killCommand, &killOptions.Latest) registry.Commands = append(registry.Commands, registry.CliCommand{ @@ -65,7 +72,7 @@ func init() { Command: containerKillCommand, Parent: containerCmd, }) - killFlags(containerKillCommand.Flags()) + killFlags(containerKillCommand) validate.AddLatestFlag(containerKillCommand, &killOptions.Latest) } diff --git a/cmd/podman/containers/list.go b/cmd/podman/containers/list.go index 78a15559fa02..834413c2cccb 100644 --- a/cmd/podman/containers/list.go +++ b/cmd/podman/containers/list.go @@ -1,6 +1,7 @@ package containers import ( + "github.com/containers/common/pkg/completion" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/validate" "github.com/containers/podman/v2/pkg/domain/entities" @@ -10,12 +11,13 @@ import ( var ( // podman container _list_ listCmd = &cobra.Command{ - Use: "list [options]", - Aliases: []string{"ls"}, - Args: validate.NoArgs, - Short: "List containers", - Long: "Prints out information about the containers", - RunE: ps, + Use: "list [options]", + Aliases: []string{"ls"}, + Args: validate.NoArgs, + Short: "List containers", + Long: "Prints out information about the containers", + RunE: ps, + ValidArgsFunction: completion.AutocompleteNone, Example: `podman container list -a podman container list -a --format "{{.ID}} {{.Image}} {{.Labels}} {{.Mounts}}" podman container list --size --sort names`, @@ -28,6 +30,6 @@ func init() { Command: listCmd, Parent: containerCmd, }) - listFlagSet(listCmd.Flags()) + listFlagSet(listCmd) validate.AddLatestFlag(listCmd, &listOpts.Latest) } diff --git a/cmd/podman/containers/logs.go b/cmd/podman/containers/logs.go index 8ad2d7e163a4..1fa4ac11f0a8 100644 --- a/cmd/podman/containers/logs.go +++ b/cmd/podman/containers/logs.go @@ -3,13 +3,14 @@ package containers import ( "os" + "github.com/containers/common/pkg/completion" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/validate" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/containers/podman/v2/pkg/util" "github.com/pkg/errors" "github.com/spf13/cobra" - "github.com/spf13/pflag" ) // logsOptionsWrapper wraps entities.LogsOptions and prevents leaking @@ -43,7 +44,8 @@ var ( } return nil }, - RunE: logs, + RunE: logs, + ValidArgsFunction: common.AutocompleteContainers, Example: `podman logs ctrID podman logs --names ctrID1 ctrID2 podman logs --tail 2 mywebserver @@ -52,11 +54,12 @@ var ( } containerLogsCommand = &cobra.Command{ - Use: logsCommand.Use, - Short: logsCommand.Short, - Long: logsCommand.Long, - Args: logsCommand.Args, - RunE: logsCommand.RunE, + Use: logsCommand.Use, + Short: logsCommand.Short, + Long: logsCommand.Long, + Args: logsCommand.Args, + RunE: logsCommand.RunE, + ValidArgsFunction: logsCommand.ValidArgsFunction, Example: `podman container logs ctrID podman container logs --names ctrID1 ctrID2 podman container logs --tail 2 mywebserver @@ -71,7 +74,7 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: logsCommand, }) - logsFlags(logsCommand.Flags()) + logsFlags(logsCommand) validate.AddLatestFlag(logsCommand, &logsOptions.Latest) // container logs @@ -80,15 +83,24 @@ func init() { Command: containerLogsCommand, Parent: containerCmd, }) - logsFlags(containerLogsCommand.Flags()) + logsFlags(containerLogsCommand) validate.AddLatestFlag(containerLogsCommand, &logsOptions.Latest) } -func logsFlags(flags *pflag.FlagSet) { +func logsFlags(cmd *cobra.Command) { + flags := cmd.Flags() + flags.BoolVar(&logsOptions.Details, "details", false, "Show extra details provided to the logs") flags.BoolVarP(&logsOptions.Follow, "follow", "f", false, "Follow log output. The default is false") - flags.StringVar(&logsOptions.SinceRaw, "since", "", "Show logs since TIMESTAMP") - flags.Int64Var(&logsOptions.Tail, "tail", -1, "Output the specified number of LINES at the end of the logs. Defaults to -1, which prints all lines") + + sinceFlagName := "since" + flags.StringVar(&logsOptions.SinceRaw, sinceFlagName, "", "Show logs since TIMESTAMP") + _ = cmd.RegisterFlagCompletionFunc(sinceFlagName, completion.AutocompleteNone) + + tailFlagName := "tail" + flags.Int64Var(&logsOptions.Tail, tailFlagName, -1, "Output the specified number of LINES at the end of the logs. Defaults to -1, which prints all lines") + _ = cmd.RegisterFlagCompletionFunc(tailFlagName, completion.AutocompleteNone) + flags.BoolVarP(&logsOptions.Timestamps, "timestamps", "t", false, "Output the timestamps in the log") flags.BoolVarP(&logsOptions.Names, "names", "n", false, "Output the container name in the log") flags.SetInterspersed(false) diff --git a/cmd/podman/containers/mount.go b/cmd/podman/containers/mount.go index 335367e18593..fb2101d64ffc 100644 --- a/cmd/podman/containers/mount.go +++ b/cmd/podman/containers/mount.go @@ -7,13 +7,13 @@ import ( "text/template" "github.com/containers/common/pkg/report" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" "github.com/containers/podman/v2/cmd/podman/validate" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/pkg/errors" "github.com/spf13/cobra" - "github.com/spf13/pflag" ) var ( @@ -36,15 +36,17 @@ var ( registry.UnshareNSRequired: "", registry.ParentNSRequired: "", }, + ValidArgsFunction: common.AutocompleteContainers, } containerMountCommmand = &cobra.Command{ - Use: mountCommand.Use, - Short: mountCommand.Short, - Long: mountCommand.Long, - RunE: mountCommand.RunE, - Args: mountCommand.Args, - Annotations: mountCommand.Annotations, + Use: mountCommand.Use, + Short: mountCommand.Short, + Long: mountCommand.Long, + RunE: mountCommand.RunE, + Args: mountCommand.Args, + Annotations: mountCommand.Annotations, + ValidArgsFunction: mountCommand.ValidArgsFunction, } ) @@ -52,9 +54,15 @@ var ( mountOpts entities.ContainerMountOptions ) -func mountFlags(flags *pflag.FlagSet) { +func mountFlags(cmd *cobra.Command) { + flags := cmd.Flags() + flags.BoolVarP(&mountOpts.All, "all", "a", false, "Mount all containers") - flags.StringVar(&mountOpts.Format, "format", "", "Print the mounted containers in specified format (json)") + + formatFlagName := "format" + flags.StringVar(&mountOpts.Format, formatFlagName, "", "Print the mounted containers in specified format (json)") + _ = cmd.RegisterFlagCompletionFunc(formatFlagName, common.AutocompleteJSONFormat) + flags.BoolVar(&mountOpts.NoTruncate, "notruncate", false, "Do not truncate output") } @@ -63,7 +71,7 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode}, Command: mountCommand, }) - mountFlags(mountCommand.Flags()) + mountFlags(mountCommand) validate.AddLatestFlag(mountCommand, &mountOpts.Latest) registry.Commands = append(registry.Commands, registry.CliCommand{ @@ -71,7 +79,7 @@ func init() { Command: containerMountCommmand, Parent: containerCmd, }) - mountFlags(containerMountCommmand.Flags()) + mountFlags(containerMountCommmand) validate.AddLatestFlag(containerMountCommmand, &mountOpts.Latest) } diff --git a/cmd/podman/containers/pause.go b/cmd/podman/containers/pause.go index 89a76ab25a6d..18b37adfdd71 100644 --- a/cmd/podman/containers/pause.go +++ b/cmd/podman/containers/pause.go @@ -4,6 +4,7 @@ import ( "context" "fmt" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" "github.com/containers/podman/v2/pkg/cgroups" @@ -17,20 +18,22 @@ import ( var ( pauseDescription = `Pauses one or more running containers. The container name or ID can be used.` pauseCommand = &cobra.Command{ - Use: "pause [options] CONTAINER [CONTAINER...]", - Short: "Pause all the processes in one or more containers", - Long: pauseDescription, - RunE: pause, + Use: "pause [options] CONTAINER [CONTAINER...]", + Short: "Pause all the processes in one or more containers", + Long: pauseDescription, + RunE: pause, + ValidArgsFunction: common.AutocompleteContainersRunning, Example: `podman pause mywebserver podman pause 860a4b23 podman pause -a`, } containerPauseCommand = &cobra.Command{ - Use: pauseCommand.Use, - Short: pauseCommand.Short, - Long: pauseCommand.Long, - RunE: pauseCommand.RunE, + Use: pauseCommand.Use, + Short: pauseCommand.Short, + Long: pauseCommand.Long, + RunE: pauseCommand.RunE, + ValidArgsFunction: pauseCommand.ValidArgsFunction, Example: `podman container pause mywebserver podman container pause 860a4b23 podman container pause -a`, diff --git a/cmd/podman/containers/port.go b/cmd/podman/containers/port.go index a895f24b1088..ac31e158e0d9 100644 --- a/cmd/podman/containers/port.go +++ b/cmd/podman/containers/port.go @@ -5,6 +5,7 @@ import ( "strconv" "strings" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/validate" "github.com/containers/podman/v2/pkg/domain/entities" @@ -25,6 +26,7 @@ var ( Args: func(cmd *cobra.Command, args []string) error { return validate.CheckAllLatestAndCIDFile(cmd, args, true, false) }, + ValidArgsFunction: common.AutocompleteContainers, Example: `podman port --all podman port ctrID 80/tcp podman port --latest 80`, @@ -38,6 +40,7 @@ var ( Args: func(cmd *cobra.Command, args []string) error { return validate.CheckAllLatestAndCIDFile(cmd, args, true, false) }, + ValidArgsFunction: portCommand.ValidArgsFunction, Example: `podman container port --all podman container port --latest 80`, } diff --git a/cmd/podman/containers/prune.go b/cmd/podman/containers/prune.go index bfdace086cf1..e8debd3ad7ac 100644 --- a/cmd/podman/containers/prune.go +++ b/cmd/podman/containers/prune.go @@ -8,6 +8,7 @@ import ( "os" "strings" + "github.com/containers/common/pkg/completion" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" "github.com/containers/podman/v2/cmd/podman/validate" @@ -21,12 +22,13 @@ var ( Removes all non running containers`) pruneCommand = &cobra.Command{ - Use: "prune [options]", - Short: "Remove all non running containers", - Long: pruneDescription, - RunE: prune, - Example: `podman container prune`, - Args: validate.NoArgs, + Use: "prune [options]", + Short: "Remove all non running containers", + Long: pruneDescription, + RunE: prune, + ValidArgsFunction: completion.AutocompleteNone, + Example: `podman container prune`, + Args: validate.NoArgs, } force bool filter = []string{} @@ -40,7 +42,9 @@ func init() { }) flags := pruneCommand.Flags() flags.BoolVarP(&force, "force", "f", false, "Do not prompt for confirmation. The default is false") - flags.StringArrayVar(&filter, "filter", []string{}, "Provide filter values (e.g. 'label==')") + filterFlagName := "filter" + flags.StringArrayVar(&filter, filterFlagName, []string{}, "Provide filter values (e.g. 'label==')") + _ = pruneCommand.RegisterFlagCompletionFunc(filterFlagName, completion.AutocompleteNone) } func prune(cmd *cobra.Command, args []string) error { diff --git a/cmd/podman/containers/ps.go b/cmd/podman/containers/ps.go index 7da430bc6035..a9e2d2e35407 100644 --- a/cmd/podman/containers/ps.go +++ b/cmd/podman/containers/ps.go @@ -11,7 +11,9 @@ import ( "time" tm "github.com/buger/goterm" + "github.com/containers/common/pkg/completion" "github.com/containers/common/pkg/report" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/parse" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" @@ -21,17 +23,17 @@ import ( "github.com/docker/go-units" "github.com/pkg/errors" "github.com/spf13/cobra" - "github.com/spf13/pflag" ) var ( psDescription = "Prints out information about the containers" psCommand = &cobra.Command{ - Use: "ps [options]", - Args: validate.NoArgs, - Short: "List containers", - Long: psDescription, - RunE: ps, + Use: "ps [options]", + Args: validate.NoArgs, + Short: "List containers", + Long: psDescription, + RunE: ps, + ValidArgsFunction: completion.AutocompleteNone, Example: `podman ps -a podman ps -a --format "{{.ID}} {{.Image}} {{.Labels}} {{.Mounts}}" podman ps --size --sort names`, @@ -50,26 +52,45 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: psCommand, }) - listFlagSet(psCommand.Flags()) + listFlagSet(psCommand) validate.AddLatestFlag(psCommand, &listOpts.Latest) } -func listFlagSet(flags *pflag.FlagSet) { +func listFlagSet(cmd *cobra.Command) { + flags := cmd.Flags() + flags.BoolVarP(&listOpts.All, "all", "a", false, "Show all the containers, default is only running containers") - flags.StringSliceVarP(&filters, "filter", "f", []string{}, "Filter output based on conditions given") flags.BoolVar(&listOpts.Storage, "external", false, "Show containers in storage not controlled by Podman") - flags.StringVar(&listOpts.Format, "format", "", "Pretty-print containers to JSON or using a Go template") - flags.IntVarP(&listOpts.Last, "last", "n", -1, "Print the n last created containers (all states)") + + filterFlagName := "filter" + flags.StringSliceVarP(&filters, filterFlagName, "f", []string{}, "Filter output based on conditions given") + //TODO add custom filter function + _ = cmd.RegisterFlagCompletionFunc(filterFlagName, completion.AutocompleteNone) + + formatFlagName := "format" + flags.StringVar(&listOpts.Format, formatFlagName, "", "Pretty-print containers to JSON or using a Go template") + _ = cmd.RegisterFlagCompletionFunc(formatFlagName, common.AutocompleteJSONFormat) + + lastFlagName := "last" + flags.IntVarP(&listOpts.Last, lastFlagName, "n", -1, "Print the n last created containers (all states)") + _ = cmd.RegisterFlagCompletionFunc(lastFlagName, completion.AutocompleteNone) + flags.BoolVar(&listOpts.Namespace, "ns", false, "Display namespace information") flags.BoolVar(&noTrunc, "no-trunc", false, "Display the extended information") flags.BoolVarP(&listOpts.Pod, "pod", "p", false, "Print the ID and name of the pod the containers are associated with") flags.BoolVarP(&listOpts.Quiet, "quiet", "q", false, "Print the numeric IDs of the containers only") flags.BoolVarP(&listOpts.Size, "size", "s", false, "Display the total file sizes") flags.BoolVar(&listOpts.Sync, "sync", false, "Sync container state with OCI runtime") - flags.UintVarP(&listOpts.Watch, "watch", "w", 0, "Watch the ps output on an interval in seconds") + + watchFlagName := "watch" + flags.UintVarP(&listOpts.Watch, watchFlagName, "w", 0, "Watch the ps output on an interval in seconds") + _ = cmd.RegisterFlagCompletionFunc(watchFlagName, completion.AutocompleteNone) sort := validate.Value(&listOpts.Sort, "command", "created", "id", "image", "names", "runningfor", "size", "status") - flags.Var(sort, "sort", "Sort output by: "+sort.Choices()) + sortFlagName := "sort" + flags.Var(sort, sortFlagName, "Sort output by: "+sort.Choices()) + _ = cmd.RegisterFlagCompletionFunc(sortFlagName, common.AutocompletePsSort) + flags.SetNormalizeFunc(utils.AliasFlags) } func checkFlags(c *cobra.Command) error { diff --git a/cmd/podman/containers/restart.go b/cmd/podman/containers/restart.go index 1cc28c20df49..a513551946c5 100644 --- a/cmd/podman/containers/restart.go +++ b/cmd/podman/containers/restart.go @@ -4,6 +4,8 @@ import ( "context" "fmt" + "github.com/containers/common/pkg/completion" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" "github.com/containers/podman/v2/cmd/podman/validate" @@ -11,7 +13,6 @@ import ( "github.com/containers/podman/v2/pkg/domain/entities" "github.com/pkg/errors" "github.com/spf13/cobra" - "github.com/spf13/pflag" ) var ( @@ -27,16 +28,18 @@ var ( Args: func(cmd *cobra.Command, args []string) error { return validate.CheckAllLatestAndCIDFile(cmd, args, false, false) }, + ValidArgsFunction: common.AutocompleteContainers, Example: `podman restart ctrID podman restart --latest podman restart ctrID1 ctrID2`, } containerRestartCommand = &cobra.Command{ - Use: restartCommand.Use, - Short: restartCommand.Short, - Long: restartCommand.Long, - RunE: restartCommand.RunE, + Use: restartCommand.Use, + Short: restartCommand.Short, + Long: restartCommand.Long, + RunE: restartCommand.RunE, + ValidArgsFunction: restartCommand.ValidArgsFunction, Example: `podman container restart ctrID podman container restart --latest podman container restart ctrID1 ctrID2`, @@ -48,10 +51,15 @@ var ( restartTimeout uint ) -func restartFlags(flags *pflag.FlagSet) { +func restartFlags(cmd *cobra.Command) { + flags := cmd.Flags() + flags.BoolVarP(&restartOptions.All, "all", "a", false, "Restart all non-running containers") flags.BoolVar(&restartOptions.Running, "running", false, "Restart only running containers when --all is used") - flags.UintVarP(&restartTimeout, "time", "t", containerConfig.Engine.StopTimeout, "Seconds to wait for stop before killing the container") + + timeFlagName := "time" + flags.UintVarP(&restartTimeout, timeFlagName, "t", containerConfig.Engine.StopTimeout, "Seconds to wait for stop before killing the container") + _ = cmd.RegisterFlagCompletionFunc(timeFlagName, completion.AutocompleteNone) flags.SetNormalizeFunc(utils.AliasFlags) } @@ -61,7 +69,7 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: restartCommand, }) - restartFlags(restartCommand.Flags()) + restartFlags(restartCommand) validate.AddLatestFlag(restartCommand, &restartOptions.Latest) registry.Commands = append(registry.Commands, registry.CliCommand{ @@ -69,7 +77,7 @@ func init() { Command: containerRestartCommand, Parent: containerCmd, }) - restartFlags(containerRestartCommand.Flags()) + restartFlags(containerRestartCommand) validate.AddLatestFlag(containerRestartCommand, &restartOptions.Latest) } diff --git a/cmd/podman/containers/restore.go b/cmd/podman/containers/restore.go index 314bf75647ea..6a1d2b319087 100644 --- a/cmd/podman/containers/restore.go +++ b/cmd/podman/containers/restore.go @@ -4,6 +4,8 @@ import ( "context" "fmt" + "github.com/containers/common/pkg/completion" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" "github.com/containers/podman/v2/cmd/podman/validate" @@ -27,6 +29,7 @@ var ( Args: func(cmd *cobra.Command, args []string) error { return validate.CheckAllLatestAndCIDFile(cmd, args, true, false) }, + ValidArgsFunction: common.AutocompleteContainers, Example: `podman container restore ctrID podman container restore --latest podman container restore --all`, @@ -47,8 +50,15 @@ func init() { flags.BoolVarP(&restoreOptions.All, "all", "a", false, "Restore all checkpointed containers") flags.BoolVarP(&restoreOptions.Keep, "keep", "k", false, "Keep all temporary checkpoint files") flags.BoolVar(&restoreOptions.TCPEstablished, "tcp-established", false, "Restore a container with established TCP connections") - flags.StringVarP(&restoreOptions.Import, "import", "i", "", "Restore from exported checkpoint archive (tar.gz)") - flags.StringVarP(&restoreOptions.Name, "name", "n", "", "Specify new name for container restored from exported checkpoint (only works with --import)") + + importFlagName := "import" + flags.StringVarP(&restoreOptions.Import, importFlagName, "i", "", "Restore from exported checkpoint archive (tar.gz)") + _ = restoreCommand.RegisterFlagCompletionFunc(importFlagName, completion.AutocompleteDefault) + + nameFlagName := "name" + flags.StringVarP(&restoreOptions.Name, nameFlagName, "n", "", "Specify new name for container restored from exported checkpoint (only works with --import)") + _ = restoreCommand.RegisterFlagCompletionFunc(nameFlagName, completion.AutocompleteNone) + flags.BoolVar(&restoreOptions.IgnoreRootFS, "ignore-rootfs", false, "Do not apply root file-system changes when importing from exported checkpoint") flags.BoolVar(&restoreOptions.IgnoreStaticIP, "ignore-static-ip", false, "Ignore IP address set via --static-ip") flags.BoolVar(&restoreOptions.IgnoreStaticMAC, "ignore-static-mac", false, "Ignore MAC address set via --mac-address") diff --git a/cmd/podman/containers/rm.go b/cmd/podman/containers/rm.go index ccdd2ef05815..ee9dc4c78ae2 100644 --- a/cmd/podman/containers/rm.go +++ b/cmd/podman/containers/rm.go @@ -5,6 +5,8 @@ import ( "fmt" "strings" + "github.com/containers/common/pkg/completion" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" "github.com/containers/podman/v2/cmd/podman/validate" @@ -13,7 +15,6 @@ import ( "github.com/pkg/errors" "github.com/sirupsen/logrus" "github.com/spf13/cobra" - "github.com/spf13/pflag" ) var ( @@ -28,6 +29,7 @@ var ( Args: func(cmd *cobra.Command, args []string) error { return validate.CheckAllLatestAndCIDFile(cmd, args, false, true) }, + ValidArgsFunction: common.AutocompleteContainers, Example: `podman rm imageID podman rm mywebserver myflaskserver 860a4b23 podman rm --force --all @@ -42,6 +44,7 @@ var ( Args: func(cmd *cobra.Command, args []string) error { return validate.CheckAllLatestAndCIDFile(cmd, args, false, true) }, + ValidArgsFunction: rmCommand.ValidArgsFunction, Example: `podman container rm imageID podman container rm mywebserver myflaskserver 860a4b23 podman container rm --force --all @@ -53,12 +56,17 @@ var ( rmOptions = entities.RmOptions{} ) -func rmFlags(flags *pflag.FlagSet) { +func rmFlags(cmd *cobra.Command) { + flags := cmd.Flags() + flags.BoolVarP(&rmOptions.All, "all", "a", false, "Remove all containers") flags.BoolVarP(&rmOptions.Ignore, "ignore", "i", false, "Ignore errors when a specified container is missing") flags.BoolVarP(&rmOptions.Force, "force", "f", false, "Force removal of a running or unusable container. The default is false") flags.BoolVarP(&rmOptions.Volumes, "volumes", "v", false, "Remove anonymous volumes associated with the container") - flags.StringArrayVarP(&rmOptions.CIDFiles, "cidfile", "", nil, "Read the container ID from the file") + + cidfileFlagName := "cidfile" + flags.StringArrayVarP(&rmOptions.CIDFiles, cidfileFlagName, "", nil, "Read the container ID from the file") + _ = cmd.RegisterFlagCompletionFunc(cidfileFlagName, completion.AutocompleteDefault) if !registry.IsRemote() { // This option is deprecated, but needs to still exists for backwards compatibility @@ -72,7 +80,7 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: rmCommand, }) - rmFlags(rmCommand.Flags()) + rmFlags(rmCommand) validate.AddLatestFlag(rmCommand, &rmOptions.Latest) registry.Commands = append(registry.Commands, registry.CliCommand{ @@ -80,7 +88,7 @@ func init() { Command: containerRmCommand, Parent: containerCmd, }) - rmFlags(containerRmCommand.Flags()) + rmFlags(containerRmCommand) validate.AddLatestFlag(containerRmCommand, &rmOptions.Latest) } diff --git a/cmd/podman/containers/run.go b/cmd/podman/containers/run.go index 780cd0c0d952..b17c13f46cb0 100644 --- a/cmd/podman/containers/run.go +++ b/cmd/podman/containers/run.go @@ -6,6 +6,7 @@ import ( "strconv" "strings" + "github.com/containers/common/pkg/completion" "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" @@ -18,28 +19,29 @@ import ( "github.com/pkg/errors" "github.com/sirupsen/logrus" "github.com/spf13/cobra" - "github.com/spf13/pflag" ) var ( runDescription = "Runs a command in a new container from the given image" runCommand = &cobra.Command{ - Args: cobra.MinimumNArgs(1), - Use: "run [options] IMAGE [COMMAND [ARG...]]", - Short: "Run a command in a new container", - Long: runDescription, - RunE: run, + Args: cobra.MinimumNArgs(1), + Use: "run [options] IMAGE [COMMAND [ARG...]]", + Short: "Run a command in a new container", + Long: runDescription, + RunE: run, + ValidArgsFunction: common.AutocompleteCreateRun, Example: `podman run imageID ls -alF /etc podman run --network=host imageID dnf -y install java podman run --volume /var/hostdir:/var/ctrdir -i -t fedora /bin/bash`, } containerRunCommand = &cobra.Command{ - Args: cobra.MinimumNArgs(1), - Use: runCommand.Use, - Short: runCommand.Short, - Long: runCommand.Long, - RunE: runCommand.RunE, + Args: cobra.MinimumNArgs(1), + Use: runCommand.Use, + Short: runCommand.Short, + Long: runCommand.Long, + RunE: runCommand.RunE, + ValidArgsFunction: runCommand.ValidArgsFunction, Example: `podman container run imageID ls -alF /etc podman container run --network=host imageID dnf -y install java podman container run --volume /var/hostdir:/var/ctrdir -i -t fedora /bin/bash`, @@ -55,16 +57,26 @@ var ( runRmi bool ) -func runFlags(flags *pflag.FlagSet) { +func runFlags(cmd *cobra.Command) { + flags := cmd.Flags() + flags.SetInterspersed(false) - flags.AddFlagSet(common.GetCreateFlags(&cliVals)) - flags.AddFlagSet(common.GetNetFlags()) + common.DefineCreateFlags(cmd, &cliVals) + common.DefineNetFlags(cmd) + flags.SetNormalizeFunc(utils.AliasFlags) flags.BoolVar(&runOpts.SigProxy, "sig-proxy", true, "Proxy received signals to the process") flags.BoolVar(&runRmi, "rmi", false, "Remove container image unless used by other containers") + + preserveFdsFlagName := "preserve-fds" flags.UintVar(&runOpts.PreserveFDs, "preserve-fds", 0, "Pass a number of additional file descriptors into the container") + _ = cmd.RegisterFlagCompletionFunc(preserveFdsFlagName, completion.AutocompleteNone) + flags.BoolVarP(&runOpts.Detach, "detach", "d", false, "Run container in background and print container ID") - flags.StringVar(&runOpts.DetachKeys, "detach-keys", containerConfig.DetachKeys(), "Override the key sequence for detaching a container. Format is a single character `[a-Z]` or a comma separated sequence of `ctrl-`, where `` is one of: `a-cf`, `@`, `^`, `[`, `\\`, `]`, `^` or `_`") + + detachKeysFlagName := "detach-keys" + flags.StringVar(&runOpts.DetachKeys, detachKeysFlagName, containerConfig.DetachKeys(), "Override the key sequence for detaching a container. Format is a single character `[a-Z]` or a comma separated sequence of `ctrl-`, where `` is one of: `a-cf`, `@`, `^`, `[`, `\\`, `]`, `^` or `_`") + _ = cmd.RegisterFlagCompletionFunc(detachKeysFlagName, common.AutocompleteDetachKeys) _ = flags.MarkHidden("signature-policy") if registry.IsRemote() { @@ -77,8 +89,8 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: runCommand, }) - flags := runCommand.Flags() - runFlags(flags) + + runFlags(runCommand) registry.Commands = append(registry.Commands, registry.CliCommand{ Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, @@ -86,8 +98,7 @@ func init() { Parent: containerCmd, }) - containerRunFlags := containerRunCommand.Flags() - runFlags(containerRunFlags) + runFlags(containerRunCommand) } func run(cmd *cobra.Command, args []string) error { diff --git a/cmd/podman/containers/runlabel.go b/cmd/podman/containers/runlabel.go index 92581c26f78d..2f6d2eb0582b 100644 --- a/cmd/podman/containers/runlabel.go +++ b/cmd/podman/containers/runlabel.go @@ -5,7 +5,9 @@ import ( "os" "github.com/containers/common/pkg/auth" + "github.com/containers/common/pkg/completion" "github.com/containers/image/v5/types" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/sirupsen/logrus" @@ -23,11 +25,12 @@ var ( runlabelOptions = runlabelOptionsWrapper{} runlabelDescription = "Executes a command as described by a container image label." runlabelCommand = &cobra.Command{ - Use: "runlabel [options] LABEL IMAGE [ARG...]", - Short: "Execute the command described by an image label", - Long: runlabelDescription, - RunE: runlabel, - Args: cobra.MinimumNArgs(2), + Use: "runlabel [options] LABEL IMAGE [ARG...]", + Short: "Execute the command described by an image label", + Long: runlabelDescription, + RunE: runlabel, + Args: cobra.MinimumNArgs(2), + ValidArgsFunction: common.AutocompleteImages, Example: `podman container runlabel run imageID podman container runlabel install imageID arg1 arg2 podman container runlabel --display run myImage`, @@ -42,11 +45,25 @@ func init() { }) flags := runlabelCommand.Flags() - flags.StringVar(&runlabelOptions.Authfile, "authfile", auth.GetDefaultAuthFile(), "Path of the authentication file. Use REGISTRY_AUTH_FILE environment variable to override") - flags.StringVar(&runlabelOptions.CertDir, "cert-dir", "", "`Pathname` of a directory containing TLS certificates and keys") - flags.StringVar(&runlabelOptions.Credentials, "creds", "", "`Credentials` (USERNAME:PASSWORD) to use for authenticating to a registry") + + authfileflagName := "authfile" + flags.StringVar(&runlabelOptions.Authfile, authfileflagName, auth.GetDefaultAuthFile(), "Path of the authentication file. Use REGISTRY_AUTH_FILE environment variable to override") + _ = runlabelCommand.RegisterFlagCompletionFunc(authfileflagName, completion.AutocompleteDefault) + + certDirFlagName := "cert-dir" + flags.StringVar(&runlabelOptions.CertDir, certDirFlagName, "", "`Pathname` of a directory containing TLS certificates and keys") + _ = runlabelCommand.RegisterFlagCompletionFunc(certDirFlagName, completion.AutocompleteDefault) + + credsFlagName := "creds" + flags.StringVar(&runlabelOptions.Credentials, credsFlagName, "", "`Credentials` (USERNAME:PASSWORD) to use for authenticating to a registry") + _ = runlabelCommand.RegisterFlagCompletionFunc(credsFlagName, completion.AutocompleteNone) + flags.BoolVar(&runlabelOptions.Display, "display", false, "Preview the command that the label would run") - flags.StringVarP(&runlabelOptions.Name, "name", "n", "", "Assign a name to the container") + + nameFlagName := "name" + flags.StringVarP(&runlabelOptions.Name, nameFlagName, "n", "", "Assign a name to the container") + _ = runlabelCommand.RegisterFlagCompletionFunc(nameFlagName, completion.AutocompleteNone) + flags.StringVar(&runlabelOptions.Optional1, "opt1", "", "Optional parameter to pass for install") flags.StringVar(&runlabelOptions.Optional2, "opt2", "", "Optional parameter to pass for install") flags.StringVar(&runlabelOptions.Optional3, "opt3", "", "Optional parameter to pass for install") diff --git a/cmd/podman/containers/start.go b/cmd/podman/containers/start.go index 21f31d3609d9..dba2c3c3e433 100644 --- a/cmd/podman/containers/start.go +++ b/cmd/podman/containers/start.go @@ -4,6 +4,7 @@ import ( "fmt" "os" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" "github.com/containers/podman/v2/cmd/podman/validate" @@ -11,26 +12,27 @@ import ( "github.com/containers/podman/v2/pkg/domain/entities" "github.com/pkg/errors" "github.com/spf13/cobra" - "github.com/spf13/pflag" ) var ( startDescription = `Starts one or more containers. The container name or ID can be used.` startCommand = &cobra.Command{ - Use: "start [options] CONTAINER [CONTAINER...]", - Short: "Start one or more containers", - Long: startDescription, - RunE: start, + Use: "start [options] CONTAINER [CONTAINER...]", + Short: "Start one or more containers", + Long: startDescription, + RunE: start, + ValidArgsFunction: common.AutocompleteContainersStartable, Example: `podman start --latest podman start 860a4b231279 5421ab43b45 podman start --interactive --attach imageID`, } containerStartCommand = &cobra.Command{ - Use: startCommand.Use, - Short: startCommand.Short, - Long: startCommand.Long, - RunE: startCommand.RunE, + Use: startCommand.Use, + Short: startCommand.Short, + Long: startCommand.Long, + RunE: startCommand.RunE, + ValidArgsFunction: startCommand.ValidArgsFunction, Example: `podman container start --latest podman container start 860a4b231279 5421ab43b45 podman container start --interactive --attach imageID`, @@ -41,9 +43,15 @@ var ( startOptions entities.ContainerStartOptions ) -func startFlags(flags *pflag.FlagSet) { +func startFlags(cmd *cobra.Command) { + flags := cmd.Flags() + flags.BoolVarP(&startOptions.Attach, "attach", "a", false, "Attach container's STDOUT and STDERR") - flags.StringVar(&startOptions.DetachKeys, "detach-keys", containerConfig.DetachKeys(), "Select the key sequence for detaching a container. Format is a single character `[a-Z]` or a comma separated sequence of `ctrl-`, where `` is one of: `a-z`, `@`, `^`, `[`, `\\`, `]`, `^` or `_`") + + detachKeysFlagName := "detach-keys" + flags.StringVar(&startOptions.DetachKeys, detachKeysFlagName, containerConfig.DetachKeys(), "Select the key sequence for detaching a container. Format is a single character `[a-Z]` or a comma separated sequence of `ctrl-`, where `` is one of: `a-z`, `@`, `^`, `[`, `\\`, `]`, `^` or `_`") + _ = cmd.RegisterFlagCompletionFunc(detachKeysFlagName, common.AutocompleteDetachKeys) + flags.BoolVarP(&startOptions.Interactive, "interactive", "i", false, "Keep STDIN open even if not attached") flags.BoolVar(&startOptions.SigProxy, "sig-proxy", false, "Proxy received signals to the process (default true if attaching, false otherwise)") @@ -56,7 +64,7 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: startCommand, }) - startFlags(startCommand.Flags()) + startFlags(startCommand) validate.AddLatestFlag(startCommand, &startOptions.Latest) registry.Commands = append(registry.Commands, registry.CliCommand{ @@ -64,9 +72,8 @@ func init() { Command: containerStartCommand, Parent: containerCmd, }) - startFlags(containerStartCommand.Flags()) + startFlags(containerStartCommand) validate.AddLatestFlag(containerStartCommand, &startOptions.Latest) - } func start(cmd *cobra.Command, args []string) error { diff --git a/cmd/podman/containers/stats.go b/cmd/podman/containers/stats.go index bfab469cad8c..ca5c0fdb8627 100644 --- a/cmd/podman/containers/stats.go +++ b/cmd/podman/containers/stats.go @@ -8,6 +8,7 @@ import ( tm "github.com/buger/goterm" "github.com/containers/common/pkg/report" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/parse" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/validate" @@ -20,28 +21,29 @@ import ( "github.com/pkg/errors" "github.com/sirupsen/logrus" "github.com/spf13/cobra" - "github.com/spf13/pflag" ) var ( statsDescription = "Display percentage of CPU, memory, network I/O, block I/O and PIDs for one or more containers." statsCommand = &cobra.Command{ - Use: "stats [options] [CONTAINER...]", - Short: "Display a live stream of container resource usage statistics", - Long: statsDescription, - RunE: stats, - Args: checkStatOptions, + Use: "stats [options] [CONTAINER...]", + Short: "Display a live stream of container resource usage statistics", + Long: statsDescription, + RunE: stats, + Args: checkStatOptions, + ValidArgsFunction: common.AutocompleteContainersRunning, Example: `podman stats --all --no-stream podman stats ctrID podman stats --no-stream --format "table {{.ID}} {{.Name}} {{.MemUsage}}" ctrID`, } containerStatsCommand = &cobra.Command{ - Use: statsCommand.Use, - Short: statsCommand.Short, - Long: statsCommand.Long, - RunE: statsCommand.RunE, - Args: checkStatOptions, + Use: statsCommand.Use, + Short: statsCommand.Short, + Long: statsCommand.Long, + RunE: statsCommand.RunE, + Args: checkStatOptions, + ValidArgsFunction: statsCommand.ValidArgsFunction, Example: `podman container stats --all --no-stream podman container stats ctrID podman container stats --no-stream --format "table {{.ID}} {{.Name}} {{.MemUsage}}" ctrID`, @@ -62,9 +64,15 @@ var ( statsOptions statsOptionsCLI ) -func statFlags(flags *pflag.FlagSet) { +func statFlags(cmd *cobra.Command) { + flags := cmd.Flags() + flags.BoolVarP(&statsOptions.All, "all", "a", false, "Show all containers. Only running containers are shown by default. The default is false") - flags.StringVar(&statsOptions.Format, "format", "", "Pretty-print container statistics to JSON or using a Go template") + + formatFlagName := "format" + flags.StringVar(&statsOptions.Format, formatFlagName, "", "Pretty-print container statistics to JSON or using a Go template") + _ = cmd.RegisterFlagCompletionFunc(formatFlagName, common.AutocompleteJSONFormat) + flags.BoolVar(&statsOptions.NoReset, "no-reset", false, "Disable resetting the screen between intervals") flags.BoolVar(&statsOptions.NoStream, "no-stream", false, "Disable streaming stats and only pull the first result, default setting is false") } @@ -74,7 +82,7 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: statsCommand, }) - statFlags(statsCommand.Flags()) + statFlags(statsCommand) validate.AddLatestFlag(statsCommand, &statsOptions.Latest) registry.Commands = append(registry.Commands, registry.CliCommand{ @@ -82,7 +90,7 @@ func init() { Command: containerStatsCommand, Parent: containerCmd, }) - statFlags(containerStatsCommand.Flags()) + statFlags(containerStatsCommand) validate.AddLatestFlag(containerStatsCommand, &statsOptions.Latest) } diff --git a/cmd/podman/containers/stop.go b/cmd/podman/containers/stop.go index 7c8c1b50e49b..3a4211357aa8 100644 --- a/cmd/podman/containers/stop.go +++ b/cmd/podman/containers/stop.go @@ -4,12 +4,13 @@ import ( "context" "fmt" + "github.com/containers/common/pkg/completion" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" "github.com/containers/podman/v2/cmd/podman/validate" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/spf13/cobra" - "github.com/spf13/pflag" ) var ( @@ -24,6 +25,7 @@ var ( Args: func(cmd *cobra.Command, args []string) error { return validate.CheckAllLatestAndCIDFile(cmd, args, false, true) }, + ValidArgsFunction: common.AutocompleteContainersRunning, Example: `podman stop ctrID podman stop --latest podman stop --time 2 mywebserver 6e534f14da9d`, @@ -37,6 +39,7 @@ var ( Args: func(cmd *cobra.Command, args []string) error { return validate.CheckAllLatestAndCIDFile(cmd, args, false, true) }, + ValidArgsFunction: stopCommand.ValidArgsFunction, Example: `podman container stop ctrID podman container stop --latest podman container stop --time 2 mywebserver 6e534f14da9d`, @@ -48,11 +51,19 @@ var ( stopTimeout uint ) -func stopFlags(flags *pflag.FlagSet) { +func stopFlags(cmd *cobra.Command) { + flags := cmd.Flags() + flags.BoolVarP(&stopOptions.All, "all", "a", false, "Stop all running containers") flags.BoolVarP(&stopOptions.Ignore, "ignore", "i", false, "Ignore errors when a specified container is missing") - flags.StringArrayVarP(&stopOptions.CIDFiles, "cidfile", "", nil, "Read the container ID from the file") - flags.UintVarP(&stopTimeout, "time", "t", containerConfig.Engine.StopTimeout, "Seconds to wait for stop before killing the container") + + cidfileFlagName := "cidfile" + flags.StringArrayVarP(&stopOptions.CIDFiles, cidfileFlagName, "", nil, "Read the container ID from the file") + _ = cmd.RegisterFlagCompletionFunc(cidfileFlagName, completion.AutocompleteDefault) + + timeFlagName := "time" + flags.UintVarP(&stopTimeout, timeFlagName, "t", containerConfig.Engine.StopTimeout, "Seconds to wait for stop before killing the container") + _ = cmd.RegisterFlagCompletionFunc(timeFlagName, completion.AutocompleteNone) if registry.IsRemote() { _ = flags.MarkHidden("cidfile") @@ -66,7 +77,7 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: stopCommand, }) - stopFlags(stopCommand.Flags()) + stopFlags(stopCommand) validate.AddLatestFlag(stopCommand, &stopOptions.Latest) registry.Commands = append(registry.Commands, registry.CliCommand{ @@ -74,8 +85,7 @@ func init() { Command: containerStopCommand, Parent: containerCmd, }) - - stopFlags(containerStopCommand.Flags()) + stopFlags(containerStopCommand) validate.AddLatestFlag(containerStopCommand, &stopOptions.Latest) } diff --git a/cmd/podman/containers/top.go b/cmd/podman/containers/top.go index 361d30516df5..3eb6d2af28f6 100644 --- a/cmd/podman/containers/top.go +++ b/cmd/podman/containers/top.go @@ -7,6 +7,7 @@ import ( "strings" "text/tabwriter" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/validate" "github.com/containers/podman/v2/pkg/domain/entities" @@ -26,11 +27,12 @@ var ( topOptions = entities.TopOptions{} topCommand = &cobra.Command{ - Use: "top [options] CONTAINER [FORMAT-DESCRIPTORS|ARGS...]", - Short: "Display the running processes of a container", - Long: topDescription, - RunE: top, - Args: cobra.ArbitraryArgs, + Use: "top [options] CONTAINER [FORMAT-DESCRIPTORS|ARGS...]", + Short: "Display the running processes of a container", + Long: topDescription, + RunE: top, + Args: cobra.ArbitraryArgs, + ValidArgsFunction: common.AutocompleteContainersRunning, Example: `podman top ctrID podman top --latest podman top ctrID pid seccomp args %C @@ -38,10 +40,11 @@ podman top ctrID -eo user,pid,comm`, } containerTopCommand = &cobra.Command{ - Use: topCommand.Use, - Short: topCommand.Short, - Long: topCommand.Long, - RunE: topCommand.RunE, + Use: topCommand.Use, + Short: topCommand.Short, + Long: topCommand.Long, + RunE: topCommand.RunE, + ValidArgsFunction: topCommand.ValidArgsFunction, Example: `podman container top ctrID podman container top --latest podman container top ctrID pid seccomp args %C diff --git a/cmd/podman/containers/unmount.go b/cmd/podman/containers/unmount.go index c3159cfed66c..22e0768e3852 100644 --- a/cmd/podman/containers/unmount.go +++ b/cmd/podman/containers/unmount.go @@ -3,6 +3,7 @@ package containers import ( "fmt" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" "github.com/containers/podman/v2/cmd/podman/validate" @@ -27,6 +28,7 @@ var ( Args: func(cmd *cobra.Command, args []string) error { return validate.CheckAllLatestAndCIDFile(cmd, args, false, false) }, + ValidArgsFunction: common.AutocompleteContainers, Example: `podman unmount ctrID podman unmount ctrID1 ctrID2 ctrID3 podman unmount --all`, @@ -41,6 +43,7 @@ var ( Args: func(cmd *cobra.Command, args []string) error { return validate.CheckAllLatestAndCIDFile(cmd, args, false, false) }, + ValidArgsFunction: common.AutocompleteContainers, Example: `podman container unmount ctrID podman container unmount ctrID1 ctrID2 ctrID3 podman container unmount --all`, diff --git a/cmd/podman/containers/unpause.go b/cmd/podman/containers/unpause.go index 8927fc426cbc..0e8b5919224e 100644 --- a/cmd/podman/containers/unpause.go +++ b/cmd/podman/containers/unpause.go @@ -4,6 +4,7 @@ import ( "context" "fmt" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" "github.com/containers/podman/v2/pkg/cgroups" @@ -17,20 +18,22 @@ import ( var ( unpauseDescription = `Unpauses one or more previously paused containers. The container name or ID can be used.` unpauseCommand = &cobra.Command{ - Use: "unpause [options] CONTAINER [CONTAINER...]", - Short: "Unpause the processes in one or more containers", - Long: unpauseDescription, - RunE: unpause, + Use: "unpause [options] CONTAINER [CONTAINER...]", + Short: "Unpause the processes in one or more containers", + Long: unpauseDescription, + RunE: unpause, + ValidArgsFunction: common.AutocompleteContainersPaused, Example: `podman unpause ctrID podman unpause --all`, } unPauseOptions = entities.PauseUnPauseOptions{} containerUnpauseCommand = &cobra.Command{ - Use: unpauseCommand.Use, - Short: unpauseCommand.Short, - Long: unpauseCommand.Long, - RunE: unpauseCommand.RunE, + Use: unpauseCommand.Use, + Short: unpauseCommand.Short, + Long: unpauseCommand.Long, + RunE: unpauseCommand.RunE, + ValidArgsFunction: unpauseCommand.ValidArgsFunction, Example: `podman container unpause ctrID podman container unpause --all`, } diff --git a/cmd/podman/containers/wait.go b/cmd/podman/containers/wait.go index b4986143b97f..2bbfbccc9ec1 100644 --- a/cmd/podman/containers/wait.go +++ b/cmd/podman/containers/wait.go @@ -5,6 +5,8 @@ import ( "fmt" "time" + "github.com/containers/common/pkg/completion" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" "github.com/containers/podman/v2/cmd/podman/validate" @@ -12,26 +14,27 @@ import ( "github.com/containers/podman/v2/pkg/domain/entities" "github.com/pkg/errors" "github.com/spf13/cobra" - "github.com/spf13/pflag" ) var ( waitDescription = `Block until one or more containers stop and then print their exit codes. ` waitCommand = &cobra.Command{ - Use: "wait [options] CONTAINER [CONTAINER...]", - Short: "Block on one or more containers", - Long: waitDescription, - RunE: wait, + Use: "wait [options] CONTAINER [CONTAINER...]", + Short: "Block on one or more containers", + Long: waitDescription, + RunE: wait, + ValidArgsFunction: common.AutocompleteContainers, Example: `podman wait --interval 5s ctrID podman wait ctrID1 ctrID2`, } containerWaitCommand = &cobra.Command{ - Use: waitCommand.Use, - Short: waitCommand.Short, - Long: waitCommand.Long, - RunE: waitCommand.RunE, + Use: waitCommand.Use, + Short: waitCommand.Short, + Long: waitCommand.Long, + RunE: waitCommand.RunE, + ValidArgsFunction: waitCommand.ValidArgsFunction, Example: `podman container wait --interval 5s ctrID podman container wait ctrID1 ctrID2`, } @@ -43,9 +46,17 @@ var ( waitInterval string ) -func waitFlags(flags *pflag.FlagSet) { - flags.StringVarP(&waitInterval, "interval", "i", "250ns", "Time Interval to wait before polling for completion") - flags.StringVar(&waitCondition, "condition", "stopped", "Condition to wait on") +func waitFlags(cmd *cobra.Command) { + flags := cmd.Flags() + + intervalFlagName := "interval" + flags.StringVarP(&waitInterval, intervalFlagName, "i", "250ns", "Time Interval to wait before polling for completion") + _ = cmd.RegisterFlagCompletionFunc(intervalFlagName, completion.AutocompleteNone) + + conditionFlagName := "condition" + flags.StringVar(&waitCondition, conditionFlagName, "stopped", "Condition to wait on") + _ = cmd.RegisterFlagCompletionFunc(conditionFlagName, common.AutocompleteWaitCondition) + } func init() { @@ -53,7 +64,7 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: waitCommand, }) - waitFlags(waitCommand.Flags()) + waitFlags(waitCommand) validate.AddLatestFlag(waitCommand, &waitOptions.Latest) registry.Commands = append(registry.Commands, registry.CliCommand{ @@ -61,9 +72,8 @@ func init() { Command: containerWaitCommand, Parent: containerCmd, }) - waitFlags(containerWaitCommand.Flags()) + waitFlags(containerWaitCommand) validate.AddLatestFlag(containerWaitCommand, &waitOptions.Latest) - } func wait(cmd *cobra.Command, args []string) error { diff --git a/cmd/podman/diff.go b/cmd/podman/diff.go index bad31a4a220d..5e6abe2437f7 100644 --- a/cmd/podman/diff.go +++ b/cmd/podman/diff.go @@ -3,6 +3,7 @@ package main import ( "fmt" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/containers" "github.com/containers/podman/v2/cmd/podman/images" "github.com/containers/podman/v2/cmd/podman/registry" @@ -17,11 +18,12 @@ var ( // Command: podman _diff_ Object_ID diffDescription = `Displays changes on a container or image's filesystem. The container or image will be compared to its parent layer.` diffCmd = &cobra.Command{ - Use: "diff [options] {CONTAINER_ID | IMAGE_ID}", - Args: validate.IDOrLatestArgs, - Short: "Display the changes to the object's file system", - Long: diffDescription, - RunE: diff, + Use: "diff [options] {CONTAINER_ID | IMAGE_ID}", + Args: validate.IDOrLatestArgs, + Short: "Display the changes to the object's file system", + Long: diffDescription, + RunE: diff, + ValidArgsFunction: common.AutocompleteContainersAndImages, Example: `podman diff imageID podman diff ctrID podman diff --format json redis:alpine`, @@ -38,7 +40,11 @@ func init() { flags := diffCmd.Flags() flags.BoolVar(&diffOpts.Archive, "archive", true, "Save the diff as a tar archive") _ = flags.MarkHidden("archive") - flags.StringVar(&diffOpts.Format, "format", "", "Change the output format") + + formatFlagName := "format" + flags.StringVar(&diffOpts.Format, formatFlagName, "", "Change the output format") + _ = diffCmd.RegisterFlagCompletionFunc(formatFlagName, common.AutocompleteJSONFormat) + validate.AddLatestFlag(diffCmd, &diffOpts.Latest) } diff --git a/cmd/podman/generate/kube.go b/cmd/podman/generate/kube.go index 87f7501e395f..e47bd35b5e00 100644 --- a/cmd/podman/generate/kube.go +++ b/cmd/podman/generate/kube.go @@ -5,6 +5,8 @@ import ( "io/ioutil" "os" + "github.com/containers/common/pkg/completion" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" "github.com/containers/podman/v2/pkg/domain/entities" @@ -20,11 +22,12 @@ var ( Whether the input is for a container or pod, Podman will always generate the specification as a pod.` kubeCmd = &cobra.Command{ - Use: "kube [options] CONTAINER | POD", - Short: "Generate Kubernetes YAML from a container or pod.", - Long: kubeDescription, - RunE: kube, - Args: cobra.ExactArgs(1), + Use: "kube [options] CONTAINER | POD", + Short: "Generate Kubernetes YAML from a container or pod.", + Long: kubeDescription, + RunE: kube, + Args: cobra.ExactArgs(1), + ValidArgsFunction: common.AutocompleteContainersAndPods, Example: `podman generate kube ctrID podman generate kube podID podman generate kube --service podID`, @@ -39,7 +42,11 @@ func init() { }) flags := kubeCmd.Flags() flags.BoolVarP(&kubeOptions.Service, "service", "s", false, "Generate YAML for a Kubernetes service object") - flags.StringVarP(&kubeFile, "filename", "f", "", "Write output to the specified path") + + filenameFlagName := "filename" + flags.StringVarP(&kubeFile, filenameFlagName, "f", "", "Write output to the specified path") + _ = kubeCmd.RegisterFlagCompletionFunc(filenameFlagName, completion.AutocompleteDefault) + flags.SetNormalizeFunc(utils.AliasFlags) } diff --git a/cmd/podman/generate/systemd.go b/cmd/podman/generate/systemd.go index 8e937fa90e16..e9cf76aae642 100644 --- a/cmd/podman/generate/systemd.go +++ b/cmd/podman/generate/systemd.go @@ -6,7 +6,9 @@ import ( "os" "path/filepath" + "github.com/containers/common/pkg/completion" "github.com/containers/common/pkg/report" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" "github.com/containers/podman/v2/pkg/domain/entities" @@ -24,11 +26,12 @@ var ( The generated units can later be controlled via systemctl(1).` systemdCmd = &cobra.Command{ - Use: "systemd [options] CTR|POD", - Short: "Generate systemd units.", - Long: systemdDescription, - RunE: systemd, - Args: cobra.ExactArgs(1), + Use: "systemd [options] CTR|POD", + Short: "Generate systemd units.", + Long: systemdDescription, + RunE: systemd, + Args: cobra.ExactArgs(1), + ValidArgsFunction: common.AutocompleteContainersAndPods, Example: `podman generate systemd CTR podman generate systemd --new --time 10 CTR podman generate systemd --files --name POD`, @@ -44,13 +47,32 @@ func init() { flags := systemdCmd.Flags() flags.BoolVarP(&systemdOptions.Name, "name", "n", false, "Use container/pod names instead of IDs") flags.BoolVarP(&files, "files", "f", false, "Generate .service files instead of printing to stdout") - flags.UintVarP(&systemdTimeout, "time", "t", containerConfig.Engine.StopTimeout, "Stop timeout override") - flags.StringVar(&systemdOptions.RestartPolicy, "restart-policy", "on-failure", "Systemd restart-policy") + + timeFlagName := "time" + flags.UintVarP(&systemdTimeout, timeFlagName, "t", containerConfig.Engine.StopTimeout, "Stop timeout override") + _ = systemdCmd.RegisterFlagCompletionFunc(timeFlagName, completion.AutocompleteNone) flags.BoolVarP(&systemdOptions.New, "new", "", false, "Create a new container instead of starting an existing one") - flags.StringVar(&systemdOptions.ContainerPrefix, "container-prefix", "container", "Systemd unit name prefix for containers") - flags.StringVar(&systemdOptions.PodPrefix, "pod-prefix", "pod", "Systemd unit name prefix for pods") - flags.StringVar(&systemdOptions.Separator, "separator", "-", "Systemd unit name separator between name/id and prefix") - flags.StringVar(&format, "format", "", "Print the created units in specified format (json)") + + containerPrefixFlagName := "container-prefix" + flags.StringVar(&systemdOptions.ContainerPrefix, containerPrefixFlagName, "container", "Systemd unit name prefix for containers") + _ = systemdCmd.RegisterFlagCompletionFunc(containerPrefixFlagName, completion.AutocompleteNone) + + podPrefixFlagName := "pod-prefix" + flags.StringVar(&systemdOptions.PodPrefix, podPrefixFlagName, "pod", "Systemd unit name prefix for pods") + _ = systemdCmd.RegisterFlagCompletionFunc(podPrefixFlagName, completion.AutocompleteNone) + + separatorFlagName := "separator" + flags.StringVar(&systemdOptions.Separator, separatorFlagName, "-", "Systemd unit name separator between name/id and prefix") + _ = systemdCmd.RegisterFlagCompletionFunc(separatorFlagName, completion.AutocompleteNone) + + restartPolicyFlagName := "restart-policy" + flags.StringVar(&systemdOptions.RestartPolicy, restartPolicyFlagName, "on-failure", "Systemd restart-policy") + _ = systemdCmd.RegisterFlagCompletionFunc(restartPolicyFlagName, common.AutocompleteSystemdRestartOptions) + + formatFlagName := "format" + flags.StringVar(&format, formatFlagName, "", "Print the created units in specified format (json)") + _ = systemdCmd.RegisterFlagCompletionFunc(formatFlagName, common.AutocompleteJSONFormat) + flags.SetNormalizeFunc(utils.AliasFlags) } diff --git a/cmd/podman/healthcheck/run.go b/cmd/podman/healthcheck/run.go index 6d7f0b548e22..b4331d04e16d 100644 --- a/cmd/podman/healthcheck/run.go +++ b/cmd/podman/healthcheck/run.go @@ -4,6 +4,7 @@ import ( "context" "fmt" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/spf13/cobra" @@ -18,6 +19,7 @@ var ( Example: `podman healthcheck run mywebapp`, RunE: run, Args: cobra.ExactArgs(1), + ValidArgsFunction: common.AutocompleteContainersRunning, DisableFlagsInUseLine: true, } ) diff --git a/cmd/podman/images/build.go b/cmd/podman/images/build.go index ccae252767fb..c76e4ac80c34 100644 --- a/cmd/podman/images/build.go +++ b/cmd/podman/images/build.go @@ -9,6 +9,7 @@ import ( "github.com/containers/buildah/imagebuildah" buildahCLI "github.com/containers/buildah/pkg/cli" "github.com/containers/buildah/pkg/parse" + "github.com/containers/common/pkg/completion" "github.com/containers/common/pkg/config" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" @@ -17,7 +18,6 @@ import ( "github.com/pkg/errors" "github.com/sirupsen/logrus" "github.com/spf13/cobra" - "github.com/spf13/pflag" ) // buildFlagsWrapper are local to cmd/ as the build code is using Buildah-internal @@ -39,22 +39,24 @@ var ( // Command: podman _diff_ Object_ID buildDescription = "Builds an OCI or Docker image using instructions from one or more Containerfiles and a specified build context directory." buildCmd = &cobra.Command{ - Use: "build [options] [CONTEXT]", - Short: "Build an image using instructions from Containerfiles", - Long: buildDescription, - Args: cobra.MaximumNArgs(1), - RunE: build, + Use: "build [options] [CONTEXT]", + Short: "Build an image using instructions from Containerfiles", + Long: buildDescription, + Args: cobra.MaximumNArgs(1), + RunE: build, + ValidArgsFunction: completion.AutocompleteDefault, Example: `podman build . podman build --creds=username:password -t imageName -f Containerfile.simple . podman build --layers --force-rm --tag imageName .`, } imageBuildCmd = &cobra.Command{ - Args: buildCmd.Args, - Use: buildCmd.Use, - Short: buildCmd.Short, - Long: buildCmd.Long, - RunE: buildCmd.RunE, + Args: buildCmd.Args, + Use: buildCmd.Use, + Short: buildCmd.Short, + Long: buildCmd.Long, + RunE: buildCmd.RunE, + ValidArgsFunction: buildCmd.ValidArgsFunction, Example: `podman image build . podman image build --creds=username:password -t imageName -f Containerfile.simple . podman image build --layers --force-rm --tag imageName .`, @@ -78,22 +80,25 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: buildCmd, }) - buildFlags(buildCmd.Flags()) + buildFlags(buildCmd) registry.Commands = append(registry.Commands, registry.CliCommand{ Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: imageBuildCmd, Parent: imageCmd, }) - buildFlags(imageBuildCmd.Flags()) + buildFlags(imageBuildCmd) } -func buildFlags(flags *pflag.FlagSet) { +func buildFlags(cmd *cobra.Command) { + flags := cmd.Flags() + // Podman flags flags.BoolVarP(&buildOpts.SquashAll, "squash-all", "", false, "Squash all layers into a single layer") // Bud flags budFlags := buildahCLI.GetBudFlags(&buildOpts.BudResults) + // --pull flag flag := budFlags.Lookup("pull") if err := flag.Value.Set("true"); err != nil { @@ -101,6 +106,9 @@ func buildFlags(flags *pflag.FlagSet) { } flag.DefValue = "true" flags.AddFlagSet(&budFlags) + // Add the completion functions + budCompletions := buildahCLI.GetBudFlagsCompletions() + completion.CompleteCommandFlags(cmd, budCompletions) // Layer flags layerFlags := buildahCLI.GetLayerFlags(&buildOpts.LayerResults) @@ -126,6 +134,9 @@ func buildFlags(flags *pflag.FlagSet) { os.Exit(1) } flags.AddFlagSet(&fromAndBudFlags) + // Add the completion functions + fromAndBudFlagsCompletions := buildahCLI.GetFromAndBudFlagsCompletions() + completion.CompleteCommandFlags(cmd, fromAndBudFlagsCompletions) _ = flags.MarkHidden("signature-policy") flags.SetNormalizeFunc(buildahCLI.AliasFlags) } diff --git a/cmd/podman/images/diff.go b/cmd/podman/images/diff.go index b7722e5e518a..71793c70731e 100644 --- a/cmd/podman/images/diff.go +++ b/cmd/podman/images/diff.go @@ -13,11 +13,12 @@ import ( var ( // podman container _inspect_ diffCmd = &cobra.Command{ - Use: "diff [options] IMAGE", - Args: cobra.ExactArgs(1), - Short: "Inspect changes to the image's file systems", - Long: `Displays changes to the image's filesystem. The image will be compared to its parent layer.`, - RunE: diff, + Use: "diff [options] IMAGE", + Args: cobra.ExactArgs(1), + Short: "Inspect changes to the image's file systems", + Long: `Displays changes to the image's filesystem. The image will be compared to its parent layer.`, + RunE: diff, + ValidArgsFunction: common.AutocompleteImages, Example: `podman image diff myImage podman image diff --format json redis:alpine`, } @@ -37,7 +38,10 @@ func diffFlags(flags *pflag.FlagSet) { diffOpts = &entities.DiffOptions{} flags.BoolVar(&diffOpts.Archive, "archive", true, "Save the diff as a tar archive") _ = flags.MarkDeprecated("archive", "Provided for backwards compatibility, has no impact on output.") - flags.StringVar(&diffOpts.Format, "format", "", "Change the output format") + + formatFlagName := "format" + flags.StringVar(&diffOpts.Format, formatFlagName, "", "Change the output format") + _ = diffCmd.RegisterFlagCompletionFunc(formatFlagName, common.AutocompleteJSONFormat) } func diff(cmd *cobra.Command, args []string) error { diff --git a/cmd/podman/images/exists.go b/cmd/podman/images/exists.go index 31bdc791e9d7..cb1ca029511f 100644 --- a/cmd/podman/images/exists.go +++ b/cmd/podman/images/exists.go @@ -1,6 +1,7 @@ package images import ( + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/spf13/cobra" @@ -8,11 +9,12 @@ import ( var ( existsCmd = &cobra.Command{ - Use: "exists IMAGE", - Short: "Check if an image exists in local storage", - Long: `If the named image exists in local storage, podman image exists exits with 0, otherwise the exit code will be 1.`, - Args: cobra.ExactArgs(1), - RunE: exists, + Use: "exists IMAGE", + Short: "Check if an image exists in local storage", + Long: `If the named image exists in local storage, podman image exists exits with 0, otherwise the exit code will be 1.`, + Args: cobra.ExactArgs(1), + RunE: exists, + ValidArgsFunction: common.AutocompleteImages, Example: `podman image exists ID podman image exists IMAGE && podman pull IMAGE`, DisableFlagsInUseLine: true, diff --git a/cmd/podman/images/history.go b/cmd/podman/images/history.go index e9751b3657d5..964c7a975244 100644 --- a/cmd/podman/images/history.go +++ b/cmd/podman/images/history.go @@ -11,13 +11,13 @@ import ( "unicode" "github.com/containers/common/pkg/report" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/parse" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/docker/go-units" "github.com/pkg/errors" "github.com/spf13/cobra" - "github.com/spf13/pflag" ) var ( @@ -27,21 +27,23 @@ var ( // podman _history_ historyCmd = &cobra.Command{ - Use: "history [options] IMAGE", - Short: "Show history of a specified image", - Long: long, - Args: cobra.ExactArgs(1), - RunE: history, - Example: "podman history quay.io/fedora/fedora", + Use: "history [options] IMAGE", + Short: "Show history of a specified image", + Long: long, + Args: cobra.ExactArgs(1), + RunE: history, + ValidArgsFunction: common.AutocompleteImages, + Example: "podman history quay.io/fedora/fedora", } imageHistoryCmd = &cobra.Command{ - Args: historyCmd.Args, - Use: historyCmd.Use, - Short: historyCmd.Short, - Long: historyCmd.Long, - RunE: historyCmd.RunE, - Example: `podman image history quay.io/fedora/fedora`, + Args: historyCmd.Args, + Use: historyCmd.Use, + Short: historyCmd.Short, + Long: historyCmd.Long, + ValidArgsFunction: historyCmd.ValidArgsFunction, + RunE: historyCmd.RunE, + Example: `podman image history quay.io/fedora/fedora`, } opts = struct { @@ -57,18 +59,23 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: historyCmd, }) - historyFlags(historyCmd.Flags()) + historyFlags(historyCmd) registry.Commands = append(registry.Commands, registry.CliCommand{ Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: imageHistoryCmd, Parent: imageCmd, }) - historyFlags(imageHistoryCmd.Flags()) + historyFlags(imageHistoryCmd) } -func historyFlags(flags *pflag.FlagSet) { - flags.StringVar(&opts.format, "format", "", "Change the output to JSON or a Go template") +func historyFlags(cmd *cobra.Command) { + flags := cmd.Flags() + + formatFlagName := "format" + flags.StringVar(&opts.format, formatFlagName, "", "Change the output to JSON or a Go template") + _ = cmd.RegisterFlagCompletionFunc(formatFlagName, common.AutocompleteJSONFormat) + flags.BoolVarP(&opts.human, "human", "H", true, "Display sizes and dates in human readable format") flags.BoolVar(&opts.noTrunc, "no-trunc", false, "Do not truncate the output") flags.BoolVar(&opts.noTrunc, "notruncate", false, "Do not truncate the output") diff --git a/cmd/podman/images/images.go b/cmd/podman/images/images.go index 14ea010470c3..499bfd2ad0a5 100644 --- a/cmd/podman/images/images.go +++ b/cmd/podman/images/images.go @@ -16,6 +16,7 @@ var ( Short: listCmd.Short, Long: listCmd.Long, RunE: listCmd.RunE, + ValidArgsFunction: listCmd.ValidArgsFunction, Example: strings.Replace(listCmd.Example, "podman image list", "podman images", -1), DisableFlagsInUseLine: true, } @@ -27,5 +28,5 @@ func init() { Command: imagesCmd, }) - imageListFlagSet(imagesCmd.Flags()) + imageListFlagSet(imagesCmd) } diff --git a/cmd/podman/images/import.go b/cmd/podman/images/import.go index e3545da69a40..f38ab3b19e17 100644 --- a/cmd/podman/images/import.go +++ b/cmd/podman/images/import.go @@ -3,14 +3,16 @@ package images import ( "context" "fmt" + "strings" + "github.com/containers/common/pkg/completion" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/parse" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/hashicorp/go-multierror" "github.com/pkg/errors" "github.com/spf13/cobra" - "github.com/spf13/pflag" ) var ( @@ -19,21 +21,23 @@ var ( Note remote tar balls can be specified, via web address. Optionally tag the image. You can specify the instructions using the --change option.` importCommand = &cobra.Command{ - Use: "import [options] PATH [REFERENCE]", - Short: "Import a tarball to create a filesystem image", - Long: importDescription, - RunE: importCon, + Use: "import [options] PATH [REFERENCE]", + Short: "Import a tarball to create a filesystem image", + Long: importDescription, + RunE: importCon, + ValidArgsFunction: completion.AutocompleteDefault, Example: `podman import http://example.com/ctr.tar url-image cat ctr.tar | podman -q import --message "importing the ctr.tar tarball" - image-imported cat ctr.tar | podman import -`, } imageImportCommand = &cobra.Command{ - Args: cobra.MinimumNArgs(1), - Use: importCommand.Use, - Short: importCommand.Short, - Long: importCommand.Long, - RunE: importCommand.RunE, + Args: cobra.MinimumNArgs(1), + Use: importCommand.Use, + Short: importCommand.Short, + Long: importCommand.Long, + RunE: importCommand.RunE, + ValidArgsFunction: importCommand.ValidArgsFunction, Example: `podman image import http://example.com/ctr.tar url-image cat ctr.tar | podman -q image import --message "importing the ctr.tar tarball" - image-imported cat ctr.tar | podman image import -`, @@ -49,19 +53,27 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: importCommand, }) - importFlags(importCommand.Flags()) + importFlags(importCommand) registry.Commands = append(registry.Commands, registry.CliCommand{ Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: imageImportCommand, Parent: imageCmd, }) - importFlags(imageImportCommand.Flags()) + importFlags(imageImportCommand) } -func importFlags(flags *pflag.FlagSet) { - flags.StringArrayVarP(&importOpts.Changes, "change", "c", []string{}, "Apply the following possible instructions to the created image (default []): CMD | ENTRYPOINT | ENV | EXPOSE | LABEL | STOPSIGNAL | USER | VOLUME | WORKDIR") - flags.StringVarP(&importOpts.Message, "message", "m", "", "Set commit message for imported image") +func importFlags(cmd *cobra.Command) { + flags := cmd.Flags() + + changeFlagName := "change" + flags.StringArrayVarP(&importOpts.Changes, changeFlagName, "c", []string{}, "Apply the following possible instructions to the created image (default []): "+strings.Join(common.ChangeCmds, " | ")) + _ = cmd.RegisterFlagCompletionFunc(changeFlagName, common.AutocompleteChangeInstructions) + + messageFlagName := "message" + flags.StringVarP(&importOpts.Message, messageFlagName, "m", "", "Set commit message for imported image") + _ = cmd.RegisterFlagCompletionFunc(messageFlagName, completion.AutocompleteNone) + flags.BoolVarP(&importOpts.Quiet, "quiet", "q", false, "Suppress output") flags.StringVar(&importOpts.SignaturePolicy, "signature-policy", "", "Path to a signature-policy file") _ = flags.MarkHidden("signature-policy") diff --git a/cmd/podman/images/inspect.go b/cmd/podman/images/inspect.go index 8f005553d3c3..488f037604e2 100644 --- a/cmd/podman/images/inspect.go +++ b/cmd/podman/images/inspect.go @@ -1,6 +1,7 @@ package images import ( + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/inspect" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/domain/entities" @@ -10,10 +11,11 @@ import ( var ( // Command: podman image _inspect_ inspectCmd = &cobra.Command{ - Use: "inspect [options] IMAGE [IMAGE...]", - Short: "Display the configuration of an image", - Long: `Displays the low-level information of an image identified by name or ID.`, - RunE: inspectExec, + Use: "inspect [options] IMAGE [IMAGE...]", + Short: "Display the configuration of an image", + Long: `Displays the low-level information of an image identified by name or ID.`, + RunE: inspectExec, + ValidArgsFunction: common.AutocompleteImages, Example: `podman inspect alpine podman inspect --format "imageId: {{.Id}} size: {{.Size}}" alpine podman inspect --format "image: {{.ImageName}} driver: {{.Driver}}" myctr`, @@ -29,7 +31,10 @@ func init() { }) inspectOpts = new(entities.InspectOptions) flags := inspectCmd.Flags() - flags.StringVarP(&inspectOpts.Format, "format", "f", "json", "Format the output to a Go template or json") + + formatFlagName := "format" + flags.StringVarP(&inspectOpts.Format, formatFlagName, "f", "json", "Format the output to a Go template or json") + _ = inspectCmd.RegisterFlagCompletionFunc(formatFlagName, common.AutocompleteJSONFormat) } func inspectExec(cmd *cobra.Command, args []string) error { diff --git a/cmd/podman/images/list.go b/cmd/podman/images/list.go index e24631b2403c..4692699f2458 100644 --- a/cmd/podman/images/list.go +++ b/cmd/podman/images/list.go @@ -10,15 +10,16 @@ import ( "time" "unicode" + "github.com/containers/common/pkg/completion" "github.com/containers/common/pkg/report" "github.com/containers/image/v5/docker/reference" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/parse" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/docker/go-units" "github.com/pkg/errors" "github.com/spf13/cobra" - "github.com/spf13/pflag" ) type listFlagType struct { @@ -35,12 +36,13 @@ type listFlagType struct { var ( // Command: podman image _list_ listCmd = &cobra.Command{ - Use: "list [options] [IMAGE]", - Aliases: []string{"ls"}, - Args: cobra.MaximumNArgs(1), - Short: "List images in local storage", - Long: "Lists images previously pulled to the system or created on the system.", - RunE: images, + Use: "list [options] [IMAGE]", + Aliases: []string{"ls"}, + Args: cobra.MaximumNArgs(1), + Short: "List images in local storage", + Long: "Lists images previously pulled to the system or created on the system.", + RunE: images, + ValidArgsFunction: common.AutocompleteImages, Example: `podman image list --format json podman image list --sort repository --format "table {{.ID}} {{.Repository}} {{.Tag}}" podman image list --filter dangling=true`, @@ -67,18 +69,32 @@ func init() { Command: listCmd, Parent: imageCmd, }) - imageListFlagSet(listCmd.Flags()) + imageListFlagSet(listCmd) } -func imageListFlagSet(flags *pflag.FlagSet) { +func imageListFlagSet(cmd *cobra.Command) { + flags := cmd.Flags() + flags.BoolVarP(&listOptions.All, "all", "a", false, "Show all images (default hides intermediate images)") - flags.StringSliceVarP(&listOptions.Filter, "filter", "f", []string{}, "Filter output based on conditions provided (default [])") - flags.StringVar(&listFlag.format, "format", "", "Change the output format to JSON or a Go template") + + filterFlagName := "filter" + flags.StringSliceVarP(&listOptions.Filter, filterFlagName, "f", []string{}, "Filter output based on conditions provided (default [])") + // TODO: add completion function for filters + _ = cmd.RegisterFlagCompletionFunc(filterFlagName, completion.AutocompleteNone) + + formatFlagName := "format" + flags.StringVar(&listFlag.format, formatFlagName, "", "Change the output format to JSON or a Go template") + _ = cmd.RegisterFlagCompletionFunc(formatFlagName, common.AutocompleteJSONFormat) + flags.BoolVar(&listFlag.digests, "digests", false, "Show digests") flags.BoolVarP(&listFlag.noHeading, "noheading", "n", false, "Do not print column headings") flags.BoolVar(&listFlag.noTrunc, "no-trunc", false, "Do not truncate output") flags.BoolVarP(&listFlag.quiet, "quiet", "q", false, "Display only image IDs") - flags.StringVar(&listFlag.sort, "sort", "created", "Sort by "+sortFields.String()) + + sortFlagName := "sort" + flags.StringVar(&listFlag.sort, sortFlagName, "created", "Sort by "+sortFields.String()) + _ = cmd.RegisterFlagCompletionFunc(sortFlagName, completion.AutocompleteNone) + flags.BoolVarP(&listFlag.history, "history", "", false, "Display the image name history") } diff --git a/cmd/podman/images/load.go b/cmd/podman/images/load.go index 02f1b3b394d9..a7884f4c5de4 100644 --- a/cmd/podman/images/load.go +++ b/cmd/podman/images/load.go @@ -8,6 +8,7 @@ import ( "os" "strings" + "github.com/containers/common/pkg/completion" "github.com/containers/image/v5/docker/reference" "github.com/containers/podman/v2/cmd/podman/parse" "github.com/containers/podman/v2/cmd/podman/registry" @@ -15,26 +16,27 @@ import ( "github.com/containers/podman/v2/pkg/util" "github.com/pkg/errors" "github.com/spf13/cobra" - "github.com/spf13/pflag" "golang.org/x/crypto/ssh/terminal" ) var ( loadDescription = "Loads an image from a locally stored archive (tar file) into container storage." loadCommand = &cobra.Command{ - Use: "load [options] [NAME[:TAG]]", - Short: "Load an image from container archive", - Long: loadDescription, - RunE: load, - Args: cobra.MaximumNArgs(1), + Use: "load [options] [NAME[:TAG]]", + Short: "Load an image from container archive", + Long: loadDescription, + RunE: load, + Args: cobra.MaximumNArgs(1), + ValidArgsFunction: completion.AutocompleteNone, } imageLoadCommand = &cobra.Command{ - Args: loadCommand.Args, - Use: loadCommand.Use, - Short: loadCommand.Short, - Long: loadCommand.Long, - RunE: loadCommand.RunE, + Args: loadCommand.Args, + Use: loadCommand.Use, + Short: loadCommand.Short, + Long: loadCommand.Long, + ValidArgsFunction: loadCommand.ValidArgsFunction, + RunE: loadCommand.RunE, } ) @@ -47,17 +49,22 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: loadCommand, }) - loadFlags(loadCommand.Flags()) + loadFlags(loadCommand) registry.Commands = append(registry.Commands, registry.CliCommand{ Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: imageLoadCommand, Parent: imageCmd, }) - loadFlags(imageLoadCommand.Flags()) + loadFlags(imageLoadCommand) } -func loadFlags(flags *pflag.FlagSet) { - flags.StringVarP(&loadOpts.Input, "input", "i", "", "Read from specified archive file (default: stdin)") +func loadFlags(cmd *cobra.Command) { + flags := cmd.Flags() + + inputFlagName := "input" + flags.StringVarP(&loadOpts.Input, inputFlagName, "i", "", "Read from specified archive file (default: stdin)") + _ = cmd.RegisterFlagCompletionFunc(inputFlagName, completion.AutocompleteDefault) + flags.BoolVarP(&loadOpts.Quiet, "quiet", "q", false, "Suppress the output") flags.StringVar(&loadOpts.SignaturePolicy, "signature-policy", "", "Pathname of signature policy file") _ = flags.MarkHidden("signature-policy") diff --git a/cmd/podman/images/mount.go b/cmd/podman/images/mount.go index 28e9264ee7a2..1eac59ef904d 100644 --- a/cmd/podman/images/mount.go +++ b/cmd/podman/images/mount.go @@ -7,12 +7,12 @@ import ( "text/template" "github.com/containers/common/pkg/report" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/pkg/errors" "github.com/spf13/cobra" - "github.com/spf13/pflag" ) var ( @@ -24,10 +24,11 @@ var ( ` mountCommand = &cobra.Command{ - Use: "mount [options] [IMAGE...]", - Short: "Mount an image's root filesystem", - Long: mountDescription, - RunE: mount, + Use: "mount [options] [IMAGE...]", + Short: "Mount an image's root filesystem", + Long: mountDescription, + RunE: mount, + ValidArgsFunction: common.AutocompleteImages, Example: `podman image mount imgID podman image mount imgID1 imgID2 imgID3 podman image mount @@ -43,9 +44,14 @@ var ( mountOpts entities.ImageMountOptions ) -func mountFlags(flags *pflag.FlagSet) { +func mountFlags(cmd *cobra.Command) { + flags := cmd.Flags() + flags.BoolVarP(&mountOpts.All, "all", "a", false, "Mount all images") - flags.StringVar(&mountOpts.Format, "format", "", "Print the mounted images in specified format (json)") + + formatFlagName := "format" + flags.StringVar(&mountOpts.Format, formatFlagName, "", "Print the mounted images in specified format (json)") + _ = cmd.RegisterFlagCompletionFunc(formatFlagName, common.AutocompleteJSONFormat) } func init() { @@ -54,7 +60,7 @@ func init() { Command: mountCommand, Parent: imageCmd, }) - mountFlags(mountCommand.Flags()) + mountFlags(mountCommand) } func mount(cmd *cobra.Command, args []string) error { diff --git a/cmd/podman/images/prune.go b/cmd/podman/images/prune.go index b6e6b9562056..3af56b0157c4 100644 --- a/cmd/podman/images/prune.go +++ b/cmd/podman/images/prune.go @@ -6,6 +6,7 @@ import ( "os" "strings" + "github.com/containers/common/pkg/completion" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" "github.com/containers/podman/v2/cmd/podman/validate" @@ -19,12 +20,13 @@ var ( If an image is not being used by a container, it will be removed from the system.` pruneCmd = &cobra.Command{ - Use: "prune [options]", - Args: validate.NoArgs, - Short: "Remove unused images", - Long: pruneDescription, - RunE: prune, - Example: `podman image prune`, + Use: "prune [options]", + Args: validate.NoArgs, + Short: "Remove unused images", + Long: pruneDescription, + RunE: prune, + ValidArgsFunction: completion.AutocompleteNone, + Example: `podman image prune`, } pruneOpts = entities.ImagePruneOptions{} @@ -42,7 +44,11 @@ func init() { flags := pruneCmd.Flags() flags.BoolVarP(&pruneOpts.All, "all", "a", false, "Remove all unused images, not just dangling ones") flags.BoolVarP(&force, "force", "f", false, "Do not prompt for confirmation") - flags.StringArrayVar(&filter, "filter", []string{}, "Provide filter values (e.g. 'label==')") + + filterFlagName := "filter" + flags.StringArrayVar(&filter, filterFlagName, []string{}, "Provide filter values (e.g. 'label==')") + //TODO: add completion for filters + _ = pruneCmd.RegisterFlagCompletionFunc(filterFlagName, completion.AutocompleteNone) } diff --git a/cmd/podman/images/pull.go b/cmd/podman/images/pull.go index ab3b0a197233..a6f41688c83c 100644 --- a/cmd/podman/images/pull.go +++ b/cmd/podman/images/pull.go @@ -5,12 +5,13 @@ import ( "os" "github.com/containers/common/pkg/auth" + "github.com/containers/common/pkg/completion" "github.com/containers/image/v5/types" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/containers/podman/v2/pkg/util" "github.com/spf13/cobra" - "github.com/spf13/pflag" ) // pullOptionsWrapper wraps entities.ImagePullOptions and prevents leaking @@ -29,11 +30,12 @@ var ( // Command: podman pull pullCmd = &cobra.Command{ - Use: "pull [options] IMAGE", - Args: cobra.ExactArgs(1), - Short: "Pull an image from a registry", - Long: pullDescription, - RunE: imagePull, + Use: "pull [options] IMAGE", + Args: cobra.ExactArgs(1), + Short: "Pull an image from a registry", + Long: pullDescription, + RunE: imagePull, + ValidArgsFunction: common.AutocompleteImages, Example: `podman pull imageName podman pull fedora:latest`, } @@ -42,11 +44,12 @@ var ( // It's basically a clone of `pullCmd` with the exception of being a // child of the images command. imagesPullCmd = &cobra.Command{ - Use: pullCmd.Use, - Args: pullCmd.Args, - Short: pullCmd.Short, - Long: pullCmd.Long, - RunE: pullCmd.RunE, + Use: pullCmd.Use, + Args: pullCmd.Args, + Short: pullCmd.Short, + Long: pullCmd.Long, + RunE: pullCmd.RunE, + ValidArgsFunction: pullCmd.ValidArgsFunction, Example: `podman image pull imageName podman image pull fedora:latest`, } @@ -58,9 +61,7 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: pullCmd, }) - - flags := pullCmd.Flags() - pullFlags(flags) + pullFlags(pullCmd) // images pull registry.Commands = append(registry.Commands, registry.CliCommand{ @@ -68,26 +69,46 @@ func init() { Command: imagesPullCmd, Parent: imageCmd, }) - - imagesPullFlags := imagesPullCmd.Flags() - pullFlags(imagesPullFlags) + pullFlags(imagesPullCmd) } // pullFlags set the flags for the pull command. -func pullFlags(flags *pflag.FlagSet) { +func pullFlags(cmd *cobra.Command) { + flags := cmd.Flags() + flags.BoolVar(&pullOptions.AllTags, "all-tags", false, "All tagged images in the repository will be pulled") - flags.StringVar(&pullOptions.CredentialsCLI, "creds", "", "`Credentials` (USERNAME:PASSWORD) to use for authenticating to a registry") - flags.StringVar(&pullOptions.OverrideArch, "override-arch", "", "Use `ARCH` instead of the architecture of the machine for choosing images") - flags.StringVar(&pullOptions.OverrideOS, "override-os", "", "Use `OS` instead of the running OS for choosing images") - flags.StringVar(&pullOptions.OverrideVariant, "override-variant", "", " use VARIANT instead of the running architecture variant for choosing images") + + credsFlagName := "creds" + flags.StringVar(&pullOptions.CredentialsCLI, credsFlagName, "", "`Credentials` (USERNAME:PASSWORD) to use for authenticating to a registry") + _ = cmd.RegisterFlagCompletionFunc(credsFlagName, completion.AutocompleteNone) + + overrideArchFlagName := "override-arch" + flags.StringVar(&pullOptions.OverrideArch, overrideArchFlagName, "", "Use `ARCH` instead of the architecture of the machine for choosing images") + _ = cmd.RegisterFlagCompletionFunc(overrideArchFlagName, completion.AutocompleteNone) + + overrideOsFlagName := "override-os" + flags.StringVar(&pullOptions.OverrideOS, overrideOsFlagName, "", "Use `OS` instead of the running OS for choosing images") + _ = cmd.RegisterFlagCompletionFunc(overrideOsFlagName, completion.AutocompleteNone) + + overrideVariantFlagName := "override-variant" + flags.StringVar(&pullOptions.OverrideVariant, overrideVariantFlagName, "", " use VARIANT instead of the running architecture variant for choosing images") + _ = cmd.RegisterFlagCompletionFunc(overrideVariantFlagName, completion.AutocompleteNone) + flags.Bool("disable-content-trust", false, "This is a Docker specific option and is a NOOP") flags.BoolVarP(&pullOptions.Quiet, "quiet", "q", false, "Suppress output information when pulling images") flags.StringVar(&pullOptions.SignaturePolicy, "signature-policy", "", "`Pathname` of signature policy file (not usually used)") flags.BoolVar(&pullOptions.TLSVerifyCLI, "tls-verify", true, "Require HTTPS and verify certificates when contacting registries") - flags.StringVar(&pullOptions.Authfile, "authfile", auth.GetDefaultAuthFile(), "Path of the authentication file. Use REGISTRY_AUTH_FILE environment variable to override") + + authfileFlagName := "authfile" + flags.StringVar(&pullOptions.Authfile, authfileFlagName, auth.GetDefaultAuthFile(), "Path of the authentication file. Use REGISTRY_AUTH_FILE environment variable to override") + _ = cmd.RegisterFlagCompletionFunc(authfileFlagName, completion.AutocompleteDefault) if !registry.IsRemote() { - flags.StringVar(&pullOptions.CertDir, "cert-dir", "", "`Pathname` of a directory containing TLS certificates and keys") + + certDirFlagName := "cert-dir" + flags.StringVar(&pullOptions.CertDir, certDirFlagName, "", "`Pathname` of a directory containing TLS certificates and keys") + _ = cmd.RegisterFlagCompletionFunc(certDirFlagName, completion.AutocompleteDefault) + } _ = flags.MarkHidden("signature-policy") } diff --git a/cmd/podman/images/push.go b/cmd/podman/images/push.go index dd45a790fdea..447b02fbe7e0 100644 --- a/cmd/podman/images/push.go +++ b/cmd/podman/images/push.go @@ -4,12 +4,13 @@ import ( "os" "github.com/containers/common/pkg/auth" + "github.com/containers/common/pkg/completion" "github.com/containers/image/v5/types" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/containers/podman/v2/pkg/util" "github.com/spf13/cobra" - "github.com/spf13/pflag" ) // pushOptionsWrapper wraps entities.ImagepushOptions and prevents leaking @@ -28,11 +29,12 @@ var ( // Command: podman push pushCmd = &cobra.Command{ - Use: "push [options] SOURCE [DESTINATION]", - Short: "Push an image to a specified destination", - Long: pushDescription, - RunE: imagePush, - Args: cobra.RangeArgs(1, 2), + Use: "push [options] SOURCE [DESTINATION]", + Short: "Push an image to a specified destination", + Long: pushDescription, + RunE: imagePush, + Args: cobra.RangeArgs(1, 2), + ValidArgsFunction: common.AutocompleteImages, Example: `podman push imageID docker://registry.example.com/repository:tag podman push imageID oci-archive:/path/to/layout:image:tag`, } @@ -41,11 +43,12 @@ var ( // It's basically a clone of `pushCmd` with the exception of being a // child of the images command. imagePushCmd = &cobra.Command{ - Use: pushCmd.Use, - Short: pushCmd.Short, - Long: pushCmd.Long, - RunE: pushCmd.RunE, - Args: pushCmd.Args, + Use: pushCmd.Use, + Short: pushCmd.Short, + Long: pushCmd.Long, + RunE: pushCmd.RunE, + Args: pushCmd.Args, + ValidArgsFunction: pushCmd.ValidArgsFunction, Example: `podman image push imageID docker://registry.example.com/repository:tag podman image push imageID oci-archive:/path/to/layout:image:tag`, } @@ -57,9 +60,7 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: pushCmd, }) - - flags := pushCmd.Flags() - pushFlags(flags) + pushFlags(pushCmd) // images push registry.Commands = append(registry.Commands, registry.CliCommand{ @@ -67,23 +68,45 @@ func init() { Command: imagePushCmd, Parent: imageCmd, }) - - pushFlags(imagePushCmd.Flags()) + pushFlags(imagePushCmd) } // pushFlags set the flags for the push command. -func pushFlags(flags *pflag.FlagSet) { - flags.StringVar(&pushOptions.Authfile, "authfile", auth.GetDefaultAuthFile(), "Path of the authentication file. Use REGISTRY_AUTH_FILE environment variable to override") - flags.StringVar(&pushOptions.CertDir, "cert-dir", "", "Path to a directory containing TLS certificates and keys") +func pushFlags(cmd *cobra.Command) { + flags := cmd.Flags() + + authfileFlagName := "authfile" + flags.StringVar(&pushOptions.Authfile, authfileFlagName, auth.GetDefaultAuthFile(), "Path of the authentication file. Use REGISTRY_AUTH_FILE environment variable to override") + _ = cmd.RegisterFlagCompletionFunc(authfileFlagName, completion.AutocompleteDefault) + + certDirFlagName := "cert-dir" + flags.StringVar(&pushOptions.CertDir, certDirFlagName, "", "Path to a directory containing TLS certificates and keys") + _ = cmd.RegisterFlagCompletionFunc(certDirFlagName, completion.AutocompleteDefault) + flags.BoolVar(&pushOptions.Compress, "compress", false, "Compress tarball image layers when pushing to a directory using the 'dir' transport. (default is same compression type as source)") - flags.StringVar(&pushOptions.CredentialsCLI, "creds", "", "`Credentials` (USERNAME:PASSWORD) to use for authenticating to a registry") - flags.StringVar(&pushOptions.DigestFile, "digestfile", "", "Write the digest of the pushed image to the specified file") + + credsFlagName := "creds" + flags.StringVar(&pushOptions.CredentialsCLI, credsFlagName, "", "`Credentials` (USERNAME:PASSWORD) to use for authenticating to a registry") + _ = cmd.RegisterFlagCompletionFunc(credsFlagName, completion.AutocompleteNone) + flags.Bool("disable-content-trust", false, "This is a Docker specific option and is a NOOP") - flags.StringVarP(&pushOptions.Format, "format", "f", "", "Manifest type (oci, v2s1, or v2s2) to use when pushing an image using the 'dir' transport (default is manifest type of source)") + + digestfileFlagName := "digestfile" + flags.StringVar(&pushOptions.DigestFile, digestfileFlagName, "", "Write the digest of the pushed image to the specified file") + _ = cmd.RegisterFlagCompletionFunc(digestfileFlagName, completion.AutocompleteDefault) + + formatFlagName := "format" + flags.StringVarP(&pushOptions.Format, formatFlagName, "f", "", "Manifest type (oci, v2s1, or v2s2) to use when pushing an image using the 'dir' transport (default is manifest type of source)") + _ = cmd.RegisterFlagCompletionFunc(formatFlagName, common.AutocompleteManifestFormat) + flags.BoolVarP(&pushOptions.Quiet, "quiet", "q", false, "Suppress output information when pushing images") flags.BoolVar(&pushOptions.RemoveSignatures, "remove-signatures", false, "Discard any pre-existing signatures in the image") flags.StringVar(&pushOptions.SignaturePolicy, "signature-policy", "", "Path to a signature-policy file") - flags.StringVar(&pushOptions.SignBy, "sign-by", "", "Add a signature at the destination using the specified key") + + signByFlagName := "sign-by" + flags.StringVar(&pushOptions.SignBy, signByFlagName, "", "Add a signature at the destination using the specified key") + _ = cmd.RegisterFlagCompletionFunc(signByFlagName, completion.AutocompleteNone) + flags.BoolVar(&pushOptions.TLSVerifyCLI, "tls-verify", true, "Require HTTPS and verify certificates when contacting registries") if registry.IsRemote() { diff --git a/cmd/podman/images/rm.go b/cmd/podman/images/rm.go index 9dddef48f07e..587f08c29738 100644 --- a/cmd/podman/images/rm.go +++ b/cmd/podman/images/rm.go @@ -3,6 +3,7 @@ package images import ( "fmt" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/containers/podman/v2/pkg/errorhandling" @@ -14,10 +15,11 @@ import ( var ( rmDescription = "Removes one or more previously pulled or locally created images." rmCmd = &cobra.Command{ - Use: "rm [options] IMAGE [IMAGE...]", - Short: "Removes one or more images from local storage", - Long: rmDescription, - RunE: rm, + Use: "rm [options] IMAGE [IMAGE...]", + Short: "Removes one or more images from local storage", + Long: rmDescription, + RunE: rm, + ValidArgsFunction: common.AutocompleteImages, Example: `podman image rm imageID podman image rm --force alpine podman image rm c4dfb1609ee2 93fd78260bd1 c0ed59d05ff7`, diff --git a/cmd/podman/images/rmi.go b/cmd/podman/images/rmi.go index 52084789029a..ab174d75075f 100644 --- a/cmd/podman/images/rmi.go +++ b/cmd/podman/images/rmi.go @@ -10,12 +10,13 @@ import ( var ( rmiCmd = &cobra.Command{ - Use: strings.Replace(rmCmd.Use, "rm ", "rmi ", 1), - Args: rmCmd.Args, - Short: rmCmd.Short, - Long: rmCmd.Long, - RunE: rmCmd.RunE, - Example: strings.Replace(rmCmd.Example, "podman image rm", "podman rmi", -1), + Use: strings.Replace(rmCmd.Use, "rm ", "rmi ", 1), + Args: rmCmd.Args, + Short: rmCmd.Short, + Long: rmCmd.Long, + RunE: rmCmd.RunE, + ValidArgsFunction: rmCmd.ValidArgsFunction, + Example: strings.Replace(rmCmd.Example, "podman image rm", "podman rmi", -1), } ) diff --git a/cmd/podman/images/save.go b/cmd/podman/images/save.go index db1fa7159e5d..9ef2d0c911d5 100644 --- a/cmd/podman/images/save.go +++ b/cmd/podman/images/save.go @@ -5,6 +5,8 @@ import ( "os" "strings" + "github.com/containers/common/pkg/completion" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/parse" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/libpod/define" @@ -12,7 +14,6 @@ import ( "github.com/containers/podman/v2/pkg/util" "github.com/pkg/errors" "github.com/spf13/cobra" - "github.com/spf13/pflag" "golang.org/x/crypto/ssh/terminal" ) @@ -42,16 +43,18 @@ var ( } return nil }, + ValidArgsFunction: completion.AutocompleteNone, Example: `podman save --quiet -o myimage.tar imageID podman save --format docker-dir -o ubuntu-dir ubuntu podman save > alpine-all.tar alpine:latest`, } imageSaveCommand = &cobra.Command{ - Args: saveCommand.Args, - Use: saveCommand.Use, - Short: saveCommand.Short, - Long: saveCommand.Long, - RunE: saveCommand.RunE, + Args: saveCommand.Args, + Use: saveCommand.Use, + Short: saveCommand.Short, + Long: saveCommand.Long, + RunE: saveCommand.RunE, + ValidArgsFunction: saveCommand.ValidArgsFunction, Example: `podman image save --quiet -o myimage.tar imageID podman image save --format docker-dir -o ubuntu-dir ubuntu podman image save > alpine-all.tar alpine:latest`, @@ -67,20 +70,29 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: saveCommand, }) - saveFlags(saveCommand.Flags()) + saveFlags(saveCommand) registry.Commands = append(registry.Commands, registry.CliCommand{ Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: imageSaveCommand, Parent: imageCmd, }) - saveFlags(imageSaveCommand.Flags()) + saveFlags(imageSaveCommand) } -func saveFlags(flags *pflag.FlagSet) { +func saveFlags(cmd *cobra.Command) { + flags := cmd.Flags() + flags.BoolVar(&saveOpts.Compress, "compress", false, "Compress tarball image layers when saving to a directory using the 'dir' transport. (default is same compression type as source)") - flags.StringVar(&saveOpts.Format, "format", define.V2s2Archive, "Save image to oci-archive, oci-dir (directory with oci manifest type), docker-archive, docker-dir (directory with v2s2 manifest type)") - flags.StringVarP(&saveOpts.Output, "output", "o", "", "Write to a specified file (default: stdout, which must be redirected)") + + formatFlagName := "format" + flags.StringVar(&saveOpts.Format, formatFlagName, define.V2s2Archive, "Save image to oci-archive, oci-dir (directory with oci manifest type), docker-archive, docker-dir (directory with v2s2 manifest type)") + _ = cmd.RegisterFlagCompletionFunc(formatFlagName, common.AutocompleteImageSaveFormat) + + outputFlagName := "output" + flags.StringVarP(&saveOpts.Output, outputFlagName, "o", "", "Write to a specified file (default: stdout, which must be redirected)") + _ = cmd.RegisterFlagCompletionFunc(outputFlagName, completion.AutocompleteDefault) + flags.BoolVarP(&saveOpts.Quiet, "quiet", "q", false, "Suppress the output") flags.BoolVarP(&saveOpts.MultiImageArchive, "multi-image-archive", "m", containerConfig.Engine.MultiImageArchive, "Interpret additional arguments as images not tags and create a multi-image-archive (only for docker-archive)") } diff --git a/cmd/podman/images/search.go b/cmd/podman/images/search.go index 7de6a731661e..c2ef7d767f2a 100644 --- a/cmd/podman/images/search.go +++ b/cmd/podman/images/search.go @@ -7,6 +7,7 @@ import ( "text/template" "github.com/containers/common/pkg/auth" + "github.com/containers/common/pkg/completion" "github.com/containers/common/pkg/report" "github.com/containers/image/v5/types" "github.com/containers/podman/v2/cmd/podman/parse" @@ -14,7 +15,6 @@ import ( "github.com/containers/podman/v2/pkg/domain/entities" "github.com/pkg/errors" "github.com/spf13/cobra" - "github.com/spf13/pflag" ) // searchOptionsWrapper wraps entities.ImagePullOptions and prevents leaking @@ -34,11 +34,12 @@ var ( // Command: podman search searchCmd = &cobra.Command{ - Use: "search [options] TERM", - Short: "Search registry for image", - Long: searchDescription, - RunE: imageSearch, - Args: cobra.ExactArgs(1), + Use: "search [options] TERM", + Short: "Search registry for image", + Long: searchDescription, + RunE: imageSearch, + Args: cobra.ExactArgs(1), + ValidArgsFunction: completion.AutocompleteNone, Example: `podman search --filter=is-official --limit 3 alpine podman search registry.fedoraproject.org/ # only works with v2 registries podman search --format "table {{.Index}} {{.Name}}" registry.fedoraproject.org/fedora`, @@ -46,12 +47,13 @@ var ( // Command: podman image search imageSearchCmd = &cobra.Command{ - Use: searchCmd.Use, - Short: searchCmd.Short, - Long: searchCmd.Long, - RunE: searchCmd.RunE, - Args: searchCmd.Args, - Annotations: searchCmd.Annotations, + Use: searchCmd.Use, + Short: searchCmd.Short, + Long: searchCmd.Long, + RunE: searchCmd.RunE, + Args: searchCmd.Args, + Annotations: searchCmd.Annotations, + ValidArgsFunction: searchCmd.ValidArgsFunction, Example: `podman image search --filter=is-official --limit 3 alpine podman image search registry.fedoraproject.org/ # only works with v2 registries podman image search --format "table {{.Index}} {{.Name}}" registry.fedoraproject.org/fedora`, @@ -64,9 +66,7 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: searchCmd, }) - - flags := searchCmd.Flags() - searchFlags(flags) + searchFlags(searchCmd) // images search registry.Commands = append(registry.Commands, registry.CliCommand{ @@ -74,18 +74,32 @@ func init() { Command: imageSearchCmd, Parent: imageCmd, }) - - imageSearchFlags := imageSearchCmd.Flags() - searchFlags(imageSearchFlags) + searchFlags(imageSearchCmd) } // searchFlags set the flags for the pull command. -func searchFlags(flags *pflag.FlagSet) { - flags.StringSliceVarP(&searchOptions.Filters, "filter", "f", []string{}, "Filter output based on conditions provided (default [])") - flags.StringVar(&searchOptions.Format, "format", "", "Change the output format to JSON or a Go template") - flags.IntVar(&searchOptions.Limit, "limit", 0, "Limit the number of results") +func searchFlags(cmd *cobra.Command) { + flags := cmd.Flags() + + filterFlagName := "filter" + flags.StringSliceVarP(&searchOptions.Filters, filterFlagName, "f", []string{}, "Filter output based on conditions provided (default [])") + //TODO add custom filter function + _ = cmd.RegisterFlagCompletionFunc(filterFlagName, completion.AutocompleteNone) + + formatFlagName := "format" + flags.StringVar(&searchOptions.Format, formatFlagName, "", "Change the output format to JSON or a Go template") + _ = cmd.RegisterFlagCompletionFunc(formatFlagName, completion.AutocompleteNone) + + limitFlagName := "limit" + flags.IntVar(&searchOptions.Limit, limitFlagName, 0, "Limit the number of results") + _ = cmd.RegisterFlagCompletionFunc(limitFlagName, completion.AutocompleteNone) + flags.BoolVar(&searchOptions.NoTrunc, "no-trunc", false, "Do not truncate the output") - flags.StringVar(&searchOptions.Authfile, "authfile", auth.GetDefaultAuthFile(), "Path of the authentication file. Use REGISTRY_AUTH_FILE environment variable to override") + + authfileFlagName := "authfile" + flags.StringVar(&searchOptions.Authfile, authfileFlagName, auth.GetDefaultAuthFile(), "Path of the authentication file. Use REGISTRY_AUTH_FILE environment variable to override") + _ = cmd.RegisterFlagCompletionFunc(authfileFlagName, completion.AutocompleteDefault) + flags.BoolVar(&searchOptions.TLSVerifyCLI, "tls-verify", true, "Require HTTPS and verify certificates when contacting registries") flags.BoolVar(&searchOptions.ListTags, "list-tags", false, "List the tags of the input registry") } diff --git a/cmd/podman/images/sign.go b/cmd/podman/images/sign.go index f6c1f9856364..529fb3d92048 100644 --- a/cmd/podman/images/sign.go +++ b/cmd/podman/images/sign.go @@ -3,6 +3,8 @@ package images import ( "os" + "github.com/containers/common/pkg/completion" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/pkg/errors" @@ -12,11 +14,12 @@ import ( var ( signDescription = "Create a signature file that can be used later to verify the image." signCommand = &cobra.Command{ - Use: "sign [options] IMAGE [IMAGE...]", - Short: "Sign an image", - Long: signDescription, - RunE: sign, - Args: cobra.MinimumNArgs(1), + Use: "sign [options] IMAGE [IMAGE...]", + Short: "Sign an image", + Long: signDescription, + RunE: sign, + Args: cobra.MinimumNArgs(1), + ValidArgsFunction: common.AutocompleteImages, Example: `podman image sign --sign-by mykey imageID podman image sign --sign-by mykey --directory ./mykeydir imageID`, } @@ -33,9 +36,17 @@ func init() { Parent: imageCmd, }) flags := signCommand.Flags() - flags.StringVarP(&signOptions.Directory, "directory", "d", "", "Define an alternate directory to store signatures") - flags.StringVar(&signOptions.SignBy, "sign-by", "", "Name of the signing key") - flags.StringVar(&signOptions.CertDir, "cert-dir", "", "`Pathname` of a directory containing TLS certificates and keys") + directoryFlagName := "directory" + flags.StringVarP(&signOptions.Directory, directoryFlagName, "d", "", "Define an alternate directory to store signatures") + _ = signCommand.RegisterFlagCompletionFunc(directoryFlagName, completion.AutocompleteDefault) + + signByFlagName := "sign-by" + flags.StringVar(&signOptions.SignBy, signByFlagName, "", "Name of the signing key") + _ = signCommand.RegisterFlagCompletionFunc(signByFlagName, completion.AutocompleteNone) + + certDirFlagName := "cert-dir" + flags.StringVar(&signOptions.CertDir, certDirFlagName, "", "`Pathname` of a directory containing TLS certificates and keys") + _ = signCommand.RegisterFlagCompletionFunc(certDirFlagName, completion.AutocompleteDefault) } func sign(cmd *cobra.Command, args []string) error { diff --git a/cmd/podman/images/tag.go b/cmd/podman/images/tag.go index be7f8458842f..157db49ca47f 100644 --- a/cmd/podman/images/tag.go +++ b/cmd/podman/images/tag.go @@ -1,6 +1,7 @@ package images import ( + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/spf13/cobra" @@ -15,6 +16,7 @@ var ( RunE: tag, Args: cobra.MinimumNArgs(2), DisableFlagsInUseLine: true, + ValidArgsFunction: common.AutocompleteImages, Example: `podman tag 0e3bbc2 fedora:latest podman tag imageID:latest myNewImage:newTag podman tag httpd myregistryhost:5000/fedora/httpd:v2`, @@ -27,6 +29,7 @@ var ( Short: tagCommand.Short, Long: tagCommand.Long, RunE: tagCommand.RunE, + ValidArgsFunction: tagCommand.ValidArgsFunction, Example: `podman image tag 0e3bbc2 fedora:latest podman image tag imageID:latest myNewImage:newTag podman image tag httpd myregistryhost:5000/fedora/httpd:v2`, diff --git a/cmd/podman/images/tree.go b/cmd/podman/images/tree.go index 237a2ab9149c..76c69b37e5ee 100644 --- a/cmd/podman/images/tree.go +++ b/cmd/podman/images/tree.go @@ -3,6 +3,7 @@ package images import ( "fmt" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/spf13/cobra" @@ -11,12 +12,13 @@ import ( var ( treeDescription = "Prints layer hierarchy of an image in a tree format" treeCmd = &cobra.Command{ - Use: "tree [options] IMAGE", - Args: cobra.ExactArgs(1), - Short: treeDescription, - Long: treeDescription, - RunE: tree, - Example: "podman image tree alpine:latest", + Use: "tree [options] IMAGE", + Args: cobra.ExactArgs(1), + Short: treeDescription, + Long: treeDescription, + RunE: tree, + ValidArgsFunction: common.AutocompleteImages, + Example: "podman image tree alpine:latest", } treeOpts entities.ImageTreeOptions ) diff --git a/cmd/podman/images/trust_set.go b/cmd/podman/images/trust_set.go index 2e4b4fe17183..f0399b1109e9 100644 --- a/cmd/podman/images/trust_set.go +++ b/cmd/podman/images/trust_set.go @@ -1,6 +1,8 @@ package images import ( + "github.com/containers/common/pkg/completion" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/libpod/image" "github.com/containers/podman/v2/pkg/domain/entities" @@ -12,12 +14,13 @@ import ( var ( setTrustDescription = "Set default trust policy or add a new trust policy for a registry" setTrustCommand = &cobra.Command{ - Use: "set [options] REGISTRY", - Short: "Set default trust policy or a new trust policy for a registry", - Long: setTrustDescription, - Example: "", - RunE: setTrust, - Args: cobra.ExactArgs(1), + Use: "set [options] REGISTRY", + Short: "Set default trust policy or a new trust policy for a registry", + Long: setTrustDescription, + Example: "", + RunE: setTrust, + Args: cobra.ExactArgs(1), + ValidArgsFunction: common.AutocompleteRegistries, } ) @@ -34,11 +37,17 @@ func init() { setFlags := setTrustCommand.Flags() setFlags.StringVar(&setOptions.PolicyPath, "policypath", "", "") _ = setFlags.MarkHidden("policypath") - setFlags.StringSliceVarP(&setOptions.PubKeysFile, "pubkeysfile", "f", []string{}, `Path of installed public key(s) to trust for TARGET. + + pubkeysfileFlagName := "pubkeysfile" + setFlags.StringSliceVarP(&setOptions.PubKeysFile, pubkeysfileFlagName, "f", []string{}, `Path of installed public key(s) to trust for TARGET. Absolute path to keys is added to policy.json. May used multiple times to define multiple public keys. File(s) must exist before using this command`) - setFlags.StringVarP(&setOptions.Type, "type", "t", "signedBy", "Trust type, accept values: signedBy(default), accept, reject") + _ = setTrustCommand.RegisterFlagCompletionFunc(pubkeysfileFlagName, completion.AutocompleteDefault) + + typeFlagName := "type" + setFlags.StringVarP(&setOptions.Type, typeFlagName, "t", "signedBy", "Trust type, accept values: signedBy(default), accept, reject") + _ = setTrustCommand.RegisterFlagCompletionFunc(typeFlagName, common.AutocompleteTrustType) } func setTrust(cmd *cobra.Command, args []string) error { diff --git a/cmd/podman/images/trust_show.go b/cmd/podman/images/trust_show.go index ba3b4e7fbc81..dc35dc6a159c 100644 --- a/cmd/podman/images/trust_show.go +++ b/cmd/podman/images/trust_show.go @@ -6,6 +6,7 @@ import ( "text/tabwriter" "text/template" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/spf13/cobra" @@ -14,12 +15,13 @@ import ( var ( showTrustDescription = "Display trust policy for the system" showTrustCommand = &cobra.Command{ - Use: "show [options] [REGISTRY]", - Short: "Display trust policy for the system", - Long: showTrustDescription, - RunE: showTrust, - Args: cobra.MaximumNArgs(1), - Example: "", + Use: "show [options] [REGISTRY]", + Short: "Display trust policy for the system", + Long: showTrustDescription, + RunE: showTrust, + Args: cobra.MaximumNArgs(1), + ValidArgsFunction: common.AutocompleteRegistries, + Example: "", } ) diff --git a/cmd/podman/images/unmount.go b/cmd/podman/images/unmount.go index 50dc972e8137..3af959b9fc94 100644 --- a/cmd/podman/images/unmount.go +++ b/cmd/podman/images/unmount.go @@ -3,6 +3,7 @@ package images import ( "fmt" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" "github.com/containers/podman/v2/pkg/domain/entities" @@ -19,11 +20,12 @@ var ( An unmount can be forced with the --force flag. ` unmountCommand = &cobra.Command{ - Use: "unmount [options] IMAGE [IMAGE...]", - Aliases: []string{"umount"}, - Short: "Unmount an image's root filesystem", - Long: description, - RunE: unmount, + Use: "unmount [options] IMAGE [IMAGE...]", + Aliases: []string{"umount"}, + Short: "Unmount an image's root filesystem", + Long: description, + RunE: unmount, + ValidArgsFunction: common.AutocompleteImages, Example: `podman unmount imgID podman unmount imgID1 imgID2 imgID3 podman unmount --all`, diff --git a/cmd/podman/images/untag.go b/cmd/podman/images/untag.go index da749c8a5a78..17dc21203f71 100644 --- a/cmd/podman/images/untag.go +++ b/cmd/podman/images/untag.go @@ -1,6 +1,7 @@ package images import ( + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/spf13/cobra" @@ -14,6 +15,7 @@ var ( RunE: untag, Args: cobra.MinimumNArgs(1), DisableFlagsInUseLine: true, + ValidArgsFunction: common.AutocompleteImages, Example: `podman untag 0e3bbc2 podman untag imageID:latest otherImageName:latest podman untag httpd myregistryhost:5000/fedora/httpd:v2`, @@ -26,6 +28,7 @@ var ( Short: untagCommand.Short, Long: untagCommand.Long, RunE: untagCommand.RunE, + ValidArgsFunction: untagCommand.ValidArgsFunction, Example: `podman image untag 0e3bbc2 podman image untag imageID:latest otherImageName:latest podman image untag httpd myregistryhost:5000/fedora/httpd:v2`, diff --git a/cmd/podman/inspect.go b/cmd/podman/inspect.go index f1d673a2186a..f62abe9313fc 100644 --- a/cmd/podman/inspect.go +++ b/cmd/podman/inspect.go @@ -1,6 +1,7 @@ package main import ( + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/inspect" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/domain/entities" @@ -19,11 +20,12 @@ var ( // Command: podman _inspect_ Object_ID inspectCmd = &cobra.Command{ - Use: "inspect [options] {CONTAINER_ID | IMAGE_ID} [...]", - Short: "Display the configuration of object denoted by ID", - RunE: inspectExec, - Long: inspectDescription, - TraverseChildren: true, + Use: "inspect [options] {CONTAINER_ID | IMAGE_ID} [...]", + Short: "Display the configuration of object denoted by ID", + RunE: inspectExec, + Long: inspectDescription, + TraverseChildren: true, + ValidArgsFunction: common.AutocompleteContainersAndImages, Example: `podman inspect fedora podman inspect --type image fedora podman inspect CtrID ImgID diff --git a/cmd/podman/inspect/inspect.go b/cmd/podman/inspect/inspect.go index 9c400d506ac5..f9bd75c936b1 100644 --- a/cmd/podman/inspect/inspect.go +++ b/cmd/podman/inspect/inspect.go @@ -9,7 +9,9 @@ import ( "text/tabwriter" "text/template" + "github.com/containers/common/pkg/completion" "github.com/containers/common/pkg/report" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/validate" "github.com/containers/podman/v2/libpod/define" @@ -44,8 +46,14 @@ func AddInspectFlagSet(cmd *cobra.Command) *entities.InspectOptions { flags := cmd.Flags() flags.BoolVarP(&opts.Size, "size", "s", false, "Display total file size") - flags.StringVarP(&opts.Format, "format", "f", "json", "Format the output to a Go template or json") - flags.StringVarP(&opts.Type, "type", "t", AllType, fmt.Sprintf("Specify inspect-oject type (%q, %q or %q)", ImageType, ContainerType, AllType)) + + formatFlagName := "format" + flags.StringVarP(&opts.Format, formatFlagName, "f", "json", "Format the output to a Go template or json") + _ = cmd.RegisterFlagCompletionFunc(formatFlagName, completion.AutocompleteNone) + + typeFlagName := "type" + flags.StringVarP(&opts.Type, typeFlagName, "t", AllType, fmt.Sprintf("Specify inspect-oject type (%q, %q or %q)", ImageType, ContainerType, AllType)) + _ = cmd.RegisterFlagCompletionFunc(typeFlagName, common.AutocompleteInspectType) validate.AddLatestFlag(cmd, &opts.Latest) return &opts diff --git a/cmd/podman/login.go b/cmd/podman/login.go index a789cef3334d..7c8fe03dc97a 100644 --- a/cmd/podman/login.go +++ b/cmd/podman/login.go @@ -5,7 +5,9 @@ import ( "os" "github.com/containers/common/pkg/auth" + "github.com/containers/common/pkg/completion" "github.com/containers/image/v5/types" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/containers/podman/v2/pkg/registries" @@ -20,11 +22,12 @@ type loginOptionsWrapper struct { var ( loginOptions = loginOptionsWrapper{} loginCommand = &cobra.Command{ - Use: "login [options] [REGISTRY]", - Short: "Login to a container registry", - Long: "Login to a container registry on a specified server.", - RunE: login, - Args: cobra.MaximumNArgs(1), + Use: "login [options] [REGISTRY]", + Short: "Login to a container registry", + Long: "Login to a container registry on a specified server.", + RunE: login, + Args: cobra.MaximumNArgs(1), + ValidArgsFunction: common.AutocompleteRegistries, Example: `podman login quay.io podman login --username ... --password ... quay.io podman login --authfile dir/auth.json quay.io`, @@ -44,6 +47,9 @@ func init() { // Flags from the auth package. flags.AddFlagSet(auth.GetLoginFlags(&loginOptions.LoginOptions)) + // Add flag completion + completion.CompleteCommandFlags(loginCommand, auth.GetLoginFlagsCompletions()) + // Podman flags. flags.BoolVarP(&loginOptions.tlsVerify, "tls-verify", "", false, "Require HTTPS and verify certificates when contacting registries") loginOptions.Stdin = os.Stdin diff --git a/cmd/podman/logout.go b/cmd/podman/logout.go index 7b5615d30a02..3cb11071be0b 100644 --- a/cmd/podman/logout.go +++ b/cmd/podman/logout.go @@ -4,7 +4,9 @@ import ( "os" "github.com/containers/common/pkg/auth" + "github.com/containers/common/pkg/completion" "github.com/containers/image/v5/types" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/containers/podman/v2/pkg/registries" @@ -14,11 +16,12 @@ import ( var ( logoutOptions = auth.LogoutOptions{} logoutCommand = &cobra.Command{ - Use: "logout [options] [REGISTRY]", - Short: "Logout of a container registry", - Long: "Remove the cached username and password for the registry.", - RunE: logout, - Args: cobra.MaximumNArgs(1), + Use: "logout [options] [REGISTRY]", + Short: "Logout of a container registry", + Long: "Remove the cached username and password for the registry.", + RunE: logout, + Args: cobra.MaximumNArgs(1), + ValidArgsFunction: common.AutocompleteRegistries, Example: `podman logout quay.io podman logout --authfile dir/auth.json quay.io podman logout --all`, @@ -37,6 +40,10 @@ func init() { // Flags from the auth package. flags.AddFlagSet(auth.GetLogoutFlags(&logoutOptions)) + + // Add flag completion + completion.CompleteCommandFlags(logoutCommand, auth.GetLogoutFlagsCompletions()) + logoutOptions.Stdout = os.Stdout logoutOptions.AcceptUnspecifiedRegistry = true } diff --git a/cmd/podman/main.go b/cmd/podman/main.go index 9747769c7d5e..c3aaf84a8d3e 100644 --- a/cmd/podman/main.go +++ b/cmd/podman/main.go @@ -4,6 +4,7 @@ import ( "fmt" "os" + _ "github.com/containers/podman/v2/cmd/podman/completion" _ "github.com/containers/podman/v2/cmd/podman/containers" _ "github.com/containers/podman/v2/cmd/podman/generate" _ "github.com/containers/podman/v2/cmd/podman/healthcheck" @@ -35,6 +36,13 @@ func main() { os.Setenv("TMPDIR", "/var/tmp") } + rootCmd = parseCommands() + + Execute() + os.Exit(0) +} + +func parseCommands() *cobra.Command { cfg := registry.PodmanConfig() for _, c := range registry.Commands { for _, m := range c.Mode { @@ -75,6 +83,5 @@ func main() { os.Exit(1) } - Execute() - os.Exit(0) + return rootCmd } diff --git a/cmd/podman/manifest/add.go b/cmd/podman/manifest/add.go index 4b85f4c2ae8f..91bd423b8449 100644 --- a/cmd/podman/manifest/add.go +++ b/cmd/podman/manifest/add.go @@ -5,7 +5,9 @@ import ( "fmt" "github.com/containers/common/pkg/auth" + "github.com/containers/common/pkg/completion" "github.com/containers/image/v5/types" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/containers/podman/v2/pkg/util" @@ -25,10 +27,11 @@ type manifestAddOptsWrapper struct { var ( manifestAddOpts = manifestAddOptsWrapper{} addCmd = &cobra.Command{ - Use: "add [options] LIST LIST", - Short: "Add images to a manifest list or image index", - Long: "Adds an image to a manifest list or image index.", - RunE: add, + Use: "add [options] LIST LIST", + Short: "Add images to a manifest list or image index", + Long: "Adds an image to a manifest list or image index.", + RunE: add, + ValidArgsFunction: common.AutocompleteImages, Example: `podman manifest add mylist:v1.11 image:v1.11-amd64 podman manifest add mylist:v1.11 transport:imageName`, Args: cobra.ExactArgs(2), @@ -43,17 +46,44 @@ func init() { }) flags := addCmd.Flags() flags.BoolVar(&manifestAddOpts.All, "all", false, "add all of the list's images if the image is a list") - flags.StringSliceVar(&manifestAddOpts.Annotation, "annotation", nil, "set an `annotation` for the specified image") - flags.StringVar(&manifestAddOpts.Arch, "arch", "", "override the `architecture` of the specified image") - flags.StringVar(&manifestAddOpts.Authfile, "authfile", auth.GetDefaultAuthFile(), "path of the authentication file. Use REGISTRY_AUTH_FILE environment variable to override") - flags.StringVar(&manifestAddOpts.CertDir, "cert-dir", "", "use certificates at the specified path to access the registry") - flags.StringVar(&manifestAddOpts.CredentialsCLI, "creds", "", "use `[username[:password]]` for accessing the registry") - - flags.StringSliceVar(&manifestAddOpts.Features, "features", nil, "override the `features` of the specified image") - flags.StringVar(&manifestAddOpts.OS, "os", "", "override the `OS` of the specified image") - flags.StringVar(&manifestAddOpts.OSVersion, "os-version", "", "override the OS `version` of the specified image") + + annotationFlagName := "annotation" + flags.StringSliceVar(&manifestAddOpts.Annotation, annotationFlagName, nil, "set an `annotation` for the specified image") + _ = addCmd.RegisterFlagCompletionFunc(annotationFlagName, completion.AutocompleteNone) + + archFlagName := "arch" + flags.StringVar(&manifestAddOpts.Arch, archFlagName, "", "override the `architecture` of the specified image") + _ = addCmd.RegisterFlagCompletionFunc(archFlagName, completion.AutocompleteNone) + + authfileFlagName := "authfile" + flags.StringVar(&manifestAddOpts.Authfile, authfileFlagName, auth.GetDefaultAuthFile(), "path of the authentication file. Use REGISTRY_AUTH_FILE environment variable to override") + _ = addCmd.RegisterFlagCompletionFunc(authfileFlagName, completion.AutocompleteDefault) + + certDirFlagName := "cert-dir" + flags.StringVar(&manifestAddOpts.CertDir, certDirFlagName, "", "use certificates at the specified path to access the registry") + _ = addCmd.RegisterFlagCompletionFunc(certDirFlagName, completion.AutocompleteDefault) + + credsFlagName := "creds" + flags.StringVar(&manifestAddOpts.CredentialsCLI, credsFlagName, "", "use `[username[:password]]` for accessing the registry") + _ = addCmd.RegisterFlagCompletionFunc(credsFlagName, completion.AutocompleteNone) + + featuresFlagName := "features" + flags.StringSliceVar(&manifestAddOpts.Features, featuresFlagName, nil, "override the `features` of the specified image") + _ = addCmd.RegisterFlagCompletionFunc(featuresFlagName, completion.AutocompleteNone) + + osFlagName := "os" + flags.StringVar(&manifestAddOpts.OS, osFlagName, "", "override the `OS` of the specified image") + _ = addCmd.RegisterFlagCompletionFunc(osFlagName, completion.AutocompleteNone) + + osVersionFlagName := "os-version" + flags.StringVar(&manifestAddOpts.OSVersion, osVersionFlagName, "", "override the OS `version` of the specified image") + _ = addCmd.RegisterFlagCompletionFunc(osVersionFlagName, completion.AutocompleteNone) + flags.BoolVar(&manifestAddOpts.TLSVerifyCLI, "tls-verify", true, "require HTTPS and verify certificates when accessing the registry") - flags.StringVar(&manifestAddOpts.Variant, "variant", "", "override the `Variant` of the specified image") + + variantFlagName := "variant" + flags.StringVar(&manifestAddOpts.Variant, variantFlagName, "", "override the `Variant` of the specified image") + _ = addCmd.RegisterFlagCompletionFunc(variantFlagName, completion.AutocompleteNone) if registry.IsRemote() { _ = flags.MarkHidden("cert-dir") diff --git a/cmd/podman/manifest/annotate.go b/cmd/podman/manifest/annotate.go index 861e940343d3..dab8c4da6c22 100644 --- a/cmd/podman/manifest/annotate.go +++ b/cmd/podman/manifest/annotate.go @@ -4,6 +4,8 @@ import ( "context" "fmt" + "github.com/containers/common/pkg/completion" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/pkg/errors" @@ -13,12 +15,13 @@ import ( var ( manifestAnnotateOpts = entities.ManifestAnnotateOptions{} annotateCmd = &cobra.Command{ - Use: "annotate [options] LIST IMAGE", - Short: "Add or update information about an entry in a manifest list or image index", - Long: "Adds or updates information about an entry in a manifest list or image index.", - RunE: annotate, - Example: `podman manifest annotate --annotation left=right mylist:v1.11 image:v1.11-amd64`, - Args: cobra.ExactArgs(2), + Use: "annotate [options] LIST IMAGE", + Short: "Add or update information about an entry in a manifest list or image index", + Long: "Adds or updates information about an entry in a manifest list or image index.", + RunE: annotate, + Example: `podman manifest annotate --annotation left=right mylist:v1.11 image:v1.11-amd64`, + Args: cobra.ExactArgs(2), + ValidArgsFunction: common.AutocompleteImages, } ) @@ -29,13 +32,34 @@ func init() { Parent: manifestCmd, }) flags := annotateCmd.Flags() - flags.StringSliceVar(&manifestAnnotateOpts.Annotation, "annotation", nil, "set an `annotation` for the specified image") - flags.StringVar(&manifestAnnotateOpts.Arch, "arch", "", "override the `architecture` of the specified image") - flags.StringSliceVar(&manifestAnnotateOpts.Features, "features", nil, "override the `features` of the specified image") - flags.StringVar(&manifestAnnotateOpts.OS, "os", "", "override the `OS` of the specified image") - flags.StringSliceVar(&manifestAnnotateOpts.OSFeatures, "os-features", nil, "override the OS `features` of the specified image") - flags.StringVar(&manifestAnnotateOpts.OSVersion, "os-version", "", "override the OS `version` of the specified image") - flags.StringVar(&manifestAnnotateOpts.Variant, "variant", "", "override the `variant` of the specified image") + + annotationFlagName := "annotation" + flags.StringSliceVar(&manifestAnnotateOpts.Annotation, annotationFlagName, nil, "set an `annotation` for the specified image") + _ = annotateCmd.RegisterFlagCompletionFunc(annotationFlagName, completion.AutocompleteNone) + + archFlagName := "arch" + flags.StringVar(&manifestAnnotateOpts.Arch, archFlagName, "", "override the `architecture` of the specified image") + _ = annotateCmd.RegisterFlagCompletionFunc(archFlagName, completion.AutocompleteNone) + + featuresFlagName := "features" + flags.StringSliceVar(&manifestAnnotateOpts.Features, featuresFlagName, nil, "override the `features` of the specified image") + _ = annotateCmd.RegisterFlagCompletionFunc(featuresFlagName, completion.AutocompleteNone) + + osFlagName := "os" + flags.StringVar(&manifestAnnotateOpts.OS, osFlagName, "", "override the `OS` of the specified image") + _ = annotateCmd.RegisterFlagCompletionFunc(osFlagName, completion.AutocompleteNone) + + osFeaturesFlagName := "os-features" + flags.StringSliceVar(&manifestAnnotateOpts.OSFeatures, osFeaturesFlagName, nil, "override the OS `features` of the specified image") + _ = annotateCmd.RegisterFlagCompletionFunc(osFeaturesFlagName, completion.AutocompleteNone) + + osVersionFlagName := "os-version" + flags.StringVar(&manifestAnnotateOpts.OSVersion, osVersionFlagName, "", "override the OS `version` of the specified image") + _ = annotateCmd.RegisterFlagCompletionFunc(osVersionFlagName, completion.AutocompleteNone) + + variantFlagName := "variant" + flags.StringVar(&manifestAnnotateOpts.Variant, variantFlagName, "", "override the `Variant` of the specified image") + _ = annotateCmd.RegisterFlagCompletionFunc(variantFlagName, completion.AutocompleteNone) } func annotate(cmd *cobra.Command, args []string) error { diff --git a/cmd/podman/manifest/create.go b/cmd/podman/manifest/create.go index 956946f9dd52..c903c6fa8821 100644 --- a/cmd/podman/manifest/create.go +++ b/cmd/podman/manifest/create.go @@ -4,6 +4,7 @@ import ( "context" "fmt" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/pkg/errors" @@ -13,10 +14,11 @@ import ( var ( manifestCreateOpts = entities.ManifestCreateOptions{} createCmd = &cobra.Command{ - Use: "create [options] LIST [IMAGE]", - Short: "Create manifest list or image index", - Long: "Creates manifest lists or image indexes.", - RunE: create, + Use: "create [options] LIST [IMAGE]", + Short: "Create manifest list or image index", + Long: "Creates manifest lists or image indexes.", + RunE: create, + ValidArgsFunction: common.AutocompleteImages, Example: `podman manifest create mylist:v1.11 podman manifest create mylist:v1.11 arch-specific-image-to-add podman manifest create --all mylist:v1.11 transport:tagged-image-to-add`, diff --git a/cmd/podman/manifest/inspect.go b/cmd/podman/manifest/inspect.go index 19396ceb3fb3..17c94aaba707 100644 --- a/cmd/podman/manifest/inspect.go +++ b/cmd/podman/manifest/inspect.go @@ -4,6 +4,7 @@ import ( "context" "fmt" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/pkg/errors" @@ -16,6 +17,7 @@ var ( Short: "Display the contents of a manifest list or image index", Long: "Display the contents of a manifest list or image index.", RunE: inspect, + ValidArgsFunction: common.AutocompleteImages, Example: "podman manifest inspect localhost/list", Args: cobra.ExactArgs(1), DisableFlagsInUseLine: true, diff --git a/cmd/podman/manifest/push.go b/cmd/podman/manifest/push.go index 91881c1b37cd..9d0977834e50 100644 --- a/cmd/podman/manifest/push.go +++ b/cmd/podman/manifest/push.go @@ -2,7 +2,9 @@ package manifest import ( "github.com/containers/common/pkg/auth" + "github.com/containers/common/pkg/completion" "github.com/containers/image/v5/types" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/containers/podman/v2/pkg/util" @@ -22,12 +24,13 @@ type manifestPushOptsWrapper struct { var ( manifestPushOpts = manifestPushOptsWrapper{} pushCmd = &cobra.Command{ - Use: "push [options] SOURCE DESTINATION", - Short: "Push a manifest list or image index to a registry", - Long: "Pushes manifest lists and image indexes to registries.", - RunE: push, - Example: `podman manifest push mylist:v1.11 quay.io/myimagelist`, - Args: cobra.ExactArgs(2), + Use: "push [options] SOURCE DESTINATION", + Short: "Push a manifest list or image index to a registry", + Long: "Pushes manifest lists and image indexes to registries.", + RunE: push, + Example: `podman manifest push mylist:v1.11 quay.io/myimagelist`, + Args: cobra.ExactArgs(2), + ValidArgsFunction: common.AutocompleteImages, } ) @@ -40,13 +43,33 @@ func init() { flags := pushCmd.Flags() flags.BoolVar(&manifestPushOpts.Purge, "purge", false, "remove the manifest list if push succeeds") flags.BoolVar(&manifestPushOpts.All, "all", false, "also push the images in the list") - flags.StringVar(&manifestPushOpts.Authfile, "authfile", auth.GetDefaultAuthFile(), "path of the authentication file. Use REGISTRY_AUTH_FILE environment variable to override") - flags.StringVar(&manifestPushOpts.CertDir, "cert-dir", "", "use certificates at the specified path to access the registry") - flags.StringVar(&manifestPushOpts.CredentialsCLI, "creds", "", "use `[username[:password]]` for accessing the registry") - flags.StringVar(&manifestPushOpts.DigestFile, "digestfile", "", "after copying the image, write the digest of the resulting digest to the file") - flags.StringVarP(&manifestPushOpts.Format, "format", "f", "", "manifest type (oci or v2s2) to attempt to use when pushing the manifest list (default is manifest type of source)") + + authfileFlagName := "authfile" + flags.StringVar(&manifestPushOpts.Authfile, authfileFlagName, auth.GetDefaultAuthFile(), "path of the authentication file. Use REGISTRY_AUTH_FILE environment variable to override") + _ = pushCmd.RegisterFlagCompletionFunc(authfileFlagName, completion.AutocompleteDefault) + + certDirFlagName := "cert-dir" + flags.StringVar(&manifestPushOpts.CertDir, certDirFlagName, "", "use certificates at the specified path to access the registry") + _ = pushCmd.RegisterFlagCompletionFunc(certDirFlagName, completion.AutocompleteDefault) + + credsFlagName := "creds" + flags.StringVar(&manifestPushOpts.CredentialsCLI, credsFlagName, "", "use `[username[:password]]` for accessing the registry") + _ = pushCmd.RegisterFlagCompletionFunc(credsFlagName, completion.AutocompleteNone) + + digestfileFlagName := "digestfile" + flags.StringVar(&manifestPushOpts.DigestFile, digestfileFlagName, "", "after copying the image, write the digest of the resulting digest to the file") + _ = pushCmd.RegisterFlagCompletionFunc(digestfileFlagName, completion.AutocompleteDefault) + + formatFlagName := "format" + flags.StringVarP(&manifestPushOpts.Format, formatFlagName, "f", "", "manifest type (oci or v2s2) to attempt to use when pushing the manifest list (default is manifest type of source)") + _ = pushCmd.RegisterFlagCompletionFunc(formatFlagName, common.AutocompleteManifestFormat) + flags.BoolVarP(&manifestPushOpts.RemoveSignatures, "remove-signatures", "", false, "don't copy signatures when pushing images") - flags.StringVar(&manifestPushOpts.SignBy, "sign-by", "", "sign the image using a GPG key with the specified `FINGERPRINT`") + + signByFlagName := "sign-by" + flags.StringVar(&manifestPushOpts.SignBy, signByFlagName, "", "sign the image using a GPG key with the specified `FINGERPRINT`") + _ = pushCmd.RegisterFlagCompletionFunc(signByFlagName, completion.AutocompleteNone) + flags.BoolVar(&manifestPushOpts.TLSVerifyCLI, "tls-verify", true, "require HTTPS and verify certificates when accessing the registry") flags.BoolVarP(&manifestPushOpts.Quiet, "quiet", "q", false, "don't output progress information when pushing lists") diff --git a/cmd/podman/manifest/remove.go b/cmd/podman/manifest/remove.go index 677d45484ad6..170e68d3f86e 100644 --- a/cmd/podman/manifest/remove.go +++ b/cmd/podman/manifest/remove.go @@ -4,6 +4,7 @@ import ( "context" "fmt" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/pkg/errors" @@ -16,6 +17,7 @@ var ( Short: "Remove an entry from a manifest list or image index", Long: "Removes an image from a manifest list or image index.", RunE: remove, + ValidArgsFunction: common.AutocompleteImages, Example: `podman manifest remove mylist:v1.11 sha256:15352d97781ffdf357bf3459c037be3efac4133dc9070c2dce7eca7c05c3e736`, Args: cobra.ExactArgs(2), DisableFlagsInUseLine: true, diff --git a/cmd/podman/networks/create.go b/cmd/podman/networks/create.go index c06011ce9ab1..17de2c95dc3d 100644 --- a/cmd/podman/networks/create.go +++ b/cmd/podman/networks/create.go @@ -4,22 +4,24 @@ import ( "fmt" "net" + "github.com/containers/common/pkg/completion" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/libpod/define" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/spf13/cobra" - "github.com/spf13/pflag" ) var ( networkCreateDescription = `create CNI networks for containers and pods` networkCreateCommand = &cobra.Command{ - Use: "create [options] [NETWORK]", - Short: "network create", - Long: networkCreateDescription, - RunE: networkCreate, - Args: cobra.MaximumNArgs(1), - Example: `podman network create podman1`, + Use: "create [options] [NETWORK]", + Short: "network create", + Long: networkCreateDescription, + RunE: networkCreate, + Args: cobra.MaximumNArgs(1), + ValidArgsFunction: completion.AutocompleteNone, + Example: `podman network create podman1`, } ) @@ -27,16 +29,36 @@ var ( networkCreateOptions entities.NetworkCreateOptions ) -func networkCreateFlags(flags *pflag.FlagSet) { - flags.StringVarP(&networkCreateOptions.Driver, "driver", "d", "bridge", "driver to manage the network") - flags.IPVar(&networkCreateOptions.Gateway, "gateway", nil, "IPv4 or IPv6 gateway for the subnet") +func networkCreateFlags(cmd *cobra.Command) { + flags := cmd.Flags() + + driverFlagName := "driver" + flags.StringVarP(&networkCreateOptions.Driver, driverFlagName, "d", "bridge", "driver to manage the network") + _ = cmd.RegisterFlagCompletionFunc(driverFlagName, common.AutocompleteNetworkDriver) + + gatewayFlagName := "gateway" + flags.IPVar(&networkCreateOptions.Gateway, gatewayFlagName, nil, "IPv4 or IPv6 gateway for the subnet") + _ = cmd.RegisterFlagCompletionFunc(gatewayFlagName, completion.AutocompleteNone) + flags.BoolVar(&networkCreateOptions.Internal, "internal", false, "restrict external access from this network") - flags.IPNetVar(&networkCreateOptions.Range, "ip-range", net.IPNet{}, "allocate container IP from range") - flags.StringVar(&networkCreateOptions.MacVLAN, "macvlan", "", "create a Macvlan connection based on this device") + + ipRangeFlagName := "ip-range" + flags.IPNetVar(&networkCreateOptions.Range, ipRangeFlagName, net.IPNet{}, "allocate container IP from range") + _ = cmd.RegisterFlagCompletionFunc(ipRangeFlagName, completion.AutocompleteNone) + + macvlanFlagName := "macvlan" + flags.StringVar(&networkCreateOptions.MacVLAN, macvlanFlagName, "", "create a Macvlan connection based on this device") + _ = cmd.RegisterFlagCompletionFunc(macvlanFlagName, completion.AutocompleteNone) + // TODO not supported yet // flags.StringVar(&networkCreateOptions.IPamDriver, "ipam-driver", "", "IP Address Management Driver") + flags.BoolVar(&networkCreateOptions.IPv6, "ipv6", false, "enable IPv6 networking") - flags.IPNetVar(&networkCreateOptions.Subnet, "subnet", net.IPNet{}, "subnet in CIDR format") + + subnetFlagName := "subnet" + flags.IPNetVar(&networkCreateOptions.Subnet, subnetFlagName, net.IPNet{}, "subnet in CIDR format") + _ = cmd.RegisterFlagCompletionFunc(subnetFlagName, completion.AutocompleteNone) + flags.BoolVar(&networkCreateOptions.DisableDNS, "disable-dns", false, "disable dns plugin") } func init() { @@ -45,8 +67,7 @@ func init() { Command: networkCreateCommand, Parent: networkCmd, }) - flags := networkCreateCommand.Flags() - networkCreateFlags(flags) + networkCreateFlags(networkCreateCommand) } diff --git a/cmd/podman/networks/inspect.go b/cmd/podman/networks/inspect.go index 25ee7e574179..671b0265fb5e 100644 --- a/cmd/podman/networks/inspect.go +++ b/cmd/podman/networks/inspect.go @@ -1,6 +1,7 @@ package network import ( + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/inspect" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/domain/entities" @@ -10,12 +11,13 @@ import ( var ( networkinspectDescription = `Inspect network` networkinspectCommand = &cobra.Command{ - Use: "inspect [options] NETWORK [NETWORK...]", - Short: "network inspect", - Long: networkinspectDescription, - RunE: networkInspect, - Example: `podman network inspect podman`, - Args: cobra.MinimumNArgs(1), + Use: "inspect [options] NETWORK [NETWORK...]", + Short: "network inspect", + Long: networkinspectDescription, + RunE: networkInspect, + Example: `podman network inspect podman`, + Args: cobra.MinimumNArgs(1), + ValidArgsFunction: common.AutocompleteNetworks, } inspectOpts *entities.InspectOptions ) @@ -28,7 +30,10 @@ func init() { }) inspectOpts = new(entities.InspectOptions) flags := networkinspectCommand.Flags() - flags.StringVarP(&inspectOpts.Format, "format", "f", "", "Pretty-print network to JSON or using a Go template") + + formatFlagName := "format" + flags.StringVarP(&inspectOpts.Format, formatFlagName, "f", "", "Pretty-print network to JSON or using a Go template") + _ = networkinspectCommand.RegisterFlagCompletionFunc(formatFlagName, common.AutocompleteJSONFormat) } func networkInspect(_ *cobra.Command, args []string) error { diff --git a/cmd/podman/networks/list.go b/cmd/podman/networks/list.go index f68e4ed75383..bab6b45ea842 100644 --- a/cmd/podman/networks/list.go +++ b/cmd/podman/networks/list.go @@ -8,7 +8,9 @@ import ( "text/tabwriter" "text/template" + "github.com/containers/common/pkg/completion" "github.com/containers/common/pkg/report" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/parse" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/validate" @@ -21,12 +23,13 @@ import ( var ( networklistDescription = `List networks` networklistCommand = &cobra.Command{ - Use: "ls [options]", - Args: validate.NoArgs, - Short: "network list", - Long: networklistDescription, - RunE: networkList, - Example: `podman network list`, + Use: "ls [options]", + Args: validate.NoArgs, + Short: "network list", + Long: networklistDescription, + RunE: networkList, + ValidArgsFunction: completion.AutocompleteNone, + Example: `podman network list`, } ) @@ -35,11 +38,16 @@ var ( ) func networkListFlags(flags *pflag.FlagSet) { - // TODO enable filters based on something - // flags.StringSliceVarP(&networklistCommand.Filter, "filter", "f", []string{}, "Pause all running containers") - flags.StringVarP(&networkListOptions.Format, "format", "f", "", "Pretty-print networks to JSON or using a Go template") + formatFlagName := "format" + flags.StringVarP(&networkListOptions.Format, formatFlagName, "f", "", "Pretty-print networks to JSON or using a Go template") + _ = networklistCommand.RegisterFlagCompletionFunc(formatFlagName, common.AutocompleteJSONFormat) + flags.BoolVarP(&networkListOptions.Quiet, "quiet", "q", false, "display only names") - flags.StringVarP(&networkListOptions.Filter, "filter", "", "", "Provide filter values (e.g. 'name=podman')") + + filterFlagName := "filter" + flags.StringVarP(&networkListOptions.Filter, filterFlagName, "", "", "Provide filter values (e.g. 'name=podman')") + _ = networklistCommand.RegisterFlagCompletionFunc(filterFlagName, completion.AutocompleteNone) + } func init() { diff --git a/cmd/podman/networks/rm.go b/cmd/podman/networks/rm.go index 3d7db941a92c..34e756a3a12a 100644 --- a/cmd/podman/networks/rm.go +++ b/cmd/podman/networks/rm.go @@ -4,6 +4,7 @@ import ( "fmt" "strings" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" "github.com/containers/podman/v2/libpod/define" @@ -16,12 +17,13 @@ import ( var ( networkrmDescription = `Remove networks` networkrmCommand = &cobra.Command{ - Use: "rm [options] NETWORK [NETWORK...]", - Short: "network rm", - Long: networkrmDescription, - RunE: networkRm, - Example: `podman network rm podman`, - Args: cobra.MinimumNArgs(1), + Use: "rm [options] NETWORK [NETWORK...]", + Short: "network rm", + Long: networkrmDescription, + RunE: networkRm, + Example: `podman network rm podman`, + Args: cobra.MinimumNArgs(1), + ValidArgsFunction: common.AutocompleteNetworks, } ) diff --git a/cmd/podman/play/kube.go b/cmd/podman/play/kube.go index 4f34b2b7683c..a9e91bd68711 100644 --- a/cmd/podman/play/kube.go +++ b/cmd/podman/play/kube.go @@ -5,7 +5,9 @@ import ( "os" "github.com/containers/common/pkg/auth" + "github.com/containers/common/pkg/completion" "github.com/containers/image/v5/types" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" "github.com/containers/podman/v2/pkg/domain/entities" @@ -31,11 +33,12 @@ var ( It creates the pod and containers described in the YAML. The containers within the pod are then started and the ID of the new Pod is output.` kubeCmd = &cobra.Command{ - Use: "kube [options] KUBEFILE", - Short: "Play a pod based on Kubernetes YAML.", - Long: kubeDescription, - RunE: kube, - Args: cobra.ExactArgs(1), + Use: "kube [options] KUBEFILE", + Short: "Play a pod based on Kubernetes YAML.", + Long: kubeDescription, + RunE: kube, + Args: cobra.ExactArgs(1), + ValidArgsFunction: completion.AutocompleteDefault, Example: `podman play kube nginx.yml podman play kube --creds user:password --seccomp-profile-root /custom/path apache.yml`, } @@ -50,17 +53,41 @@ func init() { flags := kubeCmd.Flags() flags.SetNormalizeFunc(utils.AliasFlags) - flags.StringVar(&kubeOptions.CredentialsCLI, "creds", "", "`Credentials` (USERNAME:PASSWORD) to use for authenticating to a registry") - flags.StringVar(&kubeOptions.Network, "network", "", "Connect pod to CNI network(s)") - flags.StringVar(&kubeOptions.LogDriver, "log-driver", "", "Logging driver for the container") + + credsFlagName := "creds" + flags.StringVar(&kubeOptions.CredentialsCLI, credsFlagName, "", "`Credentials` (USERNAME:PASSWORD) to use for authenticating to a registry") + _ = kubeCmd.RegisterFlagCompletionFunc(credsFlagName, completion.AutocompleteNone) + + networkFlagName := "network" + flags.StringVar(&kubeOptions.Network, networkFlagName, "", "Connect pod to CNI network(s)") + _ = kubeCmd.RegisterFlagCompletionFunc(networkFlagName, common.AutocompleteNetworks) + + logDriverFlagName := "log-driver" + flags.StringVar(&kubeOptions.LogDriver, logDriverFlagName, "", "Logging driver for the container") + _ = kubeCmd.RegisterFlagCompletionFunc(logDriverFlagName, common.AutocompleteLogDriver) + flags.BoolVarP(&kubeOptions.Quiet, "quiet", "q", false, "Suppress output information when pulling images") flags.BoolVar(&kubeOptions.TLSVerifyCLI, "tls-verify", true, "Require HTTPS and verify certificates when contacting registries") - flags.StringVar(&kubeOptions.Authfile, "authfile", auth.GetDefaultAuthFile(), "Path of the authentication file. Use REGISTRY_AUTH_FILE environment variable to override") + + authfileFlagName := "authfile" + flags.StringVar(&kubeOptions.Authfile, authfileFlagName, auth.GetDefaultAuthFile(), "Path of the authentication file. Use REGISTRY_AUTH_FILE environment variable to override") + _ = kubeCmd.RegisterFlagCompletionFunc(authfileFlagName, completion.AutocompleteDefault) + if !registry.IsRemote() { - flags.StringVar(&kubeOptions.CertDir, "cert-dir", "", "`Pathname` of a directory containing TLS certificates and keys") + + certDirFlagName := "cert-dir" + flags.StringVar(&kubeOptions.CertDir, certDirFlagName, "", "`Pathname` of a directory containing TLS certificates and keys") + _ = kubeCmd.RegisterFlagCompletionFunc(certDirFlagName, completion.AutocompleteDefault) + flags.StringVar(&kubeOptions.SignaturePolicy, "signature-policy", "", "`Pathname` of signature policy file (not usually used)") - flags.StringVar(&kubeOptions.SeccompProfileRoot, "seccomp-profile-root", defaultSeccompRoot, "Directory path for seccomp profiles") - flags.StringSliceVar(&kubeOptions.ConfigMaps, "configmap", []string{}, "`Pathname` of a YAML file containing a kubernetes configmap") + + seccompProfileRootFlagName := "seccomp-profile-root" + flags.StringVar(&kubeOptions.SeccompProfileRoot, seccompProfileRootFlagName, defaultSeccompRoot, "Directory path for seccomp profiles") + _ = kubeCmd.RegisterFlagCompletionFunc(seccompProfileRootFlagName, completion.AutocompleteDefault) + + configmapFlagName := "configmap" + flags.StringSliceVar(&kubeOptions.ConfigMaps, configmapFlagName, []string{}, "`Pathname` of a YAML file containing a kubernetes configmap") + _ = kubeCmd.RegisterFlagCompletionFunc(configmapFlagName, completion.AutocompleteDefault) } _ = flags.MarkHidden("signature-policy") } diff --git a/cmd/podman/pods/create.go b/cmd/podman/pods/create.go index efa84dcb4a78..d33455e81554 100644 --- a/cmd/podman/pods/create.go +++ b/cmd/podman/pods/create.go @@ -7,6 +7,7 @@ import ( "os" "strings" + "github.com/containers/common/pkg/completion" "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/parse" "github.com/containers/podman/v2/cmd/podman/registry" @@ -27,11 +28,12 @@ var ( You can then start it at any time with the podman pod start command. The pod will be created with the initial state 'created'.` createCommand = &cobra.Command{ - Use: "create [options]", - Args: validate.NoArgs, - Short: "Create a new empty pod", - Long: podCreateDescription, - RunE: create, + Use: "create [options]", + Args: validate.NoArgs, + Short: "Create a new empty pod", + Long: podCreateDescription, + RunE: create, + ValidArgsFunction: completion.AutocompleteNone, } ) @@ -51,19 +53,53 @@ func init() { }) flags := createCommand.Flags() flags.SetInterspersed(false) - flags.AddFlagSet(common.GetNetFlags()) - flags.StringVar(&createOptions.CGroupParent, "cgroup-parent", "", "Set parent cgroup for the pod") + + common.DefineNetFlags(createCommand) + + cgroupParentflagName := "cgroup-parent" + flags.StringVar(&createOptions.CGroupParent, cgroupParentflagName, "", "Set parent cgroup for the pod") + _ = createCommand.RegisterFlagCompletionFunc(cgroupParentflagName, completion.AutocompleteDefault) + flags.BoolVar(&createOptions.Infra, "infra", true, "Create an infra container associated with the pod to share namespaces with") - flags.StringVar(&createOptions.InfraConmonPidFile, "infra-conmon-pidfile", "", "Path to the file that will receive the POD of the infra container's conmon") - flags.String("infra-image", containerConfig.Engine.InfraImage, "The image of the infra container to associate with the pod") - flags.String("infra-command", containerConfig.Engine.InfraCommand, "The command to run on the infra container when the pod is started") - flags.StringSliceVar(&labelFile, "label-file", []string{}, "Read in a line delimited file of labels") - flags.StringSliceVarP(&labels, "label", "l", []string{}, "Set metadata on pod (default [])") - flags.StringVarP(&createOptions.Name, "name", "n", "", "Assign a name to the pod") - flags.StringVarP(&createOptions.Hostname, "hostname", "", "", "Set a hostname to the pod") - flags.StringVar(&podIDFile, "pod-id-file", "", "Write the pod ID to the file") + + infraConmonPidfileFlagName := "infra-conmon-pidfile" + flags.StringVar(&createOptions.InfraConmonPidFile, infraConmonPidfileFlagName, "", "Path to the file that will receive the POD of the infra container's conmon") + _ = createCommand.RegisterFlagCompletionFunc(infraConmonPidfileFlagName, completion.AutocompleteDefault) + + infraImageFlagName := "infra-image" + flags.String(infraImageFlagName, containerConfig.Engine.InfraImage, "The image of the infra container to associate with the pod") + _ = createCommand.RegisterFlagCompletionFunc(infraImageFlagName, common.AutocompleteImages) + + infraCommandFlagName := "infra-command" + flags.String(infraCommandFlagName, containerConfig.Engine.InfraCommand, "The command to run on the infra container when the pod is started") + _ = createCommand.RegisterFlagCompletionFunc(infraCommandFlagName, completion.AutocompleteNone) + + labelFileFlagName := "label-file" + flags.StringSliceVar(&labelFile, labelFileFlagName, []string{}, "Read in a line delimited file of labels") + _ = createCommand.RegisterFlagCompletionFunc(labelFileFlagName, completion.AutocompleteDefault) + + labelFlagName := "label" + flags.StringSliceVarP(&labels, labelFlagName, "l", []string{}, "Set metadata on pod (default [])") + _ = createCommand.RegisterFlagCompletionFunc(labelFlagName, completion.AutocompleteNone) + + nameFlagName := "name" + flags.StringVarP(&createOptions.Name, nameFlagName, "n", "", "Assign a name to the pod") + _ = createCommand.RegisterFlagCompletionFunc(nameFlagName, completion.AutocompleteNone) + + hostnameFlagName := "hostname" + flags.StringVarP(&createOptions.Hostname, hostnameFlagName, "", "", "Set a hostname to the pod") + _ = createCommand.RegisterFlagCompletionFunc(hostnameFlagName, completion.AutocompleteNone) + + podIDFileFlagName := "pod-id-file" + flags.StringVar(&podIDFile, podIDFileFlagName, "", "Write the pod ID to the file") + _ = createCommand.RegisterFlagCompletionFunc(podIDFileFlagName, completion.AutocompleteDefault) + flags.BoolVar(&replace, "replace", false, "If a pod with the same exists, replace it") - flags.StringVar(&share, "share", specgen.DefaultKernelNamespaces, "A comma delimited list of kernel namespaces the pod will share") + + shareFlagName := "share" + flags.StringVar(&share, shareFlagName, specgen.DefaultKernelNamespaces, "A comma delimited list of kernel namespaces the pod will share") + _ = createCommand.RegisterFlagCompletionFunc(shareFlagName, common.AutocompletePodShareNamespace) + flags.SetNormalizeFunc(aliasNetworkFlag) } diff --git a/cmd/podman/pods/exists.go b/cmd/podman/pods/exists.go index cdaf2a707e0d..a5c45803ebb2 100644 --- a/cmd/podman/pods/exists.go +++ b/cmd/podman/pods/exists.go @@ -3,6 +3,7 @@ package pods import ( "context" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/spf13/cobra" @@ -12,11 +13,12 @@ var ( podExistsDescription = `If the named pod exists in local storage, podman pod exists exits with 0, otherwise the exit code will be 1.` existsCommand = &cobra.Command{ - Use: "exists POD", - Short: "Check if a pod exists in local storage", - Long: podExistsDescription, - RunE: exists, - Args: cobra.ExactArgs(1), + Use: "exists POD", + Short: "Check if a pod exists in local storage", + Long: podExistsDescription, + RunE: exists, + Args: cobra.ExactArgs(1), + ValidArgsFunction: common.AutocompletePods, Example: `podman pod exists podID podman pod exists mypod || podman pod create --name mypod`, DisableFlagsInUseLine: true, diff --git a/cmd/podman/pods/inspect.go b/cmd/podman/pods/inspect.go index 7f81ba8fbe8a..091094ff617f 100644 --- a/cmd/podman/pods/inspect.go +++ b/cmd/podman/pods/inspect.go @@ -8,6 +8,7 @@ import ( "text/template" "github.com/containers/common/pkg/report" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/validate" "github.com/containers/podman/v2/pkg/domain/entities" @@ -25,11 +26,12 @@ var ( By default, this will render all results in a JSON array.`) inspectCmd = &cobra.Command{ - Use: "inspect [options] POD [POD...]", - Short: "Displays a pod configuration", - Long: inspectDescription, - RunE: inspect, - Example: `podman pod inspect podID`, + Use: "inspect [options] POD [POD...]", + Short: "Displays a pod configuration", + Long: inspectDescription, + RunE: inspect, + ValidArgsFunction: common.AutocompletePods, + Example: `podman pod inspect podID`, } ) @@ -40,7 +42,11 @@ func init() { Parent: podCmd, }) flags := inspectCmd.Flags() - flags.StringVarP(&inspectOptions.Format, "format", "f", "json", "Format the output to a Go template or json") + + formatFlagName := "format" + flags.StringVarP(&inspectOptions.Format, formatFlagName, "f", "json", "Format the output to a Go template or json") + _ = inspectCmd.RegisterFlagCompletionFunc(formatFlagName, common.AutocompleteJSONFormat) + validate.AddLatestFlag(inspectCmd, &inspectOptions.Latest) } diff --git a/cmd/podman/pods/kill.go b/cmd/podman/pods/kill.go index 1902a2c808c6..be8fd31dfe8b 100644 --- a/cmd/podman/pods/kill.go +++ b/cmd/podman/pods/kill.go @@ -4,6 +4,7 @@ import ( "context" "fmt" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" "github.com/containers/podman/v2/cmd/podman/validate" @@ -23,6 +24,7 @@ var ( Args: func(cmd *cobra.Command, args []string) error { return validate.CheckAllLatestAndCIDFile(cmd, args, false, false) }, + ValidArgsFunction: common.AutocompletePodsRunning, Example: `podman pod kill podID podman pod kill --signal TERM mywebserver podman pod kill --latest`, @@ -41,7 +43,11 @@ func init() { }) flags := killCommand.Flags() flags.BoolVarP(&killOpts.All, "all", "a", false, "Kill all containers in all pods") - flags.StringVarP(&killOpts.Signal, "signal", "s", "KILL", "Signal to send to the containers in the pod") + + signalFlagName := "signal" + flags.StringVarP(&killOpts.Signal, signalFlagName, "s", "KILL", "Signal to send to the containers in the pod") + _ = killCommand.RegisterFlagCompletionFunc(signalFlagName, common.AutocompleteStopSignal) + validate.AddLatestFlag(killCommand, &killOpts.Latest) } diff --git a/cmd/podman/pods/pause.go b/cmd/podman/pods/pause.go index bba26f90d9c5..108893173153 100644 --- a/cmd/podman/pods/pause.go +++ b/cmd/podman/pods/pause.go @@ -4,6 +4,7 @@ import ( "context" "fmt" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" "github.com/containers/podman/v2/cmd/podman/validate" @@ -23,6 +24,7 @@ var ( Args: func(cmd *cobra.Command, args []string) error { return validate.CheckAllLatestAndCIDFile(cmd, args, false, false) }, + ValidArgsFunction: common.AutocompletePodsRunning, Example: `podman pod pause podID1 podID2 podman pod pause --latest podman pod pause --all`, diff --git a/cmd/podman/pods/prune.go b/cmd/podman/pods/prune.go index e3eae3f7151a..626ef2895864 100644 --- a/cmd/podman/pods/prune.go +++ b/cmd/podman/pods/prune.go @@ -7,6 +7,7 @@ import ( "os" "strings" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" "github.com/containers/podman/v2/cmd/podman/validate" @@ -23,12 +24,13 @@ var ( pruneDescription = fmt.Sprintf(`podman pod prune Removes all exited pods`) pruneCommand = &cobra.Command{ - Use: "prune [options]", - Args: validate.NoArgs, - Short: "Remove all stopped pods and their containers", - Long: pruneDescription, - RunE: prune, - Example: `podman pod prune`, + Use: "prune [options]", + Args: validate.NoArgs, + Short: "Remove all stopped pods and their containers", + Long: pruneDescription, + RunE: prune, + ValidArgsFunction: common.AutocompletePods, + Example: `podman pod prune`, } ) diff --git a/cmd/podman/pods/ps.go b/cmd/podman/pods/ps.go index 40fc71780ca9..51c2e92f0a3b 100644 --- a/cmd/podman/pods/ps.go +++ b/cmd/podman/pods/ps.go @@ -10,7 +10,9 @@ import ( "text/template" "time" + "github.com/containers/common/pkg/completion" "github.com/containers/common/pkg/report" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/parse" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/validate" @@ -25,12 +27,13 @@ var ( // Command: podman pod _ps_ psCmd = &cobra.Command{ - Use: "ps [options]", - Aliases: []string{"ls", "list"}, - Short: "List pods", - Long: psDescription, - RunE: pods, - Args: validate.NoArgs, + Use: "ps [options]", + Aliases: []string{"ls", "list"}, + Short: "List pods", + Long: psDescription, + RunE: pods, + Args: validate.NoArgs, + ValidArgsFunction: completion.AutocompleteNone, } ) @@ -51,13 +54,25 @@ func init() { flags.BoolVar(&psInput.CtrIds, "ctr-ids", false, "Display the container UUIDs. If no-trunc is not set they will be truncated") flags.BoolVar(&psInput.CtrStatus, "ctr-status", false, "Display the container status") // TODO should we make this a [] ? - flags.StringSliceVarP(&inputFilters, "filter", "f", []string{}, "Filter output based on conditions given") - flags.StringVar(&psInput.Format, "format", "", "Pretty-print pods to JSON or using a Go template") + + filterFlagName := "filter" + flags.StringSliceVarP(&inputFilters, filterFlagName, "f", []string{}, "Filter output based on conditions given") + //TODO complete filters + _ = psCmd.RegisterFlagCompletionFunc(filterFlagName, completion.AutocompleteNone) + + formatFlagName := "format" + flags.StringVar(&psInput.Format, formatFlagName, "", "Pretty-print pods to JSON or using a Go template") + _ = psCmd.RegisterFlagCompletionFunc(formatFlagName, common.AutocompleteJSONFormat) + flags.BoolVar(&psInput.Namespace, "namespace", false, "Display namespace information of the pod") flags.BoolVar(&psInput.Namespace, "ns", false, "Display namespace information of the pod") flags.BoolVar(&noTrunc, "no-trunc", false, "Do not truncate pod and container IDs") flags.BoolVarP(&psInput.Quiet, "quiet", "q", false, "Print the numeric IDs of the pods only") - flags.StringVar(&psInput.Sort, "sort", "created", "Sort output by created, id, name, or number") + + sortFlagName := "sort" + flags.StringVar(&psInput.Sort, sortFlagName, "created", "Sort output by created, id, name, or number") + _ = psCmd.RegisterFlagCompletionFunc(sortFlagName, common.AutocompletePodPsSort) + validate.AddLatestFlag(psCmd, &psInput.Latest) } diff --git a/cmd/podman/pods/restart.go b/cmd/podman/pods/restart.go index 119b4ddee5d2..7a4b28a458a3 100644 --- a/cmd/podman/pods/restart.go +++ b/cmd/podman/pods/restart.go @@ -4,6 +4,7 @@ import ( "context" "fmt" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" "github.com/containers/podman/v2/cmd/podman/validate" @@ -23,6 +24,7 @@ var ( Args: func(cmd *cobra.Command, args []string) error { return validate.CheckAllLatestAndCIDFile(cmd, args, false, false) }, + ValidArgsFunction: common.AutocompletePods, Example: `podman pod restart podID1 podID2 podman pod restart --latest podman pod restart --all`, diff --git a/cmd/podman/pods/rm.go b/cmd/podman/pods/rm.go index 714e075e284d..ff238aa20387 100644 --- a/cmd/podman/pods/rm.go +++ b/cmd/podman/pods/rm.go @@ -5,6 +5,7 @@ import ( "fmt" "strings" + "github.com/containers/common/pkg/completion" "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" @@ -35,6 +36,7 @@ var ( Args: func(cmd *cobra.Command, args []string) error { return validate.CheckAllLatestAndPodIDFile(cmd, args, false, true) }, + ValidArgsFunction: common.AutocompletePods, Example: `podman pod rm mywebserverpod podman pod rm -f 860a4b23 podman pod rm -f -a`, @@ -52,7 +54,11 @@ func init() { flags.BoolVarP(&rmOptions.All, "all", "a", false, "Remove all running pods") flags.BoolVarP(&rmOptions.Force, "force", "f", false, "Force removal of a running pod by first stopping all containers, then removing all containers in the pod. The default is false") flags.BoolVarP(&rmOptions.Ignore, "ignore", "i", false, "Ignore errors when a specified pod is missing") - flags.StringArrayVarP(&rmOptions.PodIDFiles, "pod-id-file", "", nil, "Read the pod ID from the file") + + podIDFileFlagName := "pod-id-file" + flags.StringArrayVarP(&rmOptions.PodIDFiles, podIDFileFlagName, "", nil, "Read the pod ID from the file") + _ = rmCommand.RegisterFlagCompletionFunc(podIDFileFlagName, completion.AutocompleteDefault) + validate.AddLatestFlag(rmCommand, &rmOptions.Latest) if registry.IsRemote() { diff --git a/cmd/podman/pods/start.go b/cmd/podman/pods/start.go index 28ee4769a5a4..7cd5c64d904e 100644 --- a/cmd/podman/pods/start.go +++ b/cmd/podman/pods/start.go @@ -4,6 +4,7 @@ import ( "context" "fmt" + "github.com/containers/common/pkg/completion" "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" @@ -31,6 +32,7 @@ var ( Args: func(cmd *cobra.Command, args []string) error { return validate.CheckAllLatestAndPodIDFile(cmd, args, false, true) }, + ValidArgsFunction: common.AutocompletePods, Example: `podman pod start podID podman pod start --latest podman pod start --all`, @@ -50,7 +52,11 @@ func init() { flags := startCommand.Flags() flags.BoolVarP(&startOptions.All, "all", "a", false, "Restart all running pods") - flags.StringArrayVarP(&startOptions.PodIDFiles, "pod-id-file", "", nil, "Read the pod ID from the file") + + podIDFileFlagName := "pod-id-file" + flags.StringArrayVarP(&startOptions.PodIDFiles, podIDFileFlagName, "", nil, "Read the pod ID from the file") + _ = startCommand.RegisterFlagCompletionFunc(podIDFileFlagName, completion.AutocompleteDefault) + validate.AddLatestFlag(startCommand, &startOptions.Latest) } diff --git a/cmd/podman/pods/stats.go b/cmd/podman/pods/stats.go index c5d1e7f07c44..79e7cd8ed4a1 100644 --- a/cmd/podman/pods/stats.go +++ b/cmd/podman/pods/stats.go @@ -10,6 +10,7 @@ import ( "github.com/buger/goterm" "github.com/containers/common/pkg/report" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/parse" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/validate" @@ -33,10 +34,11 @@ var ( statsDescription = `Display the containers' resource-usage statistics of one or more running pod` // Command: podman pod _pod_ statsCmd = &cobra.Command{ - Use: "stats [options] [POD...]", - Short: "Display a live stream of resource usage statistics for the containers in one or more pods", - Long: statsDescription, - RunE: stats, + Use: "stats [options] [POD...]", + Short: "Display a live stream of resource usage statistics for the containers in one or more pods", + Long: statsDescription, + RunE: stats, + ValidArgsFunction: common.AutocompletePodsRunning, Example: `podman pod stats podman pod stats a69b23034235 named-pod podman pod stats --latest @@ -53,7 +55,11 @@ func init() { flags := statsCmd.Flags() flags.BoolVarP(&statsOptions.All, "all", "a", false, "Provide stats for all pods") - flags.StringVar(&statsOptions.Format, "format", "", "Pretty-print container statistics to JSON or using a Go template") + + formatFlagName := "format" + flags.StringVar(&statsOptions.Format, formatFlagName, "", "Pretty-print container statistics to JSON or using a Go template") + _ = statsCmd.RegisterFlagCompletionFunc(formatFlagName, common.AutocompleteJSONFormat) + flags.BoolVar(&statsOptions.NoReset, "no-reset", false, "Disable resetting the screen when streaming") flags.BoolVar(&statsOptions.NoStream, "no-stream", false, "Disable streaming stats and only pull the first result") validate.AddLatestFlag(statsCmd, &statsOptions.Latest) diff --git a/cmd/podman/pods/stop.go b/cmd/podman/pods/stop.go index a2a9b0b5766e..d03364028653 100644 --- a/cmd/podman/pods/stop.go +++ b/cmd/podman/pods/stop.go @@ -4,6 +4,7 @@ import ( "context" "fmt" + "github.com/containers/common/pkg/completion" "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" @@ -36,6 +37,7 @@ var ( Args: func(cmd *cobra.Command, args []string) error { return validate.CheckAllLatestAndPodIDFile(cmd, args, false, true) }, + ValidArgsFunction: common.AutocompletePodsRunning, Example: `podman pod stop mywebserverpod podman pod stop --latest podman pod stop --time 0 490eb 3557fb`, @@ -51,8 +53,15 @@ func init() { flags := stopCommand.Flags() flags.BoolVarP(&stopOptions.All, "all", "a", false, "Stop all running pods") flags.BoolVarP(&stopOptions.Ignore, "ignore", "i", false, "Ignore errors when a specified pod is missing") - flags.UintVarP(&stopOptions.TimeoutCLI, "time", "t", containerConfig.Engine.StopTimeout, "Seconds to wait for pod stop before killing the container") - flags.StringArrayVarP(&stopOptions.PodIDFiles, "pod-id-file", "", nil, "Read the pod ID from the file") + + timeFlagName := "time" + flags.UintVarP(&stopOptions.TimeoutCLI, timeFlagName, "t", containerConfig.Engine.StopTimeout, "Seconds to wait for pod stop before killing the container") + _ = stopCommand.RegisterFlagCompletionFunc(timeFlagName, completion.AutocompleteNone) + + podIDFileFlagName := "pod-id-file" + flags.StringArrayVarP(&stopOptions.PodIDFiles, podIDFileFlagName, "", nil, "Write the pod ID to the file") + _ = stopCommand.RegisterFlagCompletionFunc(podIDFileFlagName, completion.AutocompleteDefault) + validate.AddLatestFlag(stopCommand, &stopOptions.Latest) if registry.IsRemote() { diff --git a/cmd/podman/pods/top.go b/cmd/podman/pods/top.go index 0ffa724da052..45ef1e7c288e 100644 --- a/cmd/podman/pods/top.go +++ b/cmd/podman/pods/top.go @@ -7,6 +7,7 @@ import ( "strings" "text/tabwriter" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/validate" "github.com/containers/podman/v2/pkg/domain/entities" @@ -23,11 +24,12 @@ var ( topOptions = entities.PodTopOptions{} topCommand = &cobra.Command{ - Use: "top [options] POD [FORMAT-DESCRIPTORS|ARGS...]", - Short: "Display the running processes of containers in a pod", - Long: topDescription, - RunE: top, - Args: cobra.ArbitraryArgs, + Use: "top [options] POD [FORMAT-DESCRIPTORS|ARGS...]", + Short: "Display the running processes of containers in a pod", + Long: topDescription, + RunE: top, + Args: cobra.ArbitraryArgs, + ValidArgsFunction: common.AutocompletePodsRunning, Example: `podman pod top podID podman pod top --latest podman pod top podID pid seccomp args %C diff --git a/cmd/podman/pods/unpause.go b/cmd/podman/pods/unpause.go index 15b30db144ab..499faec37ee5 100644 --- a/cmd/podman/pods/unpause.go +++ b/cmd/podman/pods/unpause.go @@ -4,6 +4,7 @@ import ( "context" "fmt" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" "github.com/containers/podman/v2/cmd/podman/validate" @@ -23,6 +24,9 @@ var ( Args: func(cmd *cobra.Command, args []string) error { return validate.CheckAllLatestAndCIDFile(cmd, args, false, false) }, + // TODO have a function which shows only pods which could be unpaused + // for now show all + ValidArgsFunction: common.AutocompletePods, Example: `podman pod unpause podID1 podID2 podman pod unpause --all podman pod unpause --latest`, diff --git a/cmd/podman/registry/remote.go b/cmd/podman/registry/remote.go index 78b8202691ac..6e9b1fdfcefd 100644 --- a/cmd/podman/registry/remote.go +++ b/cmd/podman/registry/remote.go @@ -5,6 +5,7 @@ import ( "sync" "github.com/containers/podman/v2/pkg/domain/entities" + "github.com/spf13/cobra" "github.com/spf13/pflag" ) @@ -23,7 +24,15 @@ func IsRemote() bool { fs.Usage = func() {} fs.SetInterspersed(false) fs.BoolVarP(&remoteFromCLI.Value, "remote", "r", false, "") - _ = fs.Parse(os.Args[1:]) + + // The shell completion logic will call a command called "__complete" or "__completeNoDesc" + // This command will always be the second argument + // To still parse --remote correctly in this case we have to set args offset to two in this case + start := 1 + if len(os.Args) > 1 && (os.Args[1] == cobra.ShellCompRequestCmd || os.Args[1] == cobra.ShellCompNoDescRequestCmd) { + start = 2 + } + _ = fs.Parse(os.Args[start:]) }) return podmanOptions.EngineMode == entities.TunnelMode || remoteFromCLI.Value } diff --git a/cmd/podman/root.go b/cmd/podman/root.go index b59b8341a6b3..0a44f5eac5b9 100644 --- a/cmd/podman/root.go +++ b/cmd/podman/root.go @@ -8,7 +8,9 @@ import ( "runtime/pprof" "strings" + "github.com/containers/common/pkg/completion" "github.com/containers/common/pkg/config" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/validate" "github.com/containers/podman/v2/libpod/define" @@ -21,6 +23,7 @@ import ( "github.com/pkg/errors" "github.com/sirupsen/logrus" "github.com/spf13/cobra" + "github.com/spf13/pflag" ) // HelpTemplate is the help template for podman commands @@ -67,9 +70,10 @@ var ( Version: version.Version.String(), DisableFlagsInUseLine: true, } - logLevels = []string{"debug", "info", "warn", "error", "fatal", "panic"} - logLevel = "error" - useSyslog bool + + logLevel = "error" + useSyslog bool + requireCleanup = true ) func init() { @@ -102,11 +106,36 @@ func persistentPreRunE(cmd *cobra.Command, args []string) error { // TODO: Remove trace statement in podman V2.1 logrus.Debugf("Called %s.PersistentPreRunE(%s)", cmd.Name(), strings.Join(os.Args, " ")) - // Help and commands with subcommands are special cases, no need for more setup - if cmd.Name() == "help" || cmd.HasSubCommands() { + // Help, completion and commands with subcommands are special cases, no need for more setup + // Completion cmd is used to generate the shell scripts + if cmd.Name() == "help" || cmd.Name() == "completion" || cmd.HasSubCommands() { + requireCleanup = false return nil } + // Special case if command is hidden completion command ("__complete","__completeNoDesc") + // Since __completeNoDesc is an alias the cm.Name is always __complete + if cmd.Name() == cobra.ShellCompRequestCmd { + // Parse the cli arguments after the the completion cmd (always called as second argument) + // This ensures that the --url, --identity and --connection flags are properly set + compCmd, _, err := cmd.Root().Traverse(os.Args[2:]) + if err != nil { + return err + } + // If we don't complete the root cmd hide all root flags + // so they won't show up in the completions on subcommands. + if compCmd != compCmd.Root() { + compCmd.Root().Flags().VisitAll(func(flag *pflag.Flag) { + flag.Hidden = true + }) + } + // No need for further setup when completing commands with subcommands. + if compCmd.HasSubCommands() { + requireCleanup = false + return nil + } + } + cfg := registry.PodmanConfig() // --connection is not as "special" as --remote so we can wait and process it here @@ -203,8 +232,7 @@ func persistentPostRunE(cmd *cobra.Command, args []string) error { // TODO: Remove trace statement in podman V2.1 logrus.Debugf("Called %s.PersistentPostRunE(%s)", cmd.Name(), strings.Join(os.Args, " ")) - // Help and commands with subcommands are special cases, no need for more cleanup - if cmd.Name() == "help" || cmd.HasSubCommands() { + if !requireCleanup { return nil } @@ -226,14 +254,14 @@ func persistentPostRunE(cmd *cobra.Command, args []string) error { func loggingHook() { var found bool - for _, l := range logLevels { + for _, l := range common.LogLevels { if l == strings.ToLower(logLevel) { found = true break } } if !found { - fmt.Fprintf(os.Stderr, "Log Level %q is not supported, choose from: %s\n", logLevel, strings.Join(logLevels, ", ")) + fmt.Fprintf(os.Stderr, "Log Level %q is not supported, choose from: %s\n", logLevel, strings.Join(common.LogLevels, ", ")) os.Exit(1) } @@ -254,9 +282,18 @@ func rootFlags(cmd *cobra.Command, opts *entities.PodmanConfig) { srv, uri, ident := resolveDestination() lFlags := cmd.Flags() - lFlags.StringVarP(&opts.Engine.ActiveService, "connection", "c", srv, "Connection to use for remote Podman service") - lFlags.StringVar(&opts.URI, "url", uri, "URL to access Podman service (CONTAINER_HOST)") - lFlags.StringVar(&opts.Identity, "identity", ident, "path to SSH identity file, (CONTAINER_SSHKEY)") + + connectionFlagName := "connection" + lFlags.StringVarP(&opts.Engine.ActiveService, connectionFlagName, "c", srv, "Connection to use for remote Podman service") + _ = cmd.RegisterFlagCompletionFunc(connectionFlagName, common.AutocompleteSystemConnections) + + urlFlagName := "url" + lFlags.StringVar(&opts.URI, urlFlagName, uri, "URL to access Podman service (CONTAINER_HOST)") + _ = cmd.RegisterFlagCompletionFunc(urlFlagName, completion.AutocompleteDefault) + + identityFlagName := "identity" + lFlags.StringVar(&opts.Identity, identityFlagName, ident, "path to SSH identity file, (CONTAINER_SSHKEY)") + _ = cmd.RegisterFlagCompletionFunc(identityFlagName, completion.AutocompleteDefault) lFlags.BoolVarP(&opts.Remote, "remote", "r", false, "Access remote Podman service (default false)") pFlags := cmd.PersistentFlags() @@ -266,25 +303,67 @@ func rootFlags(cmd *cobra.Command, opts *entities.PodmanConfig) { } opts.Remote = true } else { - pFlags.StringVar(&cfg.Engine.CgroupManager, "cgroup-manager", cfg.Engine.CgroupManager, "Cgroup manager to use (\"cgroupfs\"|\"systemd\")") + cgroupManagerFlagName := "cgroup-manager" + pFlags.StringVar(&cfg.Engine.CgroupManager, cgroupManagerFlagName, cfg.Engine.CgroupManager, "Cgroup manager to use (\"cgroupfs\"|\"systemd\")") + _ = cmd.RegisterFlagCompletionFunc(cgroupManagerFlagName, common.AutocompleteCgroupManager) + pFlags.StringVar(&opts.CPUProfile, "cpu-profile", "", "Path for the cpu profiling results") - pFlags.StringVar(&opts.ConmonPath, "conmon", "", "Path of the conmon binary") - pFlags.StringVar(&cfg.Engine.NetworkCmdPath, "network-cmd-path", cfg.Engine.NetworkCmdPath, "Path to the command for configuring the network") - pFlags.StringVar(&cfg.Network.NetworkConfigDir, "cni-config-dir", cfg.Network.NetworkConfigDir, "Path of the configuration directory for CNI networks") + + conmonFlagName := "conmon" + pFlags.StringVar(&opts.ConmonPath, conmonFlagName, "", "Path of the conmon binary") + _ = cmd.RegisterFlagCompletionFunc(conmonFlagName, completion.AutocompleteDefault) + + networkCmdPathFlagName := "network-cmd-path" + pFlags.StringVar(&cfg.Engine.NetworkCmdPath, networkCmdPathFlagName, cfg.Engine.NetworkCmdPath, "Path to the command for configuring the network") + _ = cmd.RegisterFlagCompletionFunc(networkCmdPathFlagName, completion.AutocompleteDefault) + + cniConfigDirFlagName := "cni-config-dir" + pFlags.StringVar(&cfg.Network.NetworkConfigDir, cniConfigDirFlagName, cfg.Network.NetworkConfigDir, "Path of the configuration directory for CNI networks") + _ = cmd.RegisterFlagCompletionFunc(cniConfigDirFlagName, completion.AutocompleteDefault) + pFlags.StringVar(&cfg.Containers.DefaultMountsFile, "default-mounts-file", cfg.Containers.DefaultMountsFile, "Path to default mounts file") - pFlags.StringVar(&cfg.Engine.EventsLogger, "events-backend", cfg.Engine.EventsLogger, `Events backend to use ("file"|"journald"|"none")`) - pFlags.StringSliceVar(&cfg.Engine.HooksDir, "hooks-dir", cfg.Engine.HooksDir, "Set the OCI hooks directory path (may be set multiple times)") + + eventsBackendFlagName := "events-backend" + pFlags.StringVar(&cfg.Engine.EventsLogger, eventsBackendFlagName, cfg.Engine.EventsLogger, `Events backend to use ("file"|"journald"|"none")`) + _ = cmd.RegisterFlagCompletionFunc(eventsBackendFlagName, common.AutocompleteEventBackend) + + hooksDirFlagName := "hooks-dir" + pFlags.StringSliceVar(&cfg.Engine.HooksDir, hooksDirFlagName, cfg.Engine.HooksDir, "Set the OCI hooks directory path (may be set multiple times)") + _ = cmd.RegisterFlagCompletionFunc(hooksDirFlagName, completion.AutocompleteDefault) + pFlags.IntVar(&opts.MaxWorks, "max-workers", (runtime.NumCPU()*3)+1, "The maximum number of workers for parallel operations") - pFlags.StringVar(&cfg.Engine.Namespace, "namespace", cfg.Engine.Namespace, "Set the libpod namespace, used to create separate views of the containers and pods on the system") - pFlags.StringVar(&cfg.Engine.StaticDir, "root", "", "Path to the root directory in which data, including images, is stored") + + namespaceFlagName := "namespace" + pFlags.StringVar(&cfg.Engine.Namespace, namespaceFlagName, cfg.Engine.Namespace, "Set the libpod namespace, used to create separate views of the containers and pods on the system") + _ = cmd.RegisterFlagCompletionFunc(namespaceFlagName, completion.AutocompleteNone) + + rootFlagName := "root" + pFlags.StringVar(&cfg.Engine.StaticDir, rootFlagName, "", "Path to the root directory in which data, including images, is stored") + _ = cmd.RegisterFlagCompletionFunc(rootFlagName, completion.AutocompleteDefault) + pFlags.StringVar(&opts.RegistriesConf, "registries-conf", "", "Path to a registries.conf to use for image processing") - pFlags.StringVar(&opts.Runroot, "runroot", "", "Path to the 'run directory' where all state information is stored") - pFlags.StringVar(&opts.RuntimePath, "runtime", "", "Path to the OCI-compatible binary used to run containers, default is /usr/bin/runc") + + runrootFlagName := "runroot" + pFlags.StringVar(&opts.Runroot, runrootFlagName, "", "Path to the 'run directory' where all state information is stored") + _ = cmd.RegisterFlagCompletionFunc(runrootFlagName, completion.AutocompleteDefault) + + runtimeFlagName := "runtime" + pFlags.StringVar(&opts.RuntimePath, runtimeFlagName, "", "Path to the OCI-compatible binary used to run containers, default is /usr/bin/runc") + _ = cmd.RegisterFlagCompletionFunc(runtimeFlagName, completion.AutocompleteDefault) + // -s is deprecated due to conflict with -s on subcommands - pFlags.StringVar(&opts.StorageDriver, "storage-driver", "", "Select which storage driver is used to manage storage of images and containers (default is overlay)") - pFlags.StringArrayVar(&opts.StorageOpts, "storage-opt", []string{}, "Used to pass an option to the storage driver") + storageDriverFlagName := "storage-driver" + pFlags.StringVar(&opts.StorageDriver, storageDriverFlagName, "", "Select which storage driver is used to manage storage of images and containers (default is overlay)") + _ = cmd.RegisterFlagCompletionFunc(storageDriverFlagName, completion.AutocompleteNone) //TODO: what can we recommend here? + + storageOptFlagName := "storage-opt" + pFlags.StringArrayVar(&opts.StorageOpts, storageOptFlagName, []string{}, "Used to pass an option to the storage driver") + _ = cmd.RegisterFlagCompletionFunc(storageOptFlagName, completion.AutocompleteNone) + + tmpdirFlagName := "tmpdir" + pFlags.StringVar(&opts.Engine.TmpDir, tmpdirFlagName, "", "Path to the tmp directory for libpod state content.\n\nNote: use the environment variable 'TMPDIR' to change the temporary storage location for container images, '/var/tmp'.\n") + _ = cmd.RegisterFlagCompletionFunc(tmpdirFlagName, completion.AutocompleteDefault) - pFlags.StringVar(&opts.Engine.TmpDir, "tmpdir", "", "Path to the tmp directory for libpod state content.\n\nNote: use the environment variable 'TMPDIR' to change the temporary storage location for container images, '/var/tmp'.\n") pFlags.BoolVar(&opts.Trace, "trace", false, "Enable opentracing output (default false)") // Hide these flags for both ABI and Tunneling @@ -303,11 +382,17 @@ func rootFlags(cmd *cobra.Command, opts *entities.PodmanConfig) { // Override default --help information of `--help` global flag var dummyHelp bool pFlags.BoolVar(&dummyHelp, "help", false, "Help for podman") - pFlags.StringVar(&logLevel, "log-level", logLevel, fmt.Sprintf("Log messages above specified level (%s)", strings.Join(logLevels, ", "))) + + logLevelFlagName := "log-level" + pFlags.StringVar(&logLevel, logLevelFlagName, logLevel, fmt.Sprintf("Log messages above specified level (%s)", strings.Join(common.LogLevels, ", "))) + _ = rootCmd.RegisterFlagCompletionFunc(logLevelFlagName, common.AutocompleteLogLevel) // Only create these flags for ABI connections if !registry.IsRemote() { - pFlags.StringArrayVar(&opts.RuntimeFlags, "runtime-flag", []string{}, "add global flags for the container runtime") + runtimeflagFlagName := "runtime-flag" + pFlags.StringArrayVar(&opts.RuntimeFlags, runtimeflagFlagName, []string{}, "add global flags for the container runtime") + _ = rootCmd.RegisterFlagCompletionFunc(runtimeflagFlagName, completion.AutocompleteNone) + pFlags.BoolVar(&useSyslog, "syslog", false, "Output logging information to syslog as well as the console (default false)") } } diff --git a/cmd/podman/shell_completion_test.go b/cmd/podman/shell_completion_test.go new file mode 100644 index 000000000000..d2b500b09b1e --- /dev/null +++ b/cmd/podman/shell_completion_test.go @@ -0,0 +1,71 @@ +/* + The purpose of this test is to keep a consistent + and great shell autocompletion experience. + + This test ensures that each command and flag has a shell completion + function set. (except boolean, hidden and deprecated flags) + + Shell completion functions are defined in: + - "github.com/containers/podman/v2/cmd/podman/common/completion.go" + - "github.com/containers/common/pkg/completion" + and are called Autocomplete... + + To apply such function to a command use the ValidArgsFunction field. + To apply such function to a flag use cmd.RegisterFlagCompletionFunc(name,func) + + If there are any questions/problems please tag Luap99. +*/ + +package main + +import ( + "testing" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" +) + +func TestShellCompletionFunctions(t *testing.T) { + + rootCmd := parseCommands() + checkCommand(t, rootCmd) + +} + +func checkCommand(t *testing.T, cmd *cobra.Command) { + + if cmd.HasSubCommands() { + for _, childCmd := range cmd.Commands() { + checkCommand(t, childCmd) + } + + // if not check if completion for that command is provided + } else if cmd.ValidArgsFunction == nil && cmd.ValidArgs == nil { + t.Errorf("%s command has no shell completion function set", cmd.CommandPath()) + } + + // loop over all local flags + cmd.LocalFlags().VisitAll(func(flag *pflag.Flag) { + + // an error means that there is a completion function for this flag + err := cmd.RegisterFlagCompletionFunc(flag.Name, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + return nil, cobra.ShellCompDirectiveDefault + }) + + switch { + case flag.Value.Type() == "bool" && err != nil: + // make sure bool flags don't have a completion function + t.Errorf(`%s --%s is a bool flag but has a shell completion function set. +You have to remove this shell completion function.`, cmd.CommandPath(), flag.Name) + return + + case flag.Value.Type() == "bool" || flag.Hidden || len(flag.Deprecated) > 0: + // skip bool, hidden and deprecated flags + return + + case err == nil: + // there is no shell completion function + t.Errorf("%s --%s flag has no shell completion function set", cmd.CommandPath(), flag.Name) + } + }) +} diff --git a/cmd/podman/system/connection/add.go b/cmd/podman/system/connection/add.go index 0d81a64ca60e..b3a23bffda45 100644 --- a/cmd/podman/system/connection/add.go +++ b/cmd/podman/system/connection/add.go @@ -10,6 +10,7 @@ import ( "os/user" "regexp" + "github.com/containers/common/pkg/completion" "github.com/containers/common/pkg/config" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/system" @@ -34,7 +35,8 @@ var ( "destination" is of the form [user@]hostname or an URI of the form ssh://[user@]hostname[:port] `, - RunE: add, + RunE: add, + ValidArgsFunction: completion.AutocompleteNone, Example: `podman system connection add laptop server.fubar.com podman system connection add --identity ~/.ssh/dev_rsa testing ssh://root@server.fubar.com:2222 podman system connection add --identity ~/.ssh/dev_rsa --port 22 production root@server.fubar.com @@ -57,9 +59,19 @@ func init() { }) flags := addCmd.Flags() - flags.IntVarP(&cOpts.Port, "port", "p", 22, "SSH port number for destination") - flags.StringVar(&cOpts.Identity, "identity", "", "path to SSH identity file") - flags.StringVar(&cOpts.UDSPath, "socket-path", "", "path to podman socket on remote host. (default '/run/podman/podman.sock' or '/run/user/{uid}/podman/podman.sock)") + + portFlagName := "port" + flags.IntVarP(&cOpts.Port, portFlagName, "p", 22, "SSH port number for destination") + _ = addCmd.RegisterFlagCompletionFunc(portFlagName, completion.AutocompleteNone) + + identityFlagName := "identity" + flags.StringVar(&cOpts.Identity, identityFlagName, "", "path to SSH identity file") + _ = addCmd.RegisterFlagCompletionFunc(identityFlagName, completion.AutocompleteDefault) + + socketPathFlagName := "socket-path" + flags.StringVar(&cOpts.UDSPath, socketPathFlagName, "", "path to podman socket on remote host. (default '/run/podman/podman.sock' or '/run/user/{uid}/podman/podman.sock)") + _ = addCmd.RegisterFlagCompletionFunc(socketPathFlagName, completion.AutocompleteDefault) + flags.BoolVarP(&cOpts.Default, "default", "d", false, "Set connection to be default") } diff --git a/cmd/podman/system/connection/default.go b/cmd/podman/system/connection/default.go index eafcf37b2633..e2ae6ae7fb06 100644 --- a/cmd/podman/system/connection/default.go +++ b/cmd/podman/system/connection/default.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/containers/common/pkg/config" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/system" "github.com/containers/podman/v2/pkg/domain/entities" @@ -18,6 +19,7 @@ var ( Short: "Set named destination as default", Long: `Set named destination as default for the Podman service`, DisableFlagsInUseLine: true, + ValidArgsFunction: common.AutocompleteSystemConnections, RunE: defaultRunE, Example: `podman system connection default testing`, } diff --git a/cmd/podman/system/connection/list.go b/cmd/podman/system/connection/list.go index 9010ec80346b..b434559b4322 100644 --- a/cmd/podman/system/connection/list.go +++ b/cmd/podman/system/connection/list.go @@ -5,6 +5,7 @@ import ( "text/tabwriter" "text/template" + "github.com/containers/common/pkg/completion" "github.com/containers/common/pkg/config" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/system" @@ -23,8 +24,9 @@ var ( DisableFlagsInUseLine: true, Example: `podman system connection list podman system connection ls`, - RunE: list, - TraverseChildren: false, + ValidArgsFunction: completion.AutocompleteNone, + RunE: list, + TraverseChildren: false, } ) diff --git a/cmd/podman/system/connection/remove.go b/cmd/podman/system/connection/remove.go index 58674efb66e9..429325f50d01 100644 --- a/cmd/podman/system/connection/remove.go +++ b/cmd/podman/system/connection/remove.go @@ -2,6 +2,7 @@ package connection import ( "github.com/containers/common/pkg/config" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/system" "github.com/containers/podman/v2/pkg/domain/entities" @@ -17,6 +18,7 @@ var ( Long: `Delete named destination from podman configuration`, Short: "Delete named destination", DisableFlagsInUseLine: true, + ValidArgsFunction: common.AutocompleteSystemConnections, RunE: rm, Example: `podman system connection remove devl podman system connection rm devl`, diff --git a/cmd/podman/system/connection/rename.go b/cmd/podman/system/connection/rename.go index bb2ca262a9bc..7ab94d49a35d 100644 --- a/cmd/podman/system/connection/rename.go +++ b/cmd/podman/system/connection/rename.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/containers/common/pkg/config" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/system" "github.com/containers/podman/v2/pkg/domain/entities" @@ -19,6 +20,7 @@ var ( Short: "Rename \"old\" to \"new\"", Long: `Rename destination for the Podman service from "old" to "new"`, DisableFlagsInUseLine: true, + ValidArgsFunction: common.AutocompleteSystemConnections, RunE: rename, Example: `podman system connection rename laptop devl, podman system connection mv laptop devl`, diff --git a/cmd/podman/system/df.go b/cmd/podman/system/df.go index fbdf274fb1c8..a9eab24bbb4b 100644 --- a/cmd/podman/system/df.go +++ b/cmd/podman/system/df.go @@ -8,6 +8,7 @@ import ( "text/template" "time" + "github.com/containers/common/pkg/completion" "github.com/containers/common/pkg/report" "github.com/containers/podman/v2/cmd/podman/parse" "github.com/containers/podman/v2/cmd/podman/registry" @@ -24,11 +25,12 @@ var ( Show podman disk usage ` dfSystemCommand = &cobra.Command{ - Use: "df [options]", - Args: validate.NoArgs, - Short: "Show podman disk usage", - Long: dfSystemDescription, - RunE: df, + Use: "df [options]", + Args: validate.NoArgs, + Short: "Show podman disk usage", + Long: dfSystemDescription, + RunE: df, + ValidArgsFunction: completion.AutocompleteNone, } ) @@ -44,7 +46,11 @@ func init() { }) flags := dfSystemCommand.Flags() flags.BoolVarP(&dfOptions.Verbose, "verbose", "v", false, "Show detailed information on disk usage") - flags.StringVar(&dfOptions.Format, "format", "", "Pretty-print images using a Go template") + + formatFlagName := "format" + flags.StringVar(&dfOptions.Format, formatFlagName, "", "Pretty-print images using a Go template") + _ = dfSystemCommand.RegisterFlagCompletionFunc(formatFlagName, completion.AutocompleteNone) + } func df(cmd *cobra.Command, args []string) error { diff --git a/cmd/podman/system/events.go b/cmd/podman/system/events.go index 368cd41a64a3..224ef89f3322 100644 --- a/cmd/podman/system/events.go +++ b/cmd/podman/system/events.go @@ -6,7 +6,9 @@ import ( "os" "text/template" + "github.com/containers/common/pkg/completion" "github.com/containers/common/pkg/report" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/validate" "github.com/containers/podman/v2/libpod/events" @@ -20,11 +22,12 @@ var ( By default, streaming mode is used, printing new events as they occur. Previous events can be listed via --since and --until.` eventsCommand = &cobra.Command{ - Use: "events [options]", - Args: validate.NoArgs, - Short: "Show podman events", - Long: eventsDescription, - RunE: eventsCmd, + Use: "events [options]", + Args: validate.NoArgs, + Short: "Show podman events", + Long: eventsDescription, + RunE: eventsCmd, + ValidArgsFunction: completion.AutocompleteNone, Example: `podman events podman events --filter event=create podman events --format {{.Image}} @@ -43,11 +46,25 @@ func init() { Command: eventsCommand, }) flags := eventsCommand.Flags() - flags.StringArrayVar(&eventOptions.Filter, "filter", []string{}, "filter output") - flags.StringVar(&eventFormat, "format", "", "format the output using a Go template") + + filterFlagName := "filter" + flags.StringArrayVar(&eventOptions.Filter, filterFlagName, []string{}, "filter output") + _ = eventsCommand.RegisterFlagCompletionFunc(filterFlagName, common.AutocompleteEventFilter) + + formatFlagName := "format" + flags.StringVar(&eventFormat, formatFlagName, "", "format the output using a Go template") + _ = eventsCommand.RegisterFlagCompletionFunc(formatFlagName, common.AutocompleteJSONFormat) + flags.BoolVar(&eventOptions.Stream, "stream", true, "stream new events; for testing only") - flags.StringVar(&eventOptions.Since, "since", "", "show all events created since timestamp") - flags.StringVar(&eventOptions.Until, "until", "", "show all events until timestamp") + + sinceFlagName := "since" + flags.StringVar(&eventOptions.Since, sinceFlagName, "", "show all events created since timestamp") + _ = eventsCommand.RegisterFlagCompletionFunc(sinceFlagName, completion.AutocompleteNone) + + untilFlagName := "until" + flags.StringVar(&eventOptions.Until, untilFlagName, "", "show all events until timestamp") + _ = eventsCommand.RegisterFlagCompletionFunc(untilFlagName, completion.AutocompleteNone) + _ = flags.MarkHidden("stream") } diff --git a/cmd/podman/system/info.go b/cmd/podman/system/info.go index dece6b37ea39..17aeb2940507 100644 --- a/cmd/podman/system/info.go +++ b/cmd/podman/system/info.go @@ -5,13 +5,14 @@ import ( "os" "text/template" + "github.com/containers/common/pkg/completion" "github.com/containers/common/pkg/report" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/validate" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/ghodss/yaml" "github.com/spf13/cobra" - "github.com/spf13/pflag" ) var ( @@ -20,21 +21,23 @@ var ( Useful for the user and when reporting issues. ` infoCommand = &cobra.Command{ - Use: "info [options]", - Args: validate.NoArgs, - Long: infoDescription, - Short: "Display podman system information", - RunE: info, - Example: `podman info`, + Use: "info [options]", + Args: validate.NoArgs, + Long: infoDescription, + Short: "Display podman system information", + RunE: info, + ValidArgsFunction: completion.AutocompleteNone, + Example: `podman info`, } systemInfoCommand = &cobra.Command{ - Args: infoCommand.Args, - Use: infoCommand.Use, - Short: infoCommand.Short, - Long: infoCommand.Long, - RunE: infoCommand.RunE, - Example: `podman system info`, + Args: infoCommand.Args, + Use: infoCommand.Use, + Short: infoCommand.Short, + Long: infoCommand.Long, + RunE: infoCommand.RunE, + ValidArgsFunction: infoCommand.ValidArgsFunction, + Example: `podman system info`, } ) @@ -48,19 +51,24 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: infoCommand, }) - infoFlags(infoCommand.Flags()) + infoFlags(infoCommand) registry.Commands = append(registry.Commands, registry.CliCommand{ Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: systemInfoCommand, Parent: systemCmd, }) - infoFlags(systemInfoCommand.Flags()) + infoFlags(systemInfoCommand) } -func infoFlags(flags *pflag.FlagSet) { +func infoFlags(cmd *cobra.Command) { + flags := cmd.Flags() + flags.BoolVarP(&debug, "debug", "D", false, "Display additional debug information") - flags.StringVarP(&inFormat, "format", "f", "", "Change the output format to JSON or a Go template") + + formatFlagName := "format" + flags.StringVarP(&inFormat, formatFlagName, "f", "", "Change the output format to JSON or a Go template") + _ = cmd.RegisterFlagCompletionFunc(formatFlagName, common.AutocompleteJSONFormat) } func info(cmd *cobra.Command, args []string) error { diff --git a/cmd/podman/system/migrate.go b/cmd/podman/system/migrate.go index 7870df60bced..234a49e4b891 100644 --- a/cmd/podman/system/migrate.go +++ b/cmd/podman/system/migrate.go @@ -6,6 +6,7 @@ import ( "fmt" "os" + "github.com/containers/common/pkg/completion" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/validate" "github.com/containers/podman/v2/pkg/domain/entities" @@ -21,11 +22,12 @@ var ( ` migrateCommand = &cobra.Command{ - Use: "migrate [options]", - Args: validate.NoArgs, - Short: "Migrate containers", - Long: migrateDescription, - Run: migrate, + Use: "migrate [options]", + Args: validate.NoArgs, + Short: "Migrate containers", + Long: migrateDescription, + Run: migrate, + ValidArgsFunction: completion.AutocompleteNone, } ) @@ -41,7 +43,10 @@ func init() { }) flags := migrateCommand.Flags() - flags.StringVar(&migrateOptions.NewRuntime, "new-runtime", "", "Specify a new runtime for all containers") + + newRuntimeFlagName := "new-runtime" + flags.StringVar(&migrateOptions.NewRuntime, newRuntimeFlagName, "", "Specify a new runtime for all containers") + _ = migrateCommand.RegisterFlagCompletionFunc(newRuntimeFlagName, completion.AutocompleteNone) } func migrate(cmd *cobra.Command, args []string) { diff --git a/cmd/podman/system/prune.go b/cmd/podman/system/prune.go index a229b06b05fe..be0d60604a1c 100644 --- a/cmd/podman/system/prune.go +++ b/cmd/podman/system/prune.go @@ -7,6 +7,7 @@ import ( "os" "strings" + "github.com/containers/common/pkg/completion" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" "github.com/containers/podman/v2/cmd/podman/validate" @@ -25,12 +26,13 @@ var ( `) pruneCommand = &cobra.Command{ - Use: "prune [options]", - Short: "Remove unused data", - Args: validate.NoArgs, - Long: pruneDescription, - RunE: prune, - Example: `podman system prune`, + Use: "prune [options]", + Short: "Remove unused data", + Args: validate.NoArgs, + Long: pruneDescription, + RunE: prune, + ValidArgsFunction: completion.AutocompleteNone, + Example: `podman system prune`, } force bool ) diff --git a/cmd/podman/system/renumber.go b/cmd/podman/system/renumber.go index 1631ab093e1b..b1683395fb6c 100644 --- a/cmd/podman/system/renumber.go +++ b/cmd/podman/system/renumber.go @@ -6,6 +6,7 @@ import ( "fmt" "os" + "github.com/containers/common/pkg/completion" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/validate" "github.com/containers/podman/v2/pkg/domain/entities" @@ -28,6 +29,7 @@ var ( Short: "Migrate lock numbers", Long: renumberDescription, Run: renumber, + ValidArgsFunction: completion.AutocompleteNone, } ) diff --git a/cmd/podman/system/reset.go b/cmd/podman/system/reset.go index 0b04c6ee0749..d38a1a42742e 100644 --- a/cmd/podman/system/reset.go +++ b/cmd/podman/system/reset.go @@ -8,6 +8,7 @@ import ( "os" "strings" + "github.com/containers/common/pkg/completion" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/validate" "github.com/containers/podman/v2/pkg/domain/entities" @@ -22,11 +23,12 @@ var ( All containers will be stopped and removed, and all images, volumes and container content will be removed. ` systemResetCommand = &cobra.Command{ - Use: "reset [options]", - Args: validate.NoArgs, - Short: "Reset podman storage", - Long: systemResetDescription, - Run: reset, + Use: "reset [options]", + Args: validate.NoArgs, + Short: "Reset podman storage", + Long: systemResetDescription, + Run: reset, + ValidArgsFunction: completion.AutocompleteNone, } forceFlag bool diff --git a/cmd/podman/system/service.go b/cmd/podman/system/service.go index 0476c632d639..78062d135584 100644 --- a/cmd/podman/system/service.go +++ b/cmd/podman/system/service.go @@ -9,6 +9,7 @@ import ( "syscall" "time" + "github.com/containers/common/pkg/completion" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/containers/podman/v2/pkg/rootless" @@ -26,12 +27,13 @@ Enable a listening service for API access to Podman commands. ` srvCmd = &cobra.Command{ - Use: "service [options] [URI]", - Args: cobra.MaximumNArgs(1), - Short: "Run API service", - Long: srvDescription, - RunE: service, - Example: `podman system service --time=0 unix:///tmp/podman.sock`, + Use: "service [options] [URI]", + Args: cobra.MaximumNArgs(1), + Short: "Run API service", + Long: srvDescription, + RunE: service, + ValidArgsFunction: completion.AutocompleteDefault, + Example: `podman system service --time=0 unix:///tmp/podman.sock`, } srvArgs = struct { @@ -48,7 +50,11 @@ func init() { }) flags := srvCmd.Flags() - flags.Int64VarP(&srvArgs.Timeout, "time", "t", 5, "Time until the service session expires in seconds. Use 0 to disable the timeout") + + timeFlagName := "time" + flags.Int64VarP(&srvArgs.Timeout, timeFlagName, "t", 5, "Time until the service session expires in seconds. Use 0 to disable the timeout") + _ = srvCmd.RegisterFlagCompletionFunc(timeFlagName, completion.AutocompleteNone) + flags.BoolVar(&srvArgs.Varlink, "varlink", false, "Use legacy varlink service instead of REST. Unit of --time changes from seconds to milliseconds.") _ = flags.MarkDeprecated("varlink", "valink API is deprecated.") diff --git a/cmd/podman/system/unshare.go b/cmd/podman/system/unshare.go index 2d01137794ef..437cf7b2e528 100644 --- a/cmd/podman/system/unshare.go +++ b/cmd/podman/system/unshare.go @@ -3,6 +3,7 @@ package system import ( "os" + "github.com/containers/common/pkg/completion" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/containers/podman/v2/pkg/rootless" @@ -18,6 +19,7 @@ var ( Short: "Run a command in a modified user namespace", Long: unshareDescription, RunE: unshare, + ValidArgsFunction: completion.AutocompleteDefault, Example: `podman unshare id podman unshare cat /proc/self/uid_map, podman unshare podman-script.sh`, diff --git a/cmd/podman/system/varlink.go b/cmd/podman/system/varlink.go index 89669d51a53f..363ac9ccae4a 100644 --- a/cmd/podman/system/varlink.go +++ b/cmd/podman/system/varlink.go @@ -5,6 +5,7 @@ package system import ( "time" + "github.com/containers/common/pkg/completion" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/domain/entities" "github.com/spf13/cobra" @@ -16,13 +17,14 @@ var ( Tools speaking varlink protocol can remotely manage pods, containers and images. ` varlinkCmd = &cobra.Command{ - Use: "varlink [options] [URI]", - Args: cobra.MinimumNArgs(1), - Short: "Run varlink interface", - Long: varlinkDescription, - RunE: varlinkE, - Deprecated: "Please see 'podman system service' for RESTful APIs", - Hidden: true, + Use: "varlink [options] [URI]", + Args: cobra.MinimumNArgs(1), + Short: "Run varlink interface", + Long: varlinkDescription, + RunE: varlinkE, + ValidArgsFunction: completion.AutocompleteDefault, + Deprecated: "Please see 'podman system service' for RESTful APIs", + Hidden: true, Example: `podman varlink unix:/run/podman/io.podman podman varlink --time 5000 unix:/run/podman/io.podman`, } @@ -37,7 +39,11 @@ func init() { Command: varlinkCmd, }) flags := varlinkCmd.Flags() - flags.Int64VarP(&varlinkArgs.Timeout, "time", "t", 1000, "Time until the varlink session expires in milliseconds. Use 0 to disable the timeout") + + timeFlagName := "time" + flags.Int64VarP(&varlinkArgs.Timeout, timeFlagName, "t", 1000, "Time until the varlink session expires in milliseconds. Use 0 to disable the timeout") + _ = varlinkCmd.RegisterFlagCompletionFunc(timeFlagName, completion.AutocompleteNone) + flags.SetNormalizeFunc(aliasTimeoutFlag) } diff --git a/cmd/podman/system/version.go b/cmd/podman/system/version.go index b790a7511f62..cb7206b8ac4c 100644 --- a/cmd/podman/system/version.go +++ b/cmd/podman/system/version.go @@ -8,7 +8,9 @@ import ( "text/tabwriter" "text/template" + "github.com/containers/common/pkg/completion" "github.com/containers/common/pkg/report" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/validate" "github.com/containers/podman/v2/libpod/define" @@ -18,10 +20,11 @@ import ( var ( versionCommand = &cobra.Command{ - Use: "version [options]", - Args: validate.NoArgs, - Short: "Display the Podman Version Information", - RunE: version, + Use: "version [options]", + Args: validate.NoArgs, + Short: "Display the Podman Version Information", + RunE: version, + ValidArgsFunction: completion.AutocompleteNone, } versionFormat string ) @@ -32,7 +35,10 @@ func init() { Command: versionCommand, }) flags := versionCommand.Flags() - flags.StringVarP(&versionFormat, "format", "f", "", "Change the output format to JSON or a Go template") + + formatFlagName := "format" + flags.StringVarP(&versionFormat, formatFlagName, "f", "", "Change the output format to JSON or a Go template") + _ = versionCommand.RegisterFlagCompletionFunc(formatFlagName, common.AutocompleteJSONFormat) } func version(cmd *cobra.Command, args []string) error { diff --git a/cmd/podman/volumes/create.go b/cmd/podman/volumes/create.go index a54530183b52..8de343a242a6 100644 --- a/cmd/podman/volumes/create.go +++ b/cmd/podman/volumes/create.go @@ -4,6 +4,7 @@ import ( "context" "fmt" + "github.com/containers/common/pkg/completion" "github.com/containers/podman/v2/cmd/podman/parse" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/domain/entities" @@ -15,10 +16,11 @@ var ( createDescription = `If using the default driver, "local", the volume will be created on the host in the volumes directory under container storage.` createCommand = &cobra.Command{ - Use: "create [options] [NAME]", - Short: "Create a new volume", - Long: createDescription, - RunE: create, + Use: "create [options] [NAME]", + Short: "Create a new volume", + Long: createDescription, + RunE: create, + ValidArgsFunction: completion.AutocompleteNone, Example: `podman volume create myvol podman volume create podman volume create --label foo=bar myvol`, @@ -40,9 +42,18 @@ func init() { Parent: volumeCmd, }) flags := createCommand.Flags() - flags.StringVar(&createOpts.Driver, "driver", "local", "Specify volume driver name") - flags.StringSliceVarP(&opts.Label, "label", "l", []string{}, "Set metadata for a volume (default [])") - flags.StringArrayVarP(&opts.Opts, "opt", "o", []string{}, "Set driver specific options (default [])") + + driverFlagName := "driver" + flags.StringVar(&createOpts.Driver, driverFlagName, "local", "Specify volume driver name") + _ = createCommand.RegisterFlagCompletionFunc(driverFlagName, completion.AutocompleteNone) + + labelFlagName := "label" + flags.StringSliceVarP(&opts.Label, labelFlagName, "l", []string{}, "Set metadata for a volume (default [])") + _ = createCommand.RegisterFlagCompletionFunc(labelFlagName, completion.AutocompleteNone) + + optFlagName := "opt" + flags.StringArrayVarP(&opts.Opts, optFlagName, "o", []string{}, "Set driver specific options (default [])") + _ = createCommand.RegisterFlagCompletionFunc(optFlagName, completion.AutocompleteNone) } func create(cmd *cobra.Command, args []string) error { diff --git a/cmd/podman/volumes/inspect.go b/cmd/podman/volumes/inspect.go index c6edcf8094d7..b5094224c0e7 100644 --- a/cmd/podman/volumes/inspect.go +++ b/cmd/podman/volumes/inspect.go @@ -1,6 +1,7 @@ package volumes import ( + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/inspect" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/pkg/domain/entities" @@ -13,10 +14,11 @@ var ( Use a Go template to change the format from JSON.` inspectCommand = &cobra.Command{ - Use: "inspect [options] VOLUME [VOLUME...]", - Short: "Display detailed information on one or more volumes", - Long: volumeInspectDescription, - RunE: volumeInspect, + Use: "inspect [options] VOLUME [VOLUME...]", + Short: "Display detailed information on one or more volumes", + Long: volumeInspectDescription, + RunE: volumeInspect, + ValidArgsFunction: common.AutocompleteVolumes, Example: `podman volume inspect myvol podman volume inspect --all podman volume inspect --format "{{.Driver}} {{.Scope}}" myvol`, @@ -36,7 +38,10 @@ func init() { inspectOpts = new(entities.InspectOptions) flags := inspectCommand.Flags() flags.BoolVarP(&inspectOpts.All, "all", "a", false, "Inspect all volumes") - flags.StringVarP(&inspectOpts.Format, "format", "f", "json", "Format volume output using Go template") + + formatFlagName := "format" + flags.StringVarP(&inspectOpts.Format, formatFlagName, "f", "json", "Format volume output using Go template") + _ = inspectCommand.RegisterFlagCompletionFunc(formatFlagName, common.AutocompleteJSONFormat) } func volumeInspect(cmd *cobra.Command, args []string) error { diff --git a/cmd/podman/volumes/list.go b/cmd/podman/volumes/list.go index ce0b7997df58..5548c9c1b330 100644 --- a/cmd/podman/volumes/list.go +++ b/cmd/podman/volumes/list.go @@ -8,7 +8,9 @@ import ( "text/tabwriter" "text/template" + "github.com/containers/common/pkg/completion" "github.com/containers/common/pkg/report" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/parse" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/validate" @@ -24,12 +26,13 @@ podman volume ls List all available volumes. The output of the volumes can be filtered and the output format can be changed to JSON or a user specified Go template.` lsCommand = &cobra.Command{ - Use: "ls [options]", - Aliases: []string{"list"}, - Args: validate.NoArgs, - Short: "List volumes", - Long: volumeLsDescription, - RunE: list, + Use: "ls [options]", + Aliases: []string{"list"}, + Args: validate.NoArgs, + Short: "List volumes", + Long: volumeLsDescription, + RunE: list, + ValidArgsFunction: completion.AutocompleteNone, } ) @@ -50,8 +53,15 @@ func init() { Parent: volumeCmd, }) flags := lsCommand.Flags() - flags.StringSliceVarP(&cliOpts.Filter, "filter", "f", []string{}, "Filter volume output") - flags.StringVar(&cliOpts.Format, "format", "{{.Driver}}\t{{.Name}}\n", "Format volume output using Go template") + + filterFlagName := "filter" + flags.StringSliceVarP(&cliOpts.Filter, filterFlagName, "f", []string{}, "Filter volume output") + _ = lsCommand.RegisterFlagCompletionFunc(filterFlagName, completion.AutocompleteNone) + + formatFlagName := "format" + flags.StringVar(&cliOpts.Format, formatFlagName, "{{.Driver}}\t{{.Name}}\n", "Format volume output using Go template") + _ = lsCommand.RegisterFlagCompletionFunc(formatFlagName, common.AutocompleteJSONFormat) + flags.BoolVarP(&cliOpts.Quiet, "quiet", "q", false, "Print volume output in quiet mode") } diff --git a/cmd/podman/volumes/prune.go b/cmd/podman/volumes/prune.go index 79e6f1a54ebd..2f58b668f008 100644 --- a/cmd/podman/volumes/prune.go +++ b/cmd/podman/volumes/prune.go @@ -7,6 +7,7 @@ import ( "os" "strings" + "github.com/containers/common/pkg/completion" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" "github.com/containers/podman/v2/cmd/podman/validate" @@ -21,11 +22,12 @@ var ( The command prompts for confirmation which can be overridden with the --force flag. Note all data will be destroyed.` pruneCommand = &cobra.Command{ - Use: "prune [options]", - Args: validate.NoArgs, - Short: "Remove all unused volumes", - Long: volumePruneDescription, - RunE: prune, + Use: "prune [options]", + Args: validate.NoArgs, + Short: "Remove all unused volumes", + Long: volumePruneDescription, + RunE: prune, + ValidArgsFunction: completion.AutocompleteNone, } ) diff --git a/cmd/podman/volumes/rm.go b/cmd/podman/volumes/rm.go index 4026764ace5b..49f7b619e824 100644 --- a/cmd/podman/volumes/rm.go +++ b/cmd/podman/volumes/rm.go @@ -5,6 +5,7 @@ import ( "fmt" "strings" + "github.com/containers/podman/v2/cmd/podman/common" "github.com/containers/podman/v2/cmd/podman/registry" "github.com/containers/podman/v2/cmd/podman/utils" "github.com/containers/podman/v2/libpod/define" @@ -18,11 +19,12 @@ var ( By default only volumes that are not being used by any containers will be removed. To remove the volumes anyways, use the --force flag.` rmCommand = &cobra.Command{ - Use: "rm [options] VOLUME [VOLUME...]", - Aliases: []string{"remove"}, - Short: "Remove one or more volumes", - Long: volumeRmDescription, - RunE: rm, + Use: "rm [options] VOLUME [VOLUME...]", + Aliases: []string{"remove"}, + Short: "Remove one or more volumes", + Long: volumeRmDescription, + RunE: rm, + ValidArgsFunction: common.AutocompleteVolumes, Example: `podman volume rm myvol1 myvol2 podman volume rm --all podman volume rm --force myvol`, diff --git a/completions/Readme.md b/completions/Readme.md new file mode 100644 index 000000000000..9a3eac480b29 --- /dev/null +++ b/completions/Readme.md @@ -0,0 +1,7 @@ +# Shell completion scripts + +Podman offers shell completion scripts for bash, zsh and fish. The completion scripts are available for both `podman` and `podman-remote`. + +The shell completion scripts are generated by `make completion`, do not edit these files directly. To install them you can run `sudo make install.completions`. + +For information about these sripts see [`man podman-completion`](../docs/source/markdown/podman-completion.1.md) diff --git a/completions/bash/podman b/completions/bash/podman index c08bb33527a9..17d1e86b7688 100644 --- a/completions/bash/podman +++ b/completions/bash/podman @@ -1,3601 +1,271 @@ -# -# This bash script was originally copied and converted from the upstream -# github.com:docker/docker project -# -: ${PROG:=$(basename ${BASH_SOURCE})} +# bash completion for podman -*- shell-script -*- - -__podman_previous_extglob_setting=$(shopt -p extglob) -shopt -s extglob - -__podman_q() { - podman ${host:+-H "$host"} ${config:+--config "$config"} 2>/dev/null "$@" -} - -# __podman_containers returns a list of containers. Additional options to -# `podman ps` may be specified in order to filter the list, e.g. -# `__podman_containers --filter status=running` -# By default, only names are returned. -# Set PODMAN_COMPLETION_SHOW_CONTAINER_IDS=yes to also complete IDs. -# An optional first option `--id|--name` may be used to limit the -# output to the IDs or names of matching items. This setting takes -# precedence over the environment setting. -__podman_containers() { - local format - if [ "$1" = "--id" ] ; then - format='{{.ID}}' - shift - elif [ "$1" = "--name" ] ; then - format='{{.Names}}' - shift - elif [ "${PODMAN_COMPLETION_SHOW_CONTAINER_IDS}" = yes ] ; then - format='{{.ID}} {{.Names}}' - else - format='{{.Names}}' - fi - __podman_q ps --format "$format" "$@" -} - -__podman_list_registries() { - sed -n -e '/registries.*=/ {s/.*\[\([^]]*\).*/\1/p;q}' /etc/containers/registries.conf | sed -e "s/[,']//g" -} - -# __podman_pods returns a list of pods. Additional options to -# `podman pod ps` may be specified in order to filter the list, e.g. -# `__podman_containers --filter status=running` -# By default, only names are returned. -# Set PODMAN_COMPLETION_SHOW_CONTAINER_IDS=yes to also complete IDs. -# An optional first option `--id|--name` may be used to limit the -# output to the IDs or names of matching items. This setting takes -# precedence over the environment setting. -__podman_pods() { - local format - if [ "$1" = "--id" ] ; then - format='{{.ID}}' - shift - elif [ "$1" = "--name" ] ; then - format='{{.Name}}' - shift - else - format='{{.Name}}' - fi - __podman_q pod ps --format "$format" "$@" -} - -# __podman_complete_containers applies completion of containers based on the current -# value of `$cur` or the value of the optional first option `--cur`, if given. -# Additional filters may be appended, see `__podman_containers`. -__podman_complete_containers() { - local current="$cur" - if [ "$1" = "--cur" ] ; then - current="$2" - shift 2 - fi - COMPREPLY=( $(compgen -W "$(__podman_containers "$@")" -- "$current") ) -} - -# __podman_complete_pods applies completion of pods based on the current -# value of `$cur` or the value of the optional first option `--cur`, if given. -# Additional filters may be appended, see `__podman_pods`. -__podman_complete_pods() { - local current="$cur" - if [ "$1" = "--cur" ] ; then - current="$2" - shift 2 - fi - COMPREPLY=( $(compgen -W "$(__podman_pods "$@")" -- "$current") ) -} - -__podman_complete_pod_names() { - local names=( $(__podman_q pod ps --format={{.Name}}) ) - COMPREPLY=( $(compgen -W "${names[*]}" -- "$cur") ) -} - -__podman_complete_containers_all() { - __podman_complete_containers "$@" --all -} - -__podman_complete_containers_created() { - __podman_complete_containers "$@" --all --filter status=created -} - -__podman_complete_containers_running() { - __podman_complete_containers "$@" --filter status=running -} - -__podman_complete_containers_stopped() { - __podman_complete_containers "$@" --all --filter status=exited -} - -__podman_complete_containers_unpauseable() { - __podman_complete_containers "$@" --all --filter status=paused -} - -__podman_complete_container_names() { - local containers=( $(__podman_q ps -aq --no-trunc) ) - local names=( $(__podman_q inspect --format '{{.Name}}' "${containers[@]}") ) - names=( "${names[@]#/}" ) # trim off the leading "/" from the container names - COMPREPLY=( $(compgen -W "${names[*]}" -- "$cur") ) -} - -__podman_complete_container_ids() { - local containers=( $(__podman_q ps -aq) ) - COMPREPLY=( $(compgen -W "${containers[*]}" -- "$cur") ) -} - -__podman_images() { - local images_args="" - - case "$PODMAN_COMPLETION_SHOW_IMAGE_IDS" in - all) - images_args="--no-trunc -a" - ;; - non-intermediate) - images_args="--no-trunc" - ;; - esac - - local repo_print_command - if [ "${PODMAN_COMPLETION_SHOW_TAGS:-yes}" = "yes" ]; then - repo_print_command='print $1; print $1":"$2' - else - repo_print_command='print $1' - fi - - local awk_script - case "$PODMAN_COMPLETION_SHOW_IMAGE_IDS" in - all|non-intermediate) - awk_script='NR>1 { print $3; if ($1 != "") { '"$repo_print_command"' } }' - ;; - none|*) - awk_script='NR>1 && $1 != "" { '"$repo_print_command"' }' - ;; - esac - - __podman_q images $images_args | awk "$awk_script" | grep -v '$' -} - -__podman_complete_images() { - COMPREPLY=( $(compgen -W "$(__podman_images)" -- "$cur") ) - __ltrim_colon_completions "$cur" -} - -__podman_complete_image_repos() { - local repos="$(__podman_q images | awk 'NR>1 && $1 != "" { print $1 }')" - COMPREPLY=( $(compgen -W "$repos" -- "$cur") ) -} - -__podman_complete_image_repos_and_tags() { - local reposAndTags="$(__podman_q images | awk 'NR>1 && $1 != "" { print $1; print $1":"$2 }')" - COMPREPLY=( $(compgen -W "$reposAndTags" -- "$cur") ) - __ltrim_colon_completions "$cur" -} - -# __podman_networks returns a list of all networks. Additional options to -# `podman network ls` may be specified in order to filter the list, e.g. -# `__podman_networks --filter type=custom` -# By default, only names are returned. -# Set PODMAN_COMPLETION_SHOW_NETWORK_IDS=yes to also complete IDs. -# An optional first option `--id|--name` may be used to limit the -# output to the IDs or names of matching items. This setting takes -# precedence over the environment setting. -__podman_networks() { - local format - if [ "$1" = "--id" ] ; then - format='{{.ID}}' - shift - elif [ "$1" = "--name" ] ; then - format='{{.Name}}' - shift - elif [ "${PODMAN_COMPLETION_SHOW_NETWORK_IDS}" = yes ] ; then - format='{{.ID}} {{.Name}}' - else - format='{{.Name}}' - fi - __podman_q network ls --format "$format" "$@" -} - -# __podman_complete_networks applies completion of networks based on the current -# value of `$cur` or the value of the optional first option `--cur`, if given. -# Additional filters may be appended, see `__podman_networks`. -__podman_complete_networks() { - local current="$cur" - if [ "$1" = "--cur" ] ; then - current="$2" - shift 2 - fi - COMPREPLY=( $(compgen -W "$(__podman_networks "$@")" -- "$current") ) -} - -__podman_complete_containers_in_network() { - local containers=$(__podman_q network inspect -f '{{range $i, $c := .Containers}}{{$i}} {{$c.Name}} {{end}}' "$1") - COMPREPLY=( $(compgen -W "$containers" -- "$cur") ) -} - -__podman_runtimes() { - __podman_q info | sed -n 's/^Runtimes: \(.*\)/\1/p' -} - -__podman_complete_runtimes() { - COMPREPLY=( $(compgen -W "$(__podman_runtimes)" -- "$cur") ) -} - -# __podman_services returns a list of all services. Additional options to -# `podman service ls` may be specified in order to filter the list, e.g. -# `__podman_services --filter name=xxx` -# By default, only node names are returned. -# Set PODMAN_COMPLETION_SHOW_SERVICE_IDS=yes to also complete IDs. -# An optional first option `--id|--name` may be used to limit the -# output to the IDs or names of matching items. This setting takes -# precedence over the environment setting. -__podman_services() { - local fields='$2' # default: service name only - [ "${PODMAN_COMPLETION_SHOW_SERVICE_IDS}" = yes ] && fields='$1,$2' # ID & name - - if [ "$1" = "--id" ] ; then - fields='$1' # IDs only - shift - elif [ "$1" = "--name" ] ; then - fields='$2' # names only - shift - fi - __podman_q service ls "$@" | awk "NR>1 {print $fields}" -} - -# __podman_complete_services applies completion of services based on the current -# value of `$cur` or the value of the optional first option `--cur`, if given. -# Additional filters may be appended, see `__podman_services`. -__podman_complete_services() { - local current="$cur" - if [ "$1" = "--cur" ] ; then - current="$2" - shift 2 - fi - COMPREPLY=( $(compgen -W "$(__podman_services "$@")" -- "$current") ) -} - -# __podman_append_to_completions appends the word passed as an argument to every -# word in `$COMPREPLY`. -# Normally you do this with `compgen -S` while generating the completions. -# This function allows you to append a suffix later. It allows you to use -# the __podman_complete_XXX functions in cases where you need a suffix. -__podman_append_to_completions() { - COMPREPLY=( ${COMPREPLY[@]/%/"$1"} ) -} - -# __podman_pos_first_nonflag finds the position of the first word that is neither -# option nor an option's argument. If there are options that require arguments, -# you should pass a glob describing those options, e.g. "--option1|-o|--option2" -# Use this function to restrict completions to exact positions after the argument list. -__podman_pos_first_nonflag() { - local argument_flags=$1 - - local counter=$((${subcommand_pos:-${command_pos}} + 1)) - while [ $counter -le $cword ]; do - if [ -n "$argument_flags" ] && eval "case '${words[$counter]}' in $argument_flags) true ;; *) false ;; esac"; then - (( counter++ )) - # eat "=" in case of --option=arg syntax - [ "${words[$counter]}" = "=" ] && (( counter++ )) - else - case "${words[$counter]}" in - -*) - ;; - *) - break - ;; - esac - fi - - # Bash splits words at "=", retaining "=" as a word, examples: - # "--debug=false" => 3 words, "--log-opt syslog-facility=daemon" => 4 words - while [ "${words[$counter + 1]}" = "=" ] ; do - counter=$(( counter + 2)) - done - - (( counter++ )) - done - - echo $counter -} - -# __podman_map_key_of_current_option returns `key` if we are currently completing the -# value of a map option (`key=value`) which matches the extglob given as an argument. -# This function is needed for key-specific completions. -__podman_map_key_of_current_option() { - local glob="$1" - - local key glob_pos - if [ "$cur" = "=" ] ; then # key= case - key="$prev" - glob_pos=$((cword - 2)) - elif [[ $cur == *=* ]] ; then # key=value case (OSX) - key=${cur%=*} - glob_pos=$((cword - 1)) - elif [ "$prev" = "=" ] ; then - key=${words[$cword - 2]} # key=value case - glob_pos=$((cword - 3)) - else - return - fi - - [ "${words[$glob_pos]}" = "=" ] && ((glob_pos--)) # --option=key=value syntax - - [[ ${words[$glob_pos]} == @($glob) ]] && echo "$key" -} - -# __podman_value_of_option returns the value of the first option matching `option_glob`. -# Valid values for `option_glob` are option names like `--log-level` and globs like -# `--log-level|-l` -# Only positions between the command and the current word are considered. -__podman_value_of_option() { - local option_extglob=$(__podman_to_extglob "$1") - - local counter=$((command_pos + 1)) - while [ $counter -lt $cword ]; do - case ${words[$counter]} in - $option_extglob ) - echo ${words[$counter + 1]} - break - ;; - esac - (( counter++ )) - done -} - -# __podman_to_alternatives transforms a multiline list of strings into a single line -# string with the words separated by `|`. -# This is used to prepare arguments to __podman_pos_first_nonflag(). -__podman_to_alternatives() { - local parts=( $1 ) - local IFS='|' - echo "${parts[*]}" -} - -# __podman_to_extglob transforms a multiline list of options into an extglob pattern -# suitable for use in case statements. -__podman_to_extglob() { - local extglob=$( __podman_to_alternatives "$1" ) - echo "@($extglob)" -} - -# __podman_subcommands processes subcommands -# Locates the first occurrence of any of the subcommands contained in the -# first argument. In case of a match, calls the corresponding completion -# function and returns 0. -# If no match is found, 1 is returned. The calling function can then -# continue processing its completion. -# -# TODO if the preceding command has options that accept arguments and an -# argument is equal to one of the subcommands, this is falsely detected as -# a match. -__podman_subcommands() { - local subcommands="$1" - - local counter=$(($command_pos + 1)) - - while [ $counter -lt $cword ]; do - case "${words[$counter]}" in - $(__podman_to_extglob "$subcommands") ) - subcommand_pos=$counter - local subcommand=${words[$counter]} - local completions_func=_podman_${command}_${subcommand} - declare -F $completions_func >/dev/null && $completions_func - return 0 - ;; - esac - (( counter++ )) - done - return 1 -} - -# __podman_nospace suppresses trailing whitespace -__podman_nospace() { - # compopt is not available in ancient bash versions - type compopt &>/dev/null && compopt -o nospace -} - -__podman_complete_resolved_hostname() { - command -v host >/dev/null 2>&1 || return - COMPREPLY=( $(host 2>/dev/null "${cur%:}" | awk '/has address/ {print $4}') ) -} - -__podman_local_interfaces() { - command -v ip >/dev/null 2>&1 || return - ip addr show scope global 2>/dev/null | sed -n 's| \+inet \([0-9.]\+\).* \([^ ]\+\)|\1 \2|p' -} - -__podman_complete_restart() { - case "$prev" in - --restart) - COMPREPLY=( $( compgen -W "always no on-failure unless-stopped" -- "$cur") ) - return - ;; - esac - return 1 -} - -__podman_complete_local_interfaces() { - local additional_interface - if [ "$1" = "--add" ] ; then - additional_interface="$2" - fi - - COMPREPLY=( $( compgen -W "$(__podman_local_interfaces) $additional_interface" -- "$cur" ) ) -} - -__podman_complete_capabilities() { - # The list of capabilities is defined in types.go, ALL was added manually. - COMPREPLY=( $( compgen -W " - ALL - AUDIT_CONTROL - AUDIT_WRITE - AUDIT_READ - BLOCK_SUSPEND - CHOWN - DAC_OVERRIDE - DAC_READ_SEARCH - FOWNER - FSETID - IPC_LOCK - IPC_OWNER - KILL - LEASE - LINUX_IMMUTABLE - MAC_ADMIN - MAC_OVERRIDE - MKNOD - NET_ADMIN - NET_BIND_SERVICE - NET_BROADCAST - NET_RAW - SETFCAP - SETGID - SETPCAP - SETUID - SYS_ADMIN - SYS_BOOT - SYS_CHROOT - SYSLOG - SYS_MODULE - SYS_NICE - SYS_PACCT - SYS_PTRACE - SYS_RAWIO - SYS_RESOURCE - SYS_TIME - SYS_TTY_CONFIG - WAKE_ALARM - " -- "$cur" ) ) -} - -__podman_complete_detach_keys() { - case "$prev" in - --detach-keys) - case "$cur" in - *,) - COMPREPLY=( $( compgen -W "${cur}ctrl-" -- "$cur" ) ) - ;; - *) - COMPREPLY=( $( compgen -W "ctrl-" -- "$cur" ) ) - ;; - esac - - __podman_nospace - return 0 - ;; - esac - return 1 -} - -__podman_complete_log_drivers() { - COMPREPLY=( $( compgen -W " - awslogs - etwlogs - fluentd - gcplogs - gelf - journald - json-file - logentries - none - splunk - syslog - k8s-file - " -- "$cur" ) ) -} - -__podman_complete_log_options() { - # see docs/reference/logging/index.md - local awslogs_options="awslogs-region awslogs-group awslogs-stream" - local fluentd_options="env fluentd-address fluentd-async-connect fluentd-buffer-limit fluentd-retry-wait fluentd-max-retries labels tag" - local gcplogs_options="env gcp-log-cmd gcp-project labels" - local gelf_options="env gelf-address gelf-compression-level gelf-compression-type labels tag" - local journald_options="env labels tag" - local json_file_options="env labels max-file max-size" - local logentries_options="logentries-token" - local syslog_options="env labels syslog-address syslog-facility syslog-format syslog-tls-ca-cert syslog-tls-cert syslog-tls-key syslog-tls-skip-verify tag" - local splunk_options="env labels splunk-caname splunk-capath splunk-format splunk-gzip splunk-gzip-level splunk-index splunk-insecureskipverify splunk-source splunk-sourcetype splunk-token splunk-url splunk-verify-connection tag" - local k8s_file_options="env labels max-file max-size" - - local all_options="$fluentd_options $gcplogs_options $gelf_options $journald_options $logentries_options $json_file_options $syslog_options $splunk_options" - - case $(__podman_value_of_option --log-driver) in - '') - COMPREPLY=( $( compgen -W "$all_options" -S = -- "$cur" ) ) - ;; - awslogs) - COMPREPLY=( $( compgen -W "$awslogs_options" -S = -- "$cur" ) ) - ;; - fluentd) - COMPREPLY=( $( compgen -W "$fluentd_options" -S = -- "$cur" ) ) - ;; - gcplogs) - COMPREPLY=( $( compgen -W "$gcplogs_options" -S = -- "$cur" ) ) - ;; - gelf) - COMPREPLY=( $( compgen -W "$gelf_options" -S = -- "$cur" ) ) - ;; - journald) - COMPREPLY=( $( compgen -W "$journald_options" -S = -- "$cur" ) ) - ;; - json-file) - COMPREPLY=( $( compgen -W "$json_file_options" -S = -- "$cur" ) ) - ;; - k8s-file) - COMPREPLY=( $( compgen -W "$k8s_file_options" -S = -- "$cur" ) ) - ;; - logentries) - COMPREPLY=( $( compgen -W "$logentries_options" -S = -- "$cur" ) ) - ;; - syslog) - COMPREPLY=( $( compgen -W "$syslog_options" -S = -- "$cur" ) ) - ;; - splunk) - COMPREPLY=( $( compgen -W "$splunk_options" -S = -- "$cur" ) ) - ;; - *) - return - ;; - esac - - __podman_nospace -} - -__podman_complete_log_driver_options() { - local key=$(__podman_map_key_of_current_option '--log-opt') - case "$key" in - fluentd-async-connect) - COMPREPLY=( $( compgen -W "false true" -- "${cur##*=}" ) ) - return - ;; - gelf-address) - COMPREPLY=( $( compgen -W "udp" -S "://" -- "${cur##*=}" ) ) - __podman_nospace - return - ;; - gelf-compression-level) - COMPREPLY=( $( compgen -W "1 2 3 4 5 6 7 8 9" -- "${cur##*=}" ) ) - return - ;; - gelf-compression-type) - COMPREPLY=( $( compgen -W "gzip none zlib" -- "${cur##*=}" ) ) - return - ;; - syslog-address) - COMPREPLY=( $( compgen -W "tcp:// tcp+tls:// udp:// unix://" -- "${cur##*=}" ) ) - __podman_nospace - __ltrim_colon_completions "${cur}" - return - ;; - syslog-facility) - COMPREPLY=( $( compgen -W " - auth - authpriv - cron - daemon - ftp - kern - local0 - local1 - local2 - local3 - local4 - local5 - local6 - local7 - lpr - mail - news - syslog - user - uucp - " -- "${cur##*=}" ) ) - return - ;; - syslog-format) - COMPREPLY=( $( compgen -W "rfc3164 rfc5424 rfc5424micro" -- "${cur##*=}" ) ) - return - ;; - syslog-tls-ca-cert|syslog-tls-cert|syslog-tls-key) - _filedir - return - ;; - syslog-tls-skip-verify) - COMPREPLY=( $( compgen -W "true" -- "${cur##*=}" ) ) - return - ;; - splunk-url) - COMPREPLY=( $( compgen -W "http:// https://" -- "${cur##*=}" ) ) - __podman_nospace - __ltrim_colon_completions "${cur}" - return - ;; - splunk-gzip|splunk-insecureskipverify|splunk-verify-connection) - COMPREPLY=( $( compgen -W "false true" -- "${cur##*=}" ) ) - return - ;; - splunk-format) - COMPREPLY=( $( compgen -W "inline json raw" -- "${cur##*=}" ) ) - return - ;; - esac - return 1 -} - -__podman_complete_log_levels() { - COMPREPLY=( $( compgen -W "debug info warn error fatal" -- "$cur" ) ) -} - -# __podman_complete_signals returns a subset of the available signals that is most likely -# relevant in the context of podman containers -__podman_complete_signals() { - local signals=( - SIGCONT - SIGHUP - SIGINT - SIGKILL - SIGQUIT - SIGSTOP - SIGTERM - SIGUSR1 - SIGUSR2 - ) - COMPREPLY=( $( compgen -W "${signals[*]} ${signals[*]#SIG}" -- "$( echo $cur | tr '[:lower:]' '[:upper:]')" ) ) -} - -__podman_complete_user_group() { - if [[ $cur == *:* ]] ; then - COMPREPLY=( $(compgen -g -- "${cur#*:}") ) - else - COMPREPLY=( $(compgen -u -S : -- "$cur") ) - __podman_nospace - fi -} - -__podman_list_images() { - COMPREPLY=($(compgen -W "$(podman images -q)" -- $cur)) -} - -__podman_list_containers() { - COMPREPLY=($(compgen -W "$(podman ps -aq)" -- $cur)) -} - -__podman_images() { - local images_args="" - - case "$PODMAN_COMPLETION_SHOW_IMAGE_IDS" in - all) - images_args="--no-trunc -a" - ;; - non-intermediate) - images_args="--no-trunc" - ;; - esac - - local repo_print_command - if [ "${PODMAN_COMPLETION_SHOW_TAGS:-yes}" = "yes" ]; then - repo_print_command='print $1; print $1":"$2' - else - repo_print_command='print $1' - fi - - local awk_script - case "$PODMAN_COMPLETION_SHOW_IMAGE_IDS" in - all|non-intermediate) - awk_script='NR>1 { print $3; if ($1 != "") { '"$repo_print_command"' } }' - ;; - none|*) - awk_script='NR>1 && $1 != "" { '"$repo_print_command"' }' - ;; - esac - - __podman_q images $images_args | awk "$awk_script" | grep -v '$' -} - -_podman_auto_update() { - local options_with_args=" - --authfile - " - - local boolean_options=" - --help - -h - " - - _complete_ "$options_with_args" "$boolean_options" - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_volume_names - ;; - esac -} - -# __podman_complete_volumes applies completion of volumes based on the current -# value of `$cur` or the value of the optional first option `--cur`, if given. -__podman_complete_volumes() { - local current="$cur" - if [ "$1" = "--cur" ] ; then - current="$2" - shift 2 - fi - COMPREPLY=( $(compgen -W "$(__podman_volume "$@")" -- "$current") ) -} - -__podman_complete_volume_names() { - local names=( $(__podman_q volume ls --quiet) ) - COMPREPLY=( $(compgen -W "${names[*]}" -- "$cur") ) -} - - -_podman_attach() { - local options_with_args=" - --detach-keys - " - local boolean_options=" - --help -h - --latest -l - --no-stdin - --sig-proxy - " - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_containers_running - ;; - esac -} - -_podman_container_attach() { - _podman_attach -} - -_podman_container_checkpoint() { - local options_with_args=" - -e - --export - " - local boolean_options=" - --all -a - --help -h - --ignore-rootfs - --keep -k - --latest -l - --leave-running -R - --tcp-established - " - case "$prev" in - -e|--export) - _filedir - return - ;; - esac - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_containers_running - ;; - esac -} - -_podman_container_commit() { - _podman_commit -} - -_podman_container_cp() { - _podman_cp -} - -_podman_container_create() { - _podman_create -} - -_podman_container_diff() { - _podman_diff -} - -_podman_container_exec() { - _podman_exec -} - -_podman_container_export() { - _podman_export -} - -_podman_container_init() { - _podman_init -} - -_podman_container_inspect() { - _podman_inspect -} - -_podman_container_kill() { - _podman_kill -} - -_podman_container_list() { - _podman_ls -} - -_podman_container_ls() { - _podman_ls -} - -_podman_container_logs() { - _podman_logs -} - -_podman_container_mount() { - _podman_mount -} - -_podman_container_pause() { - _podman_pause -} - -_podman_container_port() { - _podman_port -} - -_podman_container_ps() { - _podman_ls -} - -_podman_container_refresh() { - local options_with_args=" - " - local boolean_options=" - --help - -h - " - _complete_ "$options_with_args" "$boolean_options" -} - -_podman_container_restart() { - _podman_restart -} - -_podman_container_restore() { - local options_with_args=" - -i - --import - -n - --name - " - local boolean_options=" - --all -a - --help -h - --ignore-rootfs - --ignore-static-ip - --ignore-static-mac - --keep -k - --latest -l - --tcp-established - " - case "$prev" in - -i|--import) - _filedir - return - ;; - esac - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_containers_created - ;; - esac -} - -_podman_container_rm() { - _podman_rm -} - -_podman_container_start() { - _podman_start -} - -_podman_container_stats() { - _podman_stats -} - -_podman_container_stop() { - _podman_stop -} - -_podman_container_top() { - _podman_top -} - -_podman_container_umount() { - _podman_umount -} - -_podman_container_unmount() { - _podman_unmount -} - -_podman_container_unpause() { - _podman_unpause -} - -_podman_container_wait() { - _podman_wait -} - -_podman_healthcheck() { - local boolean_options=" - --help - -h - " - subcommands=" - run - " - __podman_subcommands "$subcommands $aliases" && return - - case "$cur" in - -*) - COMPREPLY=( $( compgen -W "--help" -- "$cur" ) ) - ;; - *) - COMPREPLY=( $( compgen -W "$subcommands" -- "$cur" ) ) - ;; - esac -} - -_podman_network() { - local boolean_options=" - --help - -h - " - subcommands=" - create - inspect - ls - rm - " - __podman_subcommands "$subcommands $aliases" && return - - case "$cur" in - -*) - COMPREPLY=( $( compgen -W "--help" -- "$cur" ) ) - ;; - *) - COMPREPLY=( $( compgen -W "$subcommands" -- "$cur" ) ) - ;; - esac -} - -_podman_network_create() { - local options_with_args=" - -d - --driver - --gateway - --ip-range - --macvlan - --subnet - " - local boolean_options=" - --disable-dns - --help -h - --internal - " - _complete_ "$options_with_args" "$boolean_options" - - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - esac -} - -_podman_network_inspect() { - local options_with_args=" - --format - -f - " - local boolean_options=" - --help - -h - " - _complete_ "$options_with_args" "$boolean_options" - - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - esac -} - -_podman_network_ls() { - local options_with_args=" - --filter - --format -f - " - local boolean_options=" - --help - -h - --quiet - -q - " - _complete_ "$options_with_args" "$boolean_options" - - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - esac -} - -_podman_network_rm() { - local options_with_args=" - " - local boolean_options=" - --force -f - --help -h - " - _complete_ "$options_with_args" "$boolean_options" - - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - esac -} - -_podman_generate() { - local boolean_options=" - --help - -h - " - subcommands=" - kube - systemd - " - __podman_subcommands "$subcommands $aliases" && return - - case "$cur" in - -*) - COMPREPLY=( $( compgen -W "--help" -- "$cur" ) ) - ;; - *) - COMPREPLY=( $( compgen -W "$subcommands" -- "$cur" ) ) - ;; - esac -} - -_podman_play() { - local boolean_options=" - --help - -h - " - subcommands=" - kube - " - __podman_subcommands "$subcommands $aliases" && return - - case "$cur" in - -*) - COMPREPLY=( $( compgen -W "--help" -- "$cur" ) ) - ;; - *) - COMPREPLY=( $( compgen -W "$subcommands" -- "$cur" ) ) - ;; - esac -} -_podman_container() { - local boolean_options=" - --help - -h - " - subcommands=" - attach - checkpoint - commit - cp - create - diff - exec - exists - export - inspect - kill - list - logs - mount - pause - port - prune - refresh - restart - restore - rm - run - runlabel - start - stats - stop - top - umount - unmount - unpause - wait - " - local aliases=" - list - ps - " - __podman_subcommands "$subcommands $aliases" && return - - case "$cur" in - -*) - COMPREPLY=( $( compgen -W "--help" -- "$cur" ) ) - ;; - *) - COMPREPLY=( $( compgen -W "$subcommands" -- "$cur" ) ) - ;; - esac -} - -_podman_system_reset() { - local options_with_args=" - " - local boolean_options=" - -h - --help - --force - " - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - esac -} - -_podman_system_df() { - local options_with_args=" - --format - --verbose - " - local boolean_options=" - -h - --help - --verbose - -v - " - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - esac -} - -_podman_system_info() { - _podman_info -} - -_podman_system_prune() { - local options_with_args=" - " - - local boolean_options=" - --all -a - --force -f - --help -h - --volumes - " - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - esac -} - -_podman_system_service() { - local options_with_args=" - -t - --timeout - " - local boolean_options=" - --help - -h - --varlink - " - _complete_ "$options_with_args" "$boolean_options" -} - -_podman_system() { - local boolean_options=" - --help - -h - " - subcommands=" - df - info - migrate - prune - renumber - reset - service - " - __podman_subcommands "$subcommands" && return - - case "$cur" in - -*) - COMPREPLY=( $( compgen -W "--help" -- "$cur" ) ) - ;; - *) - COMPREPLY=( $( compgen -W "$subcommands" -- "$cur" ) ) - ;; - esac -} - -_podman_commit() { - local options_with_args=" - --author - -a - --change - -c - --message - -m - --iidfile - " - local boolean_options=" - --help -h - --pause -p - --quiet -q - " - _complete_ "$options_with_args" "$boolean_options" - - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_container_names - ;; - esac -} - -_podman_build() { - local boolean_options=" - --force-rm - --help -h - --layers - --no-cache - --pull - --pull-always - --pull-never - --quiet -q - --rm - --squash - --squash-all - --tls-verify - " - - local options_with_args=" - --add-host - --annotation - --authfile - --build-arg - --cap-add - --cap-drop - --cgroup-parent - --cni-config-dir - --cni-plugin-path - --cpu-period - --cpu-quota - --cpu-shares - --cpuset-cpus - --cpuset-mems - --creds - --file -f - --format - --iidfile - --ipc - --label - --memory -m - --memory-swap - --mount - --net - --network - --pid - --runtime-flag - --security-opt - --shm-size - --tag -t - --ulimit - --userns - --userns-gid-map - --userns-gid-map-group - --userns-uid-map - --userns-uid-map-user - --uts - --volume -v - " - - case "$prev" in - --file|-f) - COMPREPLY=($(compgen -W "`ls`" -- "$cur")) - ;; - esac - - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - esac -} - -_podman_diff() { - local options_with_args=" - --format - " - local boolean_options=" - --help - -h - " - _complete_ "$options_with_args" "$boolean_options" - - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_container_names - ;; - esac -} - -_podman_exec() { - local options_with_args=" - --detach-keys - -e - --env - --env-file - --user - -u - --workdir - -w - " - local boolean_options=" - --help -h - --latest -l - --privileged - --tty -t - " - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_containers_running - ;; - esac - -} -_podman_export() { - local options_with_args=" - --output - -o - " - local boolean_options=" - --help - -h - " - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$options_with_args" -- "$cur")) - ;; - *) - __podman_complete_container_names - ;; - esac -} - -_podman_history() { - local options_with_args=" - --format - " - local boolean_options=" - --help -h - --human -H - --no-trunc - --quiet -q - " - _complete_ "$options_with_args" "$boolean_options" - - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_images --id - ;; - esac -} - - -_podman_import() { - local options_with_args=" - --change - -c - --message - -m - " - local boolean_options=" - --help - -h - --quiet - -q - " - case "$prev" in - --change|-c|--message|-m) - return - ;; - esac - - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - local counter=$(__podman_pos_first_nonflag '--change|-c|--message|-m') - if [ "$cword" -eq "$counter" ]; then - _filedir - return - elif [ "$cword" -eq "$((counter + 1))" ]; then - __podman_complete_images --repo --tag - return - fi - ;; - esac -} - -_podman_info() { - local boolean_options=" - --help - -h - --debug - " - local options_with_args=" - -f - --format - " - - local all_options="$options_with_args $boolean_options" - - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_list_images - ;; - esac -} - -_podman_image_umount() { - _podman_image_unmount -} - -_podman_image_unmount() { - local boolean_options=" - --all -a - --help -h - --force -f - " - local options_with_args=" - " - - local all_options="$options_with_args $boolean_options" - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_images --force-tag --id - ;; - esac -} - -_podman_image_mount() { - local boolean_options=" - --all -a - --help -h - " - - local options_with_args=" - --format - " - - local all_options="$options_with_args $boolean_options" - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_images --force-tag --id - ;; - esac -} - -_podman_image_build() { - _podman_build -} - -_podman_image_history() { - _podman_history -} - -_podman_image_import() { - _podman_import -} - -_podman_image_inspect() { - _podman_inspect -} - -_podman_image_load() { - _podman_load -} - -_podman_image_list() { - _podman_images -} - -_podman_image_ls() { - _podman_images -} - -_podman_image_pull() { - _podman_pull -} - -_podman_image_push() { - _podman_push -} - -_podman_image_rm() { - _podman_rmi -} - -_podman_image_save() { - _podman_save -} - -_podman_image_tag() { - _podman_tag -} - - -_podman_image_untag() { - _podman_untag -} - -_podman_image() { - local boolean_options=" - --help - -h - " - subcommands=" - build - exists - history - import - inspect - load - ls - mount - prune - pull - push - rm - save - sign - tag - trust - umount - unmount - untag - " - local aliases=" - list - " - __podman_subcommands "$subcommands $aliases" && return - - case "$cur" in - -*) - COMPREPLY=( $( compgen -W "--help" -- "$cur" ) ) - ;; - *) - COMPREPLY=( $( compgen -W "$subcommands" -- "$cur" ) ) - ;; - esac -} - -_podman_images() { - local boolean_options=" - --all -a - --digests - --filter -f - --help -h - --history - --no-trunc - --noheading - --notruncate -n - --quiet -q - " - local options_with_args=" - --format - --sort - " - - local all_options="$options_with_args $boolean_options" - - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_images --id - ;; - esac -} - -_podman_inspect() { - local boolean_options=" - --help -h - --latest -l - " - local options_with_args=" - --format - -f - --type - -t - --size - -s - " - - local all_options="$options_with_args $boolean_options" - - local preselected_type - local type - - if [ "$1" = "--type" ] ; then - preselected_type=yes - type="$2" - else - type=$(__podman_value_of_option --type) - fi - - case "$prev" in - --format|-f) - return - ;; - --type) - if [ -z "$preselected_type" ] ; then - COMPREPLY=( $( compgen -W "container image" -- "$cur" ) ) - return - fi - ;; - esac - - case "$cur" in - -*) - local options="--format -f --help --size -s" - if [ -z "$preselected_type" ] ; then - options+=" --type" - fi - COMPREPLY=( $( compgen -W "$options" -- "$cur" ) ) - ;; - *) - case "$type" in - '') - COMPREPLY=( $( compgen -W " - $(__podman_containers --all) - $(__podman_images --force-tag --id) - " -- "$cur" ) ) - __ltrim_colon_completions "$cur" - ;; - container) - __podman_complete_containers_all - ;; - image) - __podman_complete_images --force-tag --id - ;; - esac - esac -} - -_podman_kill() { - local options_with_args=" - --signal -s - " - local boolean_options=" - --all -a - --help -h - --latest -l - " - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_containers_running - ;; - esac -} - -_podman_logs() { - local options_with_args=" - --since - --tail - " - local boolean_options=" - --follow -f - --help -h - --latest -l - --timestamps -t - " - _complete_ "$options_with_args" "$boolean_options" - - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_list_containers - ;; - esac -} - -_podman_manifest() { - local boolean_options=" - --help - -h - " - subcommands=" - add - create - inspect - push - remove - " - __podman_subcommands "$subcommands" && return - - case "$cur" in - -*) - COMPREPLY=( $( compgen -W "--help" -- "$cur" ) ) - ;; - *) - COMPREPLY=( $( compgen -W "$subcommands" -- "$cur" ) ) - ;; - esac -} - -_podman_manifest_add() { - local options_with_args=" - --annotation - --arch - --authfile - --cert-dir - --creds - --features - --os - --os-version - --variant - " - - local boolean_options=" - --all - --help - -h - --tls-verify - " - - _complete_ "$options_with_args" "$boolean_options" - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_images --id - ;; - esac -} - -_podman_manifest_annotate() { - local options_with_args=" - --annotation - --arch - --features - --os - --os-features - --os-version - --variant - " - - local boolean_options=" - --help - -h - " - - _complete_ "$options_with_args" "$boolean_options" - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_images --id - ;; - esac -} - -_podman_manifest_create() { - local boolean_options=" - --all - --help - -h - " - - _complete_ "$boolean_options" -} - -_podman_manifest_inspect() { - local options_with_args=" - " - - local boolean_options=" - " - - _complete_ "$options_with_args" "$boolean_options" - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_images --id - - ;; - esac -} - -_podman_manifest_push() { - local options_with_args=" - --authfile - --cert-dir - --creds - --digestfile - --format -f - --sign-by - --signature-policy, - " - - local boolean_options=" - --all - --help -h - --purge - --quiet - --remove-signatures - --tls-verify - " - - _complete_ "$options_with_args" "$boolean_options" - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_images --id - ;; - esac -} - -_podman_manifest_remove() { - local options_with_args=" - " - - local boolean_options=" - " - - _complete_ "$options_with_args" "$boolean_options" - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_images --id - ;; - esac -} - -_podman_pull() { - local options_with_args=" - --authfile - --cert-dir - --creds - --override-arch - --override-os - --override-variant - " - local boolean_options=" - --all-tags -a - --disable-content-trust - --help -h - --quiet -q - --tls-verify - " - _complete_ "$options_with_args" "$boolean_options" -} - -_podman_search() { - local options_with_args=" - --authfile - --filter -f - --format - --limit - " - local boolean_options=" - --help - -h - --no-trunc - --list-tags - " - _complete_ "$options_with_args" "$boolean_options" -} - -_podman_unmount() { - _podman_umount $@ -} - -_podman_umount() { - local boolean_options=" - --all -a - --help -h - --force -f - --latest -l - " - local options_with_args=" - " - - local all_options="$options_with_args $boolean_options" - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_container_names - ;; - esac -} - -_podman_mount() { - local boolean_options=" - --all -a - --help -h - --latest -l - --notruncate - " - - local options_with_args=" - --format - " - - local all_options="$options_with_args $boolean_options" - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_container_names - ;; - esac -} - -_podman_push() { - local boolean_options=" - --compress - --digestflag - --help -h - --quiet -q - --tls-verify - " - - local options_with_args=" - --authfile - --cert-dir - --creds - --format - --sign-by - " - - local all_options="$options_with_args $boolean_options" - - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_images --id - ;; - esac -} - -_podman_container_run() { - local options_with_args=" - --add-host - --annotation - --attach -a - --blkio-weight - --blkio-weight-device - --builtin-volume - --cap-add - --cap-drop - --cgroup-conf - --cgroup-parent - --cidfile - --conmon-pidfile - --cpu-period - --cpu-quota - --cpu-rt-period - --cpu-rt-runtime - --cpu-shares -c - --cpus - --cpuset-cpus - --cpuset-mems - --device - --device-cgroup-rule - --device-read-bps - --device-read-iops - --device-write-bps - --device-write-iops - --dns - --dns-option - --dns-search - --entrypoint - --env -e - --env-file - --env-host - --expose - --gidmap - --group-add - --health-cmd - --health-interval - --health-retries - --health-start-period - --health-timeout - --hostname -h - --http-proxy - --image-volume - --init-path - --ip - --ipc - --kernel-memory - --label -l - --label-file - --log-driver - --log-opt - --mac-address - --memory -m - --memory-reservation - --memory-swap - --memory-swappiness - --name - --network - --no-healthcheck - --no-hosts - --oom-score-adj - --override-arch - --override-os - --override-variant - --pid - --pids-limit - --pod - --pod-id-file - --preserve-fds - --publish -p - --pull - --restart - --rootfs - --runtime - --security-opt - --shm-size - --stop-signal - --stop-timeout - --subgidname - --subuidname - --sysctl - --systemd - --tmpfs - --tz - --uidmap - --ulimit - --umask - --user -u - --userns - --uts - --volume -v - --volumes-from - --workdir -w - " - - local boolean_options=" - --disable-content-trust=false - --help -h - --init - --interactive -i - --oom-kill-disable - --privileged - --publish-all -P - --quiet - --read-only - --read-only-tmpfs - --tty -t - " - - if [ "$command" = "run" -o "$subcommand" = "run" ] ; then - options_with_args="$options_with_args - --detach-keys - --health-cmd - --health-interval - --health-retries - --health-start-period - --health-timeout - " - boolean_options="$boolean_options - --detach -d - --rm - --rmi - --sig-proxy=false - " - __podman_complete_detach_keys && return - __podman_complete_restart && return - fi - - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - return - ;; - *) - __podman_complete_images --id - ;; - esac - - - __podman_complete_log_driver_options && return - - local key=$(__podman_map_key_of_current_option '--security-opt') - case "$key" in - label) - [[ $cur == *: ]] && return - COMPREPLY=( $( compgen -W "user: role: type: level: disable" -- "${cur##*=}") ) - if [ "${COMPREPLY[*]}" != "disable" ] ; then - __podman_nospace - fi - return - ;; - seccomp) - local cur=${cur##*=} - _filedir - COMPREPLY+=( $( compgen -W "unconfined" -- "$cur" ) ) - return - ;; - esac - - case "$prev" in - --add-host) - case "$cur" in - *:) - __podman_complete_resolved_hostname - return - ;; - esac - ;; - --attach|-a) - COMPREPLY=( $( compgen -W 'stdin stdout stderr' -- "$cur" ) ) - return - ;; - --cap-add|--cap-drop) - __podman_complete_capabilities - return - ;; - --cidfile|--env-file|--init-path|--label-file|--pod-id-file) - _filedir - return - ;; - --device|--tmpfs|--volume|-v) - case "$cur" in - *:*) - # TODO somehow do _filedir for stuff inside the image, if it's already specified (which is also somewhat difficult to determine) - ;; - '') - COMPREPLY=( $( compgen -W '/' -- "$cur" ) ) - __podman_nospace - ;; - /*) - _filedir - __podman_nospace - ;; - esac - return - ;; - --env|-e) - # we do not append a "=" here because "-e VARNAME" is legal syntax, too - COMPREPLY=( $( compgen -e -- "$cur" ) ) - __podman_nospace - return - ;; - --ipc) - case "$cur" in - *:*) - cur="${cur#*:}" - __podman_complete_containers_running - ;; - *) - COMPREPLY=( $( compgen -W 'host private container:' -- "$cur" ) ) - if [ "$COMPREPLY" = "container:" ]; then - __podman_nospace - fi - ;; - esac - return - ;; - --log-driver) - __podman_complete_log_drivers - return - ;; - --log-opt) - __podman_complete_log_options - return - ;; - --network) - case "$cur" in - container:*) - __podman_complete_containers_all --cur "${cur#*:}" - ;; - *) - COMPREPLY=( $(compgen -W "bridge none host ns: private slirp4netns $(__podman_networks) container:" -- "$cur")) - if [ "${COMPREPLY[*]}" = "container:" ] ; then - __podman_nospace - fi - ;; - esac - return - ;; - --pod) - __podman_complete_pod_names - return - ;; - --pid) - case "$cur" in - *:*) - __podman_complete_containers_running --cur "${cur#*:}" - ;; - *) - COMPREPLY=( $( compgen -W 'host container: private' -- "$cur" ) ) - if [ "$COMPREPLY" = "container:" ]; then - __podman_nospace - fi - ;; - esac - return - ;; - --runtime) - __podman_complete_runtimes - return - ;; - --security-opt) - COMPREPLY=( $( compgen -W "apparmor= label= no-new-privileges seccomp=" -- "$cur") ) - if [ "${COMPREPLY[*]}" != "no-new-privileges" ] ; then - __podman_nospace - fi - return - ;; - --storage-opt) - COMPREPLY=( $( compgen -W "size" -S = -- "$cur") ) - __podman_nospace - return - ;; - --user|-u) - __podman_complete_user_group - return - ;; - --userns) - COMPREPLY=( $( compgen -W "auto container: host keep-id ns: private" -- "$cur" ) ) - return - ;; - --volumes-from) - __podman_complete_containers_all - return - ;; - $(__podman_to_extglob "$options_with_args") ) - return - ;; - esac - - case "$cur" in - -*) - COMPREPLY=( $( compgen -W "$all_options" -- "$cur" ) ) - ;; - *) - local counter=$( __podman_pos_first_nonflag $( __podman_to_alternatives "$options_with_args" ) ) - if [ $cword -eq $counter ]; then - __podman_complete_images - fi - ;; - esac -} - - -_podman_create() { - _podman_container_run -} - - -_podman_run() { - _podman_container_run -} - -_podman_restart() { - local options_with_args=" - --time -t - " - local boolean_options=" - --all -a - --help -h - --latest -l - --running - " - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_containers_running - ;; - esac -} - -_podman_rm() { - local boolean_options=" - --all -a - --cidfile - --force -f - --help -h - --ignore -i - --latest -l - --volumes -v - " - - local options_with_args=" - " - - local all_options="$options_with_args $boolean_options" - - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_container_names - ;; - esac -} - -_podman_rmi() { - local boolean_options=" - --all -a - --force -f - --help -h - " - - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_images --id - ;; - esac -} - -_podman_stats() { - local boolean_options=" - --all -a - --format - --help -h - --no-reset - --no-stream - " - - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_containers_running - ;; - esac -} - -_podman_tag() { - local options_with_args=" - " - local boolean_options=" - --help - -h - " - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_images - ;; - esac -} - -_podman_untag() { - local options_with_args=" - " - local boolean_options=" - --help - -h - " - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_images - ;; - esac -} - -__podman_top_descriptors() { - podman top --list-descriptors -} - -__podman_complete_top_descriptors() { - COMPREPLY=($(compgen -W "$(__podman_top_descriptors)" -- "$cur")) -} - -_podman_top() { - local options_with_args=" - " - local boolean_options=" - --help - -h - --latest - -l - " - - # podman-top works on only *one* container, which means that when we have - # three or more arguments, we can complete with top descriptors. - if [[ "${COMP_CWORD}" -ge 3 ]]; then - __podman_complete_top_descriptors - return +__podman_debug() +{ + if [[ -n ${BASH_COMP_DEBUG_FILE} ]]; then + echo "$*" >> "${BASH_COMP_DEBUG_FILE}" fi - - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_containers_running - ;; - esac -} - -_podman_version() { - local boolean_options=" - --help - -h - " - local options_with_args=" - --format - -f - " - local all_options="$options_with_args $boolean_options" - - _complete_ "$options_with_args" "$boolean_options" -} - -_podman_save() { - local options_with_args=" - --output -o - --format - " - local boolean_options=" - --compress - --help -h - --quiet -q - " - - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_images --id - ;; - esac -} - -_podman_pause() { - local boolean_options=" - --all - -a - --help - -h - " - local options_with_args=" - " - local boolean_options="" - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_containers_running - ;; - esac -} - -_podman_port() { - local options_with_args=" - " - local boolean_options=" - --all -a - --help -h - --latest -l - " - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_container_names - ;; - esac -} - -_podman_ls() { - _podman_ps -} - -_podman_ps() { - local options_with_args=" - --filter -f - --format - --last -n - --sort - --watch -w - " - local boolean_options=" - --all -a - --external - --help -h - --latest -l - --namespace --ns - --no-trunc - --pod -p - --quiet -q - --size -s - --sync - " - _complete_ "$options_with_args" "$boolean_options" -} - -_podman_init() { - local boolean_options=" - --all - -a - --help - -h - --latest - -l - " - local options_with_args=" - " - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_containers_unpauseable - ;; - esac -} - -_podman_start() { - local options_with_args=" - --detach-keys - " - - local boolean_options=" - --attach -a - --help -h - --interactive -i - --latest -l - --sig-proxy - " - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_containers_stopped - ;; - esac -} -_podman_stop() { - local options_with_args=" - --time -t - " - local boolean_options=" - --all -a - --cidfile - --help -h - --ignore -i - --latest -l - " - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_containers_running - ;; - esac -} - -_podman_unpause() { - local boolean_options=" - --all - -a - --help - -h - " - local options_with_args=" - " - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_containers_unpauseable - ;; - esac -} - -_podman_varlink() { - local options_with_args=" - --timeout -t - " - local boolean_options=" - --help - -h - " - _complete_ "$options_with_args" "$boolean_options" -} - -_podman_wait() { - local options_with_args="" - local boolean_options=" - --help -h - --interval -i - --latest -l - " - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_container_names - ;; - esac -} - -_complete_() { - local options_with_args=$1 - local boolean_options="$2 -h --help" - - case "$prev" in - $options_with_args) - return - ;; - esac - - case "$cur" in - -*) - COMPREPLY=( $( compgen -W "$boolean_options $options_with_args" -- "$cur" ) ) - ;; - esac -} - -_podman_load() { - local options_with_args=" - --input -i - " - local boolean_options=" - --help -h - --quiet -q - " - _complete_ "$options_with_args" "$boolean_options" -} - -_podman_cp() { - local boolean_options=" - --extract - --help -h - --pause - " - _complete_ "$boolean_options" -} - -_podman_login() { - local options_with_args=" - --authfile - --get-login - --password -p - --username -u - " - local boolean_options=" - --help - -h - --password-stdin - " - _complete_ "$options_with_args" "$boolean_options" -} - -_podman_logout() { - local options_with_args=" - --authfile - " - local boolean_options=" - --all - -a - --help - -h - " - _complete_ "$options_with_args" "$boolean_options" -} - -_podman_healthcheck_run() { - local options_with_args="" - - local boolean_options=" - -h - --help - " - - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - COMPREPLY=( $( compgen -W " - $(__podman_containers --all) - " -- "$cur" ) ) - __ltrim_colon_completions "$cur" - ;; - esac -} - -_podman_generate_kube() { - local options_with_args=" - --filename -f - " - - local boolean_options=" - -h - --help - -s - --service - " - - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - COMPREPLY=( $( compgen -W " - $(__podman_containers --all) - $(__podman_pods) - " -- "$cur" ) ) - __ltrim_colon_completions "$cur" - ;; - esac -} - -_podman_generate_systemd() { - local options_with_args=" - --restart-policy - -t - --time - --container-prefix - --pod-prefix - --separator" - - local boolean_options=" - -h - --help - -n - --name - " - - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - COMPREPLY=( $( compgen -W " - $(__podman_containers --all) - " -- "$cur" ) ) - __ltrim_colon_completions "$cur" - ;; - esac -} - -_podman_play_kube() { - local options_with_args=" - --authfile - --cert-dir - --creds - --network - " - - local boolean_options=" - --help -h - --quiet -q - --seccomp-profile-root - --tls-verify - " - - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - _filedir - ;; - esac -} - -_podman_events() { - local options_with_args=" - --filter - --format - --help -h - --since - --until - " - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$options_with_args" -- "$cur")) - ;; - esac -} - -_podman_container_runlabel() { - local options_with_args=" - --authfile - --cert-dir - --creds - --name - " - - local boolean_options=" - --display - --help -h - --quiet -q - --replace - --tls-verify - " - - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_images --id - ;; - esac -} - -_podman_image_sign() { - local options_with_args=" - --cert-dir - --directory -d - --sign-by - " - local boolean_options=" - --help - -h - " - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_images - ;; - esac -} - -_podman_image_trust_set() { - echo hello - local options_with_args=" - --pubkeysfile -f - --type -t - " - local boolean_options=" - --help - -h - " - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - COMPREPLY=($(compgen -W "default $( __podman_list_registries )" -- "$cur")) - ;; - esac -} - -_podman_image_trust_show() { - local options_with_args=" - " - local boolean_options=" - --help -h - --json -j - --raw - " - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_images - ;; - esac -} - -_podman_image_trust() { - local boolean_options=" - --help - -h - " - subcommands=" - set - show - " - local aliases=" - list - " - command=image_trust - __podman_subcommands "$subcommands $aliases" && return - - case "$cur" in - -*) - COMPREPLY=( $( compgen -W "--help" -- "$cur" ) ) - ;; - *) - COMPREPLY=( $( compgen -W "$subcommands" -- "$cur" ) ) - ;; - esac -} - -_podman_images_prune() { - local options_with_args=" - " - - local boolean_options=" - --all -a - --help -h - " - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - esac -} - -_podman_container_prune() { - local options_with_args=" - --filter - " - - local boolean_options=" - --force -f - --help -h - " - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - esac -} - -_podman_container_exists() { - local options_with_args=" - " - - local boolean_options=" - --external - --help -h - " - - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_images - ;; - esac - -} - -_podman_pod_exists() { - local options_with_args=" - " - - local boolean_options=" - " -} - -_podman_image_exists() { - local options_with_args=" - " - - local boolean_options=" - " -} - -_podman_pod_create() { - local options_with_args=" - --add-host - --cgroup-parent - --dns - --dns-opt - --dns-search - --infra-command - --infra-conmon-pidfile - --infra-image - --ip - --label-file - --label - -l - --mac-address - --name - --network - --no-hosts - --podidfile - --publish - -p - --share - " - - local boolean_options=" - --help -h - --infra - --replace - " - _complete_ "$options_with_args" "$boolean_options" } -_podman_pod_kill() { - local options_with_args=" - " - - local boolean_options=" - --all -a - --help -h - --latest -l - --signal -s - " - _complete_ "$options_with_args" "$boolean_options" - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_pod_names - ;; - esac -} - -__podman_pod_ps() { - local options_with_args=" - --filter -f - --format - --sort - " - - local boolean_options=" - --cgroup - --ctr-ids - --ctr-names - --ctr-status - --help -h - --labels - --latest -l - --no-trunc - --quiet -q - " - _complete_ "$options_with_args" "$boolean_options" -} - -_podman_pod_ls() { - __podman_pod_ps -} - -_podman_pod_list() { - __podman_pod_ps -} - -_podman_pod_ps() { - __podman_pod_ps -} - -_podman_pod_prune() { - local options_with_args=" - " - - local boolean_options=" - -f - -h - --help - " - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - esac -} - -_podman_pod_restart() { - local options_with_args=" - " - - local boolean_options=" - --all -a - --help -h - --latest -l - " - _complete_ "$options_with_args" "$boolean_options" - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_pod_names - ;; - esac -} - -_podman_pod_rm() { - local options_with_args=" - --pod-id-file - " - - local boolean_options=" - --all -a - --force -f - --help -h - --ignore -i - --latest -l - " - _complete_ "$options_with_args" "$boolean_options" - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_pod_names - ;; - esac -} - -_podman_pod_start() { - local options_with_args=" - --pod-id-file - " - - local boolean_options=" - --all -a - --help -h - --latest -l - " - _complete_ "$options_with_args" "$boolean_options" - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_pod_names - ;; - esac -} - -_podman_pod_stop() { - local options_with_args=" - --pod-id-file - --time -t - " - - local boolean_options=" - --all -a - --cleanup - --help -h - --ignore -i - --latest -l - " - _complete_ "$options_with_args" "$boolean_options" - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_pod_names - ;; - esac -} - -_podman_pod_pause() { - local options_with_args=" - " - - local boolean_options=" - --all -a - --help -h - --latest -l - " - _complete_ "$options_with_args" "$boolean_options" - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_pod_names - ;; - esac -} - -_podman_pod_unpause() { - local options_with_args=" - " - - local boolean_options=" - --all -a - --help -h - --latest -l - " - _complete_ "$options_with_args" "$boolean_options" - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_pod_names - ;; - esac -} - -_podman_pod_inspect() { - local options_with_args=" - --format -f - --latest -l - " - - _complete_ "$options_with_args" -} - - -_podman_pod() { - local boolean_options=" - --help - -h - " - subcommands=" - create - inspect - kill - pause - ps - restart - rm - start - stats - stop - top - unpause - " - local aliases=" - list - ls - " - __podman_subcommands "$subcommands $aliases" && return - - case "$cur" in - -*) - COMPREPLY=( $( compgen -W "--help" -- "$cur" ) ) - ;; - *) - COMPREPLY=( $( compgen -W "$subcommands" -- "$cur" ) ) - ;; - esac -} - -_podman_volume_create() { - local options_with_args=" - --driver - --label -l - --opt -o - " - - local boolean_options=" - --help - -h - " - - _complete_ "$options_with_args" "$boolean_options" -} - -_podman_volume_ls() { - local options_with_args=" - --filter - --format -f - " - - local boolean_options=" - --help -h - --quiet -q - " - - _complete_ "$options_with_args" "$boolean_options" -} - -_podman_volume_inspect() { - local options_with_args=" - --format - -f - " - - local boolean_options=" - --all -a - --help -h - " +__podman_perform_completion() +{ + __podman_debug + __podman_debug "========= starting completion logic ==========" + __podman_debug "cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}, cword is $cword" + + # The user could have moved the cursor backwards on the command-line. + # We need to trigger completion from the $cword location, so we need + # to truncate the command-line ($words) up to the $cword location. + words=("${words[@]:0:$cword+1}") + __podman_debug "Truncated words[*]: ${words[*]}," + + local shellCompDirectiveError=1 + local shellCompDirectiveNoSpace=2 + local shellCompDirectiveNoFileComp=4 + local shellCompDirectiveFilterFileExt=8 + local shellCompDirectiveFilterDirs=16 + local shellCompDirectiveLegacyCustomComp=32 + local shellCompDirectiveLegacyCustomArgsComp=64 + + local out requestComp lastParam lastChar comp directive args flagPrefix + + # Prepare the command to request completions for the program. + # Calling ${words[0]} instead of directly podman allows to handle aliases + args=("${words[@]:1}") + requestComp="${words[0]} __completeNoDesc ${args[*]}" + + lastParam=${words[$((${#words[@]}-1))]} + lastChar=${lastParam:$((${#lastParam}-1)):1} + __podman_debug "lastParam ${lastParam}, lastChar ${lastChar}" + + if [ -z "${cur}" ] && [ "${lastChar}" != "=" ]; then + # If the last parameter is complete (there is a space following it) + # We add an extra empty parameter so we can indicate this to the go method. + __podman_debug "Adding extra empty parameter" + requestComp="${requestComp} \"\"" + fi - _complete_ "$options_with_args" "$boolean_options" - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_volume_names - ;; - esac -} + # When completing a flag with an = (e.g., podman -n=) + # bash focuses on the part after the =, so we need to remove + # the flag part from $cur + if [[ "${cur}" == -*=* ]]; then + flagPrefix="${cur%%=*}=" + cur="${cur#*=}" + fi -_podman_volume_rm() { - local options_with_args="" + __podman_debug "Calling ${requestComp}" + # Use eval to handle any environment variables and such + out=$(eval "${requestComp}" 2>/dev/null) + + # Extract the directive integer at the very end of the output following a colon (:) + directive=${out##*:} + # Remove the directive + out=${out%:*} + if [ "${directive}" = "${out}" ]; then + # There is not directive specified + directive=0 + fi + __podman_debug "The completion directive is: ${directive}" + __podman_debug "The completions are: ${out[*]}" + + if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then + # Error code. No completion. + __podman_debug "Received error from custom completion go code" + return + else + if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then + if [[ $(type -t compopt) = "builtin" ]]; then + __podman_debug "Activating no space" + compopt -o nospace + fi + fi + if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then + if [[ $(type -t compopt) = "builtin" ]]; then + __podman_debug "Activating no file completion" + compopt +o default + fi + fi + fi - local boolean_options=" - --all -a - --force -f - --help -h - " + if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then + # File extension filtering + local fullFilter filter filteringCmd + + # Do not use quotes around the $out variable or else newline + # characters will be kept. + for filter in ${out[*]}; do + fullFilter+="$filter|" + done + + filteringCmd="_filedir $fullFilter" + __podman_debug "File filtering command: $filteringCmd" + $filteringCmd + elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then + # File completion for directories only + + # Use printf to strip any trailing newline + local subdir + subdir=$(printf "%s" "${out[0]}") + if [ -n "$subdir" ]; then + __podman_debug "Listing directories in $subdir" + pushd "$subdir" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return + else + __podman_debug "Listing directories in ." + _filedir -d + fi + elif [ $((directive & shellCompDirectiveLegacyCustomComp)) -ne 0 ]; then + local cmd + __podman_debug "Legacy custom completion. Directive: $directive, cmds: ${out[*]}" + + # The following variables should get their value through the commands + # we have received as completions and are parsing below. + local last_command + local nouns + + # Execute every command received + while IFS='' read -r cmd; do + __podman_debug "About to execute: $cmd" + eval "$cmd" + done < <(printf "%s\n" "${out[@]}") + + __podman_debug "last_command: $last_command" + __podman_debug "nouns[0]: ${nouns[0]}, nouns[1]: ${nouns[1]}" + + if [ $((directive & shellCompDirectiveLegacyCustomArgsComp)) -ne 0 ]; then + # We should call the global legacy custom completion function, if it is defined + if declare -F __podman_custom_func >/dev/null; then + # Use command name qualified legacy custom func + __podman_debug "About to call: __podman_custom_func" + __podman_custom_func + elif declare -F __custom_func >/dev/null; then + # Otherwise fall back to unqualified legacy custom func for compatibility + __podman_debug "About to call: __custom_func" + __custom_func + fi + fi + else + local tab + tab=$(printf '\t') + local longest=0 + # Look for the longest completion so that we can format things nicely + while IFS='' read -r comp; do + comp=${comp%%$tab*} + if ((${#comp}>longest)); then + longest=${#comp} + fi + done < <(printf "%s\n" "${out[@]}") + + local completions=() + while IFS='' read -r comp; do + if [ -z "$comp" ]; then + continue + fi + + __podman_debug "Original comp: $comp" + comp="$(__podman_format_comp_descriptions "$comp" "$longest")" + __podman_debug "Final comp: $comp" + completions+=("$comp") + done < <(printf "%s\n" "${out[@]}") + + while IFS='' read -r comp; do + # Although this script should only be used for bash + # there may be programs that still convert the bash + # script into a zsh one. To continue supporting those + # programs, we do this single adaptation for zsh + if [ -n "${ZSH_VERSION}" ]; then + # zsh completion needs --flag= prefix + COMPREPLY+=("$flagPrefix$comp") + else + COMPREPLY+=("$comp") + fi + done < <(compgen -W "${completions[*]}" -- "$cur") + + # If there is a single completion left, remove the description text + if [ ${#COMPREPLY[*]} -eq 1 ]; then + __podman_debug "COMPREPLY[0]: ${COMPREPLY[0]}" + comp="${COMPREPLY[0]%% *}" + __podman_debug "Removed description from single completion, which is now: ${comp}" + COMPREPLY=() + COMPREPLY+=("$comp") + fi + fi - _complete_ "$options_with_args" "$boolean_options" - case "$cur" in - -*) - COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) - ;; - *) - __podman_complete_volume_names - ;; - esac + __podman_handle_special_char "$cur" : + __podman_handle_special_char "$cur" = } -_podman_volume_prune() { - local options_with_args="" - - local boolean_options=" - --force -f - --help -h - " - - _complete_ "$options_with_args" "$boolean_options" +__podman_handle_special_char() +{ + local comp="$1" + local char=$2 + if [[ "$comp" == *${char}* && "$COMP_WORDBREAKS" == *${char}* ]]; then + local word=${comp%"${comp##*${char}}"} + local idx=${#COMPREPLY[*]} + while [[ $((--idx)) -ge 0 ]]; do + COMPREPLY[$idx]=${COMPREPLY[$idx]#"$word"} + done + fi } -_podman_volume() { - local boolean_options=" - --help -h - " - subcommands=" - create - inspect - ls - prune - rm - " - local aliases=" - list - remove - " - __podman_subcommands "$subcommands $aliases" && return +__podman_format_comp_descriptions() +{ + local tab + tab=$(printf '\t') + local comp="$1" + local longest=$2 + + # Properly format the description string which follows a tab character if there is one + if [[ "$comp" == *$tab* ]]; then + desc=${comp#*$tab} + comp=${comp%%$tab*} + + # $COLUMNS stores the current shell width. + # Remove an extra 4 because we add 2 spaces and 2 parentheses. + maxdesclength=$(( COLUMNS - longest - 4 )) + + # Make sure we can fit a description of at least 8 characters + # if we are to align the descriptions. + if [[ $maxdesclength -gt 8 ]]; then + # Add the proper number of spaces to align the descriptions + for ((i = ${#comp} ; i < longest ; i++)); do + comp+=" " + done + else + # Don't pad the descriptions so we can fit more text after the completion + maxdesclength=$(( COLUMNS - ${#comp} - 4 )) + fi + + # If there is enough space for any description text, + # truncate the descriptions that are too long for the shell width + if [ $maxdesclength -gt 0 ]; then + if [ ${#desc} -gt $maxdesclength ]; then + desc=${desc:0:$(( maxdesclength - 1 ))} + desc+="…" + fi + comp+=" ($desc)" + fi + fi - case "$cur" in - -*) - COMPREPLY=( $( compgen -W "--help" -- "$cur" ) ) - ;; - *) - COMPREPLY=( $( compgen -W "$subcommands" -- "$cur" ) ) - ;; - esac + # Must use printf to escape all special characters + printf "%q" "${comp}" } -_podman_podman() { - local options_with_args=" - --cni-config-dir - --conmon - --connection -c - --events-backend - --hooks-dir - --identity - --log-level - --namespace - --network-cmd-path - --root - --runroot - --runtime - --storage-driver - --storage-opt - --tmpdir - --url - " - local boolean_options=" - --help -h - --remote -r - --syslog - --version -v - " - commands=" - attach - auto-update - build - commit - container - cp - create - diff - events - exec - export - generate - healthcheck - history - image - images - import - info - inspect - kill - load - login - logout - logs - manifest - mount - network - pause - play - pod - port - ps - pull - push - restart - rm - rmi - run - save - search - start - stats - stop - system - tag - top - umount - unmount - unpause - untag - varlink - version - volume - wait - " +__start_podman() +{ + local cur prev words cword - case "$prev" in - $main_options_with_args_glob ) - return - ;; - esac + COMPREPLY=() + _get_comp_words_by_ref -n "=:" cur prev words cword - case "$cur" in - -*) - COMPREPLY=( $( compgen -W "$boolean_options $options_with_args" -- "$cur" ) ) - ;; - *) - COMPREPLY=( $( compgen -W "${commands[*]} help" -- "$cur" ) ) - ;; - esac + __podman_perform_completion } -_cli_bash_autocomplete() { - local cur opts base - - COMPREPLY=() - cur="${COMP_WORDS[COMP_CWORD]}" - COMPREPLY=() - local cur prev words cword +if [[ $(type -t compopt) = "builtin" ]]; then + complete -o default -F __start_podman podman +else + complete -o default -o nospace -F __start_podman podman +fi - _get_comp_words_by_ref -n : cur prev words cword - - local command=${PROG} cpos=0 - local counter=1 - counter=1 - while [ $counter -lt $cword ]; do - case "!${words[$counter]}" in - *) - command=$(echo "${words[$counter]}" | sed 's/-/_/g') - cpos=$counter - (( cpos++ )) - break - ;; - esac - (( counter++ )) - done - - local completions_func=_podman_${command} - declare -F $completions_func >/dev/null && $completions_func - - eval "$previous_extglob_setting" - return 0 -} +# ex: ts=4 sw=4 et filetype=sh -complete -F _cli_bash_autocomplete podman +# This file is generated with "podman completion"; see: podman-completion(1) diff --git a/completions/bash/podman-remote b/completions/bash/podman-remote new file mode 100644 index 000000000000..43a5ce959b8e --- /dev/null +++ b/completions/bash/podman-remote @@ -0,0 +1,271 @@ +# bash completion for podman-remote -*- shell-script -*- + +__podman-remote_debug() +{ + if [[ -n ${BASH_COMP_DEBUG_FILE} ]]; then + echo "$*" >> "${BASH_COMP_DEBUG_FILE}" + fi +} + +__podman-remote_perform_completion() +{ + __podman-remote_debug + __podman-remote_debug "========= starting completion logic ==========" + __podman-remote_debug "cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}, cword is $cword" + + # The user could have moved the cursor backwards on the command-line. + # We need to trigger completion from the $cword location, so we need + # to truncate the command-line ($words) up to the $cword location. + words=("${words[@]:0:$cword+1}") + __podman-remote_debug "Truncated words[*]: ${words[*]}," + + local shellCompDirectiveError=1 + local shellCompDirectiveNoSpace=2 + local shellCompDirectiveNoFileComp=4 + local shellCompDirectiveFilterFileExt=8 + local shellCompDirectiveFilterDirs=16 + local shellCompDirectiveLegacyCustomComp=32 + local shellCompDirectiveLegacyCustomArgsComp=64 + + local out requestComp lastParam lastChar comp directive args flagPrefix + + # Prepare the command to request completions for the program. + # Calling ${words[0]} instead of directly podman-remote allows to handle aliases + args=("${words[@]:1}") + requestComp="${words[0]} __completeNoDesc ${args[*]}" + + lastParam=${words[$((${#words[@]}-1))]} + lastChar=${lastParam:$((${#lastParam}-1)):1} + __podman-remote_debug "lastParam ${lastParam}, lastChar ${lastChar}" + + if [ -z "${cur}" ] && [ "${lastChar}" != "=" ]; then + # If the last parameter is complete (there is a space following it) + # We add an extra empty parameter so we can indicate this to the go method. + __podman-remote_debug "Adding extra empty parameter" + requestComp="${requestComp} \"\"" + fi + + # When completing a flag with an = (e.g., podman-remote -n=) + # bash focuses on the part after the =, so we need to remove + # the flag part from $cur + if [[ "${cur}" == -*=* ]]; then + flagPrefix="${cur%%=*}=" + cur="${cur#*=}" + fi + + __podman-remote_debug "Calling ${requestComp}" + # Use eval to handle any environment variables and such + out=$(eval "${requestComp}" 2>/dev/null) + + # Extract the directive integer at the very end of the output following a colon (:) + directive=${out##*:} + # Remove the directive + out=${out%:*} + if [ "${directive}" = "${out}" ]; then + # There is not directive specified + directive=0 + fi + __podman-remote_debug "The completion directive is: ${directive}" + __podman-remote_debug "The completions are: ${out[*]}" + + if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then + # Error code. No completion. + __podman-remote_debug "Received error from custom completion go code" + return + else + if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then + if [[ $(type -t compopt) = "builtin" ]]; then + __podman-remote_debug "Activating no space" + compopt -o nospace + fi + fi + if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then + if [[ $(type -t compopt) = "builtin" ]]; then + __podman-remote_debug "Activating no file completion" + compopt +o default + fi + fi + fi + + if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then + # File extension filtering + local fullFilter filter filteringCmd + + # Do not use quotes around the $out variable or else newline + # characters will be kept. + for filter in ${out[*]}; do + fullFilter+="$filter|" + done + + filteringCmd="_filedir $fullFilter" + __podman-remote_debug "File filtering command: $filteringCmd" + $filteringCmd + elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then + # File completion for directories only + + # Use printf to strip any trailing newline + local subdir + subdir=$(printf "%s" "${out[0]}") + if [ -n "$subdir" ]; then + __podman-remote_debug "Listing directories in $subdir" + pushd "$subdir" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return + else + __podman-remote_debug "Listing directories in ." + _filedir -d + fi + elif [ $((directive & shellCompDirectiveLegacyCustomComp)) -ne 0 ]; then + local cmd + __podman-remote_debug "Legacy custom completion. Directive: $directive, cmds: ${out[*]}" + + # The following variables should get their value through the commands + # we have received as completions and are parsing below. + local last_command + local nouns + + # Execute every command received + while IFS='' read -r cmd; do + __podman-remote_debug "About to execute: $cmd" + eval "$cmd" + done < <(printf "%s\n" "${out[@]}") + + __podman-remote_debug "last_command: $last_command" + __podman-remote_debug "nouns[0]: ${nouns[0]}, nouns[1]: ${nouns[1]}" + + if [ $((directive & shellCompDirectiveLegacyCustomArgsComp)) -ne 0 ]; then + # We should call the global legacy custom completion function, if it is defined + if declare -F __podman-remote_custom_func >/dev/null; then + # Use command name qualified legacy custom func + __podman-remote_debug "About to call: __podman-remote_custom_func" + __podman-remote_custom_func + elif declare -F __custom_func >/dev/null; then + # Otherwise fall back to unqualified legacy custom func for compatibility + __podman-remote_debug "About to call: __custom_func" + __custom_func + fi + fi + else + local tab + tab=$(printf '\t') + local longest=0 + # Look for the longest completion so that we can format things nicely + while IFS='' read -r comp; do + comp=${comp%%$tab*} + if ((${#comp}>longest)); then + longest=${#comp} + fi + done < <(printf "%s\n" "${out[@]}") + + local completions=() + while IFS='' read -r comp; do + if [ -z "$comp" ]; then + continue + fi + + __podman-remote_debug "Original comp: $comp" + comp="$(__podman-remote_format_comp_descriptions "$comp" "$longest")" + __podman-remote_debug "Final comp: $comp" + completions+=("$comp") + done < <(printf "%s\n" "${out[@]}") + + while IFS='' read -r comp; do + # Although this script should only be used for bash + # there may be programs that still convert the bash + # script into a zsh one. To continue supporting those + # programs, we do this single adaptation for zsh + if [ -n "${ZSH_VERSION}" ]; then + # zsh completion needs --flag= prefix + COMPREPLY+=("$flagPrefix$comp") + else + COMPREPLY+=("$comp") + fi + done < <(compgen -W "${completions[*]}" -- "$cur") + + # If there is a single completion left, remove the description text + if [ ${#COMPREPLY[*]} -eq 1 ]; then + __podman-remote_debug "COMPREPLY[0]: ${COMPREPLY[0]}" + comp="${COMPREPLY[0]%% *}" + __podman-remote_debug "Removed description from single completion, which is now: ${comp}" + COMPREPLY=() + COMPREPLY+=("$comp") + fi + fi + + __podman-remote_handle_special_char "$cur" : + __podman-remote_handle_special_char "$cur" = +} + +__podman-remote_handle_special_char() +{ + local comp="$1" + local char=$2 + if [[ "$comp" == *${char}* && "$COMP_WORDBREAKS" == *${char}* ]]; then + local word=${comp%"${comp##*${char}}"} + local idx=${#COMPREPLY[*]} + while [[ $((--idx)) -ge 0 ]]; do + COMPREPLY[$idx]=${COMPREPLY[$idx]#"$word"} + done + fi +} + +__podman-remote_format_comp_descriptions() +{ + local tab + tab=$(printf '\t') + local comp="$1" + local longest=$2 + + # Properly format the description string which follows a tab character if there is one + if [[ "$comp" == *$tab* ]]; then + desc=${comp#*$tab} + comp=${comp%%$tab*} + + # $COLUMNS stores the current shell width. + # Remove an extra 4 because we add 2 spaces and 2 parentheses. + maxdesclength=$(( COLUMNS - longest - 4 )) + + # Make sure we can fit a description of at least 8 characters + # if we are to align the descriptions. + if [[ $maxdesclength -gt 8 ]]; then + # Add the proper number of spaces to align the descriptions + for ((i = ${#comp} ; i < longest ; i++)); do + comp+=" " + done + else + # Don't pad the descriptions so we can fit more text after the completion + maxdesclength=$(( COLUMNS - ${#comp} - 4 )) + fi + + # If there is enough space for any description text, + # truncate the descriptions that are too long for the shell width + if [ $maxdesclength -gt 0 ]; then + if [ ${#desc} -gt $maxdesclength ]; then + desc=${desc:0:$(( maxdesclength - 1 ))} + desc+="…" + fi + comp+=" ($desc)" + fi + fi + + # Must use printf to escape all special characters + printf "%q" "${comp}" +} + +__start_podman-remote() +{ + local cur prev words cword + + COMPREPLY=() + _get_comp_words_by_ref -n "=:" cur prev words cword + + __podman-remote_perform_completion +} + +if [[ $(type -t compopt) = "builtin" ]]; then + complete -o default -F __start_podman-remote podman-remote +else + complete -o default -o nospace -F __start_podman-remote podman-remote +fi + +# ex: ts=4 sw=4 et filetype=sh + +# This file is generated with "podman-remote completion"; see: podman-completion(1) diff --git a/completions/fish/podman-remote.fish b/completions/fish/podman-remote.fish new file mode 100644 index 000000000000..e0216844d0af --- /dev/null +++ b/completions/fish/podman-remote.fish @@ -0,0 +1,182 @@ +# fish completion for podman-remote -*- shell-script -*- + +function __podman_remote_debug + set file "$BASH_COMP_DEBUG_FILE" + if test -n "$file" + echo "$argv" >> $file + end +end + +function __podman_remote_perform_completion + __podman_remote_debug "Starting __podman_remote_perform_completion" + + set args (string split -- " " (commandline -c)) + set lastArg "$args[-1]" + + __podman_remote_debug "args: $args" + __podman_remote_debug "last arg: $lastArg" + + set emptyArg "" + if test -z "$lastArg" + __podman_remote_debug "Setting emptyArg" + set emptyArg \"\" + end + __podman_remote_debug "emptyArg: $emptyArg" + + if not type -q "$args[1]" + # This can happen when "complete --do-complete podman-remote" is called when running this script. + __podman_remote_debug "Cannot find $args[1]. No completions." + return + end + + set requestComp "$args[1] __complete $args[2..-1] $emptyArg" + __podman_remote_debug "Calling $requestComp" + + set results (eval $requestComp 2> /dev/null) + set comps $results[1..-2] + set directiveLine $results[-1] + + # For Fish, when completing a flag with an = (e.g., -n=) + # completions must be prefixed with the flag + set flagPrefix (string match -r -- '-.*=' "$lastArg") + + __podman_remote_debug "Comps: $comps" + __podman_remote_debug "DirectiveLine: $directiveLine" + __podman_remote_debug "flagPrefix: $flagPrefix" + + for comp in $comps + printf "%s%s\n" "$flagPrefix" "$comp" + end + + printf "%s\n" "$directiveLine" +end + +# This function does two things: +# - Obtain the completions and store them in the global __podman_remote_comp_results +# - Return false if file completion should be performed +function __podman_remote_prepare_completions + __podman_remote_debug "" + __podman_remote_debug "========= starting completion logic ==========" + + # Start fresh + set --erase __podman_remote_comp_results + + set results (__podman_remote_perform_completion) + __podman_remote_debug "Completion results: $results" + + if test -z "$results" + __podman_remote_debug "No completion, probably due to a failure" + # Might as well do file completion, in case it helps + return 1 + end + + set directive (string sub --start 2 $results[-1]) + set --global __podman_remote_comp_results $results[1..-2] + + __podman_remote_debug "Completions are: $__podman_remote_comp_results" + __podman_remote_debug "Directive is: $directive" + + set shellCompDirectiveError 1 + set shellCompDirectiveNoSpace 2 + set shellCompDirectiveNoFileComp 4 + set shellCompDirectiveFilterFileExt 8 + set shellCompDirectiveFilterDirs 16 + set shellCompDirectiveLegacyCustomComp 32 + set shellCompDirectiveLegacyCustomArgsComp 64 + + if test -z "$directive" + set directive 0 + end + + set compErr (math (math --scale 0 $directive / $shellCompDirectiveError) % 2) + if test $compErr -eq 1 + __podman_remote_debug "Received error directive: aborting." + # Might as well do file completion, in case it helps + return 1 + end + + set legacyCustom (math (math --scale 0 $directive / $shellCompDirectiveLegacyCustomComp) % 2) + set legacyCustomArgs (math (math --scale 0 $directive / $shellCompDirectiveLegacyCustomArgsComp) % 2) + if test $legacyCustom -eq 1; or test $legacyCustomArgs -eq 1 + __podman_remote_debug "Legacy bash custom completion not applicable to fish" + # Do full file completion instead + set --global __podman_remote_comp_do_file_comp 1 + return 1 + end + + set filefilter (math (math --scale 0 $directive / $shellCompDirectiveFilterFileExt) % 2) + set dirfilter (math (math --scale 0 $directive / $shellCompDirectiveFilterDirs) % 2) + if test $filefilter -eq 1; or test $dirfilter -eq 1 + __podman_remote_debug "File extension filtering or directory filtering not supported" + # Do full file completion instead + return 1 + end + + set nospace (math (math --scale 0 $directive / $shellCompDirectiveNoSpace) % 2) + set nofiles (math (math --scale 0 $directive / $shellCompDirectiveNoFileComp) % 2) + + __podman_remote_debug "nospace: $nospace, nofiles: $nofiles" + + # If we want to prevent a space, or if file completion is NOT disabled, + # we need to count the number of valid completions. + # To do so, we will filter on prefix as the completions we have received + # may not already be filtered so as to allow fish to match on different + # criteria than prefix. + if test $nospace -ne 0; or test $nofiles -eq 0 + set prefix (commandline -t) + __podman_remote_debug "prefix: $prefix" + + set completions + for comp in $__podman_remote_comp_results + if test (string match -e -r "^$prefix" "$comp") + set -a completions $comp + end + end + set --global __podman_remote_comp_results $completions + __podman_remote_debug "Filtered completions are: $__podman_remote_comp_results" + + # Important not to quote the variable for count to work + set numComps (count $__podman_remote_comp_results) + __podman_remote_debug "numComps: $numComps" + + if test $numComps -eq 1; and test $nospace -ne 0 + # To support the "nospace" directive we trick the shell + # by outputting an extra, longer completion. + # We must first split on \t to get rid of the descriptions because + # the extra character we add to the fake second completion must be + # before the description. We don't need descriptions anyway since + # there is only a single real completion which the shell will expand + # immediately. + __podman_remote_debug "Adding second completion to perform nospace directive" + set split (string split --max 1 \t $__podman_remote_comp_results[1]) + set --global __podman_remote_comp_results $split[1] $split[1]. + __podman_remote_debug "Completions are now: $__podman_remote_comp_results" + end + + if test $numComps -eq 0; and test $nofiles -eq 0 + # To be consistent with bash and zsh, we only trigger file + # completion when there are no other completions + __podman_remote_debug "Requesting file completion" + return 1 + end + end + + return 0 +end + +# Since Fish completions are only loaded once the user triggers them, we trigger them ourselves +# so we can properly delete any completions provided by another script. +# The space after the the program name is essential to trigger completion for the program +# and not completion of the program name itself. +complete --do-complete "podman-remote " > /dev/null 2>&1 +# Using '> /dev/null 2>&1' since '&>' is not supported in older versions of fish. + +# Remove any pre-existing completions for the program since we will be handling all of them. +complete -c podman-remote -e + +# The call to __podman_remote_prepare_completions will setup __podman_remote_comp_results +# which provides the program's completion choices. +complete -c podman-remote -n '__podman_remote_prepare_completions' -f -a '$__podman_remote_comp_results' + + +# This file is generated with "podman-remote completion"; see: podman-completion(1) diff --git a/completions/fish/podman.fish b/completions/fish/podman.fish new file mode 100644 index 000000000000..2a89e7118cee --- /dev/null +++ b/completions/fish/podman.fish @@ -0,0 +1,182 @@ +# fish completion for podman -*- shell-script -*- + +function __podman_debug + set file "$BASH_COMP_DEBUG_FILE" + if test -n "$file" + echo "$argv" >> $file + end +end + +function __podman_perform_completion + __podman_debug "Starting __podman_perform_completion" + + set args (string split -- " " (commandline -c)) + set lastArg "$args[-1]" + + __podman_debug "args: $args" + __podman_debug "last arg: $lastArg" + + set emptyArg "" + if test -z "$lastArg" + __podman_debug "Setting emptyArg" + set emptyArg \"\" + end + __podman_debug "emptyArg: $emptyArg" + + if not type -q "$args[1]" + # This can happen when "complete --do-complete podman" is called when running this script. + __podman_debug "Cannot find $args[1]. No completions." + return + end + + set requestComp "$args[1] __complete $args[2..-1] $emptyArg" + __podman_debug "Calling $requestComp" + + set results (eval $requestComp 2> /dev/null) + set comps $results[1..-2] + set directiveLine $results[-1] + + # For Fish, when completing a flag with an = (e.g., -n=) + # completions must be prefixed with the flag + set flagPrefix (string match -r -- '-.*=' "$lastArg") + + __podman_debug "Comps: $comps" + __podman_debug "DirectiveLine: $directiveLine" + __podman_debug "flagPrefix: $flagPrefix" + + for comp in $comps + printf "%s%s\n" "$flagPrefix" "$comp" + end + + printf "%s\n" "$directiveLine" +end + +# This function does two things: +# - Obtain the completions and store them in the global __podman_comp_results +# - Return false if file completion should be performed +function __podman_prepare_completions + __podman_debug "" + __podman_debug "========= starting completion logic ==========" + + # Start fresh + set --erase __podman_comp_results + + set results (__podman_perform_completion) + __podman_debug "Completion results: $results" + + if test -z "$results" + __podman_debug "No completion, probably due to a failure" + # Might as well do file completion, in case it helps + return 1 + end + + set directive (string sub --start 2 $results[-1]) + set --global __podman_comp_results $results[1..-2] + + __podman_debug "Completions are: $__podman_comp_results" + __podman_debug "Directive is: $directive" + + set shellCompDirectiveError 1 + set shellCompDirectiveNoSpace 2 + set shellCompDirectiveNoFileComp 4 + set shellCompDirectiveFilterFileExt 8 + set shellCompDirectiveFilterDirs 16 + set shellCompDirectiveLegacyCustomComp 32 + set shellCompDirectiveLegacyCustomArgsComp 64 + + if test -z "$directive" + set directive 0 + end + + set compErr (math (math --scale 0 $directive / $shellCompDirectiveError) % 2) + if test $compErr -eq 1 + __podman_debug "Received error directive: aborting." + # Might as well do file completion, in case it helps + return 1 + end + + set legacyCustom (math (math --scale 0 $directive / $shellCompDirectiveLegacyCustomComp) % 2) + set legacyCustomArgs (math (math --scale 0 $directive / $shellCompDirectiveLegacyCustomArgsComp) % 2) + if test $legacyCustom -eq 1; or test $legacyCustomArgs -eq 1 + __podman_debug "Legacy bash custom completion not applicable to fish" + # Do full file completion instead + set --global __podman_comp_do_file_comp 1 + return 1 + end + + set filefilter (math (math --scale 0 $directive / $shellCompDirectiveFilterFileExt) % 2) + set dirfilter (math (math --scale 0 $directive / $shellCompDirectiveFilterDirs) % 2) + if test $filefilter -eq 1; or test $dirfilter -eq 1 + __podman_debug "File extension filtering or directory filtering not supported" + # Do full file completion instead + return 1 + end + + set nospace (math (math --scale 0 $directive / $shellCompDirectiveNoSpace) % 2) + set nofiles (math (math --scale 0 $directive / $shellCompDirectiveNoFileComp) % 2) + + __podman_debug "nospace: $nospace, nofiles: $nofiles" + + # If we want to prevent a space, or if file completion is NOT disabled, + # we need to count the number of valid completions. + # To do so, we will filter on prefix as the completions we have received + # may not already be filtered so as to allow fish to match on different + # criteria than prefix. + if test $nospace -ne 0; or test $nofiles -eq 0 + set prefix (commandline -t) + __podman_debug "prefix: $prefix" + + set completions + for comp in $__podman_comp_results + if test (string match -e -r "^$prefix" "$comp") + set -a completions $comp + end + end + set --global __podman_comp_results $completions + __podman_debug "Filtered completions are: $__podman_comp_results" + + # Important not to quote the variable for count to work + set numComps (count $__podman_comp_results) + __podman_debug "numComps: $numComps" + + if test $numComps -eq 1; and test $nospace -ne 0 + # To support the "nospace" directive we trick the shell + # by outputting an extra, longer completion. + # We must first split on \t to get rid of the descriptions because + # the extra character we add to the fake second completion must be + # before the description. We don't need descriptions anyway since + # there is only a single real completion which the shell will expand + # immediately. + __podman_debug "Adding second completion to perform nospace directive" + set split (string split --max 1 \t $__podman_comp_results[1]) + set --global __podman_comp_results $split[1] $split[1]. + __podman_debug "Completions are now: $__podman_comp_results" + end + + if test $numComps -eq 0; and test $nofiles -eq 0 + # To be consistent with bash and zsh, we only trigger file + # completion when there are no other completions + __podman_debug "Requesting file completion" + return 1 + end + end + + return 0 +end + +# Since Fish completions are only loaded once the user triggers them, we trigger them ourselves +# so we can properly delete any completions provided by another script. +# The space after the the program name is essential to trigger completion for the program +# and not completion of the program name itself. +complete --do-complete "podman " > /dev/null 2>&1 +# Using '> /dev/null 2>&1' since '&>' is not supported in older versions of fish. + +# Remove any pre-existing completions for the program since we will be handling all of them. +complete -c podman -e + +# The call to __podman_prepare_completions will setup __podman_comp_results +# which provides the program's completion choices. +complete -c podman -n '__podman_prepare_completions' -f -a '$__podman_comp_results' + + +# This file is generated with "podman completion"; see: podman-completion(1) diff --git a/completions/zsh/_podman b/completions/zsh/_podman index b65c3dbb848d..b25e9cb08eca 100644 --- a/completions/zsh/_podman +++ b/completions/zsh/_podman @@ -1,379 +1,181 @@ -#compdef podman +#compdef _podman podman -# To get zsh to reread this file: unset -f _podman;rm -f ~/.zcompdump;compinit +# zsh completion for podman -*- shell-script -*- -# On rereads, reset cache. (Not that the caching works, but some day it might) -unset -m '_podman_*' - -############################################################################### -# BEGIN 'podman help' parsers -- for options, subcommands, and usage - -# Run 'podman XX --help', set _podman_commands to a formatted list of cmds -_read_podman_commands() { - local line - - # Cache: the intention here is to run each 'podman help' only once. - # Unfortunately it doesn't seem to actually be working: even though - # I can see the var_ref in my shell, it's not visible here. - local _var_ref=_podman_commands_"${*// /_}" - typeset -ga _podman_commands - _podman_commands=(${(P)_var_ref}) - (( $#_podman_commands )) && return - - _call_program podman podman "$@" --help |\ - sed -n -e '0,/^Available Commands/d' -e '/^[A-Z]/q;p' |\ - sed -e 's/^ \+\([^ ]\+\) \+/\1:/' |\ - egrep . | while read line; do - _podman_commands+=($line) - done - - eval "typeset -ga $_var_ref" - eval "$_var_ref=(\$_podman_commands)" -} - -# Run 'podman XX --help', set _podman_option_list to a formatted list -# of option options for XX -_read_podman_options() { - local line - - local _var_ref=_podman_options_"${*// /_}" - eval "typeset -ga ${_var_ref}" - typeset -ga _podman_option_list - _podman_option_list=(${(P)_var_ref}) - (( $#_podman_option_list )) && return - - # Extract the Options; strip leading whitespace; pack '-f, --foo' - # as '-f,--foo' (no space); then add '=' to '--foo string'. - # The result will be, e.g. '-f,--foo=string Description of Option' - _call_program podman podman "$@" --help |\ - sed -n -e '0,/^Options:/d' -e '/^$/q;p' |\ - grep '^ \+-' |\ - sed -e 's/^ *//' -e 's/^\(-.,\) --/\1--/' |\ - sed -e 's/^\(-[^ ]\+\) \([^ ]\+\) /\1=\2 /' |\ - while read options desc;do - # options like --foo=string: split into --foo & string - local -a tmpa - local optval= - tmpa=(${(s.=.)options}) - if [ -n "$tmpa[2]" ]; then - options=$tmpa[1] - optval=$tmpa[2] - fi - - # 'podman attach --detach-keys' includes ']' in help msg - desc=${desc//\]/\\]} - - for option in ${(s:,:)options}; do - if [ -n "$optval" ]; then - _podman_option_list+=("${option}[$desc]:$(_podman_find_helper ${options} ${optval} ${desc})") - else - _podman_option_list+=("${option}[$desc]") - fi - done - done - - eval "typeset -ga $_var_ref=(\$_podman_option_list)" -} - -# Run 'podman XXX --help', set _podman_usage to the line after "Usage:" -_read_podman_usage() { - local _var_ref=_podman_usage_"${*// /_}" - typeset -ga _podman_usage - _podman_usage=${(P)_var_ref} - (( $#_podman_usage )) && return - - _podman_usage=$(_call_program podman podman "$@" --help |\ - grep -A1 'Usage:'|\ - tail -1 |\ - sed -e 's/^ *//') - - eval "typeset -ga $_var_ref" - eval "$_var_ref=\$_podman_usage" -} - -# END 'podman help' parsers -############################################################################### -# BEGIN custom helpers for individual option arguments - -# Find a zsh helper for a given option or command-line option -_podman_find_helper() { - local options=$1 - local optval=$2 - local desc=$3 - local helper= - - # Yes, this is a lot of hardcoding. IMHO it's still better than - # hardcoding every possible podman option. - # FIXME: there are many more options that could use helpers. - if expr "$desc" : ".*[Dd]irectory" >/dev/null; then - optval="directory" - helper="_files -/" - elif expr "$desc" : ".*[Pp]ath" >/dev/null; then - optval="path" - helper=_files - # For messages like 'restart policy ("always"|"no"|"on-failure") - elif optlist=$(expr "$desc" : '.*(\(\"[^\\)]\+|[^\\)]\+\"\))' 2>/dev/null); then - optval=${${options##--}//-/ } # "--log-level" => "log level" - optlist=${optlist//\"/} # "a"|"b"|"c" => a|b|c - optlist=${optlist//\|/ } # a|b|c => a b c - # FIXME: how to present values _in order_, not sorted alphabetically? - helper="($optlist)" +__podman_debug() +{ + local file="$BASH_COMP_DEBUG_FILE" + if [[ -n ${file} ]]; then + echo "$*" >> "${file}" fi - echo "$optval:$helper" -} - -# END custom helpers for individual option arguments -############################################################################### -# BEGIN helpers for command-line args (containers, images) - -__podman_helper_generic() { - local expl line - local -a results - - local foo1=$1; shift - local name=$2; shift - - _call_program $foo1 podman "$@" |\ - while read line; do - results+=(${=line}) - done - - _wanted $foo1 expl $name compadd ${(u)results} -} - -_podman_helper_image() { - __podman_helper_generic podman-images 'images' \ - images --format '{{.ID}}\ {{.Repository}}:{{.Tag}}' -} - -# FIXME: at some point, distinguish between running & stopped containers -_podman_helper_container() { - __podman_helper_generic podman-containers 'containers' \ - ps -a --format '{{.Names}}\ {{.ID}}' -} - -_podman_helper_pod() { - __podman_helper_generic podman-pods 'pods' pod list --format '{{.Name}}' } -_podman_helper_volume() { - __podman_helper_generic podman-volumes 'volumes' volume ls --format '{{.Name}}' -} - -# Combinations. This one seen in diff & inspect -_podman_helper_container-or-image() { - _podman_helper_image - _podman_helper_container -} - -# Seen in generate-kube -_podman_helper_container-or-pod() { - _podman_helper_container - _podman_helper_pod -} - -# For top and pod-top -_podman_helper_format-descriptors() { - __podman_helper_generic top-format-descriptors 'format descriptors' \ - top --list-descriptors -} - -# for push, login/logout, and trust -# FIXME: some day, use this to define a helper for IMAGE-PATH (in 'pull') -_podman_helper_registry() { - local expl - local -a registries +_podman() +{ + local shellCompDirectiveError=1 + local shellCompDirectiveNoSpace=2 + local shellCompDirectiveNoFileComp=4 + local shellCompDirectiveFilterFileExt=8 + local shellCompDirectiveFilterDirs=16 + local shellCompDirectiveLegacyCustomComp=32 + local shellCompDirectiveLegacyCustomArgsComp=64 + + local lastParam lastChar flagPrefix requestComp out directive comp lastComp noSpace + local -a completions + + __podman_debug "\n========= starting completion logic ==========" + __podman_debug "CURRENT: ${CURRENT}, words[*]: ${words[*]}" + + # The user could have moved the cursor backwards on the command-line. + # We need to trigger completion from the $CURRENT location, so we need + # to truncate the command-line ($words) up to the $CURRENT location. + # (We cannot use $CURSOR as its value does not work when a command is an alias.) + words=("${=words[1,CURRENT]}") + __podman_debug "Truncated words[*]: ${words[*]}," + + lastParam=${words[-1]} + lastChar=${lastParam[-1]} + __podman_debug "lastParam: ${lastParam}, lastChar: ${lastChar}" + + # For zsh, when completing a flag with an = (e.g., podman -n=) + # completions must be prefixed with the flag + setopt local_options BASH_REMATCH + if [[ "${lastParam}" =~ '-.*=' ]]; then + # We are dealing with a flag with an = + flagPrefix="-P ${BASH_REMATCH}" + fi - # Suggestions for improvement more than welcome. - python3 -c 'from configparser import ConfigParser;cp=ConfigParser();cp.read("/etc/containers/registries.conf");registries=eval(cp.get("registries.search","registries"));[print(r) for r in registries]' 2>/dev/null | while read line; do - registries+=($line) - done + # Prepare the command to obtain completions + requestComp="${words[1]} __complete ${words[2,-1]}" + if [ "${lastChar}" = "" ]; then + # If the last parameter is complete (there is a space following it) + # We add an extra empty parameter so we can indicate this to the go completion code. + __podman_debug "Adding extra empty parameter" + requestComp="${requestComp} \"\"" + fi - if (( $#registries )); then - _wanted podman-registry expl "registry" compadd ${(u)registries} + __podman_debug "About to call: eval ${requestComp}" + + # Use eval to handle any environment variables and such + out=$(eval ${requestComp} 2>/dev/null) + __podman_debug "completion output: ${out}" + + # Extract the directive integer following a : from the last line + local lastLine + while IFS='\n' read -r line; do + lastLine=${line} + done < <(printf "%s\n" "${out[@]}") + __podman_debug "last line: ${lastLine}" + + if [ "${lastLine[1]}" = : ]; then + directive=${lastLine[2,-1]} + # Remove the directive including the : and the newline + local suffix + (( suffix=${#lastLine}+2)) + out=${out[1,-$suffix]} else - _hosts + # There is no directive specified. Leave $out as is. + __podman_debug "No directive found. Setting do default" + directive=0 fi -} - -# END helpers for command-line args -############################################################################### -# BEGIN figure out completion helpers for a given (sub)command -# Read Usage string for this subcommand, set up helpers for its subargs -_set_up_podman_args() { - _read_podman_usage "$@" + __podman_debug "directive: ${directive}" + __podman_debug "completions: ${out}" + __podman_debug "flagPrefix: ${flagPrefix}" - typeset -ga _podman_args=() - # E.g. 'podman exec [options] CONTAINER [...' -> 'CONTAINER [....' - local usage_rhs=$(expr "$_podman_usage" : ".*\[options\] \+\(.*\)") - - # e.g. podman pod ps which takes no further args - if [ -z "$usage_rhs" ]; then + if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then + __podman_debug "Completion received error. Ignoring completions." return fi - # podman diff & inspect accept 'CONTAINER | IMAGE'; make into one keyword. - usage_rhs=${usage_rhs// | /-OR-} + while IFS='\n' read -r comp; do + if [ -n "$comp" ]; then + # If requested, completions are returned with a description. + # The description is preceded by a TAB character. + # For zsh's _describe, we need to use a : instead of a TAB. + # We first need to escape any : as part of the completion itself. + comp=${comp//:/\\:} - # Arg parsing. There are three possibilities in Usage messages: - # - # [IMAGE] - optional image arg (zero or one) - # IMAGE - exactly one image arg - # IMAGE [IMAGE...] - one or more image args - # and, theoretically: - # [IMAGE...] - zero or more? Haven't seen it in practice. Defer. - # - # For completion purposes, we only need to provide two options: - # one, or more than one? That is: continue offering completion - # suggestions after the first one? For that, we make two passes; - # in the first, mark an option as either '' (only one) or + local tab=$(printf '\t') + comp=${comp//$tab/:} - # Parse each command-line arg seen in usage message - local word - local -A _seen=() - for word in ${=usage_rhs}; do - local unbracketed=$(expr "$word" : "\[\(.*\)\]") + __podman_debug "Adding completion: ${comp}" + completions+=${comp} + lastComp=$comp + fi + done < <(printf "%s\n" "${out[@]}") - if [ -n "$unbracketed" ]; then - # Remove all dots; assume(!?) that they'll all be at the end - unbracketed=${unbracketed//./} + if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then + __podman_debug "Activating nospace." + noSpace="-S ''" + fi - if (( $_seen[$unbracketed] )); then - # Is this the same word as the previous arg? - if expr "$_podman_args[-1]" : ":$unbracketed:" >/dev/null; then - # Yes. Make it '*:...' instead of ':...', indicating >1 - _podman_args[-1]="*$_podman_args[-1]" - fi - continue + if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then + # File extension filtering + local filteringCmd + filteringCmd='_files' + for filter in ${completions[@]}; do + if [ ${filter[1]} != '*' ]; then + # zsh requires a glob pattern to do file filtering + filter="\*.$filter" fi - - word=$unbracketed + filteringCmd+=" -g $filter" + done + filteringCmd+=" ${flagPrefix}" + + __podman_debug "File filtering command: $filteringCmd" + _arguments '*:filename:'"$filteringCmd" + elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then + # File completion for directories only + local subDir + subdir="${completions[1]}" + if [ -n "$subdir" ]; then + __podman_debug "Listing directories in $subdir" + pushd "${subdir}" >/dev/null 2>&1 + else + __podman_debug "Listing directories in ." fi - # As of 2019-03 all such instances are '[COMMAND [ARG...]]' and are, - # of course, at the end of the line. We can't offer completion for - # these, because the container will have different commands than - # the host system... but try anyway. - if [ "$word" = '[COMMAND' ]; then - # e.g. podman create, exec, run - _podman_args+=( - ":command: _command_names -e" - "*::arguments: _normal" - ) - return + local result + _arguments '*:dirname:_files -/'" ${flagPrefix}" + result=$? + if [ -n "$subdir" ]; then + popd >/dev/null 2>&1 fi + return $result + else + __podman_debug "Calling _describe" + if eval _describe "completions" completions $flagPrefix $noSpace; then + __podman_debug "_describe found some completions" - # Look for an existing helper, e.g. IMAGE -> _podman_helper_image - local helper="_podman_helper_${(L)word}" - if (( $+functions[$helper] )); then - : + # Return the success of having called _describe + return 0 else - # No defined helper. Reset, but check for known expressions. - helper= - case "$word" in - KUBEFILE) helper='_files -g "*.y(|a)ml(-.)"' ;; - PATH) helper='_files' ;; - esac - fi - - # Another special case: 'top' actually takes multiple options - local multi= - if [ "$word" = "FORMAT-DESCRIPTORS" ]; then - multi='*' + __podman_debug "_describe did not find completions." + __podman_debug "Checking if we should do file completion." + if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then + __podman_debug "deactivating file completion" + + # We must return an error code here to let zsh know that there were no + # completions found by _describe; this is what will trigger other + # matching algorithms to attempt to find completions. + # For example zsh can match letters in the middle of words. + return 1 + else + # Perform file completion + __podman_debug "Activating file completion" + + # We must return the result of this command, so it must be the + # last command, or else we must store its result to return it. + _arguments '*:filename:_files'" ${flagPrefix}" + fi fi - _podman_args+=("$multi:${(L)word}:$helper") - _seen[$word]=1 - done -} - -# For an endpoint command, i.e. not a subcommand. -_podman_terminus() { - typeset -A opt_args - typeset -ga _podman_option_list - typeset -ga _podman_args - integer ret=1 - - # Find out what args it takes (e.g. image(s), container(s)) and see - # if we have helpers for them. - _set_up_podman_args "$@" - _arguments -C $_podman_option_list $_podman_args && ret=0 - - return ret -} - -# END figure out completion helpers for a given (sub)command -################################################################################ -# BEGIN actual entry point - -# This is the main entry point; it's also where we (recursively) come in -# to handle nested subcommands such as 'podman container' or even 3-level -# ones like 'podman generate kube'. Nesting is complicated, so here's -# my best understanding as of 2019-03-12: -# -# Easy first: when you do "podman " zsh calls us, we run 'podman --help', -# figure out the global options and subcommands, and run the magic _arguments -# command. That will offer those options/subcommands, and complete, etc. -# -# Where it gets harder is when you do "podman container mount ". -# zsh first calls us with words=(podman container mount) but we don't -# want all that full context yet! We want to go a piece at a time, -# handling 'container' first, then 'mount'; ending up with our -# final 'podman container mount --help' giving us suitable options -# and no subcommands; from which we determine that it's a terminus -# and jump to a function that handles non-subcommand arguments. -# -# This is the closest I've yet come to understanding zsh completion; -# it is still incomplete and may in fact be incorrect. But it works -# better than anything I've played with so far. -_podman_subcommand() { - local curcontext="$curcontext" state line - typeset -A opt_args - integer ret=1 - - # Run 'podman --help' / 'podman system --help' for our context (initially - # empty, then possibly under subcommands); from those, get a list of - # options appropriate for this context and, if applicable, subcommands. - _read_podman_options "$@" - _read_podman_commands "$@" - - # Now, is this a sub-subcommand, or does it have args? - if (( $#_podman_commands )); then - # Subcommands required (podman, podman system, etc) - local cmd=${words// /_} - _arguments -C $_podman_option_list \ - "(-): :->command" \ - "(-)*:: :->option-or-argument" \ - && ret=0 - - case $state in - (command) - _describe -t command "podman $* command" _podman_commands && ret=0 - ;; - (option-or-argument) - # I think this is when we have a _completed_ subcommand. - # Recurse back into here, offering options for that subcommand. - curcontext=${curcontext%:*:*}:podman-${words[1]}: - _podman_subcommand "$@" ${words[1]} && ret=0 - ;; - esac - else - # At a terminus, i.e. podman info, podman history; find out - # what args it takes. - _podman_terminus "$@" && ret=0 fi - - return ret } -_podman() { - _podman_subcommand -} +# don't run the completion function when being source-ed or eval-ed +if [ "$funcstack[1]" = "_podman" ]; then + _podman +fi -# Local Variables: -# mode: shell-script -# sh-indentation: 4 -# indent-tabs-mode: nil -# sh-basic-offset: 4 -# End: -# vim: ft=zsh sw=4 ts=4 et +# This file is generated with "podman completion"; see: podman-completion(1) diff --git a/completions/zsh/_podman-remote b/completions/zsh/_podman-remote new file mode 100644 index 000000000000..fc2984cfd439 --- /dev/null +++ b/completions/zsh/_podman-remote @@ -0,0 +1,181 @@ +#compdef _podman-remote podman-remote + +# zsh completion for podman-remote -*- shell-script -*- + +__podman-remote_debug() +{ + local file="$BASH_COMP_DEBUG_FILE" + if [[ -n ${file} ]]; then + echo "$*" >> "${file}" + fi +} + +_podman-remote() +{ + local shellCompDirectiveError=1 + local shellCompDirectiveNoSpace=2 + local shellCompDirectiveNoFileComp=4 + local shellCompDirectiveFilterFileExt=8 + local shellCompDirectiveFilterDirs=16 + local shellCompDirectiveLegacyCustomComp=32 + local shellCompDirectiveLegacyCustomArgsComp=64 + + local lastParam lastChar flagPrefix requestComp out directive comp lastComp noSpace + local -a completions + + __podman-remote_debug "\n========= starting completion logic ==========" + __podman-remote_debug "CURRENT: ${CURRENT}, words[*]: ${words[*]}" + + # The user could have moved the cursor backwards on the command-line. + # We need to trigger completion from the $CURRENT location, so we need + # to truncate the command-line ($words) up to the $CURRENT location. + # (We cannot use $CURSOR as its value does not work when a command is an alias.) + words=("${=words[1,CURRENT]}") + __podman-remote_debug "Truncated words[*]: ${words[*]}," + + lastParam=${words[-1]} + lastChar=${lastParam[-1]} + __podman-remote_debug "lastParam: ${lastParam}, lastChar: ${lastChar}" + + # For zsh, when completing a flag with an = (e.g., podman-remote -n=) + # completions must be prefixed with the flag + setopt local_options BASH_REMATCH + if [[ "${lastParam}" =~ '-.*=' ]]; then + # We are dealing with a flag with an = + flagPrefix="-P ${BASH_REMATCH}" + fi + + # Prepare the command to obtain completions + requestComp="${words[1]} __complete ${words[2,-1]}" + if [ "${lastChar}" = "" ]; then + # If the last parameter is complete (there is a space following it) + # We add an extra empty parameter so we can indicate this to the go completion code. + __podman-remote_debug "Adding extra empty parameter" + requestComp="${requestComp} \"\"" + fi + + __podman-remote_debug "About to call: eval ${requestComp}" + + # Use eval to handle any environment variables and such + out=$(eval ${requestComp} 2>/dev/null) + __podman-remote_debug "completion output: ${out}" + + # Extract the directive integer following a : from the last line + local lastLine + while IFS='\n' read -r line; do + lastLine=${line} + done < <(printf "%s\n" "${out[@]}") + __podman-remote_debug "last line: ${lastLine}" + + if [ "${lastLine[1]}" = : ]; then + directive=${lastLine[2,-1]} + # Remove the directive including the : and the newline + local suffix + (( suffix=${#lastLine}+2)) + out=${out[1,-$suffix]} + else + # There is no directive specified. Leave $out as is. + __podman-remote_debug "No directive found. Setting do default" + directive=0 + fi + + __podman-remote_debug "directive: ${directive}" + __podman-remote_debug "completions: ${out}" + __podman-remote_debug "flagPrefix: ${flagPrefix}" + + if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then + __podman-remote_debug "Completion received error. Ignoring completions." + return + fi + + while IFS='\n' read -r comp; do + if [ -n "$comp" ]; then + # If requested, completions are returned with a description. + # The description is preceded by a TAB character. + # For zsh's _describe, we need to use a : instead of a TAB. + # We first need to escape any : as part of the completion itself. + comp=${comp//:/\\:} + + local tab=$(printf '\t') + comp=${comp//$tab/:} + + __podman-remote_debug "Adding completion: ${comp}" + completions+=${comp} + lastComp=$comp + fi + done < <(printf "%s\n" "${out[@]}") + + if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then + __podman-remote_debug "Activating nospace." + noSpace="-S ''" + fi + + if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then + # File extension filtering + local filteringCmd + filteringCmd='_files' + for filter in ${completions[@]}; do + if [ ${filter[1]} != '*' ]; then + # zsh requires a glob pattern to do file filtering + filter="\*.$filter" + fi + filteringCmd+=" -g $filter" + done + filteringCmd+=" ${flagPrefix}" + + __podman-remote_debug "File filtering command: $filteringCmd" + _arguments '*:filename:'"$filteringCmd" + elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then + # File completion for directories only + local subDir + subdir="${completions[1]}" + if [ -n "$subdir" ]; then + __podman-remote_debug "Listing directories in $subdir" + pushd "${subdir}" >/dev/null 2>&1 + else + __podman-remote_debug "Listing directories in ." + fi + + local result + _arguments '*:dirname:_files -/'" ${flagPrefix}" + result=$? + if [ -n "$subdir" ]; then + popd >/dev/null 2>&1 + fi + return $result + else + __podman-remote_debug "Calling _describe" + if eval _describe "completions" completions $flagPrefix $noSpace; then + __podman-remote_debug "_describe found some completions" + + # Return the success of having called _describe + return 0 + else + __podman-remote_debug "_describe did not find completions." + __podman-remote_debug "Checking if we should do file completion." + if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then + __podman-remote_debug "deactivating file completion" + + # We must return an error code here to let zsh know that there were no + # completions found by _describe; this is what will trigger other + # matching algorithms to attempt to find completions. + # For example zsh can match letters in the middle of words. + return 1 + else + # Perform file completion + __podman-remote_debug "Activating file completion" + + # We must return the result of this command, so it must be the + # last command, or else we must store its result to return it. + _arguments '*:filename:_files'" ${flagPrefix}" + fi + fi + fi +} + +# don't run the completion function when being source-ed or eval-ed +if [ "$funcstack[1]" = "_podman-remote" ]; then + _podman-remote +fi + +# This file is generated with "podman-remote completion"; see: podman-completion(1) diff --git a/contrib/spec/podman.spec.in b/contrib/spec/podman.spec.in index 2a3041ccc971..ee8ce4d45da3 100644 --- a/contrib/spec/podman.spec.in +++ b/contrib/spec/podman.spec.in @@ -499,6 +499,7 @@ export GOPATH=%{buildroot}/%{gopath}:$(pwd)/vendor:%{gopath} %{_bindir}/%{name} %{_datadir}/bash-completion/completions/* %{_datadir}/zsh/site-functions/* +%{_datadir}/fish/vendor_completions.d/* %{_libexecdir}/%{name}/conmon %config(noreplace) %{_sysconfdir}/cni/net.d/87-%{name}-bridge.conflist %{_unitdir}/podman-auto-update.service diff --git a/docs/source/markdown/podman-completion.1.md b/docs/source/markdown/podman-completion.1.md new file mode 100644 index 000000000000..50b0b6145365 --- /dev/null +++ b/docs/source/markdown/podman-completion.1.md @@ -0,0 +1,56 @@ +% podman-completion(1) + +## NAME +podman\-completion - Generate shell completion scripts + +## SYNOPSIS +**podman completion** [*options*] *bash*|*zsh*|*fish* + +## DESCRIPTION +The completion command allows you to generate shell completion scripts. Supported shells are **bash**, **zsh** and **fish**. + +These script are used by the shell to provide suggestions and complete commands when you are typing the command and press [TAB]. + +Usually these scripts are automatically installed via the package manager. + +## OPTIONS +#### **--file**, **-f** + +Write the generated output to file. + +#### **--no-desc** + +Do not provide description in the completions. + +## Installation + +### BASH +Make sure you have `bash-completion` installed on your system. + +To load the completion script into your current session run: +`source <(podman completion bash)` + +To make it available in all your bash sessions run: +`podman completion bash -f /etc/bash_completion.d/podman` + + +### ZSH +If shell completion is not already enabled in your environment you will need to enable it. You can execute the following once: +`echo "autoload -U compinit; compinit" >> ~/.zshrc` + +To make it available in all your zsh sessions run: +`podman completion zsh -f "${fpath[1]}/_podman"` + +Once you reload the shell the autocompletion should be working. + + +### FISH +To load the completion script into your current session run: +`podman completion fish | source` + +To make it available in all your fish sessions run: +`podman completion fish -f ~/.config/fish/completions/podman.fish` + + +## SEE ALSO +[podman(1)](podman.1.md) diff --git a/docs/source/markdown/podman.1.md b/docs/source/markdown/podman.1.md index 993f285edd7a..87867bf35f5f 100644 --- a/docs/source/markdown/podman.1.md +++ b/docs/source/markdown/podman.1.md @@ -205,6 +205,7 @@ the exit codes follow the `chroot` standard, see below: | [podman-auto-update(1)](podman-auto-update.1.md) | Auto update containers according to their auto-update policy | | [podman-build(1)](podman-build.1.md) | Build a container image using a Containerfile. | | [podman-commit(1)](podman-commit.1.md) | Create new image based on the changed container. | +| [podman-completion(1)](podman-completion.1.md) | Generate shell completion scripts | | [podman-container(1)](podman-container.1.md) | Manage containers. | | [podman-cp(1)](podman-cp.1.md) | Copy files/folders between a container and the local filesystem. | | [podman-create(1)](podman-create.1.md) | Create a new container. | diff --git a/go.mod b/go.mod index 28e577a393bc..e0f4decf178b 100644 --- a/go.mod +++ b/go.mod @@ -60,6 +60,7 @@ require ( github.com/varlink/go v0.0.0-20190502142041-0f1d566d194b github.com/vishvananda/netlink v1.1.0 go.etcd.io/bbolt v1.3.5 + go.uber.org/atomic v1.7.0 // indirect golang.org/x/crypto v0.0.0-20200709230013-948cd5f35899 golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d // indirect golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208 @@ -74,3 +75,5 @@ require ( ) replace github.com/cri-o/ocicni => github.com/cri-o/ocicni v0.2.1-0.20201109200316-afdc16ba66df + +replace github.com/spf13/cobra => github.com/Luap99/cobra v1.0.1-0.20201110155035-83a59186c706 diff --git a/go.sum b/go.sum index ab8ed4246a10..fdb50960e3ad 100644 --- a/go.sum +++ b/go.sum @@ -20,6 +20,8 @@ github.com/Azure/go-autorest v11.1.2+incompatible/go.mod h1:r+4oMnoxhatjLLJ6zxSW github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/Luap99/cobra v1.0.1-0.20201110155035-83a59186c706 h1:KcMtguD/NlxB4c08lzc91o5by51Sf+Ec5+1Yv9Wqvbk= +github.com/Luap99/cobra v1.0.1-0.20201110155035-83a59186c706/go.mod h1:WnodtKOvamDL/PwE2M4iKs8aMDBZ5Q5klgD3qfVJQMI= github.com/Microsoft/go-winio v0.4.11/go.mod h1:VhR8bwka0BXejwEJY73c50VrPtXAaKcyvVC4A4RozmA= github.com/Microsoft/go-winio v0.4.15-0.20190919025122-fc70bd9a86b5/go.mod h1:tTuCMEN+UleMWgg9dVx4Hu52b1bJo+59jBh3ajtinzw= github.com/Microsoft/go-winio v0.4.15-0.20200113171025-3fe6c5262873 h1:93nQ7k53GjoMQ07HVP8g6Zj1fQZDDj7Xy2VkNNtvX8o= @@ -485,9 +487,6 @@ github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4k github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= -github.com/spf13/cobra v0.0.2-0.20171109065643-2da4a54c5cee/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= -github.com/spf13/cobra v1.1.1 h1:KfztREH0tPxJJ+geloSLaAkaPkr4ki2Er5quFV1TDo4= -github.com/spf13/cobra v1.1.1/go.mod h1:WnodtKOvamDL/PwE2M4iKs8aMDBZ5Q5klgD3qfVJQMI= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/pflag v0.0.0-20170130214245-9ff6c6923cff/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.1-0.20171106142849-4c012f6dcd95/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= @@ -552,8 +551,9 @@ go.mozilla.org/pkcs7 v0.0.0-20200128120323-432b2356ecb1/go.mod h1:SNgMg+EgDFwmvS go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.22.0 h1:C9hSCOW830chIVkdja34wa6Ky+IzWllkUinR+BtRZd4= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= -go.uber.org/atomic v1.4.0 h1:cxzIVoETapQEqDhQu3QfnvXAV4AlzcvUCxkVUFw3+EU= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= +go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw= +go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= golang.org/x/crypto v0.0.0-20171113213409-9f005a07e0d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= diff --git a/hack/podman-commands.sh b/hack/podman-commands.sh index fd4ff25017ab..0455287d4c80 100755 --- a/hack/podman-commands.sh +++ b/hack/podman-commands.sh @@ -25,6 +25,12 @@ function podman_commands() { $PODMAN help "$@" |\ awk '/^Available Commands:/{ok=1;next}/^Options:/{ok=0}ok { print $1 }' |\ grep . + + # Special case: podman-completion is a hidden command + # it does not show in podman help so add it here + if [[ -z "$@" ]]; then + echo "completion" + fi } # Read a list of subcommands from a command's metadoc diff --git a/hack/xref-helpmsgs-manpages b/hack/xref-helpmsgs-manpages index c5447c5d6df0..55c8b65824a1 100755 --- a/hack/xref-helpmsgs-manpages +++ b/hack/xref-helpmsgs-manpages @@ -181,6 +181,9 @@ sub xref_by_man { next if $k eq 'varlink'; next if "@subcommand" eq 'system' && $k eq 'service'; + # Special case: podman completion is a hidden command + next if $k eq 'completion'; + warn "$ME: podman @subcommand: $k in $man, but not --help\n"; ++$Errs; } diff --git a/pkg/systemd/generate/common.go b/pkg/systemd/generate/common.go index 1fc4479ff678..52a214883614 100644 --- a/pkg/systemd/generate/common.go +++ b/pkg/systemd/generate/common.go @@ -11,13 +11,13 @@ import ( // is set to the unit's (unique) name. const EnvVariable = "PODMAN_SYSTEMD_UNIT" -// restartPolicies includes all valid restart policies to be used in a unit +// RestartPolicies includes all valid restart policies to be used in a unit // file. -var restartPolicies = []string{"no", "on-success", "on-failure", "on-abnormal", "on-watchdog", "on-abort", "always"} +var RestartPolicies = []string{"no", "on-success", "on-failure", "on-abnormal", "on-watchdog", "on-abort", "always"} // validateRestartPolicy checks that the user-provided policy is valid. func validateRestartPolicy(restart string) error { - for _, i := range restartPolicies { + for _, i := range RestartPolicies { if i == restart { return nil } diff --git a/vendor/github.com/spf13/cobra/bash_completions.go b/vendor/github.com/spf13/cobra/bash_completions.go index 846636d75b13..2ceebc552218 100644 --- a/vendor/github.com/spf13/cobra/bash_completions.go +++ b/vendor/github.com/spf13/cobra/bash_completions.go @@ -5,70 +5,95 @@ import ( "fmt" "io" "os" - "sort" - "strings" - - "github.com/spf13/pflag" ) // Annotations for Bash completion. const ( - BashCompFilenameExt = "cobra_annotation_bash_completion_filename_extensions" + BashCompFilenameExt = "cobra_annotation_bash_completion_filename_extensions" + // BashCompCustom should be avoided as it only works for bash. + // Function RegisterFlagCompletionFunc() should be used instead. BashCompCustom = "cobra_annotation_bash_completion_custom" BashCompOneRequiredFlag = "cobra_annotation_bash_completion_one_required_flag" BashCompSubdirsInDir = "cobra_annotation_bash_completion_subdirs_in_dir" ) -func writePreamble(buf *bytes.Buffer, name string) { - buf.WriteString(fmt.Sprintf("# bash completion for %-36s -*- shell-script -*-\n", name)) - buf.WriteString(fmt.Sprintf(` -__%[1]s_debug() -{ - if [[ -n ${BASH_COMP_DEBUG_FILE} ]]; then - echo "$*" >> "${BASH_COMP_DEBUG_FILE}" - fi +// GenBashCompletion generates bash completion file and writes to the passed writer. +func (c *Command) GenBashCompletion(w io.Writer) error { + return c.genBashCompletion(w, false) } -# Homebrew on Macs have version 1.3 of bash-completion which doesn't include -# _init_completion. This is a very minimal version of that function. -__%[1]s_init_completion() -{ - COMPREPLY=() - _get_comp_words_by_ref "$@" cur prev words cword +// GenBashCompletionWithDesc generates bash completion file with descriptions and writes to the passed writer. +func (c *Command) GenBashCompletionWithDesc(w io.Writer) error { + return c.genBashCompletion(w, true) } -__%[1]s_index_of_word() -{ - local w word=$1 - shift - index=0 - for w in "$@"; do - [[ $w = "$word" ]] && return - index=$((index+1)) - done - index=-1 +// GenBashCompletionFile generates bash completion file. +func (c *Command) GenBashCompletionFile(filename string) error { + return c.genBashCompletionFile(filename, false) +} + +// GenBashCompletionFileWithDesc generates bash completion file with descriptions. +func (c *Command) GenBashCompletionFileWithDesc(filename string) error { + return c.genBashCompletionFile(filename, true) +} + +func (c *Command) genBashCompletionFile(filename string, includeDesc bool) error { + outFile, err := os.Create(filename) + if err != nil { + return err + } + defer outFile.Close() + + return c.genBashCompletion(outFile, includeDesc) } -__%[1]s_contains_word() +func (c *Command) genBashCompletion(w io.Writer, includeDesc bool) error { + buf := new(bytes.Buffer) + if len(c.BashCompletionFunction) > 0 { + buf.WriteString(c.BashCompletionFunction + "\n") + } + genBashComp(buf, c.Name(), includeDesc) + + _, err := buf.WriteTo(w) + return err +} + +func genBashComp(buf *bytes.Buffer, name string, includeDesc bool) { + compCmd := ShellCompRequestCmd + if !includeDesc { + compCmd = ShellCompNoDescRequestCmd + } + + buf.WriteString(fmt.Sprintf(`# bash completion for %-36[1]s -*- shell-script -*- + +__%[1]s_debug() { - local w word=$1; shift - for w in "$@"; do - [[ $w = "$word" ]] && return - done - return 1 + if [[ -n ${BASH_COMP_DEBUG_FILE} ]]; then + echo "$*" >> "${BASH_COMP_DEBUG_FILE}" + fi } -__%[1]s_handle_go_custom_completion() +__%[1]s_perform_completion() { - __%[1]s_debug "${FUNCNAME[0]}: cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}" + __%[1]s_debug + __%[1]s_debug "========= starting completion logic ==========" + __%[1]s_debug "cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}, cword is $cword" + + # The user could have moved the cursor backwards on the command-line. + # We need to trigger completion from the $cword location, so we need + # to truncate the command-line ($words) up to the $cword location. + words=("${words[@]:0:$cword+1}") + __%[1]s_debug "Truncated words[*]: ${words[*]}," local shellCompDirectiveError=%[3]d local shellCompDirectiveNoSpace=%[4]d local shellCompDirectiveNoFileComp=%[5]d local shellCompDirectiveFilterFileExt=%[6]d local shellCompDirectiveFilterDirs=%[7]d + local shellCompDirectiveLegacyCustomComp=%[8]d + local shellCompDirectiveLegacyCustomArgsComp=%[9]d - local out requestComp lastParam lastChar comp directive args + local out requestComp lastParam lastChar comp directive args flagPrefix # Prepare the command to request completions for the program. # Calling ${words[0]} instead of directly %[1]s allows to handle aliases @@ -77,16 +102,24 @@ __%[1]s_handle_go_custom_completion() lastParam=${words[$((${#words[@]}-1))]} lastChar=${lastParam:$((${#lastParam}-1)):1} - __%[1]s_debug "${FUNCNAME[0]}: lastParam ${lastParam}, lastChar ${lastChar}" + __%[1]s_debug "lastParam ${lastParam}, lastChar ${lastChar}" if [ -z "${cur}" ] && [ "${lastChar}" != "=" ]; then # If the last parameter is complete (there is a space following it) # We add an extra empty parameter so we can indicate this to the go method. - __%[1]s_debug "${FUNCNAME[0]}: Adding extra empty parameter" + __%[1]s_debug "Adding extra empty parameter" requestComp="${requestComp} \"\"" fi - __%[1]s_debug "${FUNCNAME[0]}: calling ${requestComp}" + # When completing a flag with an = (e.g., %[1]s -n=) + # bash focuses on the part after the =, so we need to remove + # the flag part from $cur + if [[ "${cur}" == -*=* ]]; then + flagPrefix="${cur%%%%=*}=" + cur="${cur#*=}" + fi + + __%[1]s_debug "Calling ${requestComp}" # Use eval to handle any environment variables and such out=$(eval "${requestComp}" 2>/dev/null) @@ -98,23 +131,23 @@ __%[1]s_handle_go_custom_completion() # There is not directive specified directive=0 fi - __%[1]s_debug "${FUNCNAME[0]}: the completion directive is: ${directive}" - __%[1]s_debug "${FUNCNAME[0]}: the completions are: ${out[*]}" + __%[1]s_debug "The completion directive is: ${directive}" + __%[1]s_debug "The completions are: ${out[*]}" if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then # Error code. No completion. - __%[1]s_debug "${FUNCNAME[0]}: received error from custom completion go code" + __%[1]s_debug "Received error from custom completion go code" return else if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then if [[ $(type -t compopt) = "builtin" ]]; then - __%[1]s_debug "${FUNCNAME[0]}: activating no space" + __%[1]s_debug "Activating no space" compopt -o nospace fi fi if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then if [[ $(type -t compopt) = "builtin" ]]; then - __%[1]s_debug "${FUNCNAME[0]}: activating no file completion" + __%[1]s_debug "Activating no file completion" compopt +o default fi fi @@ -123,6 +156,7 @@ __%[1]s_handle_go_custom_completion() if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then # File extension filtering local fullFilter filter filteringCmd + # Do not use quotes around the $out variable or else newline # characters will be kept. for filter in ${out[*]}; do @@ -134,545 +168,173 @@ __%[1]s_handle_go_custom_completion() $filteringCmd elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then # File completion for directories only - local subDir + # Use printf to strip any trailing newline + local subdir subdir=$(printf "%%s" "${out[0]}") if [ -n "$subdir" ]; then __%[1]s_debug "Listing directories in $subdir" - __%[1]s_handle_subdirs_in_dir_flag "$subdir" + pushd "$subdir" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return else __%[1]s_debug "Listing directories in ." _filedir -d fi + elif [ $((directive & shellCompDirectiveLegacyCustomComp)) -ne 0 ]; then + local cmd + __%[1]s_debug "Legacy custom completion. Directive: $directive, cmds: ${out[*]}" + + # The following variables should get their value through the commands + # we have received as completions and are parsing below. + local last_command + local nouns + + # Execute every command received + while IFS='' read -r cmd; do + __%[1]s_debug "About to execute: $cmd" + eval "$cmd" + done < <(printf "%%s\n" "${out[@]}") + + __%[1]s_debug "last_command: $last_command" + __%[1]s_debug "nouns[0]: ${nouns[0]}, nouns[1]: ${nouns[1]}" + + if [ $((directive & shellCompDirectiveLegacyCustomArgsComp)) -ne 0 ]; then + # We should call the global legacy custom completion function, if it is defined + if declare -F __%[1]s_custom_func >/dev/null; then + # Use command name qualified legacy custom func + __%[1]s_debug "About to call: __%[1]s_custom_func" + __%[1]s_custom_func + elif declare -F __custom_func >/dev/null; then + # Otherwise fall back to unqualified legacy custom func for compatibility + __%[1]s_debug "About to call: __custom_func" + __custom_func + fi + fi else + local tab + tab=$(printf '\t') + local longest=0 + # Look for the longest completion so that we can format things nicely while IFS='' read -r comp; do - COMPREPLY+=("$comp") - done < <(compgen -W "${out[*]}" -- "$cur") - fi -} - -__%[1]s_handle_reply() -{ - __%[1]s_debug "${FUNCNAME[0]}" - local comp - case $cur in - -*) - if [[ $(type -t compopt) = "builtin" ]]; then - compopt -o nospace - fi - local allflags - if [ ${#must_have_one_flag[@]} -ne 0 ]; then - allflags=("${must_have_one_flag[@]}") - else - allflags=("${flags[*]} ${two_word_flags[*]}") - fi - while IFS='' read -r comp; do - COMPREPLY+=("$comp") - done < <(compgen -W "${allflags[*]}" -- "$cur") - if [[ $(type -t compopt) = "builtin" ]]; then - [[ "${COMPREPLY[0]}" == *= ]] || compopt +o nospace + comp=${comp%%%%$tab*} + if ((${#comp}>longest)); then + longest=${#comp} fi + done < <(printf "%%s\n" "${out[@]}") - # complete after --flag=abc - if [[ $cur == *=* ]]; then - if [[ $(type -t compopt) = "builtin" ]]; then - compopt +o nospace - fi - - local index flag - flag="${cur%%=*}" - __%[1]s_index_of_word "${flag}" "${flags_with_completion[@]}" - COMPREPLY=() - if [[ ${index} -ge 0 ]]; then - PREFIX="" - cur="${cur#*=}" - ${flags_completion[${index}]} - if [ -n "${ZSH_VERSION}" ]; then - # zsh completion needs --flag= prefix - eval "COMPREPLY=( \"\${COMPREPLY[@]/#/${flag}=}\" )" - fi - fi + local completions=() + while IFS='' read -r comp; do + if [ -z "$comp" ]; then + continue fi - return 0; - ;; - esac - - # check if we are handling a flag with special work handling - local index - __%[1]s_index_of_word "${prev}" "${flags_with_completion[@]}" - if [[ ${index} -ge 0 ]]; then - ${flags_completion[${index}]} - return - fi - # we are parsing a flag and don't have a special handler, no completion - if [[ ${cur} != "${words[cword]}" ]]; then - return - fi + __%[1]s_debug "Original comp: $comp" + comp="$(__%[1]s_format_comp_descriptions "$comp" "$longest")" + __%[1]s_debug "Final comp: $comp" + completions+=("$comp") + done < <(printf "%%s\n" "${out[@]}") - local completions - completions=("${commands[@]}") - if [[ ${#must_have_one_noun[@]} -ne 0 ]]; then - completions+=("${must_have_one_noun[@]}") - elif [[ -n "${has_completion_function}" ]]; then - # if a go completion function is provided, defer to that function - __%[1]s_handle_go_custom_completion - fi - if [[ ${#must_have_one_flag[@]} -ne 0 ]]; then - completions+=("${must_have_one_flag[@]}") - fi - while IFS='' read -r comp; do - COMPREPLY+=("$comp") - done < <(compgen -W "${completions[*]}" -- "$cur") - - if [[ ${#COMPREPLY[@]} -eq 0 && ${#noun_aliases[@]} -gt 0 && ${#must_have_one_noun[@]} -ne 0 ]]; then while IFS='' read -r comp; do + # Although this script should only be used for bash + # there may be programs that still convert the bash + # script into a zsh one. To continue supporting those + # programs, we do this single adaptation for zsh + if [ -n "${ZSH_VERSION}" ]; then + # zsh completion needs --flag= prefix + COMPREPLY+=("$flagPrefix$comp") + else + COMPREPLY+=("$comp") + fi + done < <(compgen -W "${completions[*]}" -- "$cur") + + # If there is a single completion left, remove the description text + if [ ${#COMPREPLY[*]} -eq 1 ]; then + __%[1]s_debug "COMPREPLY[0]: ${COMPREPLY[0]}" + comp="${COMPREPLY[0]%%%% *}" + __%[1]s_debug "Removed description from single completion, which is now: ${comp}" + COMPREPLY=() COMPREPLY+=("$comp") - done < <(compgen -W "${noun_aliases[*]}" -- "$cur") - fi - - if [[ ${#COMPREPLY[@]} -eq 0 ]]; then - if declare -F __%[1]s_custom_func >/dev/null; then - # try command name qualified custom func - __%[1]s_custom_func - else - # otherwise fall back to unqualified for compatibility - declare -F __custom_func >/dev/null && __custom_func - fi - fi - - # available in bash-completion >= 2, not always present on macOS - if declare -F __ltrim_colon_completions >/dev/null; then - __ltrim_colon_completions "$cur" - fi - - # If there is only 1 completion and it is a flag with an = it will be completed - # but we don't want a space after the = - if [[ "${#COMPREPLY[@]}" -eq "1" ]] && [[ $(type -t compopt) = "builtin" ]] && [[ "${COMPREPLY[0]}" == --*= ]]; then - compopt -o nospace - fi -} - -# The arguments should be in the form "ext1|ext2|extn" -__%[1]s_handle_filename_extension_flag() -{ - local ext="$1" - _filedir "@(${ext})" -} - -__%[1]s_handle_subdirs_in_dir_flag() -{ - local dir="$1" - pushd "${dir}" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return -} - -__%[1]s_handle_flag() -{ - __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" - - # if a command required a flag, and we found it, unset must_have_one_flag() - local flagname=${words[c]} - local flagvalue - # if the word contained an = - if [[ ${words[c]} == *"="* ]]; then - flagvalue=${flagname#*=} # take in as flagvalue after the = - flagname=${flagname%%=*} # strip everything after the = - flagname="${flagname}=" # but put the = back - fi - __%[1]s_debug "${FUNCNAME[0]}: looking for ${flagname}" - if __%[1]s_contains_word "${flagname}" "${must_have_one_flag[@]}"; then - must_have_one_flag=() - fi - - # if you set a flag which only applies to this command, don't show subcommands - if __%[1]s_contains_word "${flagname}" "${local_nonpersistent_flags[@]}"; then - commands=() - fi - - # keep flag value with flagname as flaghash - # flaghash variable is an associative array which is only supported in bash > 3. - if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then - if [ -n "${flagvalue}" ] ; then - flaghash[${flagname}]=${flagvalue} - elif [ -n "${words[ $((c+1)) ]}" ] ; then - flaghash[${flagname}]=${words[ $((c+1)) ]} - else - flaghash[${flagname}]="true" # pad "true" for bool flag - fi - fi - - # skip the argument to a two word flag - if [[ ${words[c]} != *"="* ]] && __%[1]s_contains_word "${words[c]}" "${two_word_flags[@]}"; then - __%[1]s_debug "${FUNCNAME[0]}: found a flag ${words[c]}, skip the next argument" - c=$((c+1)) - # if we are looking for a flags value, don't show commands - if [[ $c -eq $cword ]]; then - commands=() fi fi - c=$((c+1)) - + __%[1]s_handle_special_char "$cur" : + __%[1]s_handle_special_char "$cur" = } -__%[1]s_handle_noun() +__%[1]s_handle_special_char() { - __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" - - if __%[1]s_contains_word "${words[c]}" "${must_have_one_noun[@]}"; then - must_have_one_noun=() - elif __%[1]s_contains_word "${words[c]}" "${noun_aliases[@]}"; then - must_have_one_noun=() + local comp="$1" + local char=$2 + if [[ "$comp" == *${char}* && "$COMP_WORDBREAKS" == *${char}* ]]; then + local word=${comp%%"${comp##*${char}}"} + local idx=${#COMPREPLY[*]} + while [[ $((--idx)) -ge 0 ]]; do + COMPREPLY[$idx]=${COMPREPLY[$idx]#"$word"} + done fi - - nouns+=("${words[c]}") - c=$((c+1)) } -__%[1]s_handle_command() +__%[1]s_format_comp_descriptions() { - __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" - - local next_command - if [[ -n ${last_command} ]]; then - next_command="_${last_command}_${words[c]//:/__}" - else - if [[ $c -eq 0 ]]; then - next_command="_%[1]s_root_command" + local tab + tab=$(printf '\t') + local comp="$1" + local longest=$2 + + # Properly format the description string which follows a tab character if there is one + if [[ "$comp" == *$tab* ]]; then + desc=${comp#*$tab} + comp=${comp%%%%$tab*} + + # $COLUMNS stores the current shell width. + # Remove an extra 4 because we add 2 spaces and 2 parentheses. + maxdesclength=$(( COLUMNS - longest - 4 )) + + # Make sure we can fit a description of at least 8 characters + # if we are to align the descriptions. + if [[ $maxdesclength -gt 8 ]]; then + # Add the proper number of spaces to align the descriptions + for ((i = ${#comp} ; i < longest ; i++)); do + comp+=" " + done else - next_command="_${words[c]//:/__}" + # Don't pad the descriptions so we can fit more text after the completion + maxdesclength=$(( COLUMNS - ${#comp} - 4 )) fi - fi - c=$((c+1)) - __%[1]s_debug "${FUNCNAME[0]}: looking for ${next_command}" - declare -F "$next_command" >/dev/null && $next_command -} -__%[1]s_handle_word() -{ - if [[ $c -ge $cword ]]; then - __%[1]s_handle_reply - return - fi - __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" - if [[ "${words[c]}" == -* ]]; then - __%[1]s_handle_flag - elif __%[1]s_contains_word "${words[c]}" "${commands[@]}"; then - __%[1]s_handle_command - elif [[ $c -eq 0 ]]; then - __%[1]s_handle_command - elif __%[1]s_contains_word "${words[c]}" "${command_aliases[@]}"; then - # aliashash variable is an associative array which is only supported in bash > 3. - if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then - words[c]=${aliashash[${words[c]}]} - __%[1]s_handle_command - else - __%[1]s_handle_noun + # If there is enough space for any description text, + # truncate the descriptions that are too long for the shell width + if [ $maxdesclength -gt 0 ]; then + if [ ${#desc} -gt $maxdesclength ]; then + desc=${desc:0:$(( maxdesclength - 1 ))} + desc+="…" + fi + comp+=" ($desc)" fi - else - __%[1]s_handle_noun fi - __%[1]s_handle_word -} -`, name, ShellCompNoDescRequestCmd, - ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, - ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs)) + # Must use printf to escape all special characters + printf "%%q" "${comp}" } -func writePostscript(buf *bytes.Buffer, name string) { - name = strings.Replace(name, ":", "__", -1) - buf.WriteString(fmt.Sprintf("__start_%s()\n", name)) - buf.WriteString(fmt.Sprintf(`{ +__start_%[1]s() +{ local cur prev words cword - declare -A flaghash 2>/dev/null || : - declare -A aliashash 2>/dev/null || : - if declare -F _init_completion >/dev/null 2>&1; then - _init_completion -s || return - else - __%[1]s_init_completion -n "=" || return - fi - local c=0 - local flags=() - local two_word_flags=() - local local_nonpersistent_flags=() - local flags_with_completion=() - local flags_completion=() - local commands=("%[1]s") - local must_have_one_flag=() - local must_have_one_noun=() - local has_completion_function - local last_command - local nouns=() - - __%[1]s_handle_word + COMPREPLY=() + _get_comp_words_by_ref -n "=:" cur prev words cword + + __%[1]s_perform_completion } -`, name)) - buf.WriteString(fmt.Sprintf(`if [[ $(type -t compopt) = "builtin" ]]; then - complete -o default -F __start_%s %s +if [[ $(type -t compopt) = "builtin" ]]; then + complete -o default -F __start_%[1]s %[1]s else - complete -o default -o nospace -F __start_%s %s + complete -o default -o nospace -F __start_%[1]s %[1]s fi -`, name, name, name, name)) - buf.WriteString("# ex: ts=4 sw=4 et filetype=sh\n") -} - -func writeCommands(buf *bytes.Buffer, cmd *Command) { - buf.WriteString(" commands=()\n") - for _, c := range cmd.Commands() { - if !c.IsAvailableCommand() && c != cmd.helpCommand { - continue - } - buf.WriteString(fmt.Sprintf(" commands+=(%q)\n", c.Name())) - writeCmdAliases(buf, c) - } - buf.WriteString("\n") -} - -func writeFlagHandler(buf *bytes.Buffer, name string, annotations map[string][]string, cmd *Command) { - for key, value := range annotations { - switch key { - case BashCompFilenameExt: - buf.WriteString(fmt.Sprintf(" flags_with_completion+=(%q)\n", name)) - - var ext string - if len(value) > 0 { - ext = fmt.Sprintf("__%s_handle_filename_extension_flag ", cmd.Root().Name()) + strings.Join(value, "|") - } else { - ext = "_filedir" - } - buf.WriteString(fmt.Sprintf(" flags_completion+=(%q)\n", ext)) - case BashCompCustom: - buf.WriteString(fmt.Sprintf(" flags_with_completion+=(%q)\n", name)) - if len(value) > 0 { - handlers := strings.Join(value, "; ") - buf.WriteString(fmt.Sprintf(" flags_completion+=(%q)\n", handlers)) - } else { - buf.WriteString(" flags_completion+=(:)\n") - } - case BashCompSubdirsInDir: - buf.WriteString(fmt.Sprintf(" flags_with_completion+=(%q)\n", name)) - - var ext string - if len(value) == 1 { - ext = fmt.Sprintf("__%s_handle_subdirs_in_dir_flag ", cmd.Root().Name()) + value[0] - } else { - ext = "_filedir -d" - } - buf.WriteString(fmt.Sprintf(" flags_completion+=(%q)\n", ext)) - } - } -} - -func writeShortFlag(buf *bytes.Buffer, flag *pflag.Flag, cmd *Command) { - name := flag.Shorthand - format := " " - if len(flag.NoOptDefVal) == 0 { - format += "two_word_" - } - format += "flags+=(\"-%s\")\n" - buf.WriteString(fmt.Sprintf(format, name)) - writeFlagHandler(buf, "-"+name, flag.Annotations, cmd) -} - -func writeFlag(buf *bytes.Buffer, flag *pflag.Flag, cmd *Command) { - name := flag.Name - format := " flags+=(\"--%s" - if len(flag.NoOptDefVal) == 0 { - format += "=" - } - format += "\")\n" - buf.WriteString(fmt.Sprintf(format, name)) - if len(flag.NoOptDefVal) == 0 { - format = " two_word_flags+=(\"--%s\")\n" - buf.WriteString(fmt.Sprintf(format, name)) - } - writeFlagHandler(buf, "--"+name, flag.Annotations, cmd) -} - -func writeLocalNonPersistentFlag(buf *bytes.Buffer, flag *pflag.Flag) { - name := flag.Name - format := " local_nonpersistent_flags+=(\"--%[1]s\")\n" - if len(flag.NoOptDefVal) == 0 { - format += " local_nonpersistent_flags+=(\"--%[1]s=\")\n" - } - buf.WriteString(fmt.Sprintf(format, name)) - if len(flag.Shorthand) > 0 { - buf.WriteString(fmt.Sprintf(" local_nonpersistent_flags+=(\"-%s\")\n", flag.Shorthand)) - } -} - -// Setup annotations for go completions for registered flags -func prepareCustomAnnotationsForFlags(cmd *Command) { - for flag := range flagCompletionFunctions { - // Make sure the completion script calls the __*_go_custom_completion function for - // every registered flag. We need to do this here (and not when the flag was registered - // for completion) so that we can know the root command name for the prefix - // of ___go_custom_completion - if flag.Annotations == nil { - flag.Annotations = map[string][]string{} - } - flag.Annotations[BashCompCustom] = []string{fmt.Sprintf("__%[1]s_handle_go_custom_completion", cmd.Root().Name())} - } -} - -func writeFlags(buf *bytes.Buffer, cmd *Command) { - prepareCustomAnnotationsForFlags(cmd) - buf.WriteString(` flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - -`) - localNonPersistentFlags := cmd.LocalNonPersistentFlags() - cmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) { - if nonCompletableFlag(flag) { - return - } - writeFlag(buf, flag, cmd) - if len(flag.Shorthand) > 0 { - writeShortFlag(buf, flag, cmd) - } - // localNonPersistentFlags are used to stop the completion of subcommands when one is set - // if TraverseChildren is true we should allow to complete subcommands - if localNonPersistentFlags.Lookup(flag.Name) != nil && !cmd.Root().TraverseChildren { - writeLocalNonPersistentFlag(buf, flag) - } - }) - cmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) { - if nonCompletableFlag(flag) { - return - } - writeFlag(buf, flag, cmd) - if len(flag.Shorthand) > 0 { - writeShortFlag(buf, flag, cmd) - } - }) - - buf.WriteString("\n") -} - -func writeRequiredFlag(buf *bytes.Buffer, cmd *Command) { - buf.WriteString(" must_have_one_flag=()\n") - flags := cmd.NonInheritedFlags() - flags.VisitAll(func(flag *pflag.Flag) { - if nonCompletableFlag(flag) { - return - } - for key := range flag.Annotations { - switch key { - case BashCompOneRequiredFlag: - format := " must_have_one_flag+=(\"--%s" - if flag.Value.Type() != "bool" { - format += "=" - } - format += "\")\n" - buf.WriteString(fmt.Sprintf(format, flag.Name)) - - if len(flag.Shorthand) > 0 { - buf.WriteString(fmt.Sprintf(" must_have_one_flag+=(\"-%s\")\n", flag.Shorthand)) - } - } - } - }) -} - -func writeRequiredNouns(buf *bytes.Buffer, cmd *Command) { - buf.WriteString(" must_have_one_noun=()\n") - sort.Sort(sort.StringSlice(cmd.ValidArgs)) - for _, value := range cmd.ValidArgs { - // Remove any description that may be included following a tab character. - // Descriptions are not supported by bash completion. - value = strings.Split(value, "\t")[0] - buf.WriteString(fmt.Sprintf(" must_have_one_noun+=(%q)\n", value)) - } - if cmd.ValidArgsFunction != nil { - buf.WriteString(" has_completion_function=1\n") - } -} - -func writeCmdAliases(buf *bytes.Buffer, cmd *Command) { - if len(cmd.Aliases) == 0 { - return - } - - sort.Sort(sort.StringSlice(cmd.Aliases)) - - buf.WriteString(fmt.Sprint(` if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then`, "\n")) - for _, value := range cmd.Aliases { - buf.WriteString(fmt.Sprintf(" command_aliases+=(%q)\n", value)) - buf.WriteString(fmt.Sprintf(" aliashash[%q]=%q\n", value, cmd.Name())) - } - buf.WriteString(` fi`) - buf.WriteString("\n") -} -func writeArgAliases(buf *bytes.Buffer, cmd *Command) { - buf.WriteString(" noun_aliases=()\n") - sort.Sort(sort.StringSlice(cmd.ArgAliases)) - for _, value := range cmd.ArgAliases { - buf.WriteString(fmt.Sprintf(" noun_aliases+=(%q)\n", value)) - } -} - -func gen(buf *bytes.Buffer, cmd *Command) { - for _, c := range cmd.Commands() { - if !c.IsAvailableCommand() && c != cmd.helpCommand { - continue - } - gen(buf, c) - } - commandName := cmd.CommandPath() - commandName = strings.Replace(commandName, " ", "_", -1) - commandName = strings.Replace(commandName, ":", "__", -1) - - if cmd.Root() == cmd { - buf.WriteString(fmt.Sprintf("_%s_root_command()\n{\n", commandName)) - } else { - buf.WriteString(fmt.Sprintf("_%s()\n{\n", commandName)) - } - - buf.WriteString(fmt.Sprintf(" last_command=%q\n", commandName)) - buf.WriteString("\n") - buf.WriteString(" command_aliases=()\n") - buf.WriteString("\n") - - writeCommands(buf, cmd) - writeFlags(buf, cmd) - writeRequiredFlag(buf, cmd) - writeRequiredNouns(buf, cmd) - writeArgAliases(buf, cmd) - buf.WriteString("}\n\n") -} - -// GenBashCompletion generates bash completion file and writes to the passed writer. -func (c *Command) GenBashCompletion(w io.Writer) error { - buf := new(bytes.Buffer) - writePreamble(buf, c.Name()) - if len(c.BashCompletionFunction) > 0 { - buf.WriteString(c.BashCompletionFunction + "\n") - } - gen(buf, c) - writePostscript(buf, c.Name()) - - _, err := buf.WriteTo(w) - return err -} - -func nonCompletableFlag(flag *pflag.Flag) bool { - return flag.Hidden || len(flag.Deprecated) > 0 -} - -// GenBashCompletionFile generates bash completion file. -func (c *Command) GenBashCompletionFile(filename string) error { - outFile, err := os.Create(filename) - if err != nil { - return err - } - defer outFile.Close() - - return c.GenBashCompletion(outFile) +# ex: ts=4 sw=4 et filetype=sh +`, name, compCmd, + ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, + ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, + shellCompDirectiveLegacyCustomComp, shellCompDirectiveLegacyCustomArgsComp)) } diff --git a/vendor/github.com/spf13/cobra/custom_completions.go b/vendor/github.com/spf13/cobra/custom_completions.go index f9e88e081fc0..e2c68ae1e7c0 100644 --- a/vendor/github.com/spf13/cobra/custom_completions.go +++ b/vendor/github.com/spf13/cobra/custom_completions.go @@ -51,6 +51,11 @@ const ( // obtain the same behavior but only for flags. ShellCompDirectiveFilterDirs + // For internal use only. + // Used to maintain backwards-compatibility with the legacy bash custom completions. + shellCompDirectiveLegacyCustomComp + shellCompDirectiveLegacyCustomArgsComp + // =========================================================================== // All directives using iota should be above this one. @@ -94,6 +99,12 @@ func (d ShellCompDirective) string() string { if d&ShellCompDirectiveFilterDirs != 0 { directives = append(directives, "ShellCompDirectiveFilterDirs") } + if d&shellCompDirectiveLegacyCustomComp != 0 { + directives = append(directives, "shellCompDirectiveLegacyCustomComp") + } + if d&shellCompDirectiveLegacyCustomArgsComp != 0 { + directives = append(directives, "shellCompDirectiveLegacyCustomArgsComp") + } if len(directives) == 0 { directives = append(directives, "ShellCompDirectiveDefault") } @@ -149,10 +160,6 @@ func (c *Command) initCompleteCmd(args []string) { fmt.Fprintln(finalCmd.OutOrStdout(), comp) } - if directive >= shellCompDirectiveMaxValue { - directive = ShellCompDirectiveDefault - } - // As the last printout, print the completion directive for the completion script to parse. // The directive integer must be that last character following a single colon (:). // The completion script expects : @@ -362,6 +369,10 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi var comps []string comps, directive = completionFn(finalCmd, finalArgs, toComplete) completions = append(completions, comps...) + } else { + // If there is no Go custom completion defined, check for legacy bash + // custom completion to preserve backwards-compatibility + completions, directive = checkLegacyCustomCompletion(finalCmd, finalArgs, flag, completions, directive) } return finalCmd, completions, directive, nil @@ -442,7 +453,16 @@ func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*p if len(lastArg) > 0 && lastArg[0] == '-' { if index := strings.Index(lastArg, "="); index >= 0 { // Flag with an = - flagName = strings.TrimLeft(lastArg[:index], "-") + if strings.HasPrefix(lastArg[:index], "--") { + // Flag has full name + flagName = lastArg[2:index] + } else { + // Flag is shorthand + // We have to get the last shorthand flag name + // e.g. `-asd` => d to provide the correct completion + // https://github.com/spf13/cobra/issues/1257 + flagName = lastArg[index-1 : index] + } lastArg = lastArg[index+1:] flagWithEqual = true } else { @@ -459,8 +479,16 @@ func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*p // If the flag contains an = it means it has already been fully processed, // so we don't need to deal with it here. if index := strings.Index(prevArg, "="); index < 0 { - flagName = strings.TrimLeft(prevArg, "-") - + if strings.HasPrefix(prevArg, "--") { + // Flag has full name + flagName = prevArg[2:] + } else { + // Flag is shorthand + // We have to get the last shorthand flag name + // e.g. `-asd` => d to provide the correct completion + // https://github.com/spf13/cobra/issues/1257 + flagName = prevArg[len(prevArg)-1:] + } // Remove the uncompleted flag or else there could be an error created // for an invalid value for that flag trimmedArgs = args[:len(args)-1] @@ -513,6 +541,65 @@ func findFlag(cmd *Command, name string) *pflag.Flag { return cmd.Flag(name) } +func nonCompletableFlag(flag *pflag.Flag) bool { + return flag.Hidden || len(flag.Deprecated) > 0 +} + +// This function checks if legacy bash custom completion should be performed and if so, +// it provides the shell script with the necessary information. +func checkLegacyCustomCompletion(cmd *Command, args []string, flag *pflag.Flag, completions []string, directive ShellCompDirective) ([]string, ShellCompDirective) { + // Check if any legacy custom completion is defined for the program + if len(cmd.Root().BashCompletionFunction) > 0 { + // Legacy custom completion is only triggered if no other completions were found. + if len(completions) == 0 { + if flag != nil { + // For legacy custom flag completion, we must let the script know the bash + // functions it should call based on the content of the annotation BashCompCustom. + if values, present := flag.Annotations[BashCompCustom]; present { + if len(values) > 0 { + handlers := strings.Join(values, "; ") + // We send the commands to set the shell variables that are needed + // for legacy custom completions followed by the functions to call + // to perform the actual flag completion + completions = append(prepareLegacyCustomCompletionVars(cmd, args), handlers) + directive = directive | shellCompDirectiveLegacyCustomComp + } + } + } else { + // Check if the legacy custom_func is defined. + // This check will work for both "__custom_func" and "___custom_func". + // This could happen if the program defined some functions for legacy flag completion + // but not the legacy custom_func. + if strings.Contains(cmd.Root().BashCompletionFunction, "_custom_func") { + // For legacy args completion, the script already knows what to call + // so we only need to tell it the commands to set the shell variables needed + completions = prepareLegacyCustomCompletionVars(cmd, args) + directive = directive | shellCompDirectiveLegacyCustomComp | shellCompDirectiveLegacyCustomArgsComp + } + } + } + } + return completions, directive +} + +// The original bash completion script had some shell variables that are used by legacy bash +// custom completions. Let's set those variables to allow those legacy custom completions +// to continue working. +func prepareLegacyCustomCompletionVars(cmd *Command, args []string) []string { + var compVarCmds []string + + // "last_command" variable + commandName := cmd.CommandPath() + commandName = strings.Replace(commandName, " ", "_", -1) + commandName = strings.Replace(commandName, ":", "__", -1) + compVarCmds = append(compVarCmds, fmt.Sprintf("last_command=%s", commandName)) + + // "nouns" array variable + compVarCmds = append(compVarCmds, fmt.Sprintf("nouns=(%s)", strings.Join(args, " "))) + + return compVarCmds +} + // CompDebug prints the specified string to the same file as where the // completion script prints its logs. // Note that completion printouts should never be on stdout as they would diff --git a/vendor/github.com/spf13/cobra/fish_completions.go b/vendor/github.com/spf13/cobra/fish_completions.go index eaae9bca8668..aeaef0087d79 100644 --- a/vendor/github.com/spf13/cobra/fish_completions.go +++ b/vendor/github.com/spf13/cobra/fish_completions.go @@ -28,9 +28,9 @@ function __%[1]s_debug end function __%[1]s_perform_completion - __%[1]s_debug "Starting __%[1]s_perform_completion with: $argv" + __%[1]s_debug "Starting __%[1]s_perform_completion" - set args (string split -- " " "$argv") + set args (string split -- " " (commandline -c)) set lastArg "$args[-1]" __%[1]s_debug "args: $args" @@ -71,31 +71,22 @@ function __%[1]s_perform_completion printf "%%s\n" "$directiveLine" end -# This function does three things: -# 1- Obtain the completions and store them in the global __%[1]s_comp_results -# 2- Set the __%[1]s_comp_do_file_comp flag if file completion should be performed -# and unset it otherwise -# 3- Return true if the completion results are not empty +# This function does two things: +# - Obtain the completions and store them in the global __%[1]s_comp_results +# - Return false if file completion should be performed function __%[1]s_prepare_completions + __%[1]s_debug "" + __%[1]s_debug "========= starting completion logic ==========" + # Start fresh - set --erase __%[1]s_comp_do_file_comp set --erase __%[1]s_comp_results - # Check if the command-line is already provided. This is useful for testing. - if not set --query __%[1]s_comp_commandLine - # Use the -c flag to allow for completion in the middle of the line - set __%[1]s_comp_commandLine (commandline -c) - end - __%[1]s_debug "commandLine is: $__%[1]s_comp_commandLine" - - set results (__%[1]s_perform_completion "$__%[1]s_comp_commandLine") - set --erase __%[1]s_comp_commandLine + set results (__%[1]s_perform_completion) __%[1]s_debug "Completion results: $results" if test -z "$results" __%[1]s_debug "No completion, probably due to a failure" # Might as well do file completion, in case it helps - set --global __%[1]s_comp_do_file_comp 1 return 1 end @@ -110,6 +101,8 @@ function __%[1]s_prepare_completions set shellCompDirectiveNoFileComp %[6]d set shellCompDirectiveFilterFileExt %[7]d set shellCompDirectiveFilterDirs %[8]d + set shellCompDirectiveLegacyCustomComp %[9]d + set shellCompDirectiveLegacyCustomArgsComp %[10]d if test -z "$directive" set directive 0 @@ -119,6 +112,14 @@ function __%[1]s_prepare_completions if test $compErr -eq 1 __%[1]s_debug "Received error directive: aborting." # Might as well do file completion, in case it helps + return 1 + end + + set legacyCustom (math (math --scale 0 $directive / $shellCompDirectiveLegacyCustomComp) %% 2) + set legacyCustomArgs (math (math --scale 0 $directive / $shellCompDirectiveLegacyCustomArgsComp) %% 2) + if test $legacyCustom -eq 1; or test $legacyCustomArgs -eq 1 + __%[1]s_debug "Legacy bash custom completion not applicable to fish" + # Do full file completion instead set --global __%[1]s_comp_do_file_comp 1 return 1 end @@ -128,7 +129,6 @@ function __%[1]s_prepare_completions if test $filefilter -eq 1; or test $dirfilter -eq 1 __%[1]s_debug "File extension filtering or directory filtering not supported" # Do full file completion instead - set --global __%[1]s_comp_do_file_comp 1 return 1 end @@ -137,27 +137,51 @@ function __%[1]s_prepare_completions __%[1]s_debug "nospace: $nospace, nofiles: $nofiles" - # Important not to quote the variable for count to work - set numComps (count $__%[1]s_comp_results) - __%[1]s_debug "numComps: $numComps" - - if test $numComps -eq 1; and test $nospace -ne 0 - # To support the "nospace" directive we trick the shell - # by outputting an extra, longer completion. - __%[1]s_debug "Adding second completion to perform nospace directive" - set --append __%[1]s_comp_results $__%[1]s_comp_results[1]. + # If we want to prevent a space, or if file completion is NOT disabled, + # we need to count the number of valid completions. + # To do so, we will filter on prefix as the completions we have received + # may not already be filtered so as to allow fish to match on different + # criteria than prefix. + if test $nospace -ne 0; or test $nofiles -eq 0 + set prefix (commandline -t) + __%[1]s_debug "prefix: $prefix" + + set completions + for comp in $__%[1]s_comp_results + if test (string match -e -r "^$prefix" "$comp") + set -a completions $comp + end + end + set --global __%[1]s_comp_results $completions + __%[1]s_debug "Filtered completions are: $__%[1]s_comp_results" + + # Important not to quote the variable for count to work + set numComps (count $__%[1]s_comp_results) + __%[1]s_debug "numComps: $numComps" + + if test $numComps -eq 1; and test $nospace -ne 0 + # To support the "nospace" directive we trick the shell + # by outputting an extra, longer completion. + # We must first split on \t to get rid of the descriptions because + # the extra character we add to the fake second completion must be + # before the description. We don't need descriptions anyway since + # there is only a single real completion which the shell will expand + # immediately. + __%[1]s_debug "Adding second completion to perform nospace directive" + set split (string split --max 1 \t $__%[1]s_comp_results[1]) + set --global __%[1]s_comp_results $split[1] $split[1]. + __%[1]s_debug "Completions are now: $__%[1]s_comp_results" + end + + if test $numComps -eq 0; and test $nofiles -eq 0 + # To be consistent with bash and zsh, we only trigger file + # completion when there are no other completions + __%[1]s_debug "Requesting file completion" + return 1 + end end - if test $numComps -eq 0; and test $nofiles -eq 0 - __%[1]s_debug "Requesting file completion" - set --global __%[1]s_comp_do_file_comp 1 - end - - # If we don't want file completion, we must return true even if there - # are no completions found. This is because fish will perform the last - # completion command, even if its condition is false, if no other - # completion command was triggered - return (not set --query __%[1]s_comp_do_file_comp) + return 0 end # Since Fish completions are only loaded once the user triggers them, we trigger them ourselves @@ -170,21 +194,14 @@ complete --do-complete "%[2]s " > /dev/null 2>&1 # Remove any pre-existing completions for the program since we will be handling all of them. complete -c %[2]s -e -# The order in which the below two lines are defined is very important so that __%[1]s_prepare_completions -# is called first. It is __%[1]s_prepare_completions that sets up the __%[1]s_comp_do_file_comp variable. -# -# This completion will be run second as complete commands are added FILO. -# It triggers file completion choices when __%[1]s_comp_do_file_comp is set. -complete -c %[2]s -n 'set --query __%[1]s_comp_do_file_comp' - -# This completion will be run first as complete commands are added FILO. -# The call to __%[1]s_prepare_completions will setup both __%[1]s_comp_results and __%[1]s_comp_do_file_comp. -# It provides the program's completion choices. +# The call to __%[1]s_prepare_completions will setup __%[1]s_comp_results +# which provides the program's completion choices. complete -c %[2]s -n '__%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results' `, nameForVar, name, compCmd, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, - ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs)) + ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, + shellCompDirectiveLegacyCustomComp, shellCompDirectiveLegacyCustomArgsComp)) } // GenFishCompletion generates fish completion file and writes to the passed writer. diff --git a/vendor/github.com/spf13/cobra/zsh_completions.go b/vendor/github.com/spf13/cobra/zsh_completions.go index 92a70394a9d1..ef290e2eb1fd 100644 --- a/vendor/github.com/spf13/cobra/zsh_completions.go +++ b/vendor/github.com/spf13/cobra/zsh_completions.go @@ -94,8 +94,10 @@ _%[1]s() local shellCompDirectiveNoFileComp=%[5]d local shellCompDirectiveFilterFileExt=%[6]d local shellCompDirectiveFilterDirs=%[7]d + local shellCompDirectiveLegacyCustomComp=%[8]d + local shellCompDirectiveLegacyCustomArgsComp=%[9]d - local lastParam lastChar flagPrefix requestComp out directive compCount comp lastComp + local lastParam lastChar flagPrefix requestComp out directive comp lastComp noSpace local -a completions __%[1]s_debug "\n========= starting completion logic ==========" @@ -163,7 +165,6 @@ _%[1]s() return fi - compCount=0 while IFS='\n' read -r comp; do if [ -n "$comp" ]; then # If requested, completions are returned with a description. @@ -175,13 +176,17 @@ _%[1]s() local tab=$(printf '\t') comp=${comp//$tab/:} - ((compCount++)) __%[1]s_debug "Adding completion: ${comp}" completions+=${comp} lastComp=$comp fi done < <(printf "%%s\n" "${out[@]}") + if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then + __%[1]s_debug "Activating nospace." + noSpace="-S ''" + fi + if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then # File extension filtering local filteringCmd @@ -208,25 +213,40 @@ _%[1]s() __%[1]s_debug "Listing directories in ." fi + local result _arguments '*:dirname:_files -/'" ${flagPrefix}" + result=$? if [ -n "$subdir" ]; then popd >/dev/null 2>&1 fi - elif [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ] && [ ${compCount} -eq 1 ]; then - __%[1]s_debug "Activating nospace." - # We can use compadd here as there is no description when - # there is only one completion. - compadd -S '' "${lastComp}" - elif [ ${compCount} -eq 0 ]; then - if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then - __%[1]s_debug "deactivating file completion" + return $result + else + __%[1]s_debug "Calling _describe" + if eval _describe "completions" completions $flagPrefix $noSpace; then + __%[1]s_debug "_describe found some completions" + + # Return the success of having called _describe + return 0 else - # Perform file completion - __%[1]s_debug "activating file completion" - _arguments '*:filename:_files'" ${flagPrefix}" + __%[1]s_debug "_describe did not find completions." + __%[1]s_debug "Checking if we should do file completion." + if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then + __%[1]s_debug "deactivating file completion" + + # We must return an error code here to let zsh know that there were no + # completions found by _describe; this is what will trigger other + # matching algorithms to attempt to find completions. + # For example zsh can match letters in the middle of words. + return 1 + else + # Perform file completion + __%[1]s_debug "Activating file completion" + + # We must return the result of this command, so it must be the + # last command, or else we must store its result to return it. + _arguments '*:filename:_files'" ${flagPrefix}" + fi fi - else - _describe "completions" completions $(echo $flagPrefix) fi } @@ -236,5 +256,6 @@ if [ "$funcstack[1]" = "_%[1]s" ]; then fi `, name, compCmd, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, - ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs)) + ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, + shellCompDirectiveLegacyCustomComp, shellCompDirectiveLegacyCustomArgsComp)) } diff --git a/vendor/go.uber.org/atomic/.codecov.yml b/vendor/go.uber.org/atomic/.codecov.yml index 6d4d1be7b574..571116cc39c6 100644 --- a/vendor/go.uber.org/atomic/.codecov.yml +++ b/vendor/go.uber.org/atomic/.codecov.yml @@ -13,3 +13,7 @@ coverage: if_not_found: success # if parent is not found report status as success, error, or failure if_ci_failed: error # if ci fails report status as success, error, or failure +# Also update COVER_IGNORE_PKGS in the Makefile. +ignore: + - /internal/gen-atomicint/ + - /internal/gen-valuewrapper/ diff --git a/vendor/go.uber.org/atomic/.gitignore b/vendor/go.uber.org/atomic/.gitignore index 0a4504f11095..c3fa253893f0 100644 --- a/vendor/go.uber.org/atomic/.gitignore +++ b/vendor/go.uber.org/atomic/.gitignore @@ -1,6 +1,7 @@ +/bin .DS_Store /vendor -/cover +cover.html cover.out lint.log diff --git a/vendor/go.uber.org/atomic/.travis.yml b/vendor/go.uber.org/atomic/.travis.yml index 0f3769e5fa6b..13d0a4f25404 100644 --- a/vendor/go.uber.org/atomic/.travis.yml +++ b/vendor/go.uber.org/atomic/.travis.yml @@ -2,26 +2,26 @@ sudo: false language: go go_import_path: go.uber.org/atomic -go: - - 1.11.x - - 1.12.x +env: + global: + - GO111MODULE=on matrix: include: - - go: 1.12.x - env: NO_TEST=yes LINT=yes + - go: oldstable + - go: stable + env: LINT=1 cache: directories: - vendor -install: - - make install_ci +before_install: + - go version script: - - test -n "$NO_TEST" || make test_ci - - test -n "$NO_TEST" || scripts/test-ubergo.sh - - test -z "$LINT" || make install_lint lint + - test -z "$LINT" || make lint + - make cover after_success: - bash <(curl -s https://codecov.io/bash) diff --git a/vendor/go.uber.org/atomic/CHANGELOG.md b/vendor/go.uber.org/atomic/CHANGELOG.md new file mode 100644 index 000000000000..24c0274dc321 --- /dev/null +++ b/vendor/go.uber.org/atomic/CHANGELOG.md @@ -0,0 +1,76 @@ +# Changelog +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [1.7.0] - 2020-09-14 +### Added +- Support JSON serialization and deserialization of primitive atomic types. +- Support Text marshalling and unmarshalling for string atomics. + +### Changed +- Disallow incorrect comparison of atomic values in a non-atomic way. + +### Removed +- Remove dependency on `golang.org/x/{lint, tools}`. + +## [1.6.0] - 2020-02-24 +### Changed +- Drop library dependency on `golang.org/x/{lint, tools}`. + +## [1.5.1] - 2019-11-19 +- Fix bug where `Bool.CAS` and `Bool.Toggle` do work correctly together + causing `CAS` to fail even though the old value matches. + +## [1.5.0] - 2019-10-29 +### Changed +- With Go modules, only the `go.uber.org/atomic` import path is supported now. + If you need to use the old import path, please add a `replace` directive to + your `go.mod`. + +## [1.4.0] - 2019-05-01 +### Added + - Add `atomic.Error` type for atomic operations on `error` values. + +## [1.3.2] - 2018-05-02 +### Added +- Add `atomic.Duration` type for atomic operations on `time.Duration` values. + +## [1.3.1] - 2017-11-14 +### Fixed +- Revert optimization for `atomic.String.Store("")` which caused data races. + +## [1.3.0] - 2017-11-13 +### Added +- Add `atomic.Bool.CAS` for compare-and-swap semantics on bools. + +### Changed +- Optimize `atomic.String.Store("")` by avoiding an allocation. + +## [1.2.0] - 2017-04-12 +### Added +- Shadow `atomic.Value` from `sync/atomic`. + +## [1.1.0] - 2017-03-10 +### Added +- Add atomic `Float64` type. + +### Changed +- Support new `go.uber.org/atomic` import path. + +## [1.0.0] - 2016-07-18 + +- Initial release. + +[1.7.0]: https://github.com/uber-go/atomic/compare/v1.6.0...v1.7.0 +[1.6.0]: https://github.com/uber-go/atomic/compare/v1.5.1...v1.6.0 +[1.5.1]: https://github.com/uber-go/atomic/compare/v1.5.0...v1.5.1 +[1.5.0]: https://github.com/uber-go/atomic/compare/v1.4.0...v1.5.0 +[1.4.0]: https://github.com/uber-go/atomic/compare/v1.3.2...v1.4.0 +[1.3.2]: https://github.com/uber-go/atomic/compare/v1.3.1...v1.3.2 +[1.3.1]: https://github.com/uber-go/atomic/compare/v1.3.0...v1.3.1 +[1.3.0]: https://github.com/uber-go/atomic/compare/v1.2.0...v1.3.0 +[1.2.0]: https://github.com/uber-go/atomic/compare/v1.1.0...v1.2.0 +[1.1.0]: https://github.com/uber-go/atomic/compare/v1.0.0...v1.1.0 +[1.0.0]: https://github.com/uber-go/atomic/releases/tag/v1.0.0 diff --git a/vendor/go.uber.org/atomic/Makefile b/vendor/go.uber.org/atomic/Makefile index 1ef263075d76..1b1376d42533 100644 --- a/vendor/go.uber.org/atomic/Makefile +++ b/vendor/go.uber.org/atomic/Makefile @@ -1,51 +1,78 @@ -# Many Go tools take file globs or directories as arguments instead of packages. -PACKAGE_FILES ?= *.go +# Directory to place `go install`ed binaries into. +export GOBIN ?= $(shell pwd)/bin -# For pre go1.6 -export GO15VENDOREXPERIMENT=1 +GOLINT = $(GOBIN)/golint +GEN_ATOMICINT = $(GOBIN)/gen-atomicint +GEN_ATOMICWRAPPER = $(GOBIN)/gen-atomicwrapper +STATICCHECK = $(GOBIN)/staticcheck +GO_FILES ?= $(shell find . '(' -path .git -o -path vendor ')' -prune -o -name '*.go' -print) + +# Also update ignore section in .codecov.yml. +COVER_IGNORE_PKGS = \ + go.uber.org/atomic/internal/gen-atomicint \ + go.uber.org/atomic/internal/gen-atomicwrapper .PHONY: build build: - go build -i ./... + go build ./... +.PHONY: test +test: + go test -race ./... -.PHONY: install -install: - glide --version || go get github.com/Masterminds/glide - glide install +.PHONY: gofmt +gofmt: + $(eval FMT_LOG := $(shell mktemp -t gofmt.XXXXX)) + gofmt -e -s -l $(GO_FILES) > $(FMT_LOG) || true + @[ ! -s "$(FMT_LOG)" ] || (echo "gofmt failed:" && cat $(FMT_LOG) && false) +$(GOLINT): + cd tools && go install golang.org/x/lint/golint -.PHONY: test -test: - go test -cover -race ./... +$(STATICCHECK): + cd tools && go install honnef.co/go/tools/cmd/staticcheck +$(GEN_ATOMICWRAPPER): $(wildcard ./internal/gen-atomicwrapper/*) + go build -o $@ ./internal/gen-atomicwrapper -.PHONY: install_ci -install_ci: install - go get github.com/wadey/gocovmerge - go get github.com/mattn/goveralls - go get golang.org/x/tools/cmd/cover +$(GEN_ATOMICINT): $(wildcard ./internal/gen-atomicint/*) + go build -o $@ ./internal/gen-atomicint -.PHONY: install_lint -install_lint: - go get golang.org/x/lint/golint +.PHONY: golint +golint: $(GOLINT) + $(GOLINT) ./... +.PHONY: staticcheck +staticcheck: $(STATICCHECK) + $(STATICCHECK) ./... .PHONY: lint -lint: - @rm -rf lint.log - @echo "Checking formatting..." - @gofmt -d -s $(PACKAGE_FILES) 2>&1 | tee lint.log - @echo "Checking vet..." - @go vet ./... 2>&1 | tee -a lint.log;) - @echo "Checking lint..." - @golint $$(go list ./...) 2>&1 | tee -a lint.log - @echo "Checking for unresolved FIXMEs..." - @git grep -i fixme | grep -v -e vendor -e Makefile | tee -a lint.log - @[ ! -s lint.log ] - - -.PHONY: test_ci -test_ci: install_ci build - ./scripts/cover.sh $(shell go list $(PACKAGES)) +lint: gofmt golint staticcheck generatenodirty + +# comma separated list of packages to consider for code coverage. +COVER_PKG = $(shell \ + go list -find ./... | \ + grep -v $(foreach pkg,$(COVER_IGNORE_PKGS),-e "^$(pkg)$$") | \ + paste -sd, -) + +.PHONY: cover +cover: + go test -coverprofile=cover.out -coverpkg $(COVER_PKG) -v ./... + go tool cover -html=cover.out -o cover.html + +.PHONY: generate +generate: $(GEN_ATOMICINT) $(GEN_ATOMICWRAPPER) + go generate ./... + +.PHONY: generatenodirty +generatenodirty: + @[ -z "$$(git status --porcelain)" ] || ( \ + echo "Working tree is dirty. Commit your changes first."; \ + exit 1 ) + @make generate + @status=$$(git status --porcelain); \ + [ -z "$$status" ] || ( \ + echo "Working tree is dirty after `make generate`:"; \ + echo "$$status"; \ + echo "Please ensure that the generated code is up-to-date." ) diff --git a/vendor/go.uber.org/atomic/README.md b/vendor/go.uber.org/atomic/README.md index 62eb8e576096..ade0c20f16b4 100644 --- a/vendor/go.uber.org/atomic/README.md +++ b/vendor/go.uber.org/atomic/README.md @@ -3,9 +3,34 @@ Simple wrappers for primitive types to enforce atomic access. ## Installation -`go get -u go.uber.org/atomic` + +```shell +$ go get -u go.uber.org/atomic@v1 +``` + +### Legacy Import Path + +As of v1.5.0, the import path `go.uber.org/atomic` is the only supported way +of using this package. If you are using Go modules, this package will fail to +compile with the legacy import path path `github.com/uber-go/atomic`. + +We recommend migrating your code to the new import path but if you're unable +to do so, or if your dependencies are still using the old import path, you +will have to add a `replace` directive to your `go.mod` file downgrading the +legacy import path to an older version. + +``` +replace github.com/uber-go/atomic => github.com/uber-go/atomic v1.4.0 +``` + +You can do so automatically by running the following command. + +```shell +$ go mod edit -replace github.com/uber-go/atomic=github.com/uber-go/atomic@v1.4.0 +``` ## Usage + The standard library's `sync/atomic` is powerful, but it's easy to forget which variables must be accessed atomically. `go.uber.org/atomic` preserves all the functionality of the standard library, but wraps the primitive types to @@ -21,9 +46,11 @@ atom.CAS(40, 11) See the [documentation][doc] for a complete API specification. ## Development Status + Stable. -___ +--- + Released under the [MIT License](LICENSE.txt). [doc-img]: https://godoc.org/github.com/uber-go/atomic?status.svg diff --git a/vendor/go.uber.org/atomic/atomic.go b/vendor/go.uber.org/atomic/atomic.go deleted file mode 100644 index 1db6849fca0a..000000000000 --- a/vendor/go.uber.org/atomic/atomic.go +++ /dev/null @@ -1,351 +0,0 @@ -// Copyright (c) 2016 Uber Technologies, Inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -// Package atomic provides simple wrappers around numerics to enforce atomic -// access. -package atomic - -import ( - "math" - "sync/atomic" - "time" -) - -// Int32 is an atomic wrapper around an int32. -type Int32 struct{ v int32 } - -// NewInt32 creates an Int32. -func NewInt32(i int32) *Int32 { - return &Int32{i} -} - -// Load atomically loads the wrapped value. -func (i *Int32) Load() int32 { - return atomic.LoadInt32(&i.v) -} - -// Add atomically adds to the wrapped int32 and returns the new value. -func (i *Int32) Add(n int32) int32 { - return atomic.AddInt32(&i.v, n) -} - -// Sub atomically subtracts from the wrapped int32 and returns the new value. -func (i *Int32) Sub(n int32) int32 { - return atomic.AddInt32(&i.v, -n) -} - -// Inc atomically increments the wrapped int32 and returns the new value. -func (i *Int32) Inc() int32 { - return i.Add(1) -} - -// Dec atomically decrements the wrapped int32 and returns the new value. -func (i *Int32) Dec() int32 { - return i.Sub(1) -} - -// CAS is an atomic compare-and-swap. -func (i *Int32) CAS(old, new int32) bool { - return atomic.CompareAndSwapInt32(&i.v, old, new) -} - -// Store atomically stores the passed value. -func (i *Int32) Store(n int32) { - atomic.StoreInt32(&i.v, n) -} - -// Swap atomically swaps the wrapped int32 and returns the old value. -func (i *Int32) Swap(n int32) int32 { - return atomic.SwapInt32(&i.v, n) -} - -// Int64 is an atomic wrapper around an int64. -type Int64 struct{ v int64 } - -// NewInt64 creates an Int64. -func NewInt64(i int64) *Int64 { - return &Int64{i} -} - -// Load atomically loads the wrapped value. -func (i *Int64) Load() int64 { - return atomic.LoadInt64(&i.v) -} - -// Add atomically adds to the wrapped int64 and returns the new value. -func (i *Int64) Add(n int64) int64 { - return atomic.AddInt64(&i.v, n) -} - -// Sub atomically subtracts from the wrapped int64 and returns the new value. -func (i *Int64) Sub(n int64) int64 { - return atomic.AddInt64(&i.v, -n) -} - -// Inc atomically increments the wrapped int64 and returns the new value. -func (i *Int64) Inc() int64 { - return i.Add(1) -} - -// Dec atomically decrements the wrapped int64 and returns the new value. -func (i *Int64) Dec() int64 { - return i.Sub(1) -} - -// CAS is an atomic compare-and-swap. -func (i *Int64) CAS(old, new int64) bool { - return atomic.CompareAndSwapInt64(&i.v, old, new) -} - -// Store atomically stores the passed value. -func (i *Int64) Store(n int64) { - atomic.StoreInt64(&i.v, n) -} - -// Swap atomically swaps the wrapped int64 and returns the old value. -func (i *Int64) Swap(n int64) int64 { - return atomic.SwapInt64(&i.v, n) -} - -// Uint32 is an atomic wrapper around an uint32. -type Uint32 struct{ v uint32 } - -// NewUint32 creates a Uint32. -func NewUint32(i uint32) *Uint32 { - return &Uint32{i} -} - -// Load atomically loads the wrapped value. -func (i *Uint32) Load() uint32 { - return atomic.LoadUint32(&i.v) -} - -// Add atomically adds to the wrapped uint32 and returns the new value. -func (i *Uint32) Add(n uint32) uint32 { - return atomic.AddUint32(&i.v, n) -} - -// Sub atomically subtracts from the wrapped uint32 and returns the new value. -func (i *Uint32) Sub(n uint32) uint32 { - return atomic.AddUint32(&i.v, ^(n - 1)) -} - -// Inc atomically increments the wrapped uint32 and returns the new value. -func (i *Uint32) Inc() uint32 { - return i.Add(1) -} - -// Dec atomically decrements the wrapped int32 and returns the new value. -func (i *Uint32) Dec() uint32 { - return i.Sub(1) -} - -// CAS is an atomic compare-and-swap. -func (i *Uint32) CAS(old, new uint32) bool { - return atomic.CompareAndSwapUint32(&i.v, old, new) -} - -// Store atomically stores the passed value. -func (i *Uint32) Store(n uint32) { - atomic.StoreUint32(&i.v, n) -} - -// Swap atomically swaps the wrapped uint32 and returns the old value. -func (i *Uint32) Swap(n uint32) uint32 { - return atomic.SwapUint32(&i.v, n) -} - -// Uint64 is an atomic wrapper around a uint64. -type Uint64 struct{ v uint64 } - -// NewUint64 creates a Uint64. -func NewUint64(i uint64) *Uint64 { - return &Uint64{i} -} - -// Load atomically loads the wrapped value. -func (i *Uint64) Load() uint64 { - return atomic.LoadUint64(&i.v) -} - -// Add atomically adds to the wrapped uint64 and returns the new value. -func (i *Uint64) Add(n uint64) uint64 { - return atomic.AddUint64(&i.v, n) -} - -// Sub atomically subtracts from the wrapped uint64 and returns the new value. -func (i *Uint64) Sub(n uint64) uint64 { - return atomic.AddUint64(&i.v, ^(n - 1)) -} - -// Inc atomically increments the wrapped uint64 and returns the new value. -func (i *Uint64) Inc() uint64 { - return i.Add(1) -} - -// Dec atomically decrements the wrapped uint64 and returns the new value. -func (i *Uint64) Dec() uint64 { - return i.Sub(1) -} - -// CAS is an atomic compare-and-swap. -func (i *Uint64) CAS(old, new uint64) bool { - return atomic.CompareAndSwapUint64(&i.v, old, new) -} - -// Store atomically stores the passed value. -func (i *Uint64) Store(n uint64) { - atomic.StoreUint64(&i.v, n) -} - -// Swap atomically swaps the wrapped uint64 and returns the old value. -func (i *Uint64) Swap(n uint64) uint64 { - return atomic.SwapUint64(&i.v, n) -} - -// Bool is an atomic Boolean. -type Bool struct{ v uint32 } - -// NewBool creates a Bool. -func NewBool(initial bool) *Bool { - return &Bool{boolToInt(initial)} -} - -// Load atomically loads the Boolean. -func (b *Bool) Load() bool { - return truthy(atomic.LoadUint32(&b.v)) -} - -// CAS is an atomic compare-and-swap. -func (b *Bool) CAS(old, new bool) bool { - return atomic.CompareAndSwapUint32(&b.v, boolToInt(old), boolToInt(new)) -} - -// Store atomically stores the passed value. -func (b *Bool) Store(new bool) { - atomic.StoreUint32(&b.v, boolToInt(new)) -} - -// Swap sets the given value and returns the previous value. -func (b *Bool) Swap(new bool) bool { - return truthy(atomic.SwapUint32(&b.v, boolToInt(new))) -} - -// Toggle atomically negates the Boolean and returns the previous value. -func (b *Bool) Toggle() bool { - return truthy(atomic.AddUint32(&b.v, 1) - 1) -} - -func truthy(n uint32) bool { - return n&1 == 1 -} - -func boolToInt(b bool) uint32 { - if b { - return 1 - } - return 0 -} - -// Float64 is an atomic wrapper around float64. -type Float64 struct { - v uint64 -} - -// NewFloat64 creates a Float64. -func NewFloat64(f float64) *Float64 { - return &Float64{math.Float64bits(f)} -} - -// Load atomically loads the wrapped value. -func (f *Float64) Load() float64 { - return math.Float64frombits(atomic.LoadUint64(&f.v)) -} - -// Store atomically stores the passed value. -func (f *Float64) Store(s float64) { - atomic.StoreUint64(&f.v, math.Float64bits(s)) -} - -// Add atomically adds to the wrapped float64 and returns the new value. -func (f *Float64) Add(s float64) float64 { - for { - old := f.Load() - new := old + s - if f.CAS(old, new) { - return new - } - } -} - -// Sub atomically subtracts from the wrapped float64 and returns the new value. -func (f *Float64) Sub(s float64) float64 { - return f.Add(-s) -} - -// CAS is an atomic compare-and-swap. -func (f *Float64) CAS(old, new float64) bool { - return atomic.CompareAndSwapUint64(&f.v, math.Float64bits(old), math.Float64bits(new)) -} - -// Duration is an atomic wrapper around time.Duration -// https://godoc.org/time#Duration -type Duration struct { - v Int64 -} - -// NewDuration creates a Duration. -func NewDuration(d time.Duration) *Duration { - return &Duration{v: *NewInt64(int64(d))} -} - -// Load atomically loads the wrapped value. -func (d *Duration) Load() time.Duration { - return time.Duration(d.v.Load()) -} - -// Store atomically stores the passed value. -func (d *Duration) Store(n time.Duration) { - d.v.Store(int64(n)) -} - -// Add atomically adds to the wrapped time.Duration and returns the new value. -func (d *Duration) Add(n time.Duration) time.Duration { - return time.Duration(d.v.Add(int64(n))) -} - -// Sub atomically subtracts from the wrapped time.Duration and returns the new value. -func (d *Duration) Sub(n time.Duration) time.Duration { - return time.Duration(d.v.Sub(int64(n))) -} - -// Swap atomically swaps the wrapped time.Duration and returns the old value. -func (d *Duration) Swap(n time.Duration) time.Duration { - return time.Duration(d.v.Swap(int64(n))) -} - -// CAS is an atomic compare-and-swap. -func (d *Duration) CAS(old, new time.Duration) bool { - return d.v.CAS(int64(old), int64(new)) -} - -// Value shadows the type of the same name from sync/atomic -// https://godoc.org/sync/atomic#Value -type Value struct{ atomic.Value } diff --git a/vendor/go.uber.org/atomic/bool.go b/vendor/go.uber.org/atomic/bool.go new file mode 100644 index 000000000000..9cf1914b1f82 --- /dev/null +++ b/vendor/go.uber.org/atomic/bool.go @@ -0,0 +1,81 @@ +// @generated Code generated by gen-atomicwrapper. + +// Copyright (c) 2020 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package atomic + +import ( + "encoding/json" +) + +// Bool is an atomic type-safe wrapper for bool values. +type Bool struct { + _ nocmp // disallow non-atomic comparison + + v Uint32 +} + +var _zeroBool bool + +// NewBool creates a new Bool. +func NewBool(v bool) *Bool { + x := &Bool{} + if v != _zeroBool { + x.Store(v) + } + return x +} + +// Load atomically loads the wrapped bool. +func (x *Bool) Load() bool { + return truthy(x.v.Load()) +} + +// Store atomically stores the passed bool. +func (x *Bool) Store(v bool) { + x.v.Store(boolToInt(v)) +} + +// CAS is an atomic compare-and-swap for bool values. +func (x *Bool) CAS(o, n bool) bool { + return x.v.CAS(boolToInt(o), boolToInt(n)) +} + +// Swap atomically stores the given bool and returns the old +// value. +func (x *Bool) Swap(o bool) bool { + return truthy(x.v.Swap(boolToInt(o))) +} + +// MarshalJSON encodes the wrapped bool into JSON. +func (x *Bool) MarshalJSON() ([]byte, error) { + return json.Marshal(x.Load()) +} + +// UnmarshalJSON decodes a bool from JSON. +func (x *Bool) UnmarshalJSON(b []byte) error { + var v bool + if err := json.Unmarshal(b, &v); err != nil { + return err + } + x.Store(v) + return nil +} diff --git a/vendor/go.uber.org/atomic/bool_ext.go b/vendor/go.uber.org/atomic/bool_ext.go new file mode 100644 index 000000000000..c7bf7a827a81 --- /dev/null +++ b/vendor/go.uber.org/atomic/bool_ext.go @@ -0,0 +1,53 @@ +// Copyright (c) 2020 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package atomic + +import ( + "strconv" +) + +//go:generate bin/gen-atomicwrapper -name=Bool -type=bool -wrapped=Uint32 -pack=boolToInt -unpack=truthy -cas -swap -json -file=bool.go + +func truthy(n uint32) bool { + return n == 1 +} + +func boolToInt(b bool) uint32 { + if b { + return 1 + } + return 0 +} + +// Toggle atomically negates the Boolean and returns the previous value. +func (b *Bool) Toggle() bool { + for { + old := b.Load() + if b.CAS(old, !old) { + return old + } + } +} + +// String encodes the wrapped value as a string. +func (b *Bool) String() string { + return strconv.FormatBool(b.Load()) +} diff --git a/vendor/go.uber.org/atomic/doc.go b/vendor/go.uber.org/atomic/doc.go new file mode 100644 index 000000000000..ae7390ee6887 --- /dev/null +++ b/vendor/go.uber.org/atomic/doc.go @@ -0,0 +1,23 @@ +// Copyright (c) 2020 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +// Package atomic provides simple wrappers around numerics to enforce atomic +// access. +package atomic diff --git a/vendor/go.uber.org/atomic/duration.go b/vendor/go.uber.org/atomic/duration.go new file mode 100644 index 000000000000..027cfcb20bf5 --- /dev/null +++ b/vendor/go.uber.org/atomic/duration.go @@ -0,0 +1,82 @@ +// @generated Code generated by gen-atomicwrapper. + +// Copyright (c) 2020 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package atomic + +import ( + "encoding/json" + "time" +) + +// Duration is an atomic type-safe wrapper for time.Duration values. +type Duration struct { + _ nocmp // disallow non-atomic comparison + + v Int64 +} + +var _zeroDuration time.Duration + +// NewDuration creates a new Duration. +func NewDuration(v time.Duration) *Duration { + x := &Duration{} + if v != _zeroDuration { + x.Store(v) + } + return x +} + +// Load atomically loads the wrapped time.Duration. +func (x *Duration) Load() time.Duration { + return time.Duration(x.v.Load()) +} + +// Store atomically stores the passed time.Duration. +func (x *Duration) Store(v time.Duration) { + x.v.Store(int64(v)) +} + +// CAS is an atomic compare-and-swap for time.Duration values. +func (x *Duration) CAS(o, n time.Duration) bool { + return x.v.CAS(int64(o), int64(n)) +} + +// Swap atomically stores the given time.Duration and returns the old +// value. +func (x *Duration) Swap(o time.Duration) time.Duration { + return time.Duration(x.v.Swap(int64(o))) +} + +// MarshalJSON encodes the wrapped time.Duration into JSON. +func (x *Duration) MarshalJSON() ([]byte, error) { + return json.Marshal(x.Load()) +} + +// UnmarshalJSON decodes a time.Duration from JSON. +func (x *Duration) UnmarshalJSON(b []byte) error { + var v time.Duration + if err := json.Unmarshal(b, &v); err != nil { + return err + } + x.Store(v) + return nil +} diff --git a/vendor/go.uber.org/atomic/duration_ext.go b/vendor/go.uber.org/atomic/duration_ext.go new file mode 100644 index 000000000000..6273b66bd659 --- /dev/null +++ b/vendor/go.uber.org/atomic/duration_ext.go @@ -0,0 +1,40 @@ +// Copyright (c) 2020 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package atomic + +import "time" + +//go:generate bin/gen-atomicwrapper -name=Duration -type=time.Duration -wrapped=Int64 -pack=int64 -unpack=time.Duration -cas -swap -json -imports time -file=duration.go + +// Add atomically adds to the wrapped time.Duration and returns the new value. +func (d *Duration) Add(n time.Duration) time.Duration { + return time.Duration(d.v.Add(int64(n))) +} + +// Sub atomically subtracts from the wrapped time.Duration and returns the new value. +func (d *Duration) Sub(n time.Duration) time.Duration { + return time.Duration(d.v.Sub(int64(n))) +} + +// String encodes the wrapped value as a string. +func (d *Duration) String() string { + return d.Load().String() +} diff --git a/vendor/go.uber.org/atomic/error.go b/vendor/go.uber.org/atomic/error.go index 0489d19badbd..a6166fbea01e 100644 --- a/vendor/go.uber.org/atomic/error.go +++ b/vendor/go.uber.org/atomic/error.go @@ -1,4 +1,6 @@ -// Copyright (c) 2016 Uber Technologies, Inc. +// @generated Code generated by gen-atomicwrapper. + +// Copyright (c) 2020 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -20,36 +22,30 @@ package atomic -// Error is an atomic type-safe wrapper around Value for errors -type Error struct{ v Value } - -// errorHolder is non-nil holder for error object. -// atomic.Value panics on saving nil object, so err object needs to be -// wrapped with valid object first. -type errorHolder struct{ err error } +// Error is an atomic type-safe wrapper for error values. +type Error struct { + _ nocmp // disallow non-atomic comparison -// NewError creates new atomic error object -func NewError(err error) *Error { - e := &Error{} - if err != nil { - e.Store(err) - } - return e + v Value } -// Load atomically loads the wrapped error -func (e *Error) Load() error { - v := e.v.Load() - if v == nil { - return nil +var _zeroError error + +// NewError creates a new Error. +func NewError(v error) *Error { + x := &Error{} + if v != _zeroError { + x.Store(v) } + return x +} - eh := v.(errorHolder) - return eh.err +// Load atomically loads the wrapped error. +func (x *Error) Load() error { + return unpackError(x.v.Load()) } -// Store atomically stores error. -// NOTE: a holder object is allocated on each Store call. -func (e *Error) Store(err error) { - e.v.Store(errorHolder{err: err}) +// Store atomically stores the passed error. +func (x *Error) Store(v error) { + x.v.Store(packError(v)) } diff --git a/vendor/go.uber.org/atomic/error_ext.go b/vendor/go.uber.org/atomic/error_ext.go new file mode 100644 index 000000000000..ffe0be21cb01 --- /dev/null +++ b/vendor/go.uber.org/atomic/error_ext.go @@ -0,0 +1,39 @@ +// Copyright (c) 2020 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package atomic + +// atomic.Value panics on nil inputs, or if the underlying type changes. +// Stabilize by always storing a custom struct that we control. + +//go:generate bin/gen-atomicwrapper -name=Error -type=error -wrapped=Value -pack=packError -unpack=unpackError -file=error.go + +type packedError struct{ Value error } + +func packError(v error) interface{} { + return packedError{v} +} + +func unpackError(v interface{}) error { + if err, ok := v.(packedError); ok { + return err.Value + } + return nil +} diff --git a/vendor/go.uber.org/atomic/float64.go b/vendor/go.uber.org/atomic/float64.go new file mode 100644 index 000000000000..0719060207da --- /dev/null +++ b/vendor/go.uber.org/atomic/float64.go @@ -0,0 +1,76 @@ +// @generated Code generated by gen-atomicwrapper. + +// Copyright (c) 2020 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package atomic + +import ( + "encoding/json" + "math" +) + +// Float64 is an atomic type-safe wrapper for float64 values. +type Float64 struct { + _ nocmp // disallow non-atomic comparison + + v Uint64 +} + +var _zeroFloat64 float64 + +// NewFloat64 creates a new Float64. +func NewFloat64(v float64) *Float64 { + x := &Float64{} + if v != _zeroFloat64 { + x.Store(v) + } + return x +} + +// Load atomically loads the wrapped float64. +func (x *Float64) Load() float64 { + return math.Float64frombits(x.v.Load()) +} + +// Store atomically stores the passed float64. +func (x *Float64) Store(v float64) { + x.v.Store(math.Float64bits(v)) +} + +// CAS is an atomic compare-and-swap for float64 values. +func (x *Float64) CAS(o, n float64) bool { + return x.v.CAS(math.Float64bits(o), math.Float64bits(n)) +} + +// MarshalJSON encodes the wrapped float64 into JSON. +func (x *Float64) MarshalJSON() ([]byte, error) { + return json.Marshal(x.Load()) +} + +// UnmarshalJSON decodes a float64 from JSON. +func (x *Float64) UnmarshalJSON(b []byte) error { + var v float64 + if err := json.Unmarshal(b, &v); err != nil { + return err + } + x.Store(v) + return nil +} diff --git a/vendor/go.uber.org/atomic/float64_ext.go b/vendor/go.uber.org/atomic/float64_ext.go new file mode 100644 index 000000000000..927b1add74e5 --- /dev/null +++ b/vendor/go.uber.org/atomic/float64_ext.go @@ -0,0 +1,47 @@ +// Copyright (c) 2020 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package atomic + +import "strconv" + +//go:generate bin/gen-atomicwrapper -name=Float64 -type=float64 -wrapped=Uint64 -pack=math.Float64bits -unpack=math.Float64frombits -cas -json -imports math -file=float64.go + +// Add atomically adds to the wrapped float64 and returns the new value. +func (f *Float64) Add(s float64) float64 { + for { + old := f.Load() + new := old + s + if f.CAS(old, new) { + return new + } + } +} + +// Sub atomically subtracts from the wrapped float64 and returns the new value. +func (f *Float64) Sub(s float64) float64 { + return f.Add(-s) +} + +// String encodes the wrapped value as a string. +func (f *Float64) String() string { + // 'g' is the behavior for floats with %v. + return strconv.FormatFloat(f.Load(), 'g', -1, 64) +} diff --git a/vendor/go.uber.org/atomic/gen.go b/vendor/go.uber.org/atomic/gen.go new file mode 100644 index 000000000000..50d6b248588f --- /dev/null +++ b/vendor/go.uber.org/atomic/gen.go @@ -0,0 +1,26 @@ +// Copyright (c) 2020 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package atomic + +//go:generate bin/gen-atomicint -name=Int32 -wrapped=int32 -file=int32.go +//go:generate bin/gen-atomicint -name=Int64 -wrapped=int64 -file=int64.go +//go:generate bin/gen-atomicint -name=Uint32 -wrapped=uint32 -unsigned -file=uint32.go +//go:generate bin/gen-atomicint -name=Uint64 -wrapped=uint64 -unsigned -file=uint64.go diff --git a/vendor/go.uber.org/atomic/glide.lock b/vendor/go.uber.org/atomic/glide.lock deleted file mode 100644 index 3c72c59976da..000000000000 --- a/vendor/go.uber.org/atomic/glide.lock +++ /dev/null @@ -1,17 +0,0 @@ -hash: f14d51408e3e0e4f73b34e4039484c78059cd7fc5f4996fdd73db20dc8d24f53 -updated: 2016-10-27T00:10:51.16960137-07:00 -imports: [] -testImports: -- name: github.com/davecgh/go-spew - version: 5215b55f46b2b919f50a1df0eaa5886afe4e3b3d - subpackages: - - spew -- name: github.com/pmezard/go-difflib - version: d8ed2627bdf02c080bf22230dbb337003b7aba2d - subpackages: - - difflib -- name: github.com/stretchr/testify - version: d77da356e56a7428ad25149ca77381849a6a5232 - subpackages: - - assert - - require diff --git a/vendor/go.uber.org/atomic/glide.yaml b/vendor/go.uber.org/atomic/glide.yaml deleted file mode 100644 index 4cf608ec0f89..000000000000 --- a/vendor/go.uber.org/atomic/glide.yaml +++ /dev/null @@ -1,6 +0,0 @@ -package: go.uber.org/atomic -testImport: -- package: github.com/stretchr/testify - subpackages: - - assert - - require diff --git a/vendor/go.uber.org/atomic/go.mod b/vendor/go.uber.org/atomic/go.mod new file mode 100644 index 000000000000..daa7599fe191 --- /dev/null +++ b/vendor/go.uber.org/atomic/go.mod @@ -0,0 +1,8 @@ +module go.uber.org/atomic + +require ( + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/stretchr/testify v1.3.0 +) + +go 1.13 diff --git a/vendor/go.uber.org/atomic/go.sum b/vendor/go.uber.org/atomic/go.sum new file mode 100644 index 000000000000..4f76e62c1f3d --- /dev/null +++ b/vendor/go.uber.org/atomic/go.sum @@ -0,0 +1,9 @@ +github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= diff --git a/vendor/go.uber.org/atomic/int32.go b/vendor/go.uber.org/atomic/int32.go new file mode 100644 index 000000000000..18ae56493ee9 --- /dev/null +++ b/vendor/go.uber.org/atomic/int32.go @@ -0,0 +1,102 @@ +// @generated Code generated by gen-atomicint. + +// Copyright (c) 2020 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package atomic + +import ( + "encoding/json" + "strconv" + "sync/atomic" +) + +// Int32 is an atomic wrapper around int32. +type Int32 struct { + _ nocmp // disallow non-atomic comparison + + v int32 +} + +// NewInt32 creates a new Int32. +func NewInt32(i int32) *Int32 { + return &Int32{v: i} +} + +// Load atomically loads the wrapped value. +func (i *Int32) Load() int32 { + return atomic.LoadInt32(&i.v) +} + +// Add atomically adds to the wrapped int32 and returns the new value. +func (i *Int32) Add(n int32) int32 { + return atomic.AddInt32(&i.v, n) +} + +// Sub atomically subtracts from the wrapped int32 and returns the new value. +func (i *Int32) Sub(n int32) int32 { + return atomic.AddInt32(&i.v, -n) +} + +// Inc atomically increments the wrapped int32 and returns the new value. +func (i *Int32) Inc() int32 { + return i.Add(1) +} + +// Dec atomically decrements the wrapped int32 and returns the new value. +func (i *Int32) Dec() int32 { + return i.Sub(1) +} + +// CAS is an atomic compare-and-swap. +func (i *Int32) CAS(old, new int32) bool { + return atomic.CompareAndSwapInt32(&i.v, old, new) +} + +// Store atomically stores the passed value. +func (i *Int32) Store(n int32) { + atomic.StoreInt32(&i.v, n) +} + +// Swap atomically swaps the wrapped int32 and returns the old value. +func (i *Int32) Swap(n int32) int32 { + return atomic.SwapInt32(&i.v, n) +} + +// MarshalJSON encodes the wrapped int32 into JSON. +func (i *Int32) MarshalJSON() ([]byte, error) { + return json.Marshal(i.Load()) +} + +// UnmarshalJSON decodes JSON into the wrapped int32. +func (i *Int32) UnmarshalJSON(b []byte) error { + var v int32 + if err := json.Unmarshal(b, &v); err != nil { + return err + } + i.Store(v) + return nil +} + +// String encodes the wrapped value as a string. +func (i *Int32) String() string { + v := i.Load() + return strconv.FormatInt(int64(v), 10) +} diff --git a/vendor/go.uber.org/atomic/int64.go b/vendor/go.uber.org/atomic/int64.go new file mode 100644 index 000000000000..2bcbbfaa9532 --- /dev/null +++ b/vendor/go.uber.org/atomic/int64.go @@ -0,0 +1,102 @@ +// @generated Code generated by gen-atomicint. + +// Copyright (c) 2020 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package atomic + +import ( + "encoding/json" + "strconv" + "sync/atomic" +) + +// Int64 is an atomic wrapper around int64. +type Int64 struct { + _ nocmp // disallow non-atomic comparison + + v int64 +} + +// NewInt64 creates a new Int64. +func NewInt64(i int64) *Int64 { + return &Int64{v: i} +} + +// Load atomically loads the wrapped value. +func (i *Int64) Load() int64 { + return atomic.LoadInt64(&i.v) +} + +// Add atomically adds to the wrapped int64 and returns the new value. +func (i *Int64) Add(n int64) int64 { + return atomic.AddInt64(&i.v, n) +} + +// Sub atomically subtracts from the wrapped int64 and returns the new value. +func (i *Int64) Sub(n int64) int64 { + return atomic.AddInt64(&i.v, -n) +} + +// Inc atomically increments the wrapped int64 and returns the new value. +func (i *Int64) Inc() int64 { + return i.Add(1) +} + +// Dec atomically decrements the wrapped int64 and returns the new value. +func (i *Int64) Dec() int64 { + return i.Sub(1) +} + +// CAS is an atomic compare-and-swap. +func (i *Int64) CAS(old, new int64) bool { + return atomic.CompareAndSwapInt64(&i.v, old, new) +} + +// Store atomically stores the passed value. +func (i *Int64) Store(n int64) { + atomic.StoreInt64(&i.v, n) +} + +// Swap atomically swaps the wrapped int64 and returns the old value. +func (i *Int64) Swap(n int64) int64 { + return atomic.SwapInt64(&i.v, n) +} + +// MarshalJSON encodes the wrapped int64 into JSON. +func (i *Int64) MarshalJSON() ([]byte, error) { + return json.Marshal(i.Load()) +} + +// UnmarshalJSON decodes JSON into the wrapped int64. +func (i *Int64) UnmarshalJSON(b []byte) error { + var v int64 + if err := json.Unmarshal(b, &v); err != nil { + return err + } + i.Store(v) + return nil +} + +// String encodes the wrapped value as a string. +func (i *Int64) String() string { + v := i.Load() + return strconv.FormatInt(int64(v), 10) +} diff --git a/vendor/go.uber.org/atomic/nocmp.go b/vendor/go.uber.org/atomic/nocmp.go new file mode 100644 index 000000000000..a8201cb4a18e --- /dev/null +++ b/vendor/go.uber.org/atomic/nocmp.go @@ -0,0 +1,35 @@ +// Copyright (c) 2020 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package atomic + +// nocmp is an uncomparable struct. Embed this inside another struct to make +// it uncomparable. +// +// type Foo struct { +// nocmp +// // ... +// } +// +// This DOES NOT: +// +// - Disallow shallow copies of structs +// - Disallow comparison of pointers to uncomparable structs +type nocmp [0]func() diff --git a/vendor/go.uber.org/atomic/string.go b/vendor/go.uber.org/atomic/string.go index ede8136face1..225b7a2be0aa 100644 --- a/vendor/go.uber.org/atomic/string.go +++ b/vendor/go.uber.org/atomic/string.go @@ -1,4 +1,6 @@ -// Copyright (c) 2016 Uber Technologies, Inc. +// @generated Code generated by gen-atomicwrapper. + +// Copyright (c) 2020 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -20,30 +22,33 @@ package atomic -// String is an atomic type-safe wrapper around Value for strings. -type String struct{ v Value } +// String is an atomic type-safe wrapper for string values. +type String struct { + _ nocmp // disallow non-atomic comparison + + v Value +} + +var _zeroString string -// NewString creates a String. -func NewString(str string) *String { - s := &String{} - if str != "" { - s.Store(str) +// NewString creates a new String. +func NewString(v string) *String { + x := &String{} + if v != _zeroString { + x.Store(v) } - return s + return x } // Load atomically loads the wrapped string. -func (s *String) Load() string { - v := s.v.Load() - if v == nil { - return "" +func (x *String) Load() string { + if v := x.v.Load(); v != nil { + return v.(string) } - return v.(string) + return _zeroString } // Store atomically stores the passed string. -// Note: Converting the string to an interface{} to store in the Value -// requires an allocation. -func (s *String) Store(str string) { - s.v.Store(str) +func (x *String) Store(v string) { + x.v.Store(v) } diff --git a/vendor/go.uber.org/atomic/string_ext.go b/vendor/go.uber.org/atomic/string_ext.go new file mode 100644 index 000000000000..3a9558213d0d --- /dev/null +++ b/vendor/go.uber.org/atomic/string_ext.go @@ -0,0 +1,43 @@ +// Copyright (c) 2020 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package atomic + +//go:generate bin/gen-atomicwrapper -name=String -type=string -wrapped=Value -file=string.go + +// String returns the wrapped value. +func (s *String) String() string { + return s.Load() +} + +// MarshalText encodes the wrapped string into a textual form. +// +// This makes it encodable as JSON, YAML, XML, and more. +func (s *String) MarshalText() ([]byte, error) { + return []byte(s.Load()), nil +} + +// UnmarshalText decodes text and replaces the wrapped string with it. +// +// This makes it decodable from JSON, YAML, XML, and more. +func (s *String) UnmarshalText(b []byte) error { + s.Store(string(b)) + return nil +} diff --git a/vendor/go.uber.org/atomic/uint32.go b/vendor/go.uber.org/atomic/uint32.go new file mode 100644 index 000000000000..a973aba1a60b --- /dev/null +++ b/vendor/go.uber.org/atomic/uint32.go @@ -0,0 +1,102 @@ +// @generated Code generated by gen-atomicint. + +// Copyright (c) 2020 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package atomic + +import ( + "encoding/json" + "strconv" + "sync/atomic" +) + +// Uint32 is an atomic wrapper around uint32. +type Uint32 struct { + _ nocmp // disallow non-atomic comparison + + v uint32 +} + +// NewUint32 creates a new Uint32. +func NewUint32(i uint32) *Uint32 { + return &Uint32{v: i} +} + +// Load atomically loads the wrapped value. +func (i *Uint32) Load() uint32 { + return atomic.LoadUint32(&i.v) +} + +// Add atomically adds to the wrapped uint32 and returns the new value. +func (i *Uint32) Add(n uint32) uint32 { + return atomic.AddUint32(&i.v, n) +} + +// Sub atomically subtracts from the wrapped uint32 and returns the new value. +func (i *Uint32) Sub(n uint32) uint32 { + return atomic.AddUint32(&i.v, ^(n - 1)) +} + +// Inc atomically increments the wrapped uint32 and returns the new value. +func (i *Uint32) Inc() uint32 { + return i.Add(1) +} + +// Dec atomically decrements the wrapped uint32 and returns the new value. +func (i *Uint32) Dec() uint32 { + return i.Sub(1) +} + +// CAS is an atomic compare-and-swap. +func (i *Uint32) CAS(old, new uint32) bool { + return atomic.CompareAndSwapUint32(&i.v, old, new) +} + +// Store atomically stores the passed value. +func (i *Uint32) Store(n uint32) { + atomic.StoreUint32(&i.v, n) +} + +// Swap atomically swaps the wrapped uint32 and returns the old value. +func (i *Uint32) Swap(n uint32) uint32 { + return atomic.SwapUint32(&i.v, n) +} + +// MarshalJSON encodes the wrapped uint32 into JSON. +func (i *Uint32) MarshalJSON() ([]byte, error) { + return json.Marshal(i.Load()) +} + +// UnmarshalJSON decodes JSON into the wrapped uint32. +func (i *Uint32) UnmarshalJSON(b []byte) error { + var v uint32 + if err := json.Unmarshal(b, &v); err != nil { + return err + } + i.Store(v) + return nil +} + +// String encodes the wrapped value as a string. +func (i *Uint32) String() string { + v := i.Load() + return strconv.FormatUint(uint64(v), 10) +} diff --git a/vendor/go.uber.org/atomic/uint64.go b/vendor/go.uber.org/atomic/uint64.go new file mode 100644 index 000000000000..3b6c71fd5a37 --- /dev/null +++ b/vendor/go.uber.org/atomic/uint64.go @@ -0,0 +1,102 @@ +// @generated Code generated by gen-atomicint. + +// Copyright (c) 2020 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package atomic + +import ( + "encoding/json" + "strconv" + "sync/atomic" +) + +// Uint64 is an atomic wrapper around uint64. +type Uint64 struct { + _ nocmp // disallow non-atomic comparison + + v uint64 +} + +// NewUint64 creates a new Uint64. +func NewUint64(i uint64) *Uint64 { + return &Uint64{v: i} +} + +// Load atomically loads the wrapped value. +func (i *Uint64) Load() uint64 { + return atomic.LoadUint64(&i.v) +} + +// Add atomically adds to the wrapped uint64 and returns the new value. +func (i *Uint64) Add(n uint64) uint64 { + return atomic.AddUint64(&i.v, n) +} + +// Sub atomically subtracts from the wrapped uint64 and returns the new value. +func (i *Uint64) Sub(n uint64) uint64 { + return atomic.AddUint64(&i.v, ^(n - 1)) +} + +// Inc atomically increments the wrapped uint64 and returns the new value. +func (i *Uint64) Inc() uint64 { + return i.Add(1) +} + +// Dec atomically decrements the wrapped uint64 and returns the new value. +func (i *Uint64) Dec() uint64 { + return i.Sub(1) +} + +// CAS is an atomic compare-and-swap. +func (i *Uint64) CAS(old, new uint64) bool { + return atomic.CompareAndSwapUint64(&i.v, old, new) +} + +// Store atomically stores the passed value. +func (i *Uint64) Store(n uint64) { + atomic.StoreUint64(&i.v, n) +} + +// Swap atomically swaps the wrapped uint64 and returns the old value. +func (i *Uint64) Swap(n uint64) uint64 { + return atomic.SwapUint64(&i.v, n) +} + +// MarshalJSON encodes the wrapped uint64 into JSON. +func (i *Uint64) MarshalJSON() ([]byte, error) { + return json.Marshal(i.Load()) +} + +// UnmarshalJSON decodes JSON into the wrapped uint64. +func (i *Uint64) UnmarshalJSON(b []byte) error { + var v uint64 + if err := json.Unmarshal(b, &v); err != nil { + return err + } + i.Store(v) + return nil +} + +// String encodes the wrapped value as a string. +func (i *Uint64) String() string { + v := i.Load() + return strconv.FormatUint(uint64(v), 10) +} diff --git a/vendor/go.uber.org/atomic/value.go b/vendor/go.uber.org/atomic/value.go new file mode 100644 index 000000000000..671f3a382475 --- /dev/null +++ b/vendor/go.uber.org/atomic/value.go @@ -0,0 +1,31 @@ +// Copyright (c) 2020 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package atomic + +import "sync/atomic" + +// Value shadows the type of the same name from sync/atomic +// https://godoc.org/sync/atomic#Value +type Value struct { + atomic.Value + + _ nocmp // disallow non-atomic comparison +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 6264a8d51953..992a1eb6fda3 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -497,7 +497,7 @@ github.com/seccomp/libseccomp-golang # github.com/sirupsen/logrus v1.7.0 github.com/sirupsen/logrus github.com/sirupsen/logrus/hooks/syslog -# github.com/spf13/cobra v1.1.1 +# github.com/spf13/cobra v1.1.1 => github.com/Luap99/cobra v1.0.1-0.20201110155035-83a59186c706 github.com/spf13/cobra # github.com/spf13/pflag v1.0.5 github.com/spf13/pflag @@ -570,7 +570,7 @@ go.opencensus.io/internal go.opencensus.io/trace go.opencensus.io/trace/internal go.opencensus.io/trace/tracestate -# go.uber.org/atomic v1.4.0 +# go.uber.org/atomic v1.7.0 go.uber.org/atomic # golang.org/x/crypto v0.0.0-20200709230013-948cd5f35899 golang.org/x/crypto/blowfish