github.com/Azure/draft-classic@v0.16.0/cmd/draft/plugin_remove.go (about)

     1  package main
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"io"
     7  	"os"
     8  	"strings"
     9  
    10  	"github.com/Azure/draft/pkg/draft/draftpath"
    11  	"github.com/Azure/draft/pkg/plugin"
    12  
    13  	"github.com/spf13/cobra"
    14  )
    15  
    16  type pluginRemoveCmd struct {
    17  	names []string
    18  	home  draftpath.Home
    19  	out   io.Writer
    20  }
    21  
    22  func newPluginRemoveCmd(out io.Writer) *cobra.Command {
    23  	pcmd := &pluginRemoveCmd{out: out}
    24  	cmd := &cobra.Command{
    25  		Use:   "remove <plugin>...",
    26  		Short: "remove one or more Draft plugins",
    27  		PreRunE: func(cmd *cobra.Command, args []string) error {
    28  			return pcmd.complete(args)
    29  		},
    30  		RunE: func(cmd *cobra.Command, args []string) error {
    31  			return pcmd.run()
    32  		},
    33  	}
    34  	return cmd
    35  }
    36  
    37  func (pcmd *pluginRemoveCmd) complete(args []string) error {
    38  	if len(args) == 0 {
    39  		return errors.New("please provide plugin name to remove")
    40  	}
    41  	pcmd.names = args
    42  	pcmd.home = draftpath.Home(homePath())
    43  	return nil
    44  }
    45  
    46  func (pcmd *pluginRemoveCmd) run() error {
    47  	debug("loading installed plugins from %s", pluginDirPath(pcmd.home))
    48  	plugins, err := findPlugins(pluginDirPath(pcmd.home))
    49  	if err != nil {
    50  		return err
    51  	}
    52  	var errorPlugins []string
    53  	for _, name := range pcmd.names {
    54  		if found := findPlugin(plugins, name); found != nil {
    55  			if err := removePlugin(found); err != nil {
    56  				errorPlugins = append(errorPlugins, fmt.Sprintf("Failed to remove plugin %s, got error (%v)", name, err))
    57  			} else {
    58  				fmt.Fprintf(pcmd.out, "Removed plugin: %s\n", name)
    59  			}
    60  		} else {
    61  			errorPlugins = append(errorPlugins, fmt.Sprintf("Plugin: %s not found", name))
    62  		}
    63  	}
    64  	if len(errorPlugins) > 0 {
    65  		return fmt.Errorf(strings.Join(errorPlugins, "\n"))
    66  	}
    67  	return nil
    68  }
    69  
    70  func removePlugin(p *plugin.Plugin) error {
    71  	if err := os.RemoveAll(p.Dir); err != nil {
    72  		return err
    73  	}
    74  	return runHook(p, plugin.Delete)
    75  }
    76  
    77  func findPlugin(plugins []*plugin.Plugin, name string) *plugin.Plugin {
    78  	for _, p := range plugins {
    79  		if p.Metadata.Name == name {
    80  			return p
    81  		}
    82  	}
    83  	return nil
    84  }