Create branch from remote branch using Magit

Jan. 10, 2025

Posted in:

(defun create-branch-from-remote (base-branch new-branch)
  "Create and switch to NEW-BRANCH from BASE-BRANCH after updating BASE-BRANCH.
BASE-BRANCH will be pulled with rebase from its upstream first."
  (interactive
   (list (magit-read-branch "Base branch")
         (magit-read-string-ns "New branch name")))
  (when (or (null base-branch)
            (string-empty-p base-branch)
            (null new-branch)
            (string-empty-p new-branch))
    (user-error "Both base branch and new branch name must be provided"))

  ;; Store current branch to handle errors
  (let ((original-branch (magit-get-current-branch)))
    (condition-case err
        (progn
          ;; Switch to base branch
          (message "Switching to base branch '%s'" base-branch)
          (magit-checkout base-branch)

          ;; Pull with rebase
          (message "Pulling latest changes with rebase")
          (magit-pull-from-upstream "--rebase")

          ;; Create and checkout new branch using magit-branch-create
          (message "Creating and switching to new branch '%s'" new-branch)
          (magit-branch-create new-branch base-branch)
          (magit-checkout new-branch)

          (message "Successfully created and switched to branch '%s' from '%s'"
                   new-branch base-branch))
      ;; Error handling
      (error
       (progn
         (message "Error occurred: %s" (error-message-string err))
         ;; Try to return to original branch on error
         (when original-branch
           (magit-checkout original-branch)
           (message "Returned to branch '%s'" original-branch)))))))

;; Bind to C-c v b for non-evil usage
(with-eval-after-load 'which-key
  (which-key-add-key-based-replacements
    "C-c v b" "Create Branch from Remote"))
(global-set-key (kbd "C-c v b") #'create-branch-from-remote)

Tags

Return to blog