GitLabgitlab-org
cli
main
1package export
3import (
4 "fmt"
5 "io"
6 "os"
7 "regexp"
8 "strings"
10 "github.com/MakeNowJust/heredoc/v2"
11 "github.com/spf13/cobra"
13 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
15 "gitlab.com/gitlab-org/cli/internal/api"
16 "gitlab.com/gitlab-org/cli/internal/cmdutils"
17 "gitlab.com/gitlab-org/cli/internal/glrepo"
18 "gitlab.com/gitlab-org/cli/internal/iostreams"
19 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
20)
22type options struct {
23 apiClient func(repoHost string) (*api.Client, error)
24 io *iostreams.IOStreams
25 baseRepo func() (glrepo.Interface, error)
27 group string
28 outputFormat string
29 scope string
31 page int
32 perPage int
33}
35func NewCmdExport(f cmdutils.Factory, runE func(opts *options) error) *cobra.Command {
36 opts := &options{
37 io: f.IO(),
38 apiClient: f.ApiClient,
39 baseRepo: f.BaseRepo,
40 }
42 cmd := &cobra.Command{
43 Use: "export",
44 Short: "Export variables from a project or group.",
45 Long: heredoc.Docf(`
46 Defaults to the current project. Use %[1]s--group%[1]s to export
47 variables for a group. Use %[1]s--output%[1]s to set the format:
48 %[1]sjson%[1]s (default), %[1]senv%[1]s (KEY=VALUE pairs), or
49 %[1]sexport%[1]s (shell export statements).
50 `, "`"),
51 Aliases: []string{"ex"},
52 Args: cobra.NoArgs,
53 ValidArgsFunction: cobra.NoFileCompletions,
54 Example: heredoc.Doc(`
55 glab variable export
56 glab variable export --per-page 1000 --page 1
57 glab variable export --group gitlab-org
58 glab variable export --group gitlab-org --per-page 1000 --page 1
59 glab variable export --output json
60 glab variable export --output env
61 glab variable export --output export`),
62 Annotations: map[string]string{
63 mcpannotations.Exclude: "true",
64 },
65 RunE: func(cmd *cobra.Command, args []string) error {
66 if err := opts.complete(cmd); err != nil {
67 return err
68 }
70 if runE != nil {
71 return runE(opts)
72 }
74 return opts.run()
75 },
76 }
78 cmdutils.EnableRepoOverride(cmd, f)
79 cmd.PersistentFlags().StringP("group", "g", "", "Select a group or subgroup. Ignored if a repository argument is set.")
81 fl := cmd.Flags()
82 fl.IntVarP(&opts.page, "page", "p", 1, "Page number.")
83 fl.IntVarP(&opts.perPage, "per-page", "P", 100, "Number of items to list per page.")
84 fl.StringVarP(&opts.outputFormat, "output", "F", "json", "Format output as: json, export, env.")
85 fl.StringVarP(&opts.scope, "scope", "s", "*", "The environment_scope of the variables. Values: '*' (default), or specific environments.")
87 // Deprecated: --format flag, use --output instead
88 fl.StringVar(&opts.outputFormat, "format", "json", "Format of output: json, export, env.")
89 _ = fl.MarkDeprecated("format", "use --output instead.")
91 cmdutils.AddJQFlag(cmd, f.IO())
92 return cmd
93}
95func (o *options) complete(cmd *cobra.Command) error {
96 group, err := cmdutils.GroupOverride(cmd)
97 if err != nil {
98 return err
99 }
100 o.group = group
102 return nil
103}
105func (o *options) run() error {
106 var out io.Writer = os.Stdout
107 if o.io != nil && o.io.StdOut != nil {
108 out = o.io.StdOut
109 }
111 // NOTE: this command can not only be used for projects,
112 // so we have to manually check for the base repo, if it doesn't exist,
113 // we bootstrap the client with the default hostname.
114 var repoHost string
115 if baseRepo, err := o.baseRepo(); err == nil {
116 repoHost = baseRepo.RepoHost()
117 }
118 apiClient, err := o.apiClient(repoHost)
119 if err != nil {
120 return err
121 }
122 client := apiClient.Lab()
124 if o.group != "" {
125 o.io.LogErrorf("Exporting variables from the %s group:\n", o.group)
126 createVarOpts := &gitlab.ListGroupVariablesOptions{
127 ListOptions: gitlab.ListOptions{
128 Page: int64(o.page),
129 PerPage: int64(o.perPage),
130 },
131 }
132 groupVariables, _, err := client.GroupVariables.ListVariables(o.group, createVarOpts)
133 if err != nil {
134 return err
135 }
137 if len(groupVariables) == 0 {
138 return nil
139 }
141 return printGroupVariables(groupVariables, o, out)
143 } else {
144 repo, err := o.baseRepo()
145 if err != nil {
146 return err
147 }
148 o.io.LogErrorf("Exporting variables from the %s project:\n", repo.FullName())
149 listOpts := &gitlab.ListProjectVariablesOptions{
150 ListOptions: gitlab.ListOptions{
151 Page: int64(o.page),
152 PerPage: int64(o.perPage),
153 },
154 }
155 projectVariables, _, err := client.ProjectVariables.ListVariables(repo.FullName(), listOpts)
156 if err != nil {
157 return err
158 }
160 if len(projectVariables) == 0 {
161 return nil
162 }
164 return printProjectVariables(projectVariables, o, out)
165 }
166}
168func matchesScope(varScope, optScope string) bool {
169 if varScope == "*" || optScope == "*" {
170 return true
171 }
172 if varScope == optScope {
173 return true
174 }
175 if strings.Contains(varScope, "*") {
176 varPattern := "^" + regexp.QuoteMeta(varScope) + "$"
177 optPattern := "^" + regexp.QuoteMeta(optScope) + "$"
179 varPattern = strings.ReplaceAll(varPattern, `\*`, ".*")
180 optPattern = strings.ReplaceAll(optPattern, `\*`, ".*")
182 matchesVar, _ := regexp.MatchString(varPattern, optScope)
183 matchesOpt, _ := regexp.MatchString(optPattern, varScope)
185 return matchesVar || matchesOpt
186 }
187 return false
188}
190func isValidEnvironmentScope(optScope string) bool {
191 pattern := `^[a-zA-Z0-9\s\-_/${}\x20]+$`
192 re, _ := regexp.Compile(pattern)
193 matched := re.MatchString(optScope)
194 return matched || optScope == "*"
195}
197func printGroupVariables(variables []*gitlab.GroupVariable, opts *options, out io.Writer) error {
198 if !isValidEnvironmentScope(opts.scope) {
199 return fmt.Errorf("invalid environment scope: %s", opts.scope)
200 }
202 writtenKeys := make([]string, 0)
203 switch opts.outputFormat {
204 case "env":
205 for _, variable := range variables {
206 if matchesScope(variable.EnvironmentScope, opts.scope) {
207 if !strings.Contains(variable.EnvironmentScope, "*") {
208 fmt.Fprintf(out, "%s=%s\n", variable.Key, variable.Value) //nolint:forbidigo // out is a generic io.Writer with an os.Stdout fallback, not IOStreams directly
209 writtenKeys = append(writtenKeys, variable.Key)
210 }
211 }
212 }
213 keysMap := CreateWrittenKeysMap(writtenKeys)
214 for _, variable := range variables {
215 if matchesScope(variable.EnvironmentScope, opts.scope) {
216 if !keysMap[variable.Key] && strings.Contains(variable.EnvironmentScope, "*") {
217 fmt.Fprintf(out, "%s=%s\n", variable.Key, variable.Value) //nolint:forbidigo // out is a generic io.Writer with an os.Stdout fallback, not IOStreams directly
218 }
219 }
220 }
221 case "export":
222 for _, variable := range variables {
223 if matchesScope(variable.EnvironmentScope, opts.scope) {
224 if !strings.Contains(variable.EnvironmentScope, "*") {
225 fmt.Fprintf(out, "export %s=%s\n", variable.Key, variable.Value) //nolint:forbidigo // out is a generic io.Writer with an os.Stdout fallback, not IOStreams directly
226 writtenKeys = append(writtenKeys, variable.Key)
227 }
228 }
229 }
230 keysMap := CreateWrittenKeysMap(writtenKeys)
231 for _, variable := range variables {
232 if matchesScope(variable.EnvironmentScope, opts.scope) {
233 if !keysMap[variable.Key] && strings.Contains(variable.EnvironmentScope, "*") {
234 fmt.Fprintf(out, "export %s=%s\n", variable.Key, variable.Value) //nolint:forbidigo // out is a generic io.Writer with an os.Stdout fallback, not IOStreams directly
235 }
236 }
237 }
238 case "json":
239 filteredVariables := make([]*gitlab.GroupVariable, 0)
240 for _, variable := range variables {
241 if matchesScope(variable.EnvironmentScope, opts.scope) {
242 filteredVariables = append(filteredVariables, variable)
243 }
244 }
245 return opts.io.PrintJSON(filteredVariables)
246 default:
247 return fmt.Errorf("unsupported output format: %s", opts.outputFormat)
248 }
250 return nil
251}
253func printProjectVariables(variables []*gitlab.ProjectVariable, opts *options, out io.Writer) error {
254 if !isValidEnvironmentScope(opts.scope) {
255 return fmt.Errorf("invalid environment scope: %s", opts.scope)
256 }
258 writtenKeys := make([]string, 0)
259 switch opts.outputFormat {
260 case "env":
261 for _, variable := range variables {
262 if matchesScope(variable.EnvironmentScope, opts.scope) {
263 if !strings.Contains(variable.EnvironmentScope, "*") {
264 fmt.Fprintf(out, "%s=\"%s\"\n", variable.Key, variable.Value) //nolint:forbidigo // out is a generic io.Writer with an os.Stdout fallback, not IOStreams directly
265 writtenKeys = append(writtenKeys, variable.Key)
266 }
267 }
268 }
269 keysMap := CreateWrittenKeysMap(writtenKeys)
270 for _, variable := range variables {
271 if matchesScope(variable.EnvironmentScope, opts.scope) {
272 if !keysMap[variable.Key] && strings.Contains(variable.EnvironmentScope, "*") {
273 fmt.Fprintf(out, "%s=\"%s\"\n", variable.Key, variable.Value) //nolint:forbidigo // out is a generic io.Writer with an os.Stdout fallback, not IOStreams directly
274 }
275 }
276 }
277 case "export":
278 for _, variable := range variables {
279 if matchesScope(variable.EnvironmentScope, opts.scope) {
280 if !strings.Contains(variable.EnvironmentScope, "*") {
281 fmt.Fprintf(out, "export %s=\"%s\"\n", variable.Key, variable.Value) //nolint:forbidigo // out is a generic io.Writer with an os.Stdout fallback, not IOStreams directly
282 writtenKeys = append(writtenKeys, variable.Key)
283 }
284 }
285 }
286 keysMap := CreateWrittenKeysMap(writtenKeys)
287 for _, variable := range variables {
288 if matchesScope(variable.EnvironmentScope, opts.scope) {
289 if !keysMap[variable.Key] && strings.Contains(variable.EnvironmentScope, "*") {
290 fmt.Fprintf(out, "export %s=\"%s\"\n", variable.Key, variable.Value) //nolint:forbidigo // out is a generic io.Writer with an os.Stdout fallback, not IOStreams directly
291 }
292 }
293 }
294 case "json":
295 filteredVariables := make([]*gitlab.ProjectVariable, 0)
296 for _, variable := range variables {
297 if matchesScope(variable.EnvironmentScope, opts.scope) {
298 filteredVariables = append(filteredVariables, variable)
299 }
300 }
301 return opts.io.PrintJSON(filteredVariables)
302 default:
303 return fmt.Errorf("unsupported output format: %s", opts.outputFormat)
304 }
306 return nil
307}
309func CreateWrittenKeysMap(writtenKeys []string) map[string]bool {
310 keysMap := make(map[string]bool)
311 for _, key := range writtenKeys {
312 keysMap[key] = true
313 }
314 return keysMap
315}
Diagnostics8 git calls · 237 ms
CallStatusSizeTime0237 ms
discover200185 B3 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=3 git.response.bytes=185 git.server.agent=git/2.56.g1891de4-Linux git.server.object_format=sha1 git.server.caps=agent ls-refs fetch server-option object-format git.server.fetch=shallow wait-for-done filter git.protocol.version=2 git.pkt.frames=9 git.pkt.data=7 git.pkt.flush=2 git.pkt.delim=0 git.pkt.bytes=185 git.pkt.payload.max=35
ls-refs20058 KiB3 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=3 git.response.bytes=59849 git.response.cache=UPDATING git.response.duration_ms=3 git.protocol.version=2 git.pkt.frames=731 git.pkt.data=730 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=59849 git.pkt.payload.max=143 git.ls_refs.count=730 git.ls_refs.head=refs/heads/main
fetchcombine:blob:none+tree:2 · deepen 12004.2 KiB · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=7 git.response.bytes=4273 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=combine:blob:none+tree:2 git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9 git.fetch.haves.count=0 git.fetch.deepen=1 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=7 git.pkt.data=5 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=4273 git.pkt.payload.max=4173 git.sideband.band1.bytes=4173 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=11 git.pack.bytes=4173 git.fetch.wide.objects=11 git.fetch.wide.extra_bytes=3930 git.fetch.wide.blobs=0
fetchtree:0 · deepen 1020032 KiB · hit7 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=32926 git.response.cache=HIT git.response.duration_ms=7 git.fetch.filter=tree:0 git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9 git.fetch.haves.count=0 git.fetch.deepen=10 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=22 git.pkt.data=20 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=32926 git.pkt.payload.max=32046 git.sideband.band1.bytes=32046 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=80 git.pack.bytes=32046 git.pack.ofs_delta=36 git.pack.ref_delta=0 git.pack.chain.max=2 git.pack.trailer=cb0bad5d7ffc514895d8b21c4dd470327f90bc91 git.pack.full=44Open pack map
fetchtree:02001.8 KiB · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=1857 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=dce174ff8c632a19d17eea99c8a9b7c37fb2b592 git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=1857 git.pkt.payload.max=1830 git.sideband.band1.bytes=1830 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=1830 git.pack.trailer=fb03183b7909876778f740d196d7516811003517Open pack map
fetchtree:0200375 B · hit2 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=2 git.response.bytes=375 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=tree:0 git.fetch.wants=210e8ccdc9766a94adae919c6922ea88d77a8fb1 git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=375 git.pkt.payload.max=348 git.sideband.band1.bytes=348 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=348 git.pack.trailer=8c3972a32424b06b4c572b8aa869b28eca201985Open pack map
fetchtree:0200137 B · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=137 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=30fdb831f7f814c1838cf2fb64d016995e2e281b git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=137 git.pkt.payload.max=110 git.sideband.band1.bytes=110 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=110 git.pack.trailer=d3d91cd62371efa2c9a2879eca0209c6b764a6e3Open pack map
fetch2002.4 KiB223 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=223 git.response.bytes=2497 git.response.cache=MISS git.response.duration_ms=223 git.fetch.wants=cd4095e6cd9455359886042b2ba2cfe3859289bc git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=2497 git.pkt.payload.max=2470 git.sideband.band1.bytes=2470 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0
Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.
- Remote
- https://gitlab.com/gitlab-org/cli
- Ref
- refs/heads/main
- Commit
- 0dd7574dce9e385c5c30540e6c15657adc6bdce9
- cf-ray
- a5e1f29b5fb6efe9
- Request
- 1a1f6f98…
- Protocol
- v2 · sha1
- Agent
- git/2.56.g1891de4-Linux
- Filter
- advertised
- Fetch
- shallow wait-for-done filter
- Capabilities
- agent ls-refs fetch server-option object-format