GitLabgitlab-org
cli
main
1package get
3import (
4 "errors"
5 "fmt"
6 "net/http"
7 "strconv"
9 "github.com/MakeNowJust/heredoc/v2"
10 "github.com/spf13/cobra"
12 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
14 "gitlab.com/gitlab-org/cli/internal/api"
15 "gitlab.com/gitlab-org/cli/internal/cmdutils"
16 "gitlab.com/gitlab-org/cli/internal/commands/variable/variableutils"
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 scope string
28 key string
29 group string
30 inherited bool
31 outputFormat string
32}
34func NewCmdGet(f cmdutils.Factory, runE func(opts *options) error) *cobra.Command {
35 opts := &options{
36 io: f.IO(),
37 apiClient: f.ApiClient,
38 baseRepo: f.BaseRepo,
39 }
41 cmd := &cobra.Command{
42 Use: "get <key>",
43 Short: "Get a variable for a project or group.",
44 Long: heredoc.Docf(`
45 Prints the value of a single variable by key. Use %[1]s--scope%[1]s to
46 select a variable in a specific environment, or %[1]s--group%[1]s to read a
47 group variable instead.
49 By default the command reads one level only. Pass %[1]s--inherited%[1]s to
50 fall back to the groups above the project and then to the instance,
51 in the order CI resolves a variable: the project first, then each
52 parent group closest first, then instance variables.
54 A level that does not define the key, or that you cannot read, is
55 skipped. Instance variables apply to every environment, so
56 %[1]s--scope%[1]s does not filter them.
57 `, "`"),
58 Args: cobra.ExactArgs(1),
59 Example: heredoc.Doc(`
60 glab variable get VAR_KEY
61 glab variable get -g GROUP VAR_KEY
62 glab variable get -s SCOPE VAR_KEY
64 # Read the project, then its parent groups, then the instance
65 glab variable get --inherited VAR_KEY`),
66 Annotations: map[string]string{
67 mcpannotations.Exclude: "true",
68 },
69 RunE: func(cmd *cobra.Command, args []string) error {
70 opts.complete(args)
72 if err := opts.validate(); err != nil {
73 return err
74 }
76 if runE != nil {
77 return runE(opts)
78 }
79 return opts.run()
80 },
81 }
83 cmd.Flags().StringVarP(&opts.scope, "scope", "s", "*", "The environment_scope of the variable. Values: all (*), or specific environments.")
84 cmd.Flags().StringVarP(&opts.group, "group", "g", "", "Get variable for a group.")
85 cmd.Flags().BoolVar(&opts.inherited, "inherited", false, "If the key is not defined at the selected level, look in the groups above it, then in instance variables.")
86 cmdutils.EnableJSONOutput(cmd, opts.io, &opts.outputFormat)
87 return cmd
88}
90func (o *options) complete(args []string) {
91 o.key = args[0]
92}
94func (o *options) validate() error {
95 if !variableutils.IsValidKey(o.key) {
96 return cmdutils.FlagError{Err: fmt.Errorf("invalid key provided.\n%s", variableutils.ValidKeyMsg)}
97 }
99 return nil
100}
102func (o *options) run() error {
103 // NOTE: this command can not only be used for projects,
104 // so we have to manually check for the base repo, if it doesn't exist,
105 // we bootstrap the client with the default hostname.
106 var repoHost string
107 if baseRepo, err := o.baseRepo(); err == nil {
108 repoHost = baseRepo.RepoHost()
109 }
110 apiClient, err := o.apiClient(repoHost)
111 if err != nil {
112 return err
113 }
114 client := apiClient.Lab()
116 found, err := o.resolve(client)
117 if err != nil {
118 return err
119 }
121 if o.outputFormat == "json" {
122 return o.io.PrintJSON(found.payload)
123 }
125 // The value goes to stdout on its own, so a shell can capture it. Any
126 // note about where it came from belongs on stderr.
127 if found.missingFrom != "" {
128 o.io.LogErrorf("%s is not defined in %s. Using the value from %s.\n", o.key, found.missingFrom, found.source)
129 }
130 o.io.LogInfof("%s", found.value)
131 return nil
132}
134// variableMatch is a variable found at one level of the lookup.
135type variableMatch struct {
136 payload any // printed as-is by --output json
137 value string
138 source string // the level that defined the key, for example "group acme"
139 missingFrom string // the selected level when it did not define the key, empty otherwise
140}
142func (o *options) resolve(client *gitlab.Client) (*variableMatch, error) {
143 if o.group != "" {
144 return o.resolveFromGroup(client)
145 }
146 return o.resolveFromProject(client)
147}
149func (o *options) resolveFromProject(client *gitlab.Client) (*variableMatch, error) {
150 baseRepo, err := o.baseRepo()
151 if err != nil {
152 return nil, err
153 }
155 project := baseRepo.FullName()
156 variable, _, err := client.ProjectVariables.GetVariable(project, o.key, &gitlab.GetProjectVariableOptions{
157 Filter: &gitlab.VariableFilter{EnvironmentScope: o.scope},
158 })
159 if err == nil {
160 return &variableMatch{payload: variable, value: variable.Value, source: "project " + project}, nil
161 }
162 if !o.inherited || !skippableLevel(err) {
163 return nil, err
164 }
166 // The project does not define the key. Walk the groups that hold it, then
167 // instance variables.
168 match, walkErr := o.walkUp(client, variableutils.GroupChain(variableutils.ParentNamespace(project)))
169 if walkErr != nil {
170 return nil, walkErr
171 }
172 if match == nil {
173 // Nothing above the project defines it either, so report the original
174 // project error, exactly as a run without --inherited would.
175 return nil, err
176 }
177 match.missingFrom = "project " + project
178 return match, nil
179}
181func (o *options) resolveFromGroup(client *gitlab.Client) (*variableMatch, error) {
182 variable, _, err := client.GroupVariables.GetVariable(o.group, o.key, &gitlab.GetGroupVariableOptions{
183 Filter: &gitlab.VariableFilter{EnvironmentScope: o.scope},
184 })
185 if err == nil {
186 return &variableMatch{payload: variable, value: variable.Value, source: "group " + o.group}, nil
187 }
188 if !o.inherited || !skippableLevel(err) {
189 return nil, err
190 }
192 group, pathErr := o.groupFullPath(client)
193 if pathErr != nil {
194 return nil, pathErr
195 }
197 match, walkErr := o.walkUp(client, variableutils.GroupChain(variableutils.ParentNamespace(group)))
198 if walkErr != nil {
199 return nil, walkErr
200 }
201 if match == nil {
202 return nil, err
203 }
204 match.missingFrom = "group " + group
205 return match, nil
206}
208// groupFullPath returns the path of the --group value. The parent groups come
209// from that path, and a numeric ID does not carry it, so the API supplies it.
210func (o *options) groupFullPath(client *gitlab.Client) (string, error) {
211 if _, parseErr := strconv.ParseUint(o.group, 10, 64); parseErr == nil {
212 group, _, err := client.Groups.GetGroup(o.group, &gitlab.GetGroupOptions{})
213 if err != nil {
214 return "", fmt.Errorf("finding the parent groups of group %s: %w", o.group, err)
215 }
216 return group.FullPath, nil
217 }
218 return o.group, nil
219}
221// walkUp reads each group in turn, then instance variables, and returns the
222// first definition of the key. A nil match means no level defined it.
223func (o *options) walkUp(client *gitlab.Client, groups []string) (*variableMatch, error) {
224 for _, group := range groups {
225 variable, _, err := client.GroupVariables.GetVariable(group, o.key, &gitlab.GetGroupVariableOptions{
226 Filter: &gitlab.VariableFilter{EnvironmentScope: o.scope},
227 })
228 if err == nil {
229 return &variableMatch{
230 payload: variable,
231 value: variable.Value,
232 source: "group " + group,
233 }, nil
234 }
235 if !skippableLevel(err) {
236 return nil, err
237 }
238 }
240 // Instance variables are not scoped to an environment, so --scope does not
241 // apply here. Reading them needs administrator access, and a user without
242 // it gets 403, which ends the walk without an error.
243 variable, _, err := client.InstanceVariables.GetVariable(o.key)
244 if err == nil {
245 return &variableMatch{
246 payload: variable,
247 value: variable.Value,
248 source: "instance variables",
249 }, nil
250 }
251 if !skippableLevel(err) {
252 return nil, err
253 }
255 return nil, nil
256}
258// skippableLevel reports whether a level can be passed over during a walk. A
259// level that does not define the key answers 404, and a level the user cannot
260// read answers 401 or 403. Any other failure is real and must surface.
261func skippableLevel(err error) bool {
262 var response *gitlab.ErrorResponse
263 if !errors.As(err, &response) {
264 return false
265 }
267 // Sentinel errors such as gitlab.ErrNotFound carry the status in the
268 // struct and no HTTP response, so both places are read.
269 status := response.StatusCode
270 if status == 0 && response.Response != nil {
271 status = response.Response.StatusCode
272 }
274 switch status {
275 case http.StatusNotFound, http.StatusUnauthorized, http.StatusForbidden:
276 return true
277 default:
278 return false
279 }
280}
Diagnostics8 git calls · 39 ms
CallStatusSizeTime039 ms
discover200185 B2 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=2 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 KiB · hit2 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=2 git.response.bytes=59849 git.response.cache=HIT git.response.duration_ms=2 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
fetchtree:0 · deepen 1020032 KiB · 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=32926 git.response.cache=HIT git.response.duration_ms=2 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
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=3 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:02001.8 KiB · hit4 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=4 git.response.bytes=1857 git.response.cache=HIT git.response.duration_ms=4 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:0200168 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=168 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=02c7459097a989bb30177cf9646054de1be6e826 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=168 git.pkt.payload.max=141 git.sideband.band1.bytes=141 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=141 git.pack.trailer=be803fa1e1de2d46dfc3fb5d2a6d0a7ef128e660Open pack map
fetch2002.9 KiB · hit25 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=25 git.response.bytes=2992 git.response.cache=HIT git.response.duration_ms=25 git.fetch.wants=2c745c0906c212de3d6632d9ff23b7eed1ec0bcf 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=2992 git.pkt.payload.max=2965 git.sideband.band1.bytes=2965 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
- a5e22c73a9f02a83
- Request
- fc021955…
- 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