GitLabgitlab-org

cli

main
ply8 git calls302 ms100 KiB5 cachedprotocol v2
255 lines7.1 KiBRaw
1package delete
3import (
4 "errors"
5 "fmt"
6 "strconv"
7 "strings"
8 "time"
10 "github.com/MakeNowJust/heredoc/v2"
11 "github.com/spf13/cobra"
12 "github.com/spf13/pflag"
14 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
16 "gitlab.com/gitlab-org/cli/internal/cmdutils"
17 "gitlab.com/gitlab-org/cli/internal/glrepo"
18 "gitlab.com/gitlab-org/cli/internal/iostreams"
19 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
22const (
23 FlagDryRun = "dry-run"
24 FlagOlderThan = "older-than"
25 FlagPage = "page"
26 FlagPaginate = "paginate"
27 FlagPerPage = "per-page"
28 FlagSource = "source"
29 FlagStatus = "status"
32var (
33 pipelineStatuses = []string{
34 string(gitlab.Running), string(gitlab.Pending), string(gitlab.Success), string(gitlab.Failed),
35 string(gitlab.Canceled), string(gitlab.Skipped), string(gitlab.Created), string(gitlab.Manual),
36 }
37 pipelineSources = []string{
38 "api", "chat", "external", "external_pull_request_event", "merge_request_event",
39 "ondemand_dast_scan", "ondemand_dast_validation", "parent_pipeline", "pipeline",
40 "push", "schedule", "security_orchestration_policy", "trigger", "web", "webide",
41 }
44func NewCmdDelete(f cmdutils.Factory) *cobra.Command {
45 pipelineDeleteCmd := &cobra.Command{
46 Use: "delete <id> [flags]",
47 Short: `Delete CI/CD pipelines.`,
48 Long: heredoc.Docf(`
49 You can delete by ID, or filter by status, source, or age. Use %[1]s--dry-run%[1]s to preview
50 the pipelines that would be deleted.
51 `, "`"),
52 Example: heredoc.Doc(`
53 # Delete a pipeline by ID
54 glab ci delete 34
56 # Delete multiple pipelines by ID
57 glab ci delete 12,34,2
59 # Delete all pipelines triggered through the API
60 glab ci delete --source=api
62 # Delete all failed pipelines
63 glab ci delete --status=failed
65 # Delete pipelines older than 24 hours
66 glab ci delete --older-than 24h
68 # Delete failed pipelines older than 24 hours
69 glab ci delete --older-than 24h --status=failed`),
70 Args: func(cmd *cobra.Command, args []string) error {
71 olderThanDuration, _ := cmd.Flags().GetDuration(FlagOlderThan)
72 status, _ := cmd.Flags().GetString(FlagStatus)
73 source, _ := cmd.Flags().GetString(FlagSource)
75 if olderThanDuration == 0 && status == "" && source == "" {
76 return cobra.ExactArgs(1)(cmd, args)
77 }
79 if len(args) > 0 {
80 return errors.New("either a status filter or a pipeline ID must be passed, but not both")
81 }
83 return nil
84 },
85 Annotations: map[string]string{
86 mcpannotations.Destructive: "true",
87 },
88 RunE: func(cmd *cobra.Command, args []string) error {
89 var err error
90 c := f.IO().Color()
91 client, err := f.GitLabClient()
92 if err != nil {
93 return err
94 }
96 repo, err := f.BaseRepo()
97 if err != nil {
98 return err
99 }
101 dryRunMode, _ := cmd.Flags().GetBool(FlagDryRun)
103 var pipelineIDs []int
104 if len(args) == 1 {
105 pipelineIDs, err = parseRawPipelineIDs(args[0])
106 if err != nil {
107 return err
108 }
110 return runDeletion(f.IO(), pipelineIDs, dryRunMode, c, client, repo)
111 }
113 paginate, _ := cmd.Flags().GetBool(FlagPaginate)
115 pipelineIDs, totalAvailable, truncated, err := listPipelineIDs(client, repo.FullName(), paginate, optsFromFlags(cmd.Flags()))
116 if err != nil {
117 return err
118 }
120 if err := runDeletion(f.IO(), pipelineIDs, dryRunMode, c, client, repo); err != nil {
121 return err
122 }
124 if truncated {
125 verb := "Deleted"
126 if dryRunMode {
127 verb = "Matched"
128 }
129 // GitLab omits X-Total for result sets larger than 10,000, so totalAvailable may be 0 even when truncated.
130 if totalAvailable > int64(len(pipelineIDs)) {
131 f.IO().LogErrorf(
132 "%s %d of %d matching pipelines. Pass --paginate to act on all matches, or --per-page to fetch more per request.\n",
133 verb, len(pipelineIDs), totalAvailable)
134 } else {
135 f.IO().LogErrorf(
136 "%s %d matching pipelines; more matches exist. Pass --paginate to act on all matches, or --per-page to fetch more per request.\n",
137 verb, len(pipelineIDs))
138 }
139 }
141 return nil
142 },
143 }
145 SetupCommandFlags(pipelineDeleteCmd.Flags())
147 return pipelineDeleteCmd
150func SetupCommandFlags(flags *pflag.FlagSet) {
151 flags.BoolP(FlagDryRun, "", false, "Simulate process, but do not delete anything.")
152 flags.StringP(FlagStatus, "s", "", fmt.Sprintf("Delete pipelines by status: %s.", strings.Join(pipelineStatuses, ", ")))
153 flags.String(FlagSource, "", fmt.Sprintf("Filter pipelines by source: %s.", strings.Join(pipelineSources, ", ")))
154 flags.Duration(FlagOlderThan, 0, "Filter pipelines older than the given duration. Valid units: h, m, s, ms, us, ns.")
155 flags.BoolP(FlagPaginate, "", false, "Make additional HTTP requests to fetch all pages of pipelines. Respects '--per-page'.")
156 flags.IntP(FlagPage, "", 0, "Page number.")
157 flags.IntP(FlagPerPage, "", 0, "Number of items to list per page.")
160func optsFromFlags(flags *pflag.FlagSet) *gitlab.ListProjectPipelinesOptions {
161 opts := &gitlab.ListProjectPipelinesOptions{}
162 page, _ := flags.GetInt(FlagPage)
163 perPage, _ := flags.GetInt(FlagPerPage)
165 if perPage != 0 {
166 opts.PerPage = int64(perPage)
167 }
168 if page != 0 {
169 opts.Page = int64(page)
170 }
172 source, _ := flags.GetString(FlagSource)
173 status, _ := flags.GetString(FlagStatus)
174 olderThanDuration, _ := flags.GetDuration(FlagOlderThan)
176 if source != "" {
177 opts.Source = new(source)
178 }
180 if status != "" {
181 opts.Status = new(gitlab.BuildStateValue(status))
182 }
184 if olderThanDuration != 0 {
185 opts.UpdatedBefore = new(time.Now().Add(-olderThanDuration))
186 }
188 return opts
191func parseRawPipelineIDs(rawPipelineIDs string) ([]int, error) {
192 var inputPipelineIDs []int
193 for stringID := range strings.SplitSeq(rawPipelineIDs, ",") {
194 id, err := strconv.Atoi(stringID)
195 if err != nil {
196 return nil, err
197 }
198 inputPipelineIDs = append(inputPipelineIDs, id)
199 }
201 return inputPipelineIDs, nil
204func runDeletion(io *iostreams.IOStreams, pipelineIDs []int, dryRunMode bool, c *iostreams.ColorPalette, apiClient *gitlab.Client, repo glrepo.Interface) error {
205 for _, id := range pipelineIDs {
206 if dryRunMode {
207 io.LogInfof("%s Pipeline #%d will be deleted.\n", c.DotWarnIcon(), id)
208 continue
209 }
211 _, err := apiClient.Pipelines.DeletePipeline(repo.FullName(), int64(id))
212 if err != nil {
213 return err
214 }
216 io.LogInfof("%s Pipeline #%d deleted successfully.\n", c.RedCheck(), id)
217 }
218 fmt.Println()
220 return nil
223func listPipelineIDs(apiClient *gitlab.Client, repoName string, paginate bool, opts *gitlab.ListProjectPipelinesOptions) ([]int, int64, bool, error) {
224 var pipelineIDs []int
225 var totalAvailable int64
226 var truncated bool
228 hasRemaining := true
229 first := true
230 for hasRemaining {
231 pipes, resp, err := apiClient.Pipelines.ListProjectPipelines(repoName, opts)
232 if err != nil {
233 return pipelineIDs, totalAvailable, truncated, err
234 }
236 if first && resp != nil {
237 totalAvailable = resp.TotalItems
238 first = false
239 }
241 for _, item := range pipes {
242 pipelineIDs = append(pipelineIDs, int(item.ID))
243 }
245 opts.Page = resp.NextPage
246 // NextPage is reliable even when X-Total-Pages is absent (large result sets);
247 // CurrentPage != TotalPages would loop forever in that case.
248 hasRemaining = paginate && resp.NextPage > 0
249 if !hasRemaining && resp.NextPage > 0 {
250 truncated = true
251 }
252 }
254 return pipelineIDs, totalAvailable, truncated, nil
Diagnostics8 git calls · 302 ms
CallStatusSizeTime0302 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 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=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=44
Open 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=3
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 · 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=fb03183b7909876778f740d196d7516811003517
Open pack map
fetchtree:0200635 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=635
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=517b073a0d5c32bc4e93f86de74b31d60ff8cf03
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=635
git.pkt.payload.max=608
git.sideband.band1.bytes=608
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=608
git.pack.trailer=178abb9456d874b7fd38fa21ad5cf9ca3ebcccaa
Open pack map
fetchtree:0200138 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=138
git.response.cache=HIT
git.response.duration_ms=4
git.fetch.filter=tree:0
git.fetch.wants=8cd12e229b33292c7d4ce2310e8accbcf780f249
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=a5319c2d5d28d769b9e23b59c3a2a96e5ec2d44a
Open pack map
fetch2002.5 KiB287 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=287
git.response.bytes=2585
git.response.cache=MISS
git.response.duration_ms=287
git.fetch.wants=376649b2ed7226607f68ae2e816ed1702bf1be79
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=2585
git.pkt.payload.max=2558
git.sideband.band1.bytes=2558
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
a5e2c915f9434b67
Request
e195f7c8…
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