-
Notifications
You must be signed in to change notification settings - Fork 32
/
envs.go
262 lines (229 loc) · 6.44 KB
/
envs.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
package cmd
import (
"context"
"fmt"
"strconv"
"strings"
"unicode/utf8"
"github.com/urfave/cli"
"github.com/arigatomachine/cli/api"
"github.com/arigatomachine/cli/config"
"github.com/arigatomachine/cli/errs"
"github.com/arigatomachine/cli/identity"
)
func init() {
envs := cli.Command{
Name: "envs",
Usage: "View and manipulate environments within an organization",
Category: "ORGANIZATIONS",
Subcommands: []cli.Command{
{
Name: "create",
Usage: "Create an environment for a service inside an organization or project",
Flags: []cli.Flag{
orgFlag("org to create environment for", false),
projectFlag("project to create environment for", false),
},
Action: chain(
ensureDaemon, ensureSession, loadDirPrefs, loadPrefDefaults,
checkRequiredFlags, createEnv,
),
},
{
Name: "list",
Usage: "List environments for an organization",
Flags: []cli.Flag{
orgFlag("org to show environments for", true),
projectFlag("project to shows environments for", false),
cli.BoolFlag{
Name: "all",
Usage: "Perform command on all projects",
},
},
Action: chain(
ensureDaemon, ensureSession, loadDirPrefs, loadPrefDefaults,
checkRequiredFlags, listEnvsCmd,
),
},
},
}
Cmds = append(Cmds, envs)
}
const envCreateFailed = "Could not create environment, please try again."
func createEnv(ctx *cli.Context) error {
cfg, err := config.LoadConfig()
if err != nil {
return errs.NewExitError(envCreateFailed)
}
args := ctx.Args()
environmentName := ""
if len(args) > 0 {
environmentName = args[0]
}
client := api.NewClient(cfg)
c := context.Background()
// Ask the user which org they want to use
org, oName, newOrg, err := SelectCreateOrg(c, client, ctx.String("org"))
if err != nil {
return handleSelectError(err, "Org selection failed.")
}
if org == nil && !newOrg {
fmt.Println("")
return errs.NewExitError("Org not found.")
}
if newOrg && oName == "" {
fmt.Println("")
return errs.NewExitError("Invalid org name.")
}
var orgID *identity.ID
if org != nil {
orgID = org.ID
}
// Ask the user which project they want to use
project, pName, newProject, err := SelectCreateProject(c, client, orgID, ctx.String("project"))
if err != nil {
return handleSelectError(err, "Project selection failed.")
}
if project == nil && !newProject {
fmt.Println("")
return errs.NewExitError("Project not found.")
}
if newProject && pName == "" {
fmt.Println("")
return errs.NewExitError("Invalid project name.")
}
label := "Environment name"
autoAccept := environmentName != ""
environmentName, err = NamePrompt(&label, environmentName, autoAccept)
if err != nil {
return handleSelectError(err, envCreateFailed)
}
// Create the org now if needed
if org == nil && newOrg {
org, err = createOrgByName(c, ctx, client, oName)
if err != nil {
fmt.Println("")
return err
}
orgID = org.ID
}
// Create the project now if needed
if project == nil && newProject {
project, err = createProjectByName(c, client, orgID, pName)
if err != nil {
fmt.Println("")
return err
}
}
// Create our new environment
fmt.Println("")
err = client.Environments.Create(c, orgID, project.ID, environmentName)
if err != nil {
if strings.Contains(err.Error(), "resource exists") {
return errs.NewExitError("Environment already exists.")
}
return errs.NewExitError(envCreateFailed)
}
fmt.Println("Environment " + environmentName + " created.")
return nil
}
const envListFailed = "Could not list envs, please try again."
func listEnvsCmd(ctx *cli.Context) error {
if !ctx.Bool("all") {
if len(ctx.String("project")) < 1 {
return errs.NewUsageExitError("Missing flags: --project", ctx)
}
}
// TODO: Error when profile flag is used with --all
cfg, err := config.LoadConfig()
if err != nil {
return err
}
client := api.NewClient(cfg)
c := context.Background()
// Look up the target org
var org *api.OrgResult
org, err = client.Orgs.GetByName(c, ctx.String("org"))
if err != nil {
return errs.NewExitError(envListFailed)
}
if org == nil {
return errs.NewExitError("Org not found.")
}
// Identify which projects to list envs for
var projectID identity.ID
var projects []api.ProjectResult
if ctx.Bool("all") {
// Pull all projects for the given orgID
projects, err = listProjects(&c, client, org.ID, nil)
if err != nil {
return errs.NewExitError(envListFailed)
}
} else {
// Retrieve only a single project by name
projectName := ctx.String("project")
projects, err = listProjects(&c, client, org.ID, &projectName)
if err != nil {
return errs.NewExitError(envListFailed)
}
if len(projects) == 1 {
projectID = *projects[0].ID
} else {
return errs.NewExitError("Project not found.")
}
}
// Retrieve envs for targeted org and project
envs, err := listEnvs(&c, client, org.ID, &projectID, nil)
if err != nil {
return errs.NewErrorExitError(envListFailed, err)
}
// Build map of envs to project
pMap := make(map[string]api.ProjectResult)
for _, project := range projects {
pMap[project.ID.String()] = project
}
eMap := make(map[string][]api.EnvironmentResult)
for _, env := range envs {
ID := env.Body.ProjectID.String()
eMap[ID] = append(eMap[ID], env)
}
// Build output of projects/envs
fmt.Println("")
for projectID, project := range pMap {
count := strconv.Itoa(len(eMap[projectID]))
title := project.Body.Name + " (" + count + ")"
fmt.Println(title)
fmt.Println(strings.Repeat("-", utf8.RuneCountInString(title)))
for _, env := range eMap[projectID] {
fmt.Println(env.Body.Name)
}
fmt.Println("")
}
return nil
}
func listEnvs(ctx *context.Context, client *api.Client, orgID, projID *identity.ID, name *string) ([]api.EnvironmentResult, error) {
c, client, err := NewAPIClient(ctx, client)
if err != nil {
return nil, cli.NewExitError(envListFailed, -1)
}
var orgIDs []*identity.ID
if orgID != nil {
orgIDs = []*identity.ID{orgID}
}
var projectIDs []*identity.ID
if projID != nil {
projectIDs = []*identity.ID{projID}
}
var names []string
if name != nil {
names = []string{*name}
}
return client.Environments.List(c, &orgIDs, &projectIDs, &names)
}
func listEnvsByProjectID(ctx *context.Context, client *api.Client, projectIDs []*identity.ID) ([]api.EnvironmentResult, error) {
c, client, err := NewAPIClient(ctx, client)
if err != nil {
return nil, cli.NewExitError(envListFailed, -1)
}
return client.Environments.List(c, nil, &projectIDs, nil)
}