github.com/lukasheimann/cloudfoundrycli@v7.1.0+incompatible/actor/pluginaction/uninstall.go (about)

     1  package pluginaction
     2  
     3  import (
     4  	"os"
     5  	"os/exec"
     6  	"time"
     7  
     8  	"code.cloudfoundry.org/cli/actor/actionerror"
     9  )
    10  
    11  //go:generate counterfeiter . PluginUninstaller
    12  
    13  type PluginUninstaller interface {
    14  	Run(pluginPath string, command string) error
    15  }
    16  
    17  func (actor Actor) UninstallPlugin(uninstaller PluginUninstaller, name string) error {
    18  	plugin, exist := actor.config.GetPlugin(name)
    19  	if !exist {
    20  		return actionerror.PluginNotFoundError{PluginName: name}
    21  	}
    22  
    23  	var binaryErr error
    24  
    25  	if actor.FileExists(plugin.Location) {
    26  		err := uninstaller.Run(plugin.Location, "CLI-MESSAGE-UNINSTALL")
    27  		if err != nil {
    28  			switch err.(type) {
    29  			case *exec.ExitError:
    30  				binaryErr = actionerror.PluginExecuteError{
    31  					Err: err,
    32  				}
    33  			case *os.PathError:
    34  				binaryErr = actionerror.PluginExecuteError{
    35  					Err: err,
    36  				}
    37  			default:
    38  				return err
    39  			}
    40  		}
    41  
    42  		// No test for sleeping for 500 ms for parity with pre-refactored behavior.
    43  		time.Sleep(500 * time.Millisecond)
    44  
    45  		removed := false
    46  		for i := 0; i < 50; i++ {
    47  			err = os.Remove(plugin.Location)
    48  			if err == nil {
    49  				removed = true
    50  				break
    51  			}
    52  
    53  			if os.IsNotExist(err) {
    54  				removed = true
    55  				break
    56  			}
    57  
    58  			if err != nil && !os.IsNotExist(err) {
    59  				if _, isPathError := err.(*os.PathError); isPathError {
    60  					time.Sleep(50 * time.Millisecond)
    61  				} else {
    62  					return err
    63  				}
    64  			}
    65  		}
    66  
    67  		if !removed {
    68  			binaryErr = actionerror.PluginBinaryRemoveFailedError{
    69  				Err: err,
    70  			}
    71  		}
    72  	}
    73  
    74  	actor.config.RemovePlugin(name)
    75  	err := actor.config.WritePluginConfig()
    76  	if err != nil {
    77  		return err
    78  	}
    79  
    80  	return binaryErr
    81  }