GitLabgitlab-org

cli

main
ply8 git calls43 ms101 KiB7 cachedprotocol v2
389 lines11 KiBRaw
1package prune
3import (
4 "context"
5 "errors"
6 "fmt"
7 "regexp"
8 "strings"
10 "github.com/MakeNowJust/heredoc/v2"
11 "github.com/spf13/cobra"
13 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
15 "gitlab.com/gitlab-org/cli/internal/cmdutils"
16 "gitlab.com/gitlab-org/cli/internal/git"
17 "gitlab.com/gitlab-org/cli/internal/glrepo"
18 "gitlab.com/gitlab-org/cli/internal/iostreams"
19 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
22type options struct {
23 dryRun bool
24 yes bool
25 excludePatterns []string
26 useMergedFlag bool
28 io *iostreams.IOStreams
29 gitLabClient func() (*gitlab.Client, error)
30 baseRepo func() (glrepo.Interface, error)
31 branch func() (string, error)
32 gitRunner git.GitRunner
35type candidate struct {
36 branch string
37 mrIID int64
38 targetBranch string
41func NewCmd(f cmdutils.Factory) *cobra.Command {
42 opts := &options{
43 io: f.IO(),
44 gitLabClient: f.GitLabClient,
45 baseRepo: f.BaseRepo,
46 branch: f.Branch,
47 gitRunner: f.GitRunner(),
48 }
50 cmd := &cobra.Command{
51 Use: "prune [flags]",
52 Short: "Delete local Git branches whose merge request has been merged.",
53 Long: heredoc.Docf(`
54 Delete local Git branches whose merge request has been merged on GitLab.
56 By default, the command queries GitLab for each local branch and only
57 deletes branches that have at least one merged merge request and no
58 merge requests still open from the same source branch.
60 Protected branches, the default branch, and the currently checked-out
61 branch are never deleted.
63 This command only affects your local Git repository. Remote branches
64 on GitLab are not touched.
66 Use --merged to skip the per-branch merge request lookup and instead
67 rely on %[1]sgit branch --merged%[1]s to decide which branches to delete.
68 The default branch and protected branches are still fetched from
69 GitLab in this mode. Falling back to Git is faster, but only detects
70 fast-forward merges — squash and rebase merges look like distinct
71 commits to Git and will not be reported as merged.
72 `, "`"),
73 Example: heredoc.Doc(`
74 # Preview branches that would be deleted
75 glab repo prune --dry-run
77 # Delete branches with merged MRs (after confirmation)
78 glab repo prune
80 # Delete without confirmation
81 glab repo prune --yes
83 # Exclude additional branches by name or glob pattern
84 glab repo prune --exclude wip-*,demo-branch
86 # Detect merged branches with Git instead of GitLab (faster, but misses squash and rebase merges)
87 glab repo prune --merged
88 `),
89 Args: cobra.NoArgs,
90 ValidArgsFunction: cobra.NoFileCompletions,
91 Annotations: map[string]string{
92 mcpannotations.Destructive: "true",
93 },
94 RunE: func(cmd *cobra.Command, _ []string) error {
95 if err := opts.validate(); err != nil {
96 return err
97 }
98 return opts.run(cmd.Context())
99 },
100 }
102 fl := cmd.Flags()
103 fl.BoolVar(&opts.dryRun, "dry-run", false, "Preview branches that would be deleted without deleting them.")
104 fl.BoolVarP(&opts.yes, "yes", "y", false, "Skip the confirmation prompt.")
105 fl.StringSliceVarP(&opts.excludePatterns, "exclude", "e", nil, "Branch name or glob pattern to exclude. Comma-separated or repeated.")
106 fl.BoolVar(&opts.useMergedFlag, "merged", false, "Use 'git branch --merged' instead of querying GitLab. Detects fast-forward merges only.")
108 return cmd
111func (o *options) validate() error {
112 if !o.yes && !o.io.PromptEnabled() && !o.dryRun {
113 return &cmdutils.FlagError{Err: errors.New("--yes or -y is required when not running interactively")}
114 }
115 return nil
118func (o *options) run(ctx context.Context) error {
119 repo, err := o.baseRepo()
120 if err != nil {
121 return err
122 }
124 currentBranch, err := o.branch()
125 if err != nil && !errors.Is(err, git.ErrNotOnAnyBranch) {
126 return err
127 }
129 apiClient, err := o.gitLabClient()
130 if err != nil {
131 return err
132 }
134 project, _, err := apiClient.Projects.GetProject(repo.FullName(), nil, gitlab.WithContext(ctx))
135 if err != nil {
136 return fmt.Errorf("could not fetch project from GitLab: %w", err)
137 }
138 defaultBranch := project.DefaultBranch
139 if defaultBranch == "" {
140 defaultBranch = git.DefaultBranchName
141 }
143 protectedPatterns, err := listProtectedBranchNames(ctx, apiClient, repo.FullName())
144 if err != nil {
145 return fmt.Errorf("could not fetch protected branches from GitLab: %w", err)
146 }
148 allBranches, err := git.ListLocalBranches(o.gitRunner)
149 if err != nil {
150 return err
151 }
153 excluded := buildMatcher(defaultBranch, currentBranch, protectedPatterns, o.excludePatterns)
155 candidateBranches := make([]string, 0, len(allBranches))
156 for _, b := range allBranches {
157 if !excluded(b) {
158 candidateBranches = append(candidateBranches, b)
159 }
160 }
162 var candidates []candidate
163 if o.useMergedFlag {
164 candidates, err = collectMergedLocally(o.gitRunner, defaultBranch, candidateBranches)
165 } else {
166 candidates, err = collectMergedViaAPI(ctx, o.io, apiClient, repo.FullName(), candidateBranches)
167 }
168 if err != nil {
169 return err
170 }
172 c := o.io.Color()
173 emptyMsg := "No local branches found with merged merge requests."
174 header := fmt.Sprintf("Found %d branch(es) with merged merge requests:", len(candidates))
175 if o.useMergedFlag {
176 emptyMsg = fmt.Sprintf("No local branches found merged into %s.", defaultBranch)
177 header = fmt.Sprintf("Found %d branch(es) merged into %s:", len(candidates), defaultBranch)
178 }
180 if len(candidates) == 0 {
181 o.io.LogInfof("%s %s\n", c.GreenCheck(), emptyMsg)
182 return nil
183 }
185 o.io.LogInfo(header)
186 for _, cand := range candidates {
187 switch {
188 case cand.mrIID != 0:
189 o.io.LogInfof(" %s %s (MR !%d → %s)\n", c.GreenCheck(), cand.branch, cand.mrIID, cand.targetBranch)
190 default:
191 o.io.LogInfof(" %s %s (merged into %s)\n", c.GreenCheck(), cand.branch, cand.targetBranch)
192 }
193 }
195 if o.dryRun {
196 o.io.LogInfo()
197 o.io.LogInfo("Dry run: no branches were deleted.")
198 return nil
199 }
201 if !o.yes {
202 o.io.LogError()
203 confirmed := false
204 if err := o.io.Confirm(ctx, &confirmed, fmt.Sprintf("Delete these %d local branch(es)?", len(candidates))); err != nil {
205 return err
206 }
207 if !confirmed {
208 o.io.LogError("aborted by user")
209 return nil
210 }
211 }
213 o.io.LogInfo()
214 deleted := 0
215 for _, cand := range candidates {
216 if err := git.DeleteLocalBranch(cand.branch, o.gitRunner); err != nil {
217 o.io.LogInfof(" %s %s: %s\n", c.FailedIcon(), cand.branch, err)
218 continue
219 }
220 o.io.LogInfof(" %s deleted %s\n", c.GreenCheck(), cand.branch)
221 deleted++
222 }
223 o.io.LogInfof("\n%d branch(es) deleted.\n", deleted)
224 return nil
227func collectMergedViaAPI(ctx context.Context, io *iostreams.IOStreams, client *gitlab.Client, projectID string, branches []string) ([]candidate, error) {
228 if len(branches) == 0 {
229 return nil, nil
230 }
232 io.StartSpinner("Checking %d local branch(es) against GitLab...", len(branches))
233 defer io.StopSpinner("")
235 var candidates []candidate
236 for _, b := range branches {
237 merged, hasOpen, err := scanBranchMRs(ctx, client, projectID, b)
238 if err != nil {
239 return nil, fmt.Errorf("listing merge requests for branch %q: %w", b, err)
240 }
241 if merged != nil && !hasOpen {
242 candidates = append(candidates, candidate{
243 branch: b,
244 mrIID: merged.IID,
245 targetBranch: merged.TargetBranch,
246 })
247 }
248 }
249 return candidates, nil
252// scanBranchMRs walks every page of merge requests with the given source
253// branch and reports the first merged MR found, along with whether any
254// open/locked MRs exist. Pagination matters here — a reused branch with
255// many MRs could otherwise hide an open one on a later page and be
256// incorrectly marked safe to delete.
257func scanBranchMRs(ctx context.Context, client *gitlab.Client, projectID, branch string) (*gitlab.BasicMergeRequest, bool, error) {
258 opts := &gitlab.ListProjectMergeRequestsOptions{
259 SourceBranch: new(branch),
260 }
261 mrs, err := gitlab.ScanAndCollect(func(p gitlab.PaginationOptionFunc) ([]*gitlab.BasicMergeRequest, *gitlab.Response, error) {
262 return client.MergeRequests.ListProjectMergeRequests(projectID, opts, p, gitlab.WithContext(ctx))
263 })
264 if err != nil {
265 return nil, false, err
266 }
268 var merged *gitlab.BasicMergeRequest
269 hasOpen := false
270 for _, mr := range mrs {
271 switch mr.State {
272 case "merged":
273 if merged == nil {
274 merged = mr
275 }
276 case "opened", "locked":
277 hasOpen = true
278 }
279 }
280 return merged, hasOpen, nil
283func collectMergedLocally(gr git.GitRunner, target string, branches []string) ([]candidate, error) {
284 if len(branches) == 0 {
285 return nil, nil
286 }
288 merged, err := git.ListMergedBranches(target, gr)
289 if err != nil {
290 return nil, err
291 }
292 mergedSet := make(map[string]struct{}, len(merged))
293 for _, b := range merged {
294 mergedSet[b] = struct{}{}
295 }
297 var candidates []candidate
298 for _, b := range branches {
299 if _, ok := mergedSet[b]; ok {
300 candidates = append(candidates, candidate{branch: b, targetBranch: target})
301 }
302 }
303 return candidates, nil
306func listProtectedBranchNames(ctx context.Context, client *gitlab.Client, projectID string) ([]string, error) {
307 opts := &gitlab.ListProtectedBranchesOptions{}
308 protected, err := gitlab.ScanAndCollect(func(p gitlab.PaginationOptionFunc) ([]*gitlab.ProtectedBranch, *gitlab.Response, error) {
309 return client.ProtectedBranches.ListProtectedBranches(projectID, opts, p, gitlab.WithContext(ctx))
310 })
311 if err != nil {
312 return nil, err
313 }
315 names := make([]string, 0, len(protected))
316 for _, p := range protected {
317 if p != nil && p.Name != "" {
318 names = append(names, p.Name)
319 }
320 }
321 return names, nil
324// buildMatcher returns a predicate that reports whether a branch should be
325// excluded from pruning. Pattern semantics match GitLab's protected-branch
326// wildcards: `*` matches any character including `/`, `?` matches exactly
327// one character. Plain strings match by full equality.
328func buildMatcher(defaultBranch, currentBranch string, protected, userPatterns []string) func(string) bool {
329 var patterns []string
330 if defaultBranch != "" {
331 patterns = append(patterns, defaultBranch)
332 }
333 if currentBranch != "" {
334 patterns = append(patterns, currentBranch)
335 }
336 patterns = append(patterns, protected...)
337 for _, raw := range userPatterns {
338 for p := range strings.SplitSeq(raw, ",") {
339 if p = strings.TrimSpace(p); p != "" {
340 patterns = append(patterns, p)
341 }
342 }
343 }
345 compiled := make([]*regexp.Regexp, 0, len(patterns))
346 literals := make(map[string]struct{}, len(patterns))
347 for _, p := range patterns {
348 if !strings.ContainsAny(p, "*?") {
349 literals[p] = struct{}{}
350 continue
351 }
352 compiled = append(compiled, compileGlob(p))
353 }
355 return func(branch string) bool {
356 if _, ok := literals[branch]; ok {
357 return true
358 }
359 for _, re := range compiled {
360 if re.MatchString(branch) {
361 return true
362 }
363 }
364 return false
365 }
368// compileGlob converts a GitLab-style wildcard pattern (`*` matches any
369// sequence of any characters including `/`, `?` matches exactly one) into
370// an anchored regular expression. Every literal character in the input
371// goes through regexp.QuoteMeta, so the resulting expression is always
372// well-formed — a compile failure here would be a programming error,
373// hence MustCompile.
374func compileGlob(pattern string) *regexp.Regexp {
375 var sb strings.Builder
376 sb.WriteString("^")
377 for _, r := range pattern {
378 switch r {
379 case '*':
380 sb.WriteString(".*")
381 case '?':
382 sb.WriteString(".")
383 default:
384 sb.WriteString(regexp.QuoteMeta(string(r)))
385 }
386 }
387 sb.WriteString("$")
388 return regexp.MustCompile(sb.String())
Diagnostics8 git calls · 43 ms
CallStatusSizeTime043 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 KiB · hit3 ms
git.upload-pack ls-refs
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=3
git.response.bytes=59849
git.response.cache=HIT
git.response.duration_ms=3
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 · 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=4273
git.response.cache=HIT
git.response.duration_ms=2
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 · 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
fetchtree:02001.8 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=1857
git.response.cache=HIT
git.response.duration_ms=2
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:0200614 B · hit2 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=614
git.response.cache=HIT
git.response.duration_ms=2
git.fetch.filter=tree:0
git.fetch.wants=3a89d0cfc8e81880c982180388e42e561a0b7eee
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=614
git.pkt.payload.max=587
git.sideband.band1.bytes=587
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=587
git.pack.trailer=eb8250f8e8340ff2fafc22c5aba90db34fd906a9
Open pack map
fetchtree:0200137 B · hit4 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=30
git.response.bytes=137
git.response.cache=HIT
git.response.duration_ms=4
git.fetch.filter=tree:0
git.fetch.wants=3c308ef932a119b9e19157e3837ba7ff25c96d51
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=9cb9fcd588b8f9432d9a73173cf6d274049bcbeb
Open pack map
fetch2003.8 KiB · hit30 ms
git.upload-pack fetch
http.response.status_code=200
git.response.bytes=3874
git.response.cache=HIT
git.response.duration_ms=30
git.fetch.wants=6890116d0c8a72698237c3a85dd5151aaea67c38
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=3874
git.pkt.payload.max=3847
git.sideband.band1.bytes=3847
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
a5ea569229937089
Request
839c4abe…
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