GitLabgitlab-org
cli
main
1package list
3import (
4 "context"
5 "fmt"
6 "net/http"
8 "github.com/MakeNowJust/heredoc/v2"
9 "github.com/spf13/cobra"
11 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
13 "gitlab.com/gitlab-org/cli/internal/api"
14 "gitlab.com/gitlab-org/cli/internal/cmdutils"
15 "gitlab.com/gitlab-org/cli/internal/commands/deploy-token/display"
16 "gitlab.com/gitlab-org/cli/internal/glrepo"
17 "gitlab.com/gitlab-org/cli/internal/iostreams"
18 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
19 "gitlab.com/gitlab-org/cli/internal/tableprinter"
20)
22type options struct {
23 io *iostreams.IOStreams
24 apiClient func(repoHost string) (*api.Client, error)
25 baseRepo func() (glrepo.Interface, error)
27 group string
28 instance bool
29 activeOnly bool
30 outputFormat string
31}
33func NewCmd(f cmdutils.Factory) *cobra.Command {
34 opts := &options{
35 io: f.IO(),
36 apiClient: f.ApiClient,
37 baseRepo: f.BaseRepo,
38 }
40 cmd := &cobra.Command{
41 Use: "list [flags]",
42 Short: "List deploy tokens.",
43 Aliases: []string{"ls"},
44 Args: cobra.NoArgs,
45 ValidArgsFunction: cobra.NoFileCompletions,
46 Long: heredoc.Docf(`
47 List the deploy tokens of a project, a group, or the instance.
49 Pass %[1]s--instance%[1]s to list every deploy token on the instance. This requires administrator access, and %[1]sGITLAB_GROUP%[1]s does not apply.
51 The output never contains the token value. A token value is shown only once, when the token is created.
53 Tokens are listed with their expiry, and whether they have been revoked or have expired. Pass %[1]s--active%[1]s to list only the tokens that are still usable.
54 `, "`"),
55 Example: heredoc.Doc(`
56 # List the current project's deploy tokens
57 glab deploy-token list
59 # List the deploy tokens of a specific project
60 glab deploy-token list --repo user/my-repo
62 # List only the tokens that are neither revoked nor expired
63 glab deploy-token list --active
65 # List a group's deploy tokens
66 glab deploy-token list --group group/sub-group
68 # List every deploy token on the instance (administrator only)
69 glab deploy-token list --instance
71 # List the current project's deploy tokens as JSON
72 glab deploy-token list --output json`),
73 Annotations: map[string]string{
74 mcpannotations.Safe: "true",
75 },
76 RunE: func(cmd *cobra.Command, args []string) error {
77 if err := opts.complete(cmd); err != nil {
78 return err
79 }
81 return opts.run(cmd.Context())
82 },
83 }
85 cmdutils.EnableRepoOverride(cmd, f)
87 fl := cmd.Flags()
88 fl.StringVarP(&opts.group, "group", "g", "", "List the deploy tokens of the group <group> instead of a project.")
89 fl.BoolVarP(&opts.activeOnly, "active", "a", false, "List only the tokens that are neither revoked nor expired.")
90 fl.BoolVarP(&opts.instance, "instance", "i", false, "List every deploy token on the instance instead of a project or group. Requires administrator access.")
92 cmdutils.EnableJSONOutput(cmd, opts.io, &opts.outputFormat)
93 cmd.MarkFlagsMutuallyExclusive("repo", "group", "instance")
95 return cmd
96}
98func (o *options) complete(cmd *cobra.Command) error {
99 if o.instance {
100 return nil
101 }
103 group, err := cmdutils.GroupOverride(cmd)
104 if err != nil {
105 return err
106 }
107 o.group = group
109 return nil
110}
112func (o *options) run(ctx context.Context) error {
113 // The group and instance scopes work outside a repository, so a missing base
114 // repo is only fatal for the project scope. Fail before building a client that would be
115 // discarded, so the caller sees why the repository was needed.
116 repo, repoErr := o.baseRepo()
117 if o.group == "" && !o.instance && repoErr != nil {
118 return repoErr
119 }
121 var repoHost string
122 if repoErr == nil {
123 repoHost = repo.RepoHost()
124 }
126 apiClient, err := o.apiClient(repoHost)
127 if err != nil {
128 return err
129 }
130 client := apiClient.Lab()
132 var tokens []*gitlab.DeployToken
133 switch {
134 case o.instance:
135 tokens, err = gitlab.ScanAndCollect(func(p gitlab.PaginationOptionFunc) ([]*gitlab.DeployToken, *gitlab.Response, error) {
136 return client.DeployTokens.ListAllDeployTokens(p, gitlab.WithContext(ctx))
137 })
138 if gitlab.HasStatusCode(err, http.StatusForbidden) {
139 err = fmt.Errorf("%w. Listing the deploy tokens of the instance requires administrator access", err)
140 }
141 case o.group != "":
142 tokens, err = gitlab.ScanAndCollect(func(p gitlab.PaginationOptionFunc) ([]*gitlab.DeployToken, *gitlab.Response, error) {
143 return client.DeployTokens.ListGroupDeployTokens(o.group, &gitlab.ListGroupDeployTokensOptions{}, p, gitlab.WithContext(ctx))
144 })
145 default:
146 tokens, err = gitlab.ScanAndCollect(func(p gitlab.PaginationOptionFunc) ([]*gitlab.DeployToken, *gitlab.Response, error) {
147 return client.DeployTokens.ListProjectDeployTokens(repo.FullName(), &gitlab.ListProjectDeployTokensOptions{}, p, gitlab.WithContext(ctx))
148 })
149 }
150 if err != nil {
151 return cmdutils.WrapError(err, "failed to list deploy tokens")
152 }
154 if o.activeOnly {
155 tokens = activeTokens(tokens)
156 }
158 // JSON output prints the response as-is, so the token value is cleared here
159 // instead of relying on the endpoint never returning it.
160 for _, token := range tokens {
161 token.Token = ""
162 }
164 switch o.outputFormat {
165 case "json":
166 return o.io.PrintJSON(tokens)
167 default:
168 return o.printTable(tokens)
169 }
170}
172// activeTokens keeps the tokens that are still usable. The deploy token list
173// endpoints in client-go accept no active filter, so this is applied here.
174func activeTokens(tokens []*gitlab.DeployToken) []*gitlab.DeployToken {
175 active := make([]*gitlab.DeployToken, 0, len(tokens))
176 for _, token := range tokens {
177 if !token.Revoked && !token.Expired {
178 active = append(active, token)
179 }
180 }
182 return active
183}
185func (o *options) printTable(tokens []*gitlab.DeployToken) error {
186 if len(tokens) == 0 {
187 o.io.LogInfo("No deploy tokens found.")
188 return nil
189 }
191 c := o.io.Color()
192 table := tableprinter.NewTablePrinter()
193 table.AddRow(c.Bold("ID"), c.Bold("Name"), c.Bold("Username"), c.Bold("Scopes"), c.Bold("Expires At"), c.Bold("Revoked"), c.Bold("Expired"))
194 for _, token := range tokens {
195 table.AddRow(token.ID, token.Name, token.Username, display.Scopes(token.Scopes), display.ExpiresAt(token.ExpiresAt), token.Revoked, token.Expired)
196 }
197 o.io.LogInfof("%s", table.Render())
199 return nil
200}
Diagnostics8 git calls · 228 ms
CallStatusSizeTime0228 ms
discover200185 B3 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch 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=4 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 · hit4 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=4 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 · 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:0200263 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=263 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=aff3dd5052d75f0afe2383713d669f993c82b2f9 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=263 git.pkt.payload.max=236 git.sideband.band1.bytes=236 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=236 git.pack.trailer=4076aed8a003d312c41b730611843784ab33181fOpen pack map
fetchtree:0200134 B · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=212 git.response.bytes=134 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=40969612a65fa6a96744b73de65446048116a040 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=134 git.pkt.payload.max=107 git.sideband.band1.bytes=107 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=107 git.pack.trailer=1e7eaae72922b05c59dc8831312483164e8f30aaOpen pack map
fetch2002.2 KiB212 ms
git.upload-pack fetch http.response.status_code=200 git.response.bytes=2247 git.response.cache=MISS git.response.duration_ms=212 git.fetch.wants=d763d8b62a27d8da12ba7b7c0faa2c51137b68ef 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=2247 git.pkt.payload.max=2220 git.sideband.band1.bytes=2220 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
- a5e2abe89b55e6b0
- Request
- 272b93c4…
- 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