Skip to content

Instantly share code, notes, and snippets.

@grafov
Last active July 21, 2025 22:27
Show Gist options
  • Save grafov/6eb2937bdca79dd4a9f4afb823d7b7fc to your computer and use it in GitHub Desktop.
Save grafov/6eb2937bdca79dd4a9f4afb823d7b7fc to your computer and use it in GitHub Desktop.
Recreate a Magit branch by deleting and creating a new one with branch name completion. I need this flow very often at my work for pushing changes to the special branches that deploy the code to test environments.
(defun my-magit-push-as-another-branch ()
"Recreate a Magit branch by deleting and creating a new one with branch name completion."
(interactive)
(let* ((branches (split-string (car (magit-git-items "for-each-ref" "--format=%(refname:short)" "refs/heads/")) "\n"))
(branch-name (ivy-read "Enter branch name: " branches
:require-match t
:preselect (magit-get-current-branch)
:sort nil))
(current-branch (magit-get-current-branch)))
(when (yes-or-no-p (format "Recreate & push branch \"%s\"?" branch-name))
(magit-run-git "branch" "-D" branch-name))
(magit-run-git "checkout" "-b" branch-name current-branch)
(magit-run-git "push" "--force" "origin" branch-name)
(magit-checkout current-branch)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment