github.com/Azure/draft-classic@v0.16.0/cmd/draft/plugin_update.go (about) 1 package main 2 3 import ( 4 "errors" 5 "fmt" 6 "io" 7 "path/filepath" 8 "strings" 9 10 "github.com/spf13/cobra" 11 12 "github.com/Azure/draft/pkg/draft/draftpath" 13 "github.com/Azure/draft/pkg/plugin" 14 "github.com/Azure/draft/pkg/plugin/installer" 15 ) 16 17 type pluginUpdateCmd struct { 18 names []string 19 home draftpath.Home 20 out io.Writer 21 } 22 23 func newPluginUpdateCmd(out io.Writer) *cobra.Command { 24 pcmd := &pluginUpdateCmd{out: out} 25 cmd := &cobra.Command{ 26 Use: "update <plugin>...", 27 Short: "update one or more Draft plugins", 28 PreRunE: func(cmd *cobra.Command, args []string) error { 29 return pcmd.complete(args) 30 }, 31 RunE: func(cmd *cobra.Command, args []string) error { 32 return pcmd.run() 33 }, 34 } 35 return cmd 36 } 37 38 func (pcmd *pluginUpdateCmd) complete(args []string) error { 39 if len(args) == 0 { 40 return errors.New("please provide plugin name to update") 41 } 42 pcmd.names = args 43 pcmd.home = draftpath.Home(homePath()) 44 return nil 45 } 46 47 func (pcmd *pluginUpdateCmd) run() error { 48 installer.Debug = flagDebug 49 pluginsDir := pluginDirPath(pcmd.home) 50 debug("loading installed plugins from %s", pluginsDir) 51 plugins, err := findPlugins(pluginsDir) 52 if err != nil { 53 return err 54 } 55 var errorPlugins []string 56 57 for _, name := range pcmd.names { 58 if found := findPlugin(plugins, name); found != nil { 59 if err := updatePlugin(found, pcmd.home); err != nil { 60 errorPlugins = append(errorPlugins, fmt.Sprintf("Failed to update plugin %s, got error (%v)", name, err)) 61 } else { 62 fmt.Fprintf(pcmd.out, "Updated plugin: %s\n", name) 63 } 64 } else { 65 errorPlugins = append(errorPlugins, fmt.Sprintf("Plugin: %s not found", name)) 66 } 67 } 68 if len(errorPlugins) > 0 { 69 return fmt.Errorf(strings.Join(errorPlugins, "\n")) 70 } 71 return nil 72 } 73 74 func updatePlugin(p *plugin.Plugin, home draftpath.Home) error { 75 exactLocation, err := filepath.EvalSymlinks(p.Dir) 76 if err != nil { 77 return err 78 } 79 absExactLocation, err := filepath.Abs(exactLocation) 80 if err != nil { 81 return err 82 } 83 84 i, err := installer.FindSource(absExactLocation, home) 85 if err != nil { 86 return err 87 } 88 if err := installer.Update(i); err != nil { 89 return err 90 } 91 92 debug("loading plugin from %s", i.Path()) 93 updatedPlugin, err := plugin.LoadDir(i.Path()) 94 if err != nil { 95 return err 96 } 97 98 return runHook(updatedPlugin, plugin.Update) 99 }