github.com/mook-as/cf-cli@v7.0.0-beta.28.0.20200120190804-b91c115fae48+incompatible/cf/util/testhelpers/commands/runner.go (about)

     1  package commands
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  
     7  	"code.cloudfoundry.org/cli/cf/commandregistry"
     8  	"code.cloudfoundry.org/cli/cf/flags"
     9  	"code.cloudfoundry.org/cli/cf/requirements"
    10  	testterm "code.cloudfoundry.org/cli/cf/util/testhelpers/terminal"
    11  )
    12  
    13  type RunCommandResult int
    14  
    15  const (
    16  	RunCommandResultSuccess = iota
    17  )
    18  
    19  func RunCLICommand(cmdName string, args []string, requirementsFactory requirements.Factory, updateFunc func(bool), pluginCall bool, ui *testterm.FakeUI) bool {
    20  	updateFunc(pluginCall)
    21  	cmd := commandregistry.Commands.FindCommand(cmdName)
    22  	context := flags.NewFlagContext(cmd.MetaData().Flags)
    23  	context.SkipFlagParsing(cmd.MetaData().SkipFlagParsing)
    24  	err := context.Parse(args...)
    25  	if err != nil {
    26  		fmt.Println("ERROR:", err)
    27  		os.Exit(1)
    28  	}
    29  
    30  	var requirements []requirements.Requirement
    31  	requirements, err = cmd.Requirements(requirementsFactory, context)
    32  	if err != nil {
    33  		return false
    34  	}
    35  
    36  	for _, requirement := range requirements {
    37  		if err = requirement.Execute(); err != nil {
    38  			ui.Failed(err.Error())
    39  			return false
    40  		}
    41  	}
    42  
    43  	err = cmd.Execute(context)
    44  	if err != nil {
    45  		ui.Failed(err.Error())
    46  		return false
    47  	}
    48  
    49  	return true
    50  }
    51  
    52  func RunCLICommandWithoutDependency(cmdName string, args []string, requirementsFactory requirements.Factory, ui *testterm.FakeUI) bool {
    53  	cmd := commandregistry.Commands.FindCommand(cmdName)
    54  	context := flags.NewFlagContext(cmd.MetaData().Flags)
    55  	context.SkipFlagParsing(cmd.MetaData().SkipFlagParsing)
    56  	err := context.Parse(args...)
    57  	if err != nil {
    58  		fmt.Println("ERROR:", err)
    59  		os.Exit(1)
    60  	}
    61  
    62  	defer func() {
    63  		errMsg := recover()
    64  
    65  		if errMsg != nil {
    66  			panic(errMsg)
    67  		}
    68  	}()
    69  
    70  	requirements, err := cmd.Requirements(requirementsFactory, context)
    71  	if err != nil {
    72  		return false
    73  	}
    74  
    75  	for _, requirement := range requirements {
    76  		if err = requirement.Execute(); err != nil {
    77  			return false
    78  		}
    79  	}
    80  
    81  	err = cmd.Execute(context)
    82  	if err != nil {
    83  		ui.Failed(err.Error())
    84  	}
    85  
    86  	return true
    87  }