7

Explaining the problem more in-depth than the titular definition:

Often I merge branches into master and want to prune based on that. M-p works fantastic for removing the remote branches (eg origin/mergedbranch) but not the local branch (eg mergedbranch) that referenced it before. I'm left with branches like the in the screenshot below.

There seem to be a lot of cli git commands such as this SO answer, but I was wondering if there was a magit equivalent.

enter image description here

3 Answers 3

10

The refs buffer has options to filter to merged branches.
Quoting C-hig (magit)References Buffer:

‘y’ (‘magit-show-refs’)
This command lists branches and tags in a dedicated buffer. However if this command is invoked again from this buffer or if it is invoked with a prefix argument, then it acts as a transient prefix command

Therefore you can access that transient menu with yy1

Within the transient menu you can refine the view with -M setting the value to the merge target (E.g develop or main).

Then type y to execute the command, comparing against HEAD. The refs list you are left with should only contain merged branches.

Now highlight all the branches you would like to delete, then press k to delete the selection.2

Remember that you can set and save default transient values with C-xs and C-xC-s respectively.


1 or C-uM-x magit-show-refs, or in Evil it's yryr.

2 or M-x magit-delete-thing, or in Evil it's x.

1

There's no such command, but it wouldn't be hard to create one if you know a little emacs lisp and look at other magit-branch-* commands and the SO answers you mentioned. If you do, then please submit a pull-request.

0

Here's what I use:

(defun my-magit/delete-merged-branches ()
  (interactive)
  (magit-fetch-all-prune)
  (let* ((default-branch
           (read-string "Default branch: " (magit-get-current-branch)))
         (merged-branches
          (magit-git-lines "branch"
                           "--format" "%(refname:short)"
                           "--merged"
                           default-branch))
         (branches-to-delete
          (remove default-branch merged-branches)))
    (if branches-to-delete
        (if (yes-or-no-p (concat "Delete branches? ["
                                 (mapconcat 'identity branches-to-delete ", ") "]"))
            (magit-branch-delete branches-to-delete))
      (message "Nothing to delete"))))
(transient-append-suffix 'magit-branch "C"
    '("K" "delete all merged" my-magit/delete-merged-branches))

Then I press b K, it shows list of unmerged branches and asks for confirmation to delete them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.