GitLabgitlab-org
cli
main
1package create
3import (
4 "bytes"
5 "context"
6 "errors"
7 "fmt"
8 "io"
9 "io/fs"
10 "net/http"
11 "os"
12 "slices"
13 "strconv"
14 "strings"
15 "time"
17 "charm.land/huh/v2"
18 "github.com/MakeNowJust/heredoc/v2"
19 "github.com/spf13/cobra"
20 "github.com/spf13/pflag"
22 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
24 "gitlab.com/gitlab-org/cli/internal/api"
25 "gitlab.com/gitlab-org/cli/internal/cmdutils"
26 catalog "gitlab.com/gitlab-org/cli/internal/commands/project/publish/catalog"
27 "gitlab.com/gitlab-org/cli/internal/commands/release/releaseutils"
28 "gitlab.com/gitlab-org/cli/internal/commands/release/releaseutils/upload"
29 "gitlab.com/gitlab-org/cli/internal/config"
30 "gitlab.com/gitlab-org/cli/internal/dbg"
31 "gitlab.com/gitlab-org/cli/internal/git"
32 "gitlab.com/gitlab-org/cli/internal/glrepo"
33 "gitlab.com/gitlab-org/cli/internal/iostreams"
34 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
35 "gitlab.com/gitlab-org/cli/internal/run"
36 "gitlab.com/gitlab-org/cli/internal/utils"
37)
39type noteOptions int
41const (
42 noteOptMyOwn noteOptions = iota
43 noteOptCommitLog
44 noteOptGitTagMessage
45 noteOptLeaveBlank
46)
48var noteOptionsNames = map[noteOptions]string{
49 noteOptMyOwn: "Write my own.",
50 noteOptCommitLog: "Write using the commit log as a template.",
51 noteOptGitTagMessage: "Write using the Git tag message as the template.",
52 noteOptLeaveBlank: "Leave blank.",
53}
55type options struct {
56 // The following fields must be exported for use with huh forms
57 Name string
58 ReleaseNotesAction string
60 ref string
61 tagName string
62 tagMessage string
63 notes string
64 notesFile string
65 experimentalNotesTextOrFile string
66 milestone []string
67 assetLinksAsJSON string
68 releasedAt string
69 repoOverride string
70 publishToCatalog bool
71 noUpdate bool
72 noCloseMilestone bool
74 noteProvided bool
75 nameProvided bool
77 assetLink []*upload.ReleaseAsset
78 assetFiles []*upload.ReleaseFile
80 usePackageRegistry bool
81 packageName string
83 ctx context.Context
84 io *iostreams.IOStreams
85 gitlabClient func() (*gitlab.Client, error)
86 apiClient func(repoHost string) (*api.Client, error)
87 baseRepo func() (glrepo.Interface, error)
88 config func() config.Config
89}
91func NewCmdCreate(f cmdutils.Factory) *cobra.Command {
92 opts := &options{
93 io: f.IO(),
94 gitlabClient: f.GitLabClient,
95 apiClient: f.ApiClient,
96 baseRepo: f.BaseRepo,
97 config: f.Config,
98 }
100 cmd := &cobra.Command{
101 Use: "create <tag> [<files>...]",
102 Short: "Create a new GitLab release, or update an existing one.",
103 Long: heredoc.Docf(`Create a new GitLab release for a repository, or
104 update an existing one. Requires at least the Developer role.
106 An existing release is updated with the new information you provide.
108 To create a release from an annotated Git tag:
110 1. Create the tag locally with Git, and push the tag to GitLab.
111 2. Run this command.
112 3. If the Git tag you specify doesn't exist, the command creates a
113 release from the latest state of the default branch, and tags it
114 with the tag name you specify.
116 To override this behavior, use %[1]s--ref%[1]s. The %[1]sref%[1]s
117 can be a commit SHA, another tag name, or a branch name.
118 4. Optional. To fetch the new tag locally after the release, run
119 %[1]sgit fetch --tags origin%[1]s.
121 Authentication in CI/CD:
123 - Recommended: Use %[1]sCI_JOB_TOKEN%[1]s and turn on CI auto-login by
124 setting %[1]sGLAB_ENABLE_CI_AUTOLOGIN=true%[1]s. glab sends
125 %[1]sCI_JOB_TOKEN%[1]s in the %[1]sJOB-TOKEN%[1]s header, which the Releases
126 API accepts.
127 - The Milestones API does not accept %[1]sCI_JOB_TOKEN%[1]s, so the token cannot
128 close milestones.
129 - If you use %[1]s--milestone%[1]s, the release is still created and the command
130 exits successfully. The milestone stays open and glab logs an error.
131 To avoid the error, use %[1]s--no-close-milestone%[1]s.
132 - Alternative: Use %[1]sGITLAB_TOKEN%[1]s set to a project or group access token with the
133 %[1]sapi%[1]s scope. With this token, %[1]s--milestone%[1]s can close milestones.
134 - Do not set %[1]sGITLAB_TOKEN=$CI_JOB_TOKEN%[1]s because the Releases API will
135 return a %[1]s404 Not Found%[1]s. %[1]sGITLAB_TOKEN%[1]s is sent as a personal access token in
136 the %[1]sPRIVATE-TOKEN%[1]s header, which the Releases API does not accept.
138 The %[1]s--publish-to-catalog%[1]s flag is an experiment: it might be
139 unstable or removed at any time, and is not ready for production use.
140 For more information, see
141 https://docs.gitlab.com/policy/development_stages_support/.
142 `, "`"),
143 Args: cobra.MinimumNArgs(1),
144 Example: heredoc.Docf(`
145 # Create a release interactively
146 glab release create v1.0.1
148 # Create a release non-interactively by specifying a note
149 glab release create v1.0.1 --notes "bugfix release"
151 # Use release notes from a file
152 glab release create v1.0.1 -F changelog.md
154 # Update an existing release (e.g., change the release date) without modifying notes
155 glab release create v1.0.1 --released-at "2024-01-15T10:00:00Z"
157 # Upload a release asset with a display name (type will default to 'other')
158 glab release create v1.0.1 '/path/to/asset.zip#My display label'
160 # Upload a release asset with a display name and type
161 glab release create v1.0.1 '/path/to/asset.png#My display label#image'
163 # Upload all assets in a specified folder (types default to 'other')
164 glab release create v1.0.1 ./dist/*
166 # Upload all tarballs in a specified folder (types default to 'other')
167 glab release create v1.0.1 ./dist/*.tar.gz
169 # Create a release from a CI/CD job using the job token
170 GLAB_ENABLE_CI_AUTOLOGIN=true glab release create v1.0.1 --notes "See CHANGELOG.md" --ref "$CI_COMMIT_SHA"
172 # Create a release from a CI/CD job using a project or group access token with the 'api' scope
173 GITLAB_TOKEN="$ACCESS_TOKEN" glab release create v1.0.1 --notes "See CHANGELOG.md" --ref "$CI_COMMIT_SHA"
175 # Create a release with assets, such as packages, specified as a JSON object
176 glab release create v1.0.1 --assets-links='
177 [
178 {
179 "name": "Asset1",
180 "url":"https://<domain>/some/location/1",
181 "link_type": "other",
182 "direct_asset_path": "path/to/file"
183 }
184 ]'
186 # (EXPERIMENTAL) Create a release and publish it to the GitLab CI/CD catalog
187 # Requires the feature flag %[1]sci_release_cli_catalog_publish_option%[1]s to be enabled
188 # for this project in your GitLab instance. Do NOT run this manually. Use it as part
189 # of a CI/CD pipeline with the "release" keyword:
190 #
191 # - It retrieves components from the current repository by searching for
192 # %[1]syml%[1]s files within the "templates" directory and its subdirectories.
193 # - It fails if the feature flag %[1]sci_release_cli_catalog_publish_option%[1]s
194 # is not enabled for this project in your GitLab instance.
196 # Components can be defined:
198 # - In single files ending in %[1]s.yml%[1]s for each component, like %[1]stemplates/secret-detection.yml%[1]s.
199 # - In subdirectories containing %[1]stemplate.yml%[1]s files as entry points,
200 # for components that bundle together multiple related files. For example,
201 # %[1]stemplates/secret-detection/template.yml%[1]s.
203 glab release create v1.0.1 --publish-to-catalog`, "`"),
204 Annotations: map[string]string{
205 mcpannotations.Destructive: "true",
206 },
207 RunE: func(cmd *cobra.Command, args []string) error {
208 opts.ctx = cmd.Context()
209 if err := opts.complete(cmd.Flags(), args); err != nil {
210 return err
211 }
213 return createRun(opts)
214 },
215 }
217 fl := cmd.Flags()
218 fl.StringVarP(&opts.Name, "name", "n", "", "The release name or title.")
219 fl.StringVarP(&opts.ref, "ref", "r", "", "If the specified tag doesn't exist, create a release from the ref and tag it with the specified tag name. Accepts a commit SHA, tag name, or branch name.")
220 fl.StringVarP(&opts.tagMessage, "tag-message", "T", "", "Message to use if creating a new annotated tag.")
221 fl.StringVarP(&opts.notes, "notes", "N", "", "The release notes or description. Accepts Markdown.")
222 fl.StringVarP(&opts.notesFile, "notes-file", "F", "", "Read release notes 'file'. To read from stdin, use '-'. If both --notes and --notes-file are set, --notes takes precedence.")
223 fl.StringVarP(&opts.releasedAt, "released-at", "D", "", "ISO 8601 datetime when the release was ready. Defaults to the current datetime.")
224 fl.StringSliceVarP(&opts.milestone, "milestone", "m", []string{}, "The title of each milestone the release is associated with. Multiple milestones can be comma-separated or specified by repeating the flag.")
225 fl.StringVarP(&opts.assetLinksAsJSON, "assets-links", "a", "", "JSON string representation of assets links. See Examples for usage.")
226 fl.BoolVar(&opts.publishToCatalog, "publish-to-catalog", false, "(EXPERIMENTAL) Publish the release to the GitLab CI/CD catalog.")
227 fl.BoolVar(&opts.noUpdate, "no-update", false, "Prevent updating the existing release.")
228 fl.BoolVar(&opts.noCloseMilestone, "no-close-milestone", false, "Prevent closing milestones after creating the release.")
229 fl.StringVar(&opts.experimentalNotesTextOrFile, "experimental-notes-text-or-file", "", "(EXPERIMENTAL) Value to use as release notes. If a file exists with this value as path, its content will be used. Otherwise, the value itself will be used as text.")
230 fl.BoolVar(&opts.usePackageRegistry, "use-package-registry", false, "Upload release assets to the generic package registry of the project. Overrides the GITLAB_RELEASE_ASSETS_USE_PACKAGE_REGISTRY environment variable.")
231 fl.StringVar(&opts.packageName, "package-name", upload.DefaultReleasePackageName, "The package name, when uploading assets to the generic package release with --use-package-registry.")
232 cobra.CheckErr(fl.MarkHidden("experimental-notes-text-or-file"))
234 // These two need to be separately exclusive to avoid a breaking change
235 // because there may be existing scripts that already use both notes and notes-file.
236 cmd.MarkFlagsMutuallyExclusive("experimental-notes-text-or-file", "notes")
237 cmd.MarkFlagsMutuallyExclusive("experimental-notes-text-or-file", "notes-file")
239 return cmd
240}
242func (o *options) complete(flags *pflag.FlagSet, args []string) error {
243 o.repoOverride, _ = flags.GetString("repo")
245 o.tagName = args[0]
247 assetFiles, err := releaseutils.AssetsFromArgs(args[1:])
248 if err != nil {
249 return err
250 }
251 o.assetFiles = assetFiles
253 if o.assetLinksAsJSON != "" {
254 o.assetLink, err = releaseutils.AssetLinksFromJSON(o.assetLinksAsJSON)
255 if err != nil {
256 return err
257 }
258 }
260 o.nameProvided = flags.Changed("name")
262 o.notes, err = resolveNotes(flags, o)
263 if err != nil {
264 return err
265 }
266 o.noteProvided = flags.Changed("notes") || flags.Changed("notes-file") || flags.Changed("experimental-notes-text-or-file") || o.notes != ""
268 if !flags.Changed("use-package-registry") {
269 if usePackageRegistry, err := strconv.ParseBool(os.Getenv("GITLAB_RELEASE_ASSETS_USE_PACKAGE_REGISTRY")); err == nil {
270 o.usePackageRegistry = usePackageRegistry
271 }
272 }
274 return nil
275}
277func resolveNotes(flags *pflag.FlagSet, opts *options) (string, error) {
278 if flags.Changed("notes") {
279 if flags.Changed("notes-file") {
280 opts.io.LogErrorf("%s --notes and --notes-file were both given: using --notes and ignoring --notes-file. Passing both will be an error in a future major release.\n", opts.io.Color().WarnIcon())
281 }
282 return opts.notes, nil
283 }
285 if opts.notesFile != "" {
286 return resolveNotesFile(opts)
287 }
289 if opts.experimentalNotesTextOrFile != "" {
290 return resolveNotesFileOrText(opts)
291 }
293 return "", nil
294}
296func resolveNotesFile(opts *options) (string, error) {
297 var b []byte
298 var err error
300 if opts.notesFile == "-" {
301 b, err = io.ReadAll(opts.io.In)
302 _ = opts.io.In.Close()
303 } else {
304 b, err = os.ReadFile(opts.notesFile)
305 }
307 if err != nil {
308 return "", err
309 }
311 return string(b), nil
312}
314func resolveNotesFileOrText(opts *options) (_ string, err error) {
315 // Rules from: https://docs.gitlab.com/ci/yaml/#releasedescription
317 // Rule 1: A file path can't have spaces
318 if strings.Contains(strings.TrimSpace(opts.experimentalNotesTextOrFile), " ") {
319 return opts.experimentalNotesTextOrFile, nil
320 }
322 // Rule 2: A file must be relative to the repository
323 baseDir, err := os.Getwd()
324 if err != nil {
325 return "", err
326 }
327 root, err := os.OpenRoot(baseDir)
328 if err != nil {
329 return "", err
330 }
331 defer func() { err = errors.Join(err, root.Close()) }()
333 f, err := root.Open(opts.experimentalNotesTextOrFile)
334 if err != nil {
335 // If the file simply doesn't exist, treat the value as text.
336 // For any other error (e.g., permission denied), report it so
337 // the user knows the file was found but couldn't be read.
338 if errors.Is(err, fs.ErrNotExist) || errors.Is(err, fs.ErrInvalid) {
339 return opts.experimentalNotesTextOrFile, nil
340 }
341 return "", fmt.Errorf("could not open file %q: %w", opts.experimentalNotesTextOrFile, err)
342 }
343 defer func() {
344 err = errors.Join(err, f.Close())
345 }()
347 b, err := io.ReadAll(f)
348 if err != nil {
349 return "", fmt.Errorf("could not read file %q: %w", opts.experimentalNotesTextOrFile, err)
350 }
352 return string(b), nil
353}
355func createRun(opts *options) error {
356 client, err := opts.gitlabClient()
357 if err != nil {
358 return err
359 }
361 repo, err := opts.baseRepo()
362 if err != nil {
363 return err
364 }
365 color := opts.io.Color()
366 var tag *gitlab.Tag
368 if opts.ref == "" {
369 opts.io.LogInfo(color.ProgressIcon(), "Validating tag", opts.tagName)
370 var resp *gitlab.Response
371 tag, resp, err = client.Tags.GetTag(repo.FullName(), opts.tagName)
372 notFound := gitlab.HasStatusCode(err, http.StatusNotFound) ||
373 (resp != nil && resp.StatusCode == http.StatusNotFound)
374 if err != nil && !notFound {
375 return cmdutils.WrapError(err, "could not fetch tag")
376 }
377 if tag == nil && notFound {
378 opts.io.LogInfo(color.DotWarnIcon(), "Tag does not exist.")
379 opts.io.LogInfo(color.DotWarnIcon(), "No ref provided. Creating the tag from the latest state of the default branch.")
380 project, err := repo.Project(client)
381 if err != nil {
382 // We are not able to retrieve the project from the API.
383 // This is most likely because we are running in CI with a CI Job Token
384 // which does not have access to the Projects API. Thus, let's check if we have access
385 // to the predefined CI/CD variable CI_DEFAULT_BRANCH and use it instead if available.
386 if defaultBranch, found := os.LookupEnv("CI_DEFAULT_BRANCH"); found {
387 opts.io.LogInfof("%s using default branch %q as ref from CI_DEFAULT_BRANCH\n", color.ProgressIcon(), defaultBranch)
388 opts.ref = defaultBranch
389 }
390 } else {
391 opts.io.LogInfof("%s using default branch %q as ref\n", color.ProgressIcon(), project.DefaultBranch)
392 opts.ref = project.DefaultBranch
393 }
394 }
395 }
397 if opts.io.PromptEnabled() && !opts.noteProvided {
398 editorCommand, err := cmdutils.GetEditor(opts.config)
399 if err != nil {
400 return err
401 }
403 var tagDescription string
404 var generatedChangelog string
405 if tag == nil {
406 tag, _, _ = client.Tags.GetTag(repo.FullName(), opts.tagName)
407 }
408 if tag != nil {
409 tagDescription = tag.Message
410 }
411 if opts.repoOverride == "" {
412 headRef := opts.tagName
413 if tagDescription == "" {
414 if opts.ref != "" {
415 headRef = opts.ref
416 brCfg := git.ReadBranchConfig(opts.ref)
417 if brCfg.MergeRef != "" {
418 headRef = brCfg.MergeRef
419 }
420 } else {
421 headRef = "HEAD"
422 }
423 }
425 if prevTag, err := detectPreviousTag(headRef); err == nil {
426 commits, _ := changelogForRange(fmt.Sprintf("%s..%s", prevTag, headRef))
427 generatedChangelog = generateChangelog(commits)
428 }
429 }
431 editorOptions := []string{noteOptionsNames[noteOptMyOwn]}
432 if generatedChangelog != "" {
433 editorOptions = append(editorOptions, noteOptionsNames[noteOptCommitLog])
434 }
435 if tagDescription != "" {
436 editorOptions = append(editorOptions, noteOptionsNames[noteOptGitTagMessage])
437 }
438 editorOptions = append(editorOptions, noteOptionsNames[noteOptLeaveBlank])
440 // Combine title and release notes selection into a single form
441 var fields []huh.Field
443 // Add title input field
444 fields = append(fields, huh.NewInput().
445 Title("Release title (optional)").
446 Value(&opts.Name))
448 // Add release notes selection field
449 fields = append(fields, huh.NewSelect[string]().
450 Title("Release notes").
451 Options(huh.NewOptions(editorOptions...)...).
452 Value(&opts.ReleaseNotesAction))
454 // Run the combined form
455 err = opts.io.RunForm(opts.ctx, fields...)
456 if err != nil {
457 return fmt.Errorf("could not prompt: %w", err)
458 }
460 var openEditor bool
461 var editorContents string
463 switch opts.ReleaseNotesAction {
464 case noteOptionsNames[noteOptMyOwn]:
465 openEditor = true
466 case noteOptionsNames[noteOptCommitLog]:
467 openEditor = true
468 editorContents = generatedChangelog
469 case noteOptionsNames[noteOptGitTagMessage]:
470 openEditor = true
471 editorContents = tagDescription
472 case noteOptionsNames[noteOptLeaveBlank]:
473 openEditor = false
474 default:
475 return fmt.Errorf("invalid action: %v", opts.ReleaseNotesAction)
476 }
478 if openEditor {
479 err = opts.io.Editor(opts.ctx, &opts.notes, "Release notes", "", editorContents, editorCommand)
480 if err != nil {
481 return err
482 }
483 opts.noteProvided = true
484 } else if opts.ReleaseNotesAction == noteOptionsNames[noteOptLeaveBlank] {
485 opts.noteProvided = false
486 opts.notes = ""
487 }
489 if opts.Name != "" {
490 opts.nameProvided = true
491 }
492 }
493 start := time.Now()
495 opts.io.LogInfof("%s Creating or updating release %s=%s %s=%s\n",
496 color.ProgressIcon(),
497 color.Blue("repo"), repo.FullName(),
498 color.Blue("tag"), opts.tagName)
500 release, resp, err := client.Releases.GetRelease(repo.FullName(), opts.tagName)
501 if err != nil && (resp == nil || (resp.StatusCode != http.StatusForbidden && resp.StatusCode != http.StatusNotFound)) {
502 return releaseFailedErr(err, start)
503 }
505 var releasedAt time.Time
507 if opts.releasedAt != "" {
508 // Parse the releasedAt to the expected format of the API
509 // From the API docs "Expected in ISO 8601 format (2019-03-15T08:00:00Z)".
510 layout := time.RFC3339
511 if len(opts.releasedAt) < len(layout) {
512 layout = layout[:len(opts.releasedAt)]
513 }
514 releasedAt, err = time.Parse(layout, opts.releasedAt)
515 if err != nil {
516 return releaseFailedErr(err, start)
517 }
518 }
520 if (resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusNotFound) || release == nil {
521 if opts.Name == "" {
522 opts.Name = opts.tagName
523 }
525 createOpts := &gitlab.CreateReleaseOptions{
526 Name: &opts.Name,
527 TagName: &opts.tagName,
528 }
530 if opts.notes != "" {
531 createOpts.Description = &opts.notes
532 }
534 if opts.ref != "" {
535 createOpts.Ref = &opts.ref
536 }
538 if opts.tagMessage != "" {
539 createOpts.TagMessage = &opts.tagMessage
540 }
542 if opts.releasedAt != "" {
543 createOpts.ReleasedAt = &releasedAt
544 }
546 if len(opts.milestone) > 0 {
547 createOpts.Milestones = &opts.milestone
548 }
550 aliasedNames, err := upload.AliasFilePaths(opts.assetLink)
551 if err != nil {
552 return releaseFailedErr(err, start)
553 }
555 uploadCtx := upload.Context{IO: opts.io, Client: client, AssetFiles: opts.assetFiles}
556 uploadedAssets, err := uploadCtx.UploadAssetFiles(opts.ctx, repo.FullName(), opts.tagName, opts.packageName, opts.usePackageRegistry)
557 if err != nil {
558 return releaseFailedErr(cmdutils.WrapError(err, "upload failed"), start)
559 }
560 createOpts.Assets = upload.ToReleaseAssetsOptions(slices.Concat(opts.assetLink, uploadedAssets))
562 release, _, err = client.Releases.CreateRelease(repo.FullName(), createOpts)
563 if err != nil {
564 return releaseFailedErr(err, start)
565 }
566 opts.io.LogInfof("%s Release created:\t%s=%s\n", color.GreenCheck(),
567 color.Blue("url"), release.Links.Self)
569 for _, link := range release.Assets.Links {
570 opts.io.LogInfof("%s Added release asset\t%s=%s %s=%s\n",
571 color.GreenCheck(), color.Blue("name"), link.Name,
572 color.Blue("url"), link.DirectAssetURL)
573 }
574 for _, name := range aliasedNames {
575 opts.io.LogInfof("\t%s Aliased deprecated `filepath` field to `direct_asset_path`. Replace `filepath` with `direct_asset_path`\t%s=%s\n",
576 color.WarnIcon(), color.Blue("name"), name)
577 }
578 } else {
579 if opts.noUpdate {
580 return releaseFailedErr(fmt.Errorf("release for tag %q already exists and --no-update flag was specified", opts.tagName), start)
581 }
583 name := release.Name
584 if opts.nameProvided {
585 name = opts.Name
586 }
587 if name == "" {
588 name = opts.tagName
589 }
591 updateOpts := &gitlab.UpdateReleaseOptions{
592 Name: &name,
593 }
594 if opts.noteProvided {
595 updateOpts.Description = &opts.notes
596 } else {
597 updateOpts.Description = &release.Description
598 }
600 if opts.releasedAt != "" {
601 updateOpts.ReleasedAt = &releasedAt
602 }
604 if len(opts.milestone) > 0 {
605 updateOpts.Milestones = &opts.milestone
606 }
608 release, _, err = client.Releases.UpdateRelease(repo.FullName(), opts.tagName, updateOpts)
609 if err != nil {
610 return releaseFailedErr(err, start)
611 }
613 opts.io.LogInfof("%s Release updated\t%s=%s\n", color.GreenCheck(),
614 color.Blue("url"), release.Links.Self)
616 // upload files and create asset links
617 err = releaseutils.CreateReleaseAssets(opts.ctx, opts.io, client, opts.assetFiles, opts.assetLink, repo.FullName(), release.TagName, opts.packageName, opts.usePackageRegistry)
618 if err != nil {
619 return releaseFailedErr(err, start)
620 }
621 }
623 if opts.noCloseMilestone {
624 opts.io.LogInfof("%s Skipping closing milestones\n", color.GreenCheck())
625 } else if len(opts.milestone) > 0 {
626 for _, milestone := range opts.milestone {
627 opts.io.StartSpinner("Closing milestone %q", milestone)
628 err := closeMilestone(opts, milestone)
629 opts.io.StopSpinner("")
630 if err != nil {
631 opts.io.LogError(color.FailedIcon(), closeMilestoneErr(opts, repo.RepoHost(), err).Error())
632 } else {
633 opts.io.LogInfof("%s Closed milestone %q\n", color.GreenCheck(), milestone)
634 }
635 }
636 }
637 opts.io.LogInfof(color.Bold("%s Release succeeded after %0.2f seconds.\n"), color.GreenCheck(), time.Since(start).Seconds())
639 if opts.publishToCatalog {
640 err = catalog.Publish(opts.io, client, repo.FullName(), release.TagName)
641 if err != nil {
642 return cmdutils.WrapError(err, "failed to publish the release to the GitLab CI/CD catalog.")
643 }
644 }
646 return nil
647}
649func releaseFailedErr(err error, start time.Time) error {
650 message := fmt.Sprintf("release failed after %0.2f seconds.", time.Since(start).Seconds())
651 if gitlab.HasStatusCode(err, http.StatusUnprocessableEntity) && strings.Contains(strings.ToLower(err.Error()), "semver must follow semantic version") {
652 err = fmt.Errorf("%w. Use a MAJOR.MINOR.PATCH tag such as 1.0.0, v1.0.0, or 1.0.0-alpha. Only a lowercase v prefix is allowed, and numeric identifiers must not have leading zeros. See https://docs.gitlab.com/ci/components/#semantic-versioning", err)
653 }
654 return cmdutils.WrapError(err, message)
655}
657// closeMilestoneErr explains a 401 or 403 only for a job token, the one
658// credential that can create a release but never reach the Milestones API.
659func closeMilestoneErr(opts *options, repoHost string, err error) error {
660 if !gitlab.HasStatusCode(err, http.StatusUnauthorized) && !gitlab.HasStatusCode(err, http.StatusForbidden) {
661 return err
662 }
663 client, clientErr := opts.apiClient(repoHost)
664 if clientErr != nil {
665 dbg.Debugf("release create: no API client for milestone hint: %v", clientErr)
666 return err
667 }
668 kind, kindErr := client.CredentialKind()
669 if kindErr != nil {
670 dbg.Debugf("release create: unknown credential kind for milestone hint: %v", kindErr)
671 }
672 if kind != api.CredentialJobToken {
673 return err
674 }
675 return fmt.Errorf("%w. A CI_JOB_TOKEN cannot access the Milestones API. To close milestones, use a project or group access token with the api scope. To avoid this error, use --no-close-milestone", err)
676}
678func getMilestoneByTitle(c *options, title string) (*gitlab.Milestone, error) {
679 opts := &gitlab.ListMilestonesOptions{
680 Title: &title,
681 }
683 client, err := c.gitlabClient()
684 if err != nil {
685 return nil, err
686 }
688 repo, err := c.baseRepo()
689 if err != nil {
690 return nil, err
691 }
693 for {
694 milestones, resp, err := client.Milestones.ListMilestones(repo.FullName(), opts)
695 if err != nil {
696 return nil, err
697 }
699 for _, milestone := range milestones {
700 if milestone != nil && milestone.Title == title {
701 return milestone, nil
702 }
703 }
705 if resp.NextPage == 0 {
706 break
707 }
709 opts.Page = resp.NextPage
710 }
712 return nil, nil
713}
715// CloseMilestone closes a given milestone.
716func closeMilestone(c *options, title string) error {
717 client, err := c.gitlabClient()
718 if err != nil {
719 return err
720 }
722 repo, err := c.baseRepo()
723 if err != nil {
724 return err
725 }
727 milestone, err := getMilestoneByTitle(c, title)
728 if err != nil {
729 return err
730 }
732 if milestone == nil {
733 return fmt.Errorf("could not find milestone: %q", title)
734 }
736 closeStateEvent := "close"
738 opts := &gitlab.UpdateMilestoneOptions{
739 Description: &milestone.Description,
740 DueDate: milestone.DueDate,
741 StartDate: milestone.StartDate,
742 StateEvent: &closeStateEvent,
743 Title: &milestone.Title,
744 }
746 _, _, err = client.Milestones.UpdateMilestone(
747 repo.FullName(),
748 milestone.ID,
749 opts,
750 )
752 return err
753}
755func detectPreviousTag(headRef string) (string, error) {
756 cmd := git.GitCommand("describe", "--tags", "--abbrev=0", fmt.Sprintf("%s^", headRef))
757 b, err := run.PrepareCmd(cmd).Output()
758 return strings.TrimSpace(string(b)), err
759}
761type logEntry struct {
762 Subject string
763 Body string
764}
766func changelogForRange(refRange string) ([]logEntry, error) {
767 cmd := git.GitCommand("-c", "log.ShowSignature=false", "log", "--first-parent", "--reverse", "--pretty=format:%B%x00", refRange)
769 b, err := run.PrepareCmd(cmd).Output()
770 if err != nil {
771 return nil, err
772 }
774 var entries []logEntry
775 for cb := range bytes.SplitSeq(b, []byte{'\000'}) {
776 c := strings.ReplaceAll(string(cb), "\r\n", "\n")
777 c = strings.TrimPrefix(c, "\n")
778 if c == "" {
779 continue
780 }
781 parts := strings.SplitN(c, "\n\n", 2)
782 var body string
783 subject := strings.ReplaceAll(parts[0], "\n", " ")
784 if len(parts) > 1 {
785 body = parts[1]
786 }
787 entries = append(entries, logEntry{
788 Subject: subject,
789 Body: body,
790 })
791 }
793 return entries, nil
794}
796func generateChangelog(commits []logEntry) string {
797 var parts []string
798 for _, c := range commits {
799 parts = append(parts, fmt.Sprintf("* %s", c.Subject))
800 if c.Body != "" {
801 parts = append(parts, utils.Indent(c.Body, " "))
802 }
803 }
804 return strings.Join(parts, "\n\n")
805}
Diagnostics8 git calls · 302 ms
CallStatusSizeTime0302 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 KiB2 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=UPDATING 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=3 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=4 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=2 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:0200350 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=350 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=tree:0 git.fetch.wants=b2a837e646ba305993f35203fafafb109e57a7ca 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=350 git.pkt.payload.max=323 git.sideband.band1.bytes=323 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=323 git.pack.trailer=1232131042f2ba4c9c4dbd99382667a1f0849e15Open pack map
fetchtree:0200245 B · hit2 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=288 git.response.bytes=245 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=tree:0 git.fetch.wants=cb03b730c0d38e0c25330b8c3edfd648a7c3425b 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=245 git.pkt.payload.max=218 git.sideband.band1.bytes=218 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=218 git.pack.trailer=abcaa1e604d6142de985dae4beacc05f23f3a7b7Open pack map
fetch2008.1 KiB288 ms
git.upload-pack fetch http.response.status_code=200 git.response.bytes=8308 git.response.cache=MISS git.response.duration_ms=288 git.fetch.wants=f916f61dbd823a87e3e5d5f0a63e1437b354f3bb 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=8308 git.pkt.payload.max=8281 git.sideband.band1.bytes=8281 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
- a5e285535b824af4
- Request
- 32df366a…
- 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