File: cobra.go

package info (click to toggle)
docker.io 28.5.2%2Bdfsg3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 68,176 kB
  • sloc: sh: 5,867; makefile: 863; ansic: 184; python: 162; asm: 159
file content (78 lines) | stat: -rw-r--r-- 2,378 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package manager

import (
	"fmt"
	"os"
	"sync"

	"github.com/docker/cli/cli-plugins/metadata"
	"github.com/docker/cli/cli/config"
	"github.com/spf13/cobra"
)

var pluginCommandStubsOnce sync.Once

// AddPluginCommandStubs adds a stub cobra.Commands for each valid and invalid
// plugin. The command stubs will have several annotations added, see
// `CommandAnnotationPlugin*`.
func AddPluginCommandStubs(dockerCLI config.Provider, rootCmd *cobra.Command) (err error) {
	pluginCommandStubsOnce.Do(func() {
		var plugins []Plugin
		plugins, err = ListPlugins(dockerCLI, rootCmd)
		if err != nil {
			return
		}
		for _, p := range plugins {
			vendor := p.Vendor
			if vendor == "" {
				vendor = "unknown"
			}
			annotations := map[string]string{
				metadata.CommandAnnotationPlugin:        "true",
				metadata.CommandAnnotationPluginVendor:  vendor,
				metadata.CommandAnnotationPluginVersion: p.Version,
			}
			if p.Err != nil {
				annotations[metadata.CommandAnnotationPluginInvalid] = p.Err.Error()
			}
			rootCmd.AddCommand(&cobra.Command{
				Use:                p.Name,
				Short:              p.ShortDescription,
				Hidden:             p.Hidden,
				Run:                func(_ *cobra.Command, _ []string) {},
				Annotations:        annotations,
				DisableFlagParsing: true,
				RunE: func(cmd *cobra.Command, args []string) error {
					flags := rootCmd.PersistentFlags()
					flags.SetOutput(nil)
					perr := flags.Parse(args)
					if perr != nil {
						return err
					}
					if flags.Changed("help") {
						cmd.HelpFunc()(rootCmd, args)
						return nil
					}
					return fmt.Errorf("docker: unknown command: docker %s\n\nRun 'docker --help' for more information", cmd.Name())
				},
				ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
					// Delegate completion to plugin
					cargs := []string{p.Path, cobra.ShellCompRequestCmd, p.Name}
					cargs = append(cargs, args...)
					cargs = append(cargs, toComplete)
					os.Args = cargs
					runCommand, runErr := PluginRunCommand(dockerCLI, p.Name, cmd)
					if runErr != nil {
						return nil, cobra.ShellCompDirectiveError
					}
					runErr = runCommand.Run()
					if runErr == nil {
						os.Exit(0) // plugin already rendered complete data
					}
					return nil, cobra.ShellCompDirectiveError
				},
			})
		}
	})
	return err
}