GitLabgitlab-org

cli

main
ply8 git calls322 ms100 KiB6 cachedprotocol v2
295 lines11 KiBRaw
1package create
3import (
4 "errors"
5 "fmt"
6 "strings"
7 "time"
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/cmdutils/tokenduration"
17 "gitlab.com/gitlab-org/cli/internal/commands/token/accesslevel"
18 "gitlab.com/gitlab-org/cli/internal/commands/token/expirationdate"
19 "gitlab.com/gitlab-org/cli/internal/commands/token/filter"
20 "gitlab.com/gitlab-org/cli/internal/commands/token/tokenutils"
21 "gitlab.com/gitlab-org/cli/internal/glrepo"
22 "gitlab.com/gitlab-org/cli/internal/iostreams"
23 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
26type options struct {
27 apiClient func(repoHost string) (*api.Client, error)
28 io *iostreams.IOStreams
29 baseRepo func() (glrepo.Interface, error)
31 name string
32 description string
33 user string
34 group string
35 accessLevel accesslevel.AccessLevel
36 scopes []string
37 duration tokenduration.TokenDuration
38 expireAt expirationdate.ExpirationDate
39 outputFormat string
42func NewCmdCreate(f cmdutils.Factory) *cobra.Command {
43 opts := &options{
44 io: f.IO(),
45 apiClient: f.ApiClient,
46 baseRepo: f.BaseRepo,
47 duration: tokenduration.TokenDuration(30 * 24 * time.Hour), // Default: 30 days
48 }
50 cmd := &cobra.Command{
51 Use: "create <name>",
52 Aliases: []string{"create", "new"},
53 Args: cobra.ExactArgs(1),
54 ValidArgsFunction: cobra.NoFileCompletions,
55 Short: "Creates user, group, or project access tokens.",
56 Long: heredoc.Doc(`
57 Creates a new access token for a user, group, or project. Defaults to a
58 project access token, unless user or group name is specified.
60 The expiration date of the token is calculated by adding the duration
61 (default: 30 days) to the current date, with expiration occurring at midnight
62 UTC on the calculated date. You can specify a different duration using days (d),
63 weeks (w), or hours (h), or provide an explicit end date.
65 The name of the token must be unique. The token is printed to stdout.
67 Administrators can create full-featured personal access tokens for themselves and for other users.
69 Non-administrators can create personal access tokens only for
70 themselves (@me). These tokens must use the scope 'k8s_proxy'. For more
71 information, see the GitLab documentation for the
72 [User tokens API](https://docs.gitlab.com/api/user_tokens/#create-a-personal-access-token).
73 `),
74 Example: heredoc.Doc(`
75 # Create project access token for current project (default 30 days)
76 glab token create --access-level developer --scope read_repository --scope read_registry my-project-token
78 # Create project access token with 7 day lifetime
79 glab token create --repo user/my-repo --access-level owner --scope api my-project-token --duration 7d
81 # Create a group access token expiring in 2 weeks
82 glab token create --group group/sub-group --access-level owner --scope api my-group-token --duration 2w
84 # Create a personal access token for current user with 90 day lifetime
85 glab token create --user @me --scope k8s_proxy my-personal-token --duration 90d
87 # (administrator only) Create a personal access token for another user
88 glab token create --user johndoe --scope api johns-personal-token --duration 180d
90 # Create a token with explicit expiration date
91 glab token create --access-level developer --scope api my-token --expires-at 2025-12-31`),
92 Annotations: map[string]string{
93 mcpannotations.Exclude: "true",
94 },
95 RunE: func(cmd *cobra.Command, args []string) error {
96 if err := opts.complete(cmd, args); err != nil {
97 return err
98 }
100 if err := opts.validate(cmd); err != nil {
101 return err
102 }
104 return opts.run()
105 },
106 }
108 cmdutils.EnableRepoOverride(cmd, f)
109 cmd.Flags().StringVarP(&opts.group, "group", "g", "", "Create a group access token. Ignored if a user or repository argument is set.")
110 cobra.CheckErr(cmd.RegisterFlagCompletionFunc("group", tokenutils.GroupCompletions))
111 cmd.Flags().StringVarP(&opts.user, "user", "U", "", "Create a personal access token. For the current user, use @me.")
112 cobra.CheckErr(cmd.RegisterFlagCompletionFunc("user", tokenutils.UserCompletions))
113 cmd.Flags().StringVarP(&opts.description, "description", "", "", "Sets the token's description.")
114 cobra.CheckErr(cmd.RegisterFlagCompletionFunc("description", cobra.NoFileCompletions))
115 cmd.Flags().VarP(&opts.duration, "duration", "D", "Sets the token lifetime in days. Accepts: days (30d), weeks (4w), or hours in multiples of 24 (24h, 168h, 720h). Maximum: 365d. The token expires at midnight UTC on the calculated date.")
116 cobra.CheckErr(cmd.RegisterFlagCompletionFunc("duration", cobra.NoFileCompletions))
117 cmd.Flags().VarP(&opts.expireAt, "expires-at", "E", "Sets the token's expiration date and time, in YYYY-MM-DD format. If not specified, --duration is used.")
118 cobra.CheckErr(cmd.RegisterFlagCompletionFunc("expires-at", cobra.NoFileCompletions))
119 cmd.Flags().StringSliceVarP(&opts.scopes, "scope", "S", []string{"read_repository"}, "Scopes for the token. Multiple scopes can be comma-separated or specified by repeating the flag. For a list, see https://docs.gitlab.com/security/tokens/access_token_scopes/.")
120 cobra.CheckErr(cmd.RegisterFlagCompletionFunc("scope", cobra.NoFileCompletions))
121 levels := []string{"guest", "reporter", "developer", "maintainer", "owner"}
122 cmd.Flags().VarP(&opts.accessLevel, "access-level", "A", "Access level of the token. Options: "+strings.Join(levels, ", ")+".")
123 cobra.CheckErr(cmd.RegisterFlagCompletionFunc("access-level", cobra.FixedCompletions(levels, cobra.ShellCompDirectiveNoFileComp)))
124 cmdutils.EnableJSONOutput(cmd, opts.io, &opts.outputFormat, "Format output as 'text' for the token value, 'json' for the actual API token structure.")
125 cmd.MarkFlagsMutuallyExclusive("user", "group")
126 cmd.MarkFlagsMutuallyExclusive("expires-at", "duration")
127 return cmd
130func (o *options) complete(cmd *cobra.Command, args []string) error {
131 o.name = args[0]
133 if group, err := cmdutils.GroupOverride(cmd); err != nil {
134 return err
135 } else {
136 o.group = group
137 }
139 if time.Time(o.expireAt).IsZero() {
140 o.expireAt = expirationdate.ExpirationDate(o.duration.CalculateExpirationDate())
141 }
143 return nil
146func (o *options) validate(cmd *cobra.Command) error {
147 if o.user == "" && !cmd.Flag("access-level").Changed {
148 return cmdutils.FlagError{Err: errors.New("the required flag '--access-level' is not set")}
149 }
151 return nil
154func (o *options) run() error {
155 // NOTE: this command can not only be used for projects,
156 // so we have to manually check for the base repo, if it doesn't exist,
157 // we bootstrap the client with the default hostname.
158 var repoHost string
159 if baseRepo, err := o.baseRepo(); err == nil {
160 repoHost = baseRepo.RepoHost()
161 }
162 apiClient, err := o.apiClient(repoHost)
163 if err != nil {
164 return err
165 }
166 client := apiClient.Lab()
168 var outputToken any
169 var outputTokenValue string
170 expirationDate := gitlab.ISOTime(o.expireAt)
172 if o.user != "" {
173 user, err := api.UserByName(client, o.user)
174 if err != nil {
175 return err
176 }
178 options := &gitlab.ListPersonalAccessTokensOptions{
179 ListOptions: gitlab.ListOptions{PerPage: 100},
180 UserID: &user.ID,
181 }
182 tokens, err := gitlab.ScanAndCollect(func(p gitlab.PaginationOptionFunc) ([]*gitlab.PersonalAccessToken, *gitlab.Response, error) {
183 return client.PersonalAccessTokens.ListPersonalAccessTokens(options, p)
184 })
185 if err != nil {
186 return err
187 }
188 tokens = filter.Filter(tokens, func(t *gitlab.PersonalAccessToken) bool {
189 return t.Active && t.Name == o.name
190 })
191 if len(tokens) > 0 {
192 return cmdutils.FlagError{Err: fmt.Errorf("a personal access token with the name %s already exists", o.name)}
193 }
195 if o.user == "@me" {
196 token, _, err := client.Users.CreatePersonalAccessTokenForCurrentUser(&gitlab.CreatePersonalAccessTokenForCurrentUserOptions{
197 Name: new(o.name),
198 Scopes: new(o.scopes),
199 ExpiresAt: new(expirationDate),
200 })
201 if err != nil {
202 return err
203 }
204 outputToken = token
205 outputTokenValue = token.Token
206 } else {
207 createOptions := &gitlab.CreatePersonalAccessTokenOptions{
208 Name: &o.name,
209 Description: &o.description,
210 ExpiresAt: &expirationDate,
211 Scopes: &o.scopes,
212 }
213 token, _, err := client.Users.CreatePersonalAccessToken(user.ID, createOptions)
214 if err != nil {
215 return err
216 }
217 outputToken = token
218 outputTokenValue = token.Token
219 }
220 } else {
221 if o.group != "" {
222 listOptions := &gitlab.ListGroupAccessTokensOptions{ListOptions: gitlab.ListOptions{PerPage: 100}}
223 tokens, err := gitlab.ScanAndCollect(func(p gitlab.PaginationOptionFunc) ([]*gitlab.GroupAccessToken, *gitlab.Response, error) {
224 return client.GroupAccessTokens.ListGroupAccessTokens(o.group, listOptions, p)
225 })
226 if err != nil {
227 return err
228 }
229 tokens = filter.Filter(tokens, func(t *gitlab.GroupAccessToken) bool {
230 return t.Active && t.Name == o.name
231 })
232 if len(tokens) > 0 {
233 return cmdutils.FlagError{Err: fmt.Errorf("a group access token with the name %s already exists", o.name)}
234 }
236 options := &gitlab.CreateGroupAccessTokenOptions{
237 Name: &o.name,
238 Description: &o.description,
239 Scopes: &o.scopes,
240 AccessLevel: &o.accessLevel.Value,
241 ExpiresAt: &expirationDate,
242 }
243 token, _, err := client.GroupAccessTokens.CreateGroupAccessToken(o.group, options)
244 if err != nil {
245 return err
246 }
247 outputToken = token
248 outputTokenValue = token.Token
250 } else {
251 repo, err := o.baseRepo()
252 if err != nil {
253 return err
254 }
255 listOptions := &gitlab.ListProjectAccessTokensOptions{ListOptions: gitlab.ListOptions{PerPage: 100}}
256 tokens, err := gitlab.ScanAndCollect(func(p gitlab.PaginationOptionFunc) ([]*gitlab.ProjectAccessToken, *gitlab.Response, error) {
257 return client.ProjectAccessTokens.ListProjectAccessTokens(repo.FullName(), listOptions, p)
258 })
259 if err != nil {
260 return err
261 }
262 tokens = filter.Filter(tokens, func(t *gitlab.ProjectAccessToken) bool {
263 return t.Active && t.Name == o.name
264 })
266 if len(tokens) > 0 {
267 return cmdutils.FlagError{Err: fmt.Errorf("a project access token with name %s already exists", o.name)}
268 }
270 options := &gitlab.CreateProjectAccessTokenOptions{
271 Name: &o.name,
272 Description: &o.description,
273 Scopes: &o.scopes,
274 AccessLevel: &o.accessLevel.Value,
275 ExpiresAt: &expirationDate,
276 }
277 token, _, err := client.ProjectAccessTokens.CreateProjectAccessToken(repo.FullName(), options)
278 if err != nil {
279 return err
280 }
281 outputToken = token
282 outputTokenValue = token.Token
283 }
284 }
286 if o.outputFormat == "json" {
287 if err := o.io.PrintJSON(outputToken); err != nil {
288 return err
289 }
290 } else if _, err := fmt.Fprintln(o.io.StdOut, outputTokenValue); err != nil { //nolint:forbidigo // write error must propagate to the caller
291 return err
292 }
294 return nil
Diagnostics8 git calls · 322 ms
CallStatusSizeTime0322 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 · 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=32926
git.response.cache=HIT
git.response.duration_ms=3
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=44
Open 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 · 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=fb03183b7909876778f740d196d7516811003517
Open pack map
fetchtree:0200358 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=358
git.response.cache=HIT
git.response.duration_ms=3
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=fbb77d44047cd3e1ee682eb9483227c59489e50f
Open pack map
fetchtree:0200138 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=138
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=f924ab3692a685efef99065da41019864d999ac9
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=138
git.pkt.payload.max=111
git.sideband.band1.bytes=111
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=111
git.pack.trailer=9ac4c7f75d8462b5054c2962ca1c06c51d22edb2
Open pack map
fetch2003.2 KiB306 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=306
git.response.bytes=3280
git.response.cache=MISS
git.response.duration_ms=306
git.fetch.wants=0846bfdcdad5567921712162ea533786145faaa2
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=3280
git.pkt.payload.max=3253
git.sideband.band1.bytes=3253
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
a5e267d0ced8df63
Request
a64b1796…
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