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

     1  package organization
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"code.cloudfoundry.org/cli/cf"
     7  	"code.cloudfoundry.org/cli/cf/api/featureflags"
     8  	"code.cloudfoundry.org/cli/cf/api/organizations"
     9  	"code.cloudfoundry.org/cli/cf/api/quotas"
    10  	"code.cloudfoundry.org/cli/cf/commandregistry"
    11  	"code.cloudfoundry.org/cli/cf/commands/user"
    12  	"code.cloudfoundry.org/cli/cf/configuration/coreconfig"
    13  	"code.cloudfoundry.org/cli/cf/errors"
    14  	"code.cloudfoundry.org/cli/cf/flags"
    15  	. "code.cloudfoundry.org/cli/cf/i18n"
    16  	"code.cloudfoundry.org/cli/cf/models"
    17  	"code.cloudfoundry.org/cli/cf/requirements"
    18  	"code.cloudfoundry.org/cli/cf/terminal"
    19  )
    20  
    21  type CreateOrg struct {
    22  	ui            terminal.UI
    23  	config        coreconfig.Reader
    24  	orgRepo       organizations.OrganizationRepository
    25  	quotaRepo     quotas.QuotaRepository
    26  	orgRoleSetter user.OrgRoleSetter
    27  	flagRepo      featureflags.FeatureFlagRepository
    28  }
    29  
    30  func init() {
    31  	commandregistry.Register(&CreateOrg{})
    32  }
    33  
    34  func (cmd *CreateOrg) MetaData() commandregistry.CommandMetadata {
    35  	fs := make(map[string]flags.FlagSet)
    36  	fs["q"] = &flags.StringFlag{ShortName: "q", Usage: T("Quota to assign to the newly created org (excluding this option results in assignment of default quota)")}
    37  
    38  	return commandregistry.CommandMetadata{
    39  		Name:        "create-org",
    40  		ShortName:   "co",
    41  		Description: T("Create an org"),
    42  		Usage: []string{
    43  			T("CF_NAME create-org ORG"),
    44  		},
    45  		Flags: fs,
    46  	}
    47  }
    48  
    49  func (cmd *CreateOrg) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) ([]requirements.Requirement, error) {
    50  	if len(fc.Args()) != 1 {
    51  		cmd.ui.Failed(T("Incorrect Usage. Requires an argument\n\n") + commandregistry.Commands.CommandUsage("create-org"))
    52  		return nil, fmt.Errorf("Incorrect usage: %d arguments of %d required", len(fc.Args()), 1)
    53  	}
    54  
    55  	reqs := []requirements.Requirement{
    56  		requirementsFactory.NewLoginRequirement(),
    57  	}
    58  
    59  	return reqs, nil
    60  }
    61  
    62  func (cmd *CreateOrg) SetDependency(deps commandregistry.Dependency, pluginCall bool) commandregistry.Command {
    63  	cmd.ui = deps.UI
    64  	cmd.config = deps.Config
    65  	cmd.orgRepo = deps.RepoLocator.GetOrganizationRepository()
    66  	cmd.quotaRepo = deps.RepoLocator.GetQuotaRepository()
    67  	cmd.flagRepo = deps.RepoLocator.GetFeatureFlagRepository()
    68  
    69  	//get command from registry for dependency
    70  	commandDep := commandregistry.Commands.FindCommand("set-org-role")
    71  	commandDep = commandDep.SetDependency(deps, false)
    72  	cmd.orgRoleSetter = commandDep.(user.OrgRoleSetter)
    73  
    74  	return cmd
    75  }
    76  
    77  func (cmd *CreateOrg) Execute(c flags.FlagContext) error {
    78  	name := c.Args()[0]
    79  	cmd.ui.Say(T("Creating org {{.OrgName}} as {{.Username}}...",
    80  		map[string]interface{}{
    81  			"OrgName":  terminal.EntityNameColor(name),
    82  			"Username": terminal.EntityNameColor(cmd.config.Username())}))
    83  
    84  	org := models.Organization{OrganizationFields: models.OrganizationFields{Name: name}}
    85  
    86  	quotaName := c.String("q")
    87  	if quotaName != "" {
    88  		quota, err := cmd.quotaRepo.FindByName(quotaName)
    89  		if err != nil {
    90  			return err
    91  		}
    92  
    93  		org.QuotaDefinition.GUID = quota.GUID
    94  	}
    95  
    96  	err := cmd.orgRepo.Create(org)
    97  	if err != nil {
    98  		if apiErr, ok := err.(errors.HTTPError); ok && apiErr.ErrorCode() == errors.OrganizationNameTaken {
    99  			cmd.ui.Ok()
   100  			cmd.ui.Warn(T("Org {{.OrgName}} already exists",
   101  				map[string]interface{}{"OrgName": name}))
   102  			return nil
   103  		}
   104  
   105  		return err
   106  	}
   107  
   108  	cmd.ui.Ok()
   109  
   110  	setRolesByUsernameFlag, err := cmd.flagRepo.FindByName("set_roles_by_username")
   111  	if err != nil {
   112  		cmd.ui.Warn(T("Warning: accessing feature flag 'set_roles_by_username'") + " - " + err.Error() + "\n" + T("Skip assigning org role to user"))
   113  	}
   114  
   115  	if setRolesByUsernameFlag.Enabled {
   116  		org, err := cmd.orgRepo.FindByName(name)
   117  		if err != nil {
   118  			return errors.New(T("Error accessing org {{.OrgName}} for GUID': ", map[string]interface{}{"Orgname": name}) + err.Error() + "\n" + T("Skip assigning org role to user"))
   119  		}
   120  
   121  		cmd.ui.Say("")
   122  		cmd.ui.Say(T("Assigning role {{.Role}} to user {{.CurrentUser}} in org {{.TargetOrg}} ...",
   123  			map[string]interface{}{
   124  				"Role":        terminal.EntityNameColor("OrgManager"),
   125  				"CurrentUser": terminal.EntityNameColor(cmd.config.Username()),
   126  				"TargetOrg":   terminal.EntityNameColor(name),
   127  			}))
   128  
   129  		err = cmd.orgRoleSetter.SetOrgRole(org.GUID, models.RoleOrgManager, "", cmd.config.Username())
   130  		if err != nil {
   131  			return errors.New(T("Failed assigning org role to user: ") + err.Error())
   132  		}
   133  
   134  		cmd.ui.Ok()
   135  	}
   136  
   137  	cmd.ui.Say(T("\nTIP: Use '{{.Command}}' to target new org",
   138  		map[string]interface{}{"Command": terminal.CommandColor(cf.Name + " target -o \"" + name + "\"")}))
   139  	return nil
   140  }