GitLabgitlab-org

cli

main
ply8 git calls367 ms100 KiB5 cachedprotocol v2
206 lines6.7 KiBRaw
1package create
3import (
4 "context"
5 "time"
7 "github.com/MakeNowJust/heredoc/v2"
8 "github.com/spf13/cobra"
10 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
12 "gitlab.com/gitlab-org/cli/internal/api"
13 "gitlab.com/gitlab-org/cli/internal/cmdutils"
14 "gitlab.com/gitlab-org/cli/internal/commands/deploy-token/display"
15 "gitlab.com/gitlab-org/cli/internal/glrepo"
16 "gitlab.com/gitlab-org/cli/internal/iostreams"
17 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
18 "gitlab.com/gitlab-org/cli/internal/tableprinter"
21type options struct {
22 io *iostreams.IOStreams
23 apiClient func(repoHost string) (*api.Client, error)
24 baseRepo func() (glrepo.Interface, error)
26 name string
27 scopes []string
28 username string
29 usernameSet bool
30 expiresAt time.Time
31 expiresAtSet bool
32 group string
33 outputFormat string
36func NewCmd(f cmdutils.Factory) *cobra.Command {
37 opts := &options{
38 io: f.IO(),
39 apiClient: f.ApiClient,
40 baseRepo: f.BaseRepo,
41 }
43 cmd := &cobra.Command{
44 Use: "create <name> [flags]",
45 Short: "Create a deploy token.",
46 Args: cobra.ExactArgs(1),
47 ValidArgsFunction: cobra.NoFileCompletions,
48 Long: heredoc.Docf(`
49 Create a deploy token for a project or a group.
51 The token value is printed only once, when the token is created, and cannot be retrieved later. Use %[1]s--output json%[1]s to capture it from a script.
53 A deploy token authenticates as a username and token pair, so both values from the output are needed to use it.
55 The token does not expire unless %[1]s--expires-at%[1]s is given.
57 Every token must be granted at least one scope with %[1]s--scope%[1]s. For the scopes you can grant, see https://docs.gitlab.com/user/project/deploy_tokens/#scope.
58 `, "`"),
59 Example: heredoc.Doc(`
60 # Create a read-only deploy token for the current project
61 glab deploy-token create ci-reader --scope read_repository
63 # Create a token that can also pull images from the container registry
64 glab deploy-token create ci-reader --scope read_repository --scope read_registry
66 # Create a token for a specific project, with a custom username
67 glab deploy-token create ci-reader --scope read_repository --username ci-reader --repo user/my-repo
69 # Create a token that is valid until the end of 2027
70 glab deploy-token create ci-reader --scope read_repository --expires-at 2028-01-01
72 # Create a group deploy token
73 glab deploy-token create ci-reader --scope read_repository --group group/sub-group
75 # Create the token that CI/CD jobs receive as CI_DEPLOY_USER and CI_DEPLOY_PASSWORD
76 glab deploy-token create gitlab-deploy-token --scope read_registry
78 # Create a token and print its username and value from a script
79 glab deploy-token create ci-reader --scope read_repository --output json --jq '"\(.username) \(.token)"'`),
80 Annotations: map[string]string{
81 // Creating a token prints a secret, so this command is kept out of MCP,
82 // as glab token create is.
83 mcpannotations.Exclude: "true",
84 },
85 RunE: func(cmd *cobra.Command, args []string) error {
86 if err := opts.complete(cmd, args); err != nil {
87 return err
88 }
90 return opts.run(cmd.Context())
91 },
92 }
94 cmdutils.EnableRepoOverride(cmd, f)
96 fl := cmd.Flags()
97 fl.StringVarP(&opts.group, "group", "g", "", "Create a deploy token for a `group` instead of a project. Accepts a group ID or full path.")
98 fl.StringSliceVarP(&opts.scopes, "scope", "S", nil, "Scope to grant the token. Multiple scopes can be comma-separated or specified by repeating the flag.")
99 fl.StringVar(&opts.username, "username", "", "Username for the token. Defaults to 'gitlab+deploy-token-<id>'.")
100 fl.TimeVarP(&opts.expiresAt, "expires-at", "E", time.Time{}, []string{time.DateOnly, time.RFC3339}, "Expiry of the token, as YYYY-MM-DD (00:00 UTC) or an RFC 3339 timestamp. The token does not expire if omitted.")
102 cobra.CheckErr(cmd.MarkFlagRequired("scope"))
104 cmdutils.EnableJSONOutput(cmd, opts.io, &opts.outputFormat)
105 cmd.MarkFlagsMutuallyExclusive("repo", "group")
107 return cmd
110func (o *options) complete(cmd *cobra.Command, args []string) error {
111 o.name = args[0]
112 o.usernameSet = cmd.Flags().Changed("username")
113 o.expiresAtSet = cmd.Flags().Changed("expires-at")
115 group, err := cmdutils.GroupOverride(cmd)
116 if err != nil {
117 return err
118 }
119 o.group = group
121 return nil
124func (o *options) run(ctx context.Context) error {
125 // The group scope works outside a repository, so a missing base repo is only
126 // fatal for the project scope. Fail before building a client that would be
127 // discarded, so the caller sees why the repository was needed.
128 repo, repoErr := o.baseRepo()
129 if o.group == "" && repoErr != nil {
130 return repoErr
131 }
133 var repoHost string
134 if repoErr == nil {
135 repoHost = repo.RepoHost()
136 }
138 apiClient, err := o.apiClient(repoHost)
139 if err != nil {
140 return err
141 }
142 client := apiClient.Lab()
144 // The API treats an omitted expiry as "never expires" and an omitted username
145 // as "assign the default one", so neither is sent unless it was asked for.
146 // Both are keyed off the flag rather than its value: the zero time is a
147 // parseable date, so a value test would read 0001-01-01 back as "no expiry".
148 var expiresAt *time.Time
149 if o.expiresAtSet {
150 expiresAt = &o.expiresAt
151 }
153 var username *string
154 if o.usernameSet {
155 username = &o.username
156 }
158 var (
159 token *gitlab.DeployToken
160 target string
161 )
162 switch {
163 case o.group != "":
164 target = "group " + o.group
165 token, _, err = client.DeployTokens.CreateGroupDeployToken(o.group, &gitlab.CreateGroupDeployTokenOptions{
166 Name: &o.name,
167 Scopes: &o.scopes,
168 Username: username,
169 ExpiresAt: expiresAt,
170 }, gitlab.WithContext(ctx))
171 default:
172 target = "project " + repo.FullName()
173 token, _, err = client.DeployTokens.CreateProjectDeployToken(repo.FullName(), &gitlab.CreateProjectDeployTokenOptions{
174 Name: &o.name,
175 Scopes: &o.scopes,
176 Username: username,
177 ExpiresAt: expiresAt,
178 }, gitlab.WithContext(ctx))
179 }
180 if err != nil {
181 return cmdutils.WrapError(err, "failed to create deploy token")
182 }
184 switch o.outputFormat {
185 case "json":
186 return o.io.PrintJSON(token)
187 default:
188 return o.printDetails(token, target)
189 }
192func (o *options) printDetails(token *gitlab.DeployToken, target string) error {
193 c := o.io.Color()
194 table := tableprinter.NewTablePrinter()
195 table.AddRow(c.Bold("ID"), token.ID)
196 table.AddRow(c.Bold("Name"), token.Name)
197 table.AddRow(c.Bold("Username"), token.Username)
198 table.AddRow(c.Bold("Scopes"), display.Scopes(token.Scopes))
199 table.AddRow(c.Bold("Expires At"), display.ExpiresAt(token.ExpiresAt))
200 table.AddRow(c.Bold("Token"), token.Token)
201 o.io.LogInfof("%s", table.Render())
203 o.io.LogErrorf("%s Created a deploy token for %s. Store the token value now. It is not shown again.\n", c.WarnIcon(), target)
205 return nil
Diagnostics8 git calls · 367 ms
CallStatusSizeTime0367 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 KiB152 ms
git.upload-pack ls-refs
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=139
git.response.bytes=59849
git.response.cache=EXPIRED
git.response.duration_ms=152
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=44
Open pack map
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:0200263 B · hit1 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=1
git.response.bytes=263
git.response.cache=HIT
git.response.duration_ms=1
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=4076aed8a003d312c41b730611843784ab33181f
Open pack map
fetchtree:0200137 B · hit5 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=5
git.response.bytes=137
git.response.cache=HIT
git.response.duration_ms=5
git.fetch.filter=tree:0
git.fetch.wants=81cde88ec377c1b5b3312ec40e8e294b0fd83139
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=af3e93156ce1ec31cf719a81df0fc78f52360639
Open pack map
fetch2002.6 KiB202 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=202
git.response.bytes=2651
git.response.cache=MISS
git.response.duration_ms=202
git.fetch.wants=fe15857828876f8977a63e679ed5f095825921e1
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=2651
git.pkt.payload.max=2624
git.sideband.band1.bytes=2624
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
a5e27eeaea700555
Request
22de31df…
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