File: export.go

package info (click to toggle)
glab 1.53.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 20,936 kB
  • sloc: sh: 295; makefile: 153; perl: 99; ruby: 68; javascript: 67
file content (293 lines) | stat: -rw-r--r-- 8,471 bytes parent folder | download
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
package export

import (
	"encoding/json"
	"fmt"
	"io"
	"os"
	"regexp"
	"strings"

	"github.com/MakeNowJust/heredoc/v2"
	"github.com/spf13/cobra"
	gitlab "gitlab.com/gitlab-org/api/client-go"
	"gitlab.com/gitlab-org/cli/api"
	"gitlab.com/gitlab-org/cli/commands/cmdutils"
	"gitlab.com/gitlab-org/cli/commands/flag"
	"gitlab.com/gitlab-org/cli/internal/glrepo"
	"gitlab.com/gitlab-org/cli/pkg/iostreams"
)

type ExportOpts struct {
	HTTPClient func() (*gitlab.Client, error)
	IO         *iostreams.IOStreams
	BaseRepo   func() (glrepo.Interface, error)

	ValueSet     bool
	Group        string
	OutputFormat string
	Scope        string

	Page    int
	PerPage int
}

func marshalJson(variables interface{}) ([]byte, error) {
	res, err := json.MarshalIndent(variables, "", "  ")
	if err != nil {
		return nil, err
	}

	return res, nil
}

func NewCmdExport(f *cmdutils.Factory, runE func(opts *ExportOpts) error) *cobra.Command {
	opts := &ExportOpts{
		IO: f.IO,
	}

	cmd := &cobra.Command{
		Use:     "export",
		Short:   "Export variables from a project or group.",
		Aliases: []string{"ex"},
		Args:    cobra.ExactArgs(0),
		Example: heredoc.Doc(`
                        glab variable export
                        glab variable export --per-page 1000 --page 1
                        glab variable export --group gitlab-org
                        glab variable export --group gitlab-org --per-page 1000 --page 1
                `),
		RunE: func(cmd *cobra.Command, args []string) (err error) {
			// Supports repo override
			opts.HTTPClient = f.HttpClient
			opts.BaseRepo = f.BaseRepo

			group, err := flag.GroupOverride(cmd)
			if err != nil {
				return err
			}
			opts.Group = group

			if runE != nil {
				err = runE(opts)
				return
			}
			err = exportRun(opts)
			return
		},
	}

	cmdutils.EnableRepoOverride(cmd, f)
	cmd.PersistentFlags().StringP("group", "g", "", "Select a group or subgroup. Ignored if a repository argument is set.")
	cmd.Flags().IntVarP(&opts.Page, "page", "p", 1, "Page number.")
	cmd.Flags().IntVarP(&opts.PerPage, "per-page", "P", 100, "Number of items to list per page.")
	cmd.Flags().StringVarP(&opts.OutputFormat, "format", "F", "json", "Format of output: json, export, env.")
	cmd.Flags().StringVarP(&opts.Scope, "scope", "s", "*", "The environment_scope of the variables. Values: '*' (default), or specific environments.")

	return cmd
}

func exportRun(opts *ExportOpts) error {
	var out io.Writer = os.Stdout
	if opts.IO != nil && opts.IO.StdOut != nil {
		out = opts.IO.StdOut
	}

	httpClient, err := opts.HTTPClient()
	if err != nil {
		return err
	}

	repo, err := opts.BaseRepo()
	if err != nil {
		return err
	}

	if opts.Group != "" {
		createVarOpts := &gitlab.ListGroupVariablesOptions{Page: opts.Page, PerPage: opts.PerPage}
		groupVariables, err := api.ListGroupVariables(httpClient, opts.Group, createVarOpts)
		if err != nil {
			return err
		}

		opts.IO.Logf("Exporting variables from the %s group:\n", opts.Group)

		if len(groupVariables) == 0 {
			return nil
		}

		return printGroupVariables(groupVariables, opts, out)

	} else {
		createVarOpts := &gitlab.ListProjectVariablesOptions{Page: opts.Page, PerPage: opts.PerPage}
		projectVariables, err := api.ListProjectVariables(httpClient, repo.FullName(), createVarOpts)
		if err != nil {
			return err
		}

		opts.IO.Logf("Exporting variables from the %s project:\n", repo.FullName())

		if len(projectVariables) == 0 {
			return nil
		}

		return printProjectVariables(projectVariables, opts, out)
	}
}

func matchesScope(varScope, optScope string) bool {
	if varScope == "*" || optScope == "*" {
		return true
	}
	if varScope == optScope {
		return true
	}
	if strings.Contains(varScope, "*") {
		varPattern := "^" + regexp.QuoteMeta(varScope) + "$"
		optPattern := "^" + regexp.QuoteMeta(optScope) + "$"

		varPattern = strings.ReplaceAll(varPattern, `\*`, ".*")
		optPattern = strings.ReplaceAll(optPattern, `\*`, ".*")

		matchesVar, _ := regexp.MatchString(varPattern, optScope)
		matchesOpt, _ := regexp.MatchString(optPattern, varScope)

		return matchesVar || matchesOpt
	}
	return false
}

