This repository has been archived by the owner on Nov 22, 2022. It is now read-only.
/
set.go
187 lines (162 loc) · 5.41 KB
/
set.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
package set
import (
"errors"
"fmt"
"io/ioutil"
"regexp"
"strings"
"github.com/profclems/glab/pkg/iostreams"
"github.com/MakeNowJust/heredoc"
"github.com/profclems/glab/api"
"github.com/profclems/glab/commands/cmdutils"
"github.com/profclems/glab/internal/glrepo"
"github.com/spf13/cobra"
"github.com/xanzy/go-gitlab"
)
type SetOpts struct {
HTTPClient func() (*gitlab.Client, error)
IO *iostreams.IOStreams
BaseRepo func() (glrepo.Interface, error)
Key string
Value string
Type string
Scope string
Protected bool
Masked bool
Group string
ValueSet bool
}
func NewCmdSet(f *cmdutils.Factory, runE func(opts *SetOpts) error) *cobra.Command {
opts := &SetOpts{
IO: f.IO,
}
validKeyMsg := "A valid key must have no more than 255 characters; only A-Z, a-z, 0-9, and _ are allowed"
cmd := &cobra.Command{
Use: "set <key> <value>",
Short: "Create a new project or group variable",
Aliases: []string{"new", "create"},
Args: cobra.RangeArgs(1, 2),
Example: heredoc.Doc(`
$ glab variable set WITH_ARG "some value"
$ glab variable set FROM_FLAG -v "some value"
$ glab variable set FROM_ENV_WITH_ARG "${ENV_VAR}"
$ glab variable set FROM_ENV_WITH_FLAG -v"${ENV_VAR}"
$ glab variable set FROM_FILE < secret.txt
$ cat file.txt | glab variable set SERVER_TOKEN
$ cat token.txt | glab variable set GROUP_TOKEN -g mygroup --scope=prod
`),
RunE: func(cmd *cobra.Command, args []string) (err error) {
// Supports repo override
opts.HTTPClient = f.HttpClient
opts.BaseRepo = f.BaseRepo
opts.Key = args[0]
if !isValidKey(opts.Key) {
err = cmdutils.FlagError{Err: fmt.Errorf("invalid key provided.\n%s", validKeyMsg)}
return
}
if opts.Value != "" && len(args) == 2 {
if opts.Value != "" {
err = cmdutils.FlagError{Err: errors.New("specify value either by second positional argument or --value flag")}
return
}
opts.Value = args[1]
}
if cmd.Flags().Changed("scope") && opts.Group != "" {
err = cmdutils.FlagError{Err: errors.New("scope is not required for group variables")}
return
}
opts.ValueSet = cmd.Flags().Changed("value") || len(args) == 2
opts.Value, err = getValue(opts)
if err != nil {
return
}
if cmd.Flags().Changed("type") {
if opts.Type != "env_var" && opts.Type != "file" {
err = cmdutils.FlagError{Err: fmt.Errorf("invalid type: %s. --type must be one of `env_var` or `file`", opts.Type)}
return
}
}
if runE != nil {
err = runE(opts)
return
}
err = setRun(opts)
return
},
}
cmd.Flags().StringVarP(&opts.Value, "value", "v", "", "The value of a variable")
cmd.Flags().StringVarP(&opts.Type, "type", "t", "env_var", "The type of a variable: {env_var|file}")
cmd.Flags().StringVarP(&opts.Scope, "scope", "s", "*", "The environment_scope of the variable. All (*), or specific environments")
cmd.Flags().StringVarP(&opts.Group, "group", "g", "", "Set variable for a group")
cmd.Flags().BoolVarP(&opts.Masked, "masked", "m", false, "Whether the variable is masked")
cmd.Flags().BoolVarP(&opts.Protected, "protected", "p", false, "Whether the variable is protected")
return cmd
}
func setRun(opts *SetOpts) error {
c := opts.IO.Color()
httpClient, err := opts.HTTPClient()
if err != nil {
return err
}
if opts.Group != "" {
// creating project-level variable
createVarOpts := &gitlab.CreateGroupVariableOptions{
Key: gitlab.String(opts.Key),
Value: gitlab.String(opts.Value),
VariableType: gitlab.VariableType(gitlab.VariableTypeValue(opts.Type)),
Masked: gitlab.Bool(opts.Masked),
Protected: gitlab.Bool(opts.Protected),
}
_, err = api.CreateGroupVariable(httpClient, opts.Group, createVarOpts)
if err != nil {
return err
}
fmt.Fprintf(opts.IO.StdOut, "%s Created variable %s for group %s\n", c.GreenCheck(), opts.Key, opts.Group)
return nil
}
// creating group-level variable
baseRepo, err := opts.BaseRepo()
if err != nil {
return err
}
createVarOpts := &gitlab.CreateProjectVariableOptions{
Key: gitlab.String(opts.Key),
Value: gitlab.String(opts.Value),
EnvironmentScope: gitlab.String(opts.Scope),
Masked: gitlab.Bool(opts.Masked),
Protected: gitlab.Bool(opts.Protected),
VariableType: gitlab.VariableType(gitlab.VariableTypeValue(opts.Type)),
}
_, err = api.CreateProjectVariable(httpClient, baseRepo.FullName(), createVarOpts)
if err != nil {
return err
}
fmt.Fprintf(opts.IO.StdOut, "%s Created variable %s for %s\n", c.GreenCheck(), opts.Key, baseRepo.FullName())
return nil
}
func getValue(opts *SetOpts) (string, error) {
if opts.Value != "" || opts.ValueSet {
return opts.Value, nil
}
if opts.IO.IsInTTY {
return "", &cmdutils.FlagError{Err: errors.New("no value specified but nothing on STDIN")}
}
// read value from STDIN if not provided
defer opts.IO.In.Close()
value, err := ioutil.ReadAll(opts.IO.In)
if err != nil {
return "", fmt.Errorf("failed to read value from STDIN: %w", err)
}
return strings.TrimSpace(string(value)), nil
}
// isValidKey checks if a key is valid if it follows the following criteria:
// must have no more than 255 characters;
// only A-Z, a-z, 0-9, and _ are allowed
func isValidKey(key string) bool {
// check if key falls within range of 1-255
if len(key) > 255 || len(key) < 1 {
return false
}
keyRE := regexp.MustCompile(`^[A-Za-z0-9_]+$`)
return keyRE.MatchString(key)
}