-
Notifications
You must be signed in to change notification settings - Fork 246
Expand file tree
/
Copy pathcontext.go
More file actions
250 lines (191 loc) · 6.5 KB
/
context.go
File metadata and controls
250 lines (191 loc) · 6.5 KB
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
package cmd
import (
"bufio"
"fmt"
"io"
"os"
"strings"
"github.com/CircleCI-Public/circleci-cli/api"
"github.com/CircleCI-Public/circleci-cli/client"
"github.com/olekukonko/tablewriter"
"github.com/pkg/errors"
"github.com/CircleCI-Public/circleci-cli/settings"
"github.com/spf13/cobra"
)
func newContextCommand(config *settings.Config) *cobra.Command {
var cl *client.Client
initClient := func(cmd *cobra.Command, args []string) error {
cl = client.NewClient(config.Host, config.Endpoint, config.Token, config.Debug)
return validateToken(config)
}
command := &cobra.Command{
Use: "context",
Short: "Contexts provide a mechanism for securing and sharing environment variables across projects. The environment variables are defined as name/value pairs and are injected at runtime.",
}
listCommand := &cobra.Command{
Short: "List all contexts",
Use: "list <vcs-type> <org-name>",
PreRunE: initClient,
RunE: func(cmd *cobra.Command, args []string) error {
return listContexts(cl, args[0], args[1])
},
Args: cobra.ExactArgs(2),
}
showContextCommand := &cobra.Command{
Short: "Show a context",
Use: "show <vcs-type> <org-name> <context-name>",
PreRunE: initClient,
RunE: func(cmd *cobra.Command, args []string) error {
return showContext(cl, args[0], args[1], args[2])
},
Args: cobra.ExactArgs(3),
}
storeCommand := &cobra.Command{
Short: "Store a new environment variable in the named context. The value is read from stdin.",
Use: "store-secret <vcs-type> <org-name> <context-name> <secret name>",
PreRunE: initClient,
RunE: func(cmd *cobra.Command, args []string) error {
return storeEnvVar(cl, args[0], args[1], args[2], args[3])
},
Args: cobra.ExactArgs(4),
}
removeCommand := &cobra.Command{
Short: "Remove an environment variable from the named context",
Use: "remove-secret <vcs-type> <org-name> <context-name> <secret name>",
PreRunE: initClient,
RunE: func(cmd *cobra.Command, args []string) error {
return removeEnvVar(cl, args[0], args[1], args[2], args[3])
},
Args: cobra.ExactArgs(4),
}
createContextCommand := &cobra.Command{
Short: "Create a new context",
Use: "create <vcs-type> <org-name> <context-name>",
PreRunE: initClient,
RunE: func(cmd *cobra.Command, args []string) error {
return createContext(cl, args[0], args[1], args[2])
},
Args: cobra.ExactArgs(3),
}
force := false
deleteContextCommand := &cobra.Command{
Short: "Delete the named context",
Use: "delete <vcs-type> <org-name> <context-name>",
PreRunE: initClient,
RunE: func(cmd *cobra.Command, args []string) error {
return deleteContext(cl, force, args[0], args[1], args[2])
},
Args: cobra.ExactArgs(3),
}
deleteContextCommand.Flags().BoolVarP(&force, "force", "f", false, "Delete the context without asking for confirmation.")
command.AddCommand(listCommand)
command.AddCommand(showContextCommand)
command.AddCommand(storeCommand)
command.AddCommand(removeCommand)
command.AddCommand(createContextCommand)
command.AddCommand(deleteContextCommand)
return command
}
func listContexts(client *client.Client, vcs, org string) error {
contexts, err := api.ListContexts(client, org, vcs)
if err != nil {
return err
}
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Provider", "Organization", "Name", "Created At"})
for _, context := range contexts.Organization.Contexts.Edges {
table.Append([]string{
vcs,
org,
context.Node.Name,
context.Node.CreatedAt,
})
}
table.Render()
return nil
}
func contextByName(client *client.Client, vcsType, orgName, contextName string) (*api.CircleCIContext, error) {
contexts, err := api.ListContexts(client, orgName, vcsType)
if err != nil {
return nil, err
}
for _, c := range contexts.Organization.Contexts.Edges {
if c.Node.Name == contextName {
return &c.Node, nil
}
}
return nil, fmt.Errorf("Could not find a context named '%s' in the '%s' organization.", contextName, orgName)
}
func showContext(client *client.Client, vcsType, orgName, contextName string) error {
context, err := contextByName(client, vcsType, orgName, contextName)
if err != nil {
return err
}
fmt.Printf("Context: %s\n", context.Name)
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Environment Variable", "Value"})
for _, envVar := range context.Resources {
table.Append([]string{envVar.Variable, "••••" + envVar.TruncatedValue})
}
table.Render()
return nil
}
// ReadSecretValue reads a secret from a buffer
func ReadSecretValue() (string, error) {
stat, _ := os.Stdin.Stat()
buffSize, err := os.Stdin.Stat()
if err != nil {
return "", err
}
reader := bufio.NewReaderSize(os.Stdin, int(buffSize.Size()))
if (stat.Mode() & os.ModeCharDevice) == 0 {
bytes := make([]byte, buffSize.Size())
_, err := io.ReadFull(reader, bytes)
return string(bytes), err
}
fmt.Print("Enter secret value and press enter: ")
str, err := reader.ReadString('\n')
return strings.TrimRight(str, "\n"), err
}
func createContext(client *client.Client, vcsType, orgName, contextName string) error {
return api.CreateContext(client, vcsType, orgName, contextName)
}
func removeEnvVar(client *client.Client, vcsType, orgName, contextName, varName string) error {
context, err := contextByName(client, vcsType, orgName, contextName)
if err != nil {
return err
}
return api.DeleteEnvironmentVariable(client, context.ID, varName)
}
func storeEnvVar(client *client.Client, vcsType, orgName, contextName, varName string) error {
context, err := contextByName(client, vcsType, orgName, contextName)
if err != nil {
return err
}
secretValue, err := ReadSecretValue()
if err != nil {
return errors.Wrap(err, "Failed to read secret value from stdin")
}
return api.StoreEnvironmentVariable(client, context.ID, varName, secretValue)
}
func askForConfirmation(message string) bool {
fmt.Println(message)
var response string
if _, err := fmt.Scanln(&response); err != nil {
return false
}
return strings.HasPrefix(strings.ToLower(response), "y")
}
func deleteContext(client *client.Client, force bool, vcsType, orgName, contextName string) error {
context, err := contextByName(client, vcsType, orgName, contextName)
if err != nil {
return err
}
message := fmt.Sprintf("Are you sure that you want to delete this context: %s/%s %s (y/n)?",
vcsType, orgName, context.Name)
shouldDelete := force || askForConfirmation(message)
if !shouldDelete {
return errors.New("OK, cancelling")
}
return api.DeleteContext(client, context.ID)
}