func isValidEnvironmentScope(optScope string) bool {
	pattern := `^[a-zA-Z0-9\s\-_/${}\x20]+$`
	re, _ := regexp.Compile(pattern)
	matched := re.MatchString(optScope)
	return matched || optScope == "*"
}

func printGroupVariables(variables []*gitlab.GroupVariable, opts *ExportOpts, out io.Writer) error {
	if !isValidEnvironmentScope((opts.Scope)) {
		return fmt.Errorf("invalid environment scope: %s", opts.Scope)
	}

	writtenKeys := make([]string, 0)
	switch opts.OutputFormat {
	case "env":
		for _, variable := range variables {
			if matchesScope(variable.EnvironmentScope, opts.Scope) {
				if !strings.Contains(variable.EnvironmentScope, "*") {
					fmt.Fprintf(out, "%s=%s\n", variable.Key, variable.Value)
					writtenKeys = append(writtenKeys, variable.Key)
				}
			}
		}
		keysMap := CreateWrittenKeysMap(writtenKeys)
		for _, variable := range variables {
			if matchesScope(variable.EnvironmentScope, opts.Scope) {
				if !(keysMap[variable.Key]) && (strings.Contains(variable.EnvironmentScope, "*")) {
					fmt.Fprintf(out, "%s=%s\n", variable.Key, variable.Value)
				}
			}
		}
	case "export":
		for _, variable := range variables {
			if matchesScope(variable.EnvironmentScope, opts.Scope) {
				if !strings.Contains(variable.EnvironmentScope, "*") {
					fmt.Fprintf(out, "export %s=%s\n", variable.Key, variable.Value)
					writtenKeys = append(writtenKeys, variable.Key)
				}
			}
		}
		keysMap := CreateWrittenKeysMap(writtenKeys)
		for _, variable := range variables {
			if matchesScope(variable.EnvironmentScope, opts.Scope) {
				if !(keysMap[variable.Key]) && (strings.Contains(variable.EnvironmentScope, "*")) {
					fmt.Fprintf(out, "export %s=%s\n", variable.Key, variable.Value)
				}
			}
		}
	case "json":
		filteredVariables := make([]*gitlab.GroupVariable, 0)
		for _, variable := range variables {
			if matchesScope(variable.EnvironmentScope, opts.Scope) {
				filteredVariables = append(filteredVariables, variable)
			}
		}
		res, err := marshalJson(filteredVariables)
		if err != nil {
			return err
		}
		fmt.Fprintln(out, string(res))
	default:
		return fmt.Errorf("unsupported output format: %s", opts.OutputFormat)
	}

	return nil
}

func printProjectVariables(variables []*gitlab.ProjectVariable, opts *ExportOpts, out io.Writer) error {
	if !isValidEnvironmentScope((opts.Scope)) {
		return fmt.Errorf("invalid environment scope: %s", opts.Scope)
	}

	writtenKeys := make([]string, 0)
	switch opts.OutputFormat {
	case "env":
		for _, variable := range variables {
			if matchesScope(variable.EnvironmentScope, opts.Scope) {
				if !strings.Contains(variable.EnvironmentScope, "*") {
					fmt.Fprintf(out, "%s=\"%s\"\n", variable.Key, variable.Value)
					writtenKeys = append(writtenKeys, variable.Key)
				}
			}
		}
		keysMap := CreateWrittenKeysMap(writtenKeys)
		for _, variable := range variables {
			if matchesScope(variable.EnvironmentScope, opts.Scope) {
				if !(keysMap[variable.Key]) && (strings.Contains(variable.EnvironmentScope, "*")) {
					fmt.Fprintf(out, "%s=\"%s\"\n", variable.Key, variable.Value)
				}
			}
		}
	case "export":
		for _, variable := range variables {
			if matchesScope(variable.EnvironmentScope, opts.Scope) {
				if !strings.Contains(variable.EnvironmentScope, "*") {
					fmt.Fprintf(out, "export %s=\"%s\"\n", variable.Key, variable.Value)
					writtenKeys = append(writtenKeys, variable.Key)
				}
			}
		}
		keysMap := CreateWrittenKeysMap(writtenKeys)
		for _, variable := range variables {
			if matchesScope(variable.EnvironmentScope, opts.Scope) {
				if !(keysMap[variable.Key]) && (strings.Contains(variable.EnvironmentScope, "*")) {
					fmt.Fprintf(out, "export %s=\"%s\"\n", variable.Key, variable.Value)
				}
			}
		}
	case "json":
		filteredVariables := make([]*gitlab.ProjectVariable, 0)
		for _, variable := range variables {
			if matchesScope(variable.EnvironmentScope, opts.Scope) {
				filteredVariables = append(filteredVariables, variable)
			}
		}
		res, err := marshalJson(filteredVariables)
		if err != nil {
			return err
		}
		fmt.Fprintln(out, string(res))
	default:
		return fmt.Errorf("unsupported output format: %s", opts.OutputFormat)
	}

	return nil
}

func CreateWrittenKeysMap(writtenKeys []string) map[string]bool {
	keysMap := make(map[string]bool)
	for _, key := range writtenKeys {
		keysMap[key] = true
	}
	return keysMap
}