github.com/loggregator/cli@v6.33.1-0.20180224010324-82334f081791+incompatible/cf/commands/target.go (about)

     1  package commands
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"code.cloudfoundry.org/cli/cf/api/organizations"
     7  	"code.cloudfoundry.org/cli/cf/api/spaces"
     8  	"code.cloudfoundry.org/cli/cf/commandregistry"
     9  	"code.cloudfoundry.org/cli/cf/configuration/coreconfig"
    10  	"code.cloudfoundry.org/cli/cf/errors"
    11  	"code.cloudfoundry.org/cli/cf/flags"
    12  	. "code.cloudfoundry.org/cli/cf/i18n"
    13  	"code.cloudfoundry.org/cli/cf/models"
    14  	"code.cloudfoundry.org/cli/cf/requirements"
    15  	"code.cloudfoundry.org/cli/cf/terminal"
    16  )
    17  
    18  type Target struct {
    19  	ui        terminal.UI
    20  	config    coreconfig.ReadWriter
    21  	orgRepo   organizations.OrganizationRepository
    22  	spaceRepo spaces.SpaceRepository
    23  }
    24  
    25  func init() {
    26  	commandregistry.Register(&Target{})
    27  }
    28  
    29  func (cmd *Target) MetaData() commandregistry.CommandMetadata {
    30  	fs := make(map[string]flags.FlagSet)
    31  	fs["o"] = &flags.StringFlag{ShortName: "o", Usage: T("Organization")}
    32  	fs["s"] = &flags.StringFlag{ShortName: "s", Usage: T("Space")}
    33  
    34  	return commandregistry.CommandMetadata{
    35  		Name:        "target",
    36  		ShortName:   "t",
    37  		Description: T("Set or view the targeted org or space"),
    38  		Usage: []string{
    39  			T("CF_NAME target [-o ORG] [-s SPACE]"),
    40  		},
    41  		Flags: fs,
    42  	}
    43  }
    44  
    45  func (cmd *Target) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) ([]requirements.Requirement, error) {
    46  	usageReq := requirements.NewUsageRequirement(commandregistry.CLICommandUsagePresenter(cmd),
    47  		T("No argument required"),
    48  		func() bool {
    49  			return len(fc.Args()) != 0
    50  		},
    51  	)
    52  
    53  	reqs := []requirements.Requirement{
    54  		usageReq,
    55  		requirementsFactory.NewAPIEndpointRequirement(),
    56  	}
    57  
    58  	if fc.IsSet("o") || fc.IsSet("s") {
    59  		reqs = append(reqs, requirementsFactory.NewLoginRequirement())
    60  	}
    61  
    62  	return reqs, nil
    63  }
    64  
    65  func (cmd *Target) SetDependency(deps commandregistry.Dependency, _ bool) commandregistry.Command {
    66  	cmd.ui = deps.UI
    67  	cmd.config = deps.Config
    68  	cmd.orgRepo = deps.RepoLocator.GetOrganizationRepository()
    69  	cmd.spaceRepo = deps.RepoLocator.GetSpaceRepository()
    70  	return cmd
    71  }
    72  
    73  func (cmd *Target) Execute(c flags.FlagContext) error {
    74  	orgName := c.String("o")
    75  	spaceName := c.String("s")
    76  
    77  	if orgName != "" {
    78  		err := cmd.setOrganization(orgName)
    79  		if err != nil {
    80  			return err
    81  		} else if spaceName == "" {
    82  			spaceList, apiErr := cmd.getSpaceList()
    83  			if apiErr == nil && len(spaceList) == 1 {
    84  				cmd.setSpace(spaceList[0].Name)
    85  			}
    86  		}
    87  	}
    88  
    89  	if spaceName != "" {
    90  		err := cmd.setSpace(spaceName)
    91  		if err != nil {
    92  			return err
    93  		}
    94  	}
    95  
    96  	err := cmd.ui.ShowConfiguration(cmd.config)
    97  	if err != nil {
    98  		return err
    99  	}
   100  	cmd.ui.NotifyUpdateIfNeeded(cmd.config)
   101  	if !cmd.config.IsLoggedIn() {
   102  		return fmt.Errorf("") // Done on purpose, do not redo this in refactor code
   103  	}
   104  	return nil
   105  }
   106  
   107  func (cmd Target) setOrganization(orgName string) error {
   108  	// setting an org necessarily invalidates any space you had previously targeted
   109  	cmd.config.SetOrganizationFields(models.OrganizationFields{})
   110  	cmd.config.SetSpaceFields(models.SpaceFields{})
   111  
   112  	org, apiErr := cmd.orgRepo.FindByName(orgName)
   113  	if apiErr != nil {
   114  		return fmt.Errorf(T("Could not target org.\n{{.APIErr}}",
   115  			map[string]interface{}{"APIErr": apiErr.Error()}))
   116  	}
   117  
   118  	cmd.config.SetOrganizationFields(org.OrganizationFields)
   119  	return nil
   120  }
   121  
   122  func (cmd Target) setSpace(spaceName string) error {
   123  	cmd.config.SetSpaceFields(models.SpaceFields{})
   124  
   125  	if !cmd.config.HasOrganization() {
   126  		return errors.New(T("An org must be targeted before targeting a space"))
   127  	}
   128  
   129  	space, apiErr := cmd.spaceRepo.FindByName(spaceName)
   130  	if apiErr != nil {
   131  		return fmt.Errorf(T("Unable to access space {{.SpaceName}}.\n{{.APIErr}}",
   132  			map[string]interface{}{"SpaceName": spaceName, "APIErr": apiErr.Error()}))
   133  	}
   134  
   135  	cmd.config.SetSpaceFields(space.SpaceFields)
   136  	return nil
   137  }
   138  
   139  func (cmd Target) getSpaceList() ([]models.Space, error) {
   140  	spaceList := []models.Space{}
   141  	apiErr := cmd.spaceRepo.ListSpaces(
   142  		func(space models.Space) bool {
   143  			spaceList = append(spaceList, space)
   144  			return true
   145  		})
   146  	return spaceList, apiErr
   147  }