GitLabgitlab-org
cli
main
1package list
3import (
4 "strconv"
5 "strings"
6 "time"
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/token/accesslevel"
16 "gitlab.com/gitlab-org/cli/internal/commands/token/tokenutils"
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 user string
28 group string
29 outputFormat string
30 listActive bool
31}
33func NewCmdList(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",
42 Short: "List user, group, or project access tokens.",
43 Aliases: []string{"ls"},
44 Args: cobra.NoArgs,
45 ValidArgsFunction: cobra.NoFileCompletions,
46 Long: heredoc.Doc(`
47 List all tokens for a user, group, or project.
49 The output contains the token's meta information, not the actual token value. The output format
50 can be "JSON" or "text". The access level property is printed in human-readable form in the text
51 output, but displays the integer value in JSON.
53 Administrators can list tokens of other users.
54 `),
55 Example: heredoc.Doc(`
56 # List the current project's access tokens
57 glab token list
58 glab token list --output json
60 # List the project access tokens of a specific project
61 glab token list --repo user/my-repo
63 # List group access tokens
64 glab token list --group group/sub-group
66 # List my personal access tokens
67 glab token list --user @me
69 # Administrators only: list the personal access tokens of another user
70 glab token list --user johndoe`),
71 Annotations: map[string]string{
72 mcpannotations.Safe: "true",
73 },
74 RunE: func(cmd *cobra.Command, args []string) error {
75 if err := opts.complete(cmd); err != nil {
76 return err
77 }
79 return opts.run()
80 },
81 }
83 cmdutils.EnableRepoOverride(cmd, f)
84 cmd.Flags().StringVarP(&opts.group, "group", "g", "", "List group access tokens. Ignored if a user or repository argument is set.")
85 cobra.CheckErr(cmd.RegisterFlagCompletionFunc("group", tokenutils.GroupCompletions))
86 cmd.Flags().StringVarP(&opts.user, "user", "U", "", "List personal access tokens. Use @me for the current user.")
87 cobra.CheckErr(cmd.RegisterFlagCompletionFunc("user", tokenutils.UserCompletions))
88 cmdutils.EnableJSONOutput(cmd, opts.io, &opts.outputFormat, "Format output as: text, json. text provides a readable table, json outputs the tokens with metadata.")
89 cmd.Flags().BoolVarP(&opts.listActive, "active", "a", false, "List only the active tokens.")
90 cmd.MarkFlagsMutuallyExclusive("group", "user")
91 return cmd
92}
94func (o *options) complete(cmd *cobra.Command) error {
95 group, err := cmdutils.GroupOverride(cmd)
96 if err != nil {
97 return err
98 }
99 o.group = group
101 return nil
102}
104type Token struct {
105 ID string `json:"id"`
106 Name string `json:"name"`
107 Description string `json:"description"`
108 AccessLevel string `json:"access_level"`
109 Active string `json:"active"`
110 Revoked string `json:"revoked"`
111 CreatedAt string `json:"created_at"`
112 ExpiresAt string `json:"expires_at"`
113 LastUsedAt string `json:"last_used_at"`
114 Scopes string `json:"scopes"`
115}
117type Tokens []Token
119func formatLastUsedAt(lastUsedAt *time.Time) string {
120 if lastUsedAt == nil {
121 return "-"
122 }
123 return lastUsedAt.Format(time.RFC3339)
124}
126func formatDescription(description string) string {
127 if description == "" {
128 return "-"
129 }
130 return description
131}
133func formatAccessLevel(accessLevel gitlab.AccessLevelValue) string {
134 level := accesslevel.AccessLevel{Value: accessLevel}
135 levelStr := level.String()
137 if levelStr == "no" {
138 return "-"
139 }
141 return levelStr
142}
144func formatExpiresAt(expiresAt *gitlab.ISOTime) string {
145 if expiresAt == nil {
146 return "-"
147 }
148 return expiresAt.String()
149}
151func (o *options) run() error {
152 // NOTE: this command can not only be used for projects,
153 // so we have to manually check for the base repo, if it doesn't exist,
154 // we bootstrap the client with the default hostname.
155 var repoHost string
156 if baseRepo, err := o.baseRepo(); err == nil {
157 repoHost = baseRepo.RepoHost()
158 }
159 apiClient, err := o.apiClient(repoHost)
160 if err != nil {
161 return err
162 }
163 client := apiClient.Lab()
165 var outputTokens Tokens
166 switch {
167 case o.user != "":
168 user, err := api.UserByName(client, o.user)
169 if err != nil {
170 return err
171 }
172 options := &gitlab.ListPersonalAccessTokensOptions{
173 UserID: &user.ID,
174 }
175 tokens, err := gitlab.ScanAndCollect(func(p gitlab.PaginationOptionFunc) ([]*gitlab.PersonalAccessToken, *gitlab.Response, error) {
176 return client.PersonalAccessTokens.ListPersonalAccessTokens(options, p)
177 })
178 if err != nil {
179 return err
180 }
181 outputTokens = make([]Token, 0, len(tokens))
182 for _, token := range tokens {
183 if !o.listActive || token.Active {
184 outputTokens = append(outputTokens, Token{
185 ID: strconv.FormatInt(token.ID, 10),
186 Name: token.Name,
187 Description: formatDescription(token.Description),
188 AccessLevel: "-",
189 Active: strconv.FormatBool(token.Active),
190 Revoked: strconv.FormatBool(token.Revoked),
191 CreatedAt: token.CreatedAt.Format(time.RFC3339),
192 ExpiresAt: formatExpiresAt(token.ExpiresAt),
193 LastUsedAt: formatLastUsedAt(token.LastUsedAt),
194 Scopes: strings.Join(token.Scopes, ","),
195 })
196 }
197 }
198 case o.group != "":
199 options := &gitlab.ListGroupAccessTokensOptions{}
200 tokens, err := gitlab.ScanAndCollect(func(p gitlab.PaginationOptionFunc) ([]*gitlab.GroupAccessToken, *gitlab.Response, error) {
201 return client.GroupAccessTokens.ListGroupAccessTokens(o.group, options, p)
202 })
203 if err != nil {
204 return err
205 }
206 outputTokens = make([]Token, 0, len(tokens))
207 for _, token := range tokens {
208 if !o.listActive || token.Active {
209 outputTokens = append(outputTokens, Token{
210 ID: strconv.FormatInt(token.ID, 10),
211 Name: token.Name,
212 Description: formatDescription(token.Description),
213 AccessLevel: formatAccessLevel(token.AccessLevel),
214 Active: strconv.FormatBool(token.Active),
215 Revoked: strconv.FormatBool(token.Revoked),
216 CreatedAt: token.CreatedAt.Format(time.RFC3339),
217 ExpiresAt: formatExpiresAt(token.ExpiresAt),
218 LastUsedAt: formatLastUsedAt(token.LastUsedAt),
219 Scopes: strings.Join(token.Scopes, ","),
220 })
221 }
222 }
223 default:
224 repo, err := o.baseRepo()
225 if err != nil {
226 return err
227 }
229 opts := &gitlab.ListProjectAccessTokensOptions{}
230 tokens, err := gitlab.ScanAndCollect(func(p gitlab.PaginationOptionFunc) ([]*gitlab.ProjectAccessToken, *gitlab.Response, error) {
231 return client.ProjectAccessTokens.ListProjectAccessTokens(repo.FullName(), opts, p)
232 })
233 if err != nil {
234 return err
235 }
236 outputTokens = make([]Token, 0, len(tokens))
237 for _, token := range tokens {
238 if !o.listActive || token.Active {
239 outputTokens = append(outputTokens, Token{
240 ID: strconv.FormatInt(token.ID, 10),
241 Name: token.Name,
242 Description: formatDescription(token.Description),
243 AccessLevel: formatAccessLevel(token.AccessLevel),
244 Active: strconv.FormatBool(token.Active),
245 Revoked: strconv.FormatBool(token.Revoked),
246 CreatedAt: token.CreatedAt.Format(time.RFC3339),
247 ExpiresAt: formatExpiresAt(token.ExpiresAt),
248 LastUsedAt: formatLastUsedAt(token.LastUsedAt),
249 Scopes: strings.Join(token.Scopes, ","),
250 })
251 }
252 }
253 }
255 if o.outputFormat == "json" {
256 return o.io.PrintJSON(outputTokens)
257 }
259 table := createTablePrinter(outputTokens)
260 o.io.LogInfof("%s", table.String())
261 return nil
262}
Diagnostics8 git calls · 393 ms
CallStatusSizeTime0393 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 KiB154 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=145 git.response.bytes=59849 git.response.cache=EXPIRED git.response.duration_ms=154 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 · 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=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:0200358 B · 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=358 git.response.cache=HIT git.response.duration_ms=4 git.fetch.filter=tree:0 git.fetch.wants=218b543e075f31e84c52193d193103408c52cb34 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=358 git.pkt.payload.max=331 git.sideband.band1.bytes=331 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=331 git.pack.trailer=fbb77d44047cd3e1ee682eb9483227c59489e50fOpen pack map
fetchtree:0200166 B · hit6 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=6 git.response.bytes=166 git.response.cache=HIT git.response.duration_ms=6 git.fetch.filter=tree:0 git.fetch.wants=7ffadcddc38f99e36058507eb8d63e0e25e9ea92 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=166 git.pkt.payload.max=139 git.sideband.band1.bytes=139 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=139 git.pack.trailer=6fdee11b341c1742d386c579f67477f500331d89Open pack map
fetch2002.3 KiB222 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=222 git.response.bytes=2349 git.response.cache=MISS git.response.duration_ms=222 git.fetch.wants=defc0a247a0d30c0d0dc021d9b86f17bfecdd659 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=2349 git.pkt.payload.max=2322 git.sideband.band1.bytes=2322 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
- a5e2b128da63e6b0
- Request
- caad1dbe…
- 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