AddPluginCommandStubs adds a stub cobra.Commands for each valid and invalid plugin. The command stubs will have several annotations added, see `CommandAnnotationPlugin*`.
(dockerCLI config.Provider, rootCmd *cobra.Command)
| 16 | // plugin. The command stubs will have several annotations added, see |
| 17 | // `CommandAnnotationPlugin*`. |
| 18 | func AddPluginCommandStubs(dockerCLI config.Provider, rootCmd *cobra.Command) (err error) { |
| 19 | pluginCommandStubsOnce.Do(func() { |
| 20 | var plugins []Plugin |
| 21 | plugins, err = ListPlugins(dockerCLI, rootCmd) |
| 22 | if err != nil { |
| 23 | return |
| 24 | } |
| 25 | for _, p := range plugins { |
| 26 | vendor := p.Vendor |
| 27 | if vendor == "" { |
| 28 | vendor = "unknown" |
| 29 | } |
| 30 | annotations := map[string]string{ |
| 31 | metadata.CommandAnnotationPlugin: "true", |
| 32 | metadata.CommandAnnotationPluginVendor: vendor, |
| 33 | metadata.CommandAnnotationPluginVersion: p.Version, |
| 34 | } |
| 35 | if p.Err != nil { |
| 36 | annotations[metadata.CommandAnnotationPluginInvalid] = p.Err.Error() |
| 37 | } |
| 38 | rootCmd.AddCommand(&cobra.Command{ |
| 39 | Use: p.Name, |
| 40 | Short: p.ShortDescription, |
| 41 | Hidden: p.Hidden, |
| 42 | Run: func(_ *cobra.Command, _ []string) {}, |
| 43 | Annotations: annotations, |
| 44 | DisableFlagParsing: true, |
| 45 | RunE: func(cmd *cobra.Command, args []string) error { |
| 46 | flags := rootCmd.PersistentFlags() |
| 47 | flags.SetOutput(nil) |
| 48 | if err := flags.Parse(args); err != nil { |
| 49 | return err |
| 50 | } |
| 51 | if flags.Changed("help") { |
| 52 | cmd.HelpFunc()(rootCmd, args) |
| 53 | return nil |
| 54 | } |
| 55 | return fmt.Errorf("docker: unknown command: docker %s\n\nRun 'docker --help' for more information", cmd.Name()) |
| 56 | }, |
| 57 | ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { |
| 58 | // Delegate completion to plugin |
| 59 | cargs := []string{p.Path, cobra.ShellCompRequestCmd, p.Name} //nolint:prealloc // no need to over-complicate things. |
| 60 | cargs = append(cargs, args...) |
| 61 | cargs = append(cargs, toComplete) |
| 62 | origArgs := os.Args |
| 63 | os.Args = cargs |
| 64 | defer func() { |
| 65 | os.Args = origArgs |
| 66 | }() |
| 67 | runCommand, runErr := PluginRunCommand(dockerCLI, p.Name, cmd) |
| 68 | if runErr != nil { |
| 69 | return nil, cobra.ShellCompDirectiveError |
| 70 | } |
| 71 | runErr = runCommand.Run() |
| 72 | if runErr == nil { |
| 73 | os.Exit(0) // plugin already rendered complete data |
| 74 | } |
| 75 | return nil, cobra.ShellCompDirectiveError |
searching dependent graphs…