forked from cloudfoundry/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
target.go
97 lines (78 loc) · 2.16 KB
/
target.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package commands
import (
"cf/api"
"cf/configuration"
"cf/errors"
"cf/models"
"cf/requirements"
"cf/terminal"
"github.com/codegangsta/cli"
)
type Target struct {
ui terminal.UI
config configuration.ReadWriter
orgRepo api.OrganizationRepository
spaceRepo api.SpaceRepository
}
func NewTarget(ui terminal.UI,
config configuration.ReadWriter,
orgRepo api.OrganizationRepository,
spaceRepo api.SpaceRepository) (cmd Target) {
cmd.ui = ui
cmd.config = config
cmd.orgRepo = orgRepo
cmd.spaceRepo = spaceRepo
return
}
func (cmd Target) GetRequirements(requirementsFactory requirements.Factory, c *cli.Context) (reqs []requirements.Requirement, err error) {
if len(c.Args()) != 0 {
err = errors.New("incorrect usage")
cmd.ui.FailWithUsage(c, "target")
return
}
if c.String("o") != "" || c.String("s") != "" {
reqs = append(reqs, requirementsFactory.NewLoginRequirement())
}
return
}
func (cmd Target) Run(c *cli.Context) {
orgName := c.String("o")
spaceName := c.String("s")
if orgName != "" {
err := cmd.setOrganization(orgName)
if err != nil {
cmd.ui.Failed(err.Error())
}
}
if spaceName != "" {
err := cmd.setSpace(spaceName)
if err != nil {
cmd.ui.Failed(err.Error())
}
}
cmd.ui.ShowConfiguration(cmd.config)
return
}
func (cmd Target) setOrganization(orgName string) error {
// setting an org necessarily invalidates any space you had previously targeted
cmd.config.SetOrganizationFields(models.OrganizationFields{})
cmd.config.SetSpaceFields(models.SpaceFields{})
org, apiErr := cmd.orgRepo.FindByName(orgName)
if apiErr != nil {
return errors.NewWithFmt("Could not target org.\n%s", apiErr.Error())
}
cmd.config.SetOrganizationFields(org.OrganizationFields)
return nil
}
func (cmd Target) setSpace(spaceName string) error {
cmd.config.SetSpaceFields(models.SpaceFields{})
if !cmd.config.HasOrganization() {
return errors.New("An org must be targeted before targeting a space")
}
space, apiErr := cmd.spaceRepo.FindByName(spaceName)
if apiErr != nil {
return errors.NewWithFmt("Unable to access space %s.\n%s", spaceName, apiErr.Error())
}
cmd.config.SetSpaceFields(space.SpaceFields)
return nil
}