config

Personal configuration.
git clone git://code.dwrz.net/config
Log | Files | Refs

magit-branch.el (42498B)


      1 ;;; magit-branch.el --- Branch support  -*- lexical-binding:t -*-
      2 
      3 ;; Copyright (C) 2008-2024 The Magit Project Contributors
      4 
      5 ;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev>
      6 ;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev>
      7 
      8 ;; SPDX-License-Identifier: GPL-3.0-or-later
      9 
     10 ;; Magit is free software: you can redistribute it and/or modify it
     11 ;; under the terms of the GNU General Public License as published by
     12 ;; the Free Software Foundation, either version 3 of the License, or
     13 ;; (at your option) any later version.
     14 ;;
     15 ;; Magit is distributed in the hope that it will be useful, but WITHOUT
     16 ;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
     17 ;; or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
     18 ;; License for more details.
     19 ;;
     20 ;; You should have received a copy of the GNU General Public License
     21 ;; along with Magit.  If not, see <https://www.gnu.org/licenses/>.
     22 
     23 ;;; Commentary:
     24 
     25 ;; This library implements support for branches.  It defines commands
     26 ;; for creating, checking out, manipulating, and configuring branches.
     27 ;; Commands defined here are mainly concerned with branches as
     28 ;; pointers, commands that deal with what a branch points at, are
     29 ;; defined elsewhere.
     30 
     31 ;;; Code:
     32 
     33 (require 'magit)
     34 (require 'magit-reset)
     35 
     36 ;;; Options
     37 
     38 (defcustom magit-branch-read-upstream-first t
     39   "Whether to read upstream before name of new branch when creating a branch.
     40 
     41 `nil'      Read the branch name first.
     42 `t'        Read the upstream first.
     43 `fallback' Read the upstream first, but if it turns out that the chosen
     44            value is not a valid upstream (because it cannot be resolved
     45            as an existing revision), then treat it as the name of the
     46            new branch and continue by reading the upstream next."
     47   :package-version '(magit . "2.2.0")
     48   :group 'magit-commands
     49   :type '(choice (const :tag "read branch name first" nil)
     50                  (const :tag "read upstream first" t)
     51                  (const :tag "read upstream first, with fallback" fallback)))
     52 
     53 (defcustom magit-branch-prefer-remote-upstream nil
     54   "Whether to favor remote upstreams when creating new branches.
     55 
     56 When a new branch is created, then the branch, commit, or stash
     57 at point is suggested as the default starting point of the new
     58 branch, or if there is no such revision at point the current
     59 branch.  In either case the user may choose another starting
     60 point.
     61 
     62 If the chosen starting point is a branch, then it may also be set
     63 as the upstream of the new branch, depending on the value of the
     64 Git variable `branch.autoSetupMerge'.  By default this is done
     65 for remote branches, but not for local branches.
     66 
     67 You might prefer to always use some remote branch as upstream.
     68 If the chosen starting point is (1) a local branch, (2) whose
     69 name matches a member of the value of this option, (3) the
     70 upstream of that local branch is a remote branch with the same
     71 name, and (4) that remote branch can be fast-forwarded to the
     72 local branch, then the chosen branch is used as starting point,
     73 but its own upstream is used as the upstream of the new branch.
     74 
     75 Members of this option's value are treated as branch names that
     76 have to match exactly unless they contain a character that makes
     77 them invalid as a branch name.  Recommended characters to use
     78 to trigger interpretation as a regexp are \"*\" and \"^\".  Some
     79 other characters which you might expect to be invalid, actually
     80 are not, e.g., \".+$\" are all perfectly valid.  More precisely,
     81 if `git check-ref-format --branch STRING' exits with a non-zero
     82 status, then treat STRING as a regexp.
     83 
     84 Assuming the chosen branch matches these conditions you would end
     85 up with with e.g.:
     86 
     87   feature --upstream--> origin/master
     88 
     89 instead of
     90 
     91   feature --upstream--> master --upstream--> origin/master
     92 
     93 Which you prefer is a matter of personal preference.  If you do
     94 prefer the former, then you should add branches such as \"master\",
     95 \"next\", and \"maint\" to the value of this options."
     96   :package-version '(magit . "2.4.0")
     97   :group 'magit-commands
     98   :type '(repeat string))
     99 
    100 (defcustom magit-branch-adjust-remote-upstream-alist nil
    101   "Alist of upstreams to be used when branching from remote branches.
    102 
    103 When creating a local branch from an ephemeral branch located
    104 on a remote, e.g., a feature or hotfix branch, then that remote
    105 branch should usually not be used as the upstream branch, since
    106 the push-remote already allows accessing it and having both the
    107 upstream and the push-remote reference the same related branch
    108 would be wasteful.  Instead a branch like \"maint\" or \"master\"
    109 should be used as the upstream.
    110 
    111 This option allows specifying the branch that should be used as
    112 the upstream when branching certain remote branches.  The value
    113 is an alist of the form ((UPSTREAM . RULE)...).  The first
    114 element is used whose UPSTREAM exists and whose RULE matches
    115 the name of the new branch.  Subsequent elements are ignored.
    116 
    117 UPSTREAM is the branch to be used as the upstream for branches
    118 specified by RULE.  It can be a local or a remote branch.
    119 
    120 RULE can either be a regular expression, matching branches whose
    121 upstream should be the one specified by UPSTREAM.  Or it can be
    122 a list of the only branches that should *not* use UPSTREAM; all
    123 other branches will.  Matching is done after stripping the remote
    124 part of the name of the branch that is being branched from.
    125 
    126 If you use a finite set of non-ephemeral branches across all your
    127 repositories, then you might use something like:
    128 
    129   ((\"origin/master\" . (\"master\" \"next\" \"maint\")))
    130 
    131 Or if the names of all your ephemeral branches contain a slash,
    132 at least in some repositories, then a good value could be:
    133 
    134   ((\"origin/master\" . \"/\"))
    135 
    136 Of course you can also fine-tune:
    137 
    138   ((\"origin/maint\" . \"\\\\\\=`hotfix/\")
    139    (\"origin/master\" . \"\\\\\\=`feature/\"))
    140 
    141 UPSTREAM can be a local branch:
    142 
    143   ((\"master\" . (\"master\" \"next\" \"maint\")))
    144 
    145 Because the main branch is no longer almost always named \"master\"
    146 you should also account for other common names:
    147 
    148   ((\"main\"  . (\"main\" \"master\" \"next\" \"maint\"))
    149    (\"master\" . (\"main\" \"master\" \"next\" \"maint\")))
    150 
    151 If you use remote branches as UPSTREAM, then you might also want
    152 to set `magit-branch-prefer-remote-upstream' to a non-nil value.
    153 However, I recommend that you use local branches as UPSTREAM."
    154   :package-version '(magit . "2.9.0")
    155   :group 'magit-commands
    156   :type '(repeat (cons (string :tag "Use upstream")
    157                        (choice :tag "for branches"
    158                                (regexp :tag "matching")
    159                                (repeat :tag "except"
    160                                        (string :tag "branch"))))))
    161 
    162 (defcustom magit-branch-rename-push-target t
    163   "Whether the push-remote setup is preserved when renaming a branch.
    164 
    165 The command `magit-branch-rename' renames a branch named OLD to
    166 NEW.  This option controls how much of the push-remote setup is
    167 preserved when doing so.
    168 
    169 When nil, then preserve nothing and unset `branch.OLD.pushRemote'.
    170 
    171 When `local-only', then first set `branch.NEW.pushRemote' to the
    172   same value as `branch.OLD.pushRemote', provided the latter is
    173   actually set and unless the former already has another value.
    174 
    175 When t, then rename the branch named OLD on the remote specified
    176   by `branch.OLD.pushRemote' to NEW, provided OLD exists on that
    177   remote and unless NEW already exists on the remote.
    178 
    179 When `forge-only' and the `forge' package is available, then
    180   behave like `t' if the remote points to a repository on a forge
    181   (currently Github or Gitlab), otherwise like `local-only'."
    182   :package-version '(magit . "2.90.0")
    183   :group 'magit-commands
    184   :type '(choice
    185           (const :tag "Don't preserve push-remote setup" nil)
    186           (const :tag "Preserve push-remote setup" local-only)
    187           (const :tag "... and rename corresponding branch on remote" t)
    188           (const :tag "... but only if remote is on a forge" forge-only)))
    189 
    190 (defcustom magit-branch-direct-configure t
    191   "Whether the command `magit-branch' shows Git variables.
    192 When set to nil, no variables are displayed by this transient
    193 command, instead the sub-transient `magit-branch-configure'
    194 has to be used to view and change branch related variables."
    195   :package-version '(magit . "2.7.0")
    196   :group 'magit-commands
    197   :type 'boolean)
    198 
    199 (defcustom magit-published-branches '("origin/master")
    200   "List of branches that are considered to be published."
    201   :package-version '(magit . "2.13.0")
    202   :group 'magit-commands
    203   :type '(repeat string))
    204 
    205 ;;; Commands
    206 
    207 ;;;###autoload (autoload 'magit-branch "magit" nil t)
    208 (transient-define-prefix magit-branch (branch)
    209   "Add, configure or remove a branch."
    210   :man-page "git-branch"
    211   [:if (lambda () (and magit-branch-direct-configure (transient-scope)))
    212    :description
    213    (lambda ()
    214      (concat (propertize "Configure " 'face 'transient-heading)
    215              (propertize (transient-scope) 'face 'magit-branch-local)))
    216    ("d" magit-branch.<branch>.description)
    217    ("u" magit-branch.<branch>.merge/remote)
    218    ("r" magit-branch.<branch>.rebase)
    219    ("p" magit-branch.<branch>.pushRemote)]
    220   [:if-non-nil magit-branch-direct-configure
    221    :description "Configure repository defaults"
    222    ("R" magit-pull.rebase)
    223    ("P" magit-remote.pushDefault)
    224    ("B" "Update default branch" magit-update-default-branch
    225     :inapt-if-not magit-get-some-remote)]
    226   ["Arguments"
    227    (7 "-r" "Recurse submodules when checking out an existing branch"
    228       "--recurse-submodules"
    229       :if (lambda () (magit-git-version>= "2.13")))]
    230   [["Checkout"
    231     ("b" "branch/revision"   magit-checkout)
    232     ("l" "local branch"      magit-branch-checkout)
    233     (6 "o" "new orphan"      magit-branch-orphan)]
    234    [""
    235     ("c" "new branch"        magit-branch-and-checkout)
    236     ("s" "new spin-off"      magit-branch-spinoff)
    237     (5 "w" "new worktree"    magit-worktree-checkout)]
    238    ["Create"
    239     ("n" "new branch"        magit-branch-create)
    240     ("S" "new spin-out"      magit-branch-spinout)
    241     (5 "W" "new worktree"    magit-worktree-branch)]
    242    ["Do"
    243     ("C" "configure..."      magit-branch-configure)
    244     ("m" "rename"            magit-branch-rename)
    245     ("x" "reset"             magit-branch-reset)
    246     ("k" "delete"            magit-branch-delete)]
    247    [""
    248     (7 "h" "shelve"          magit-branch-shelve)
    249     (7 "H" "unshelve"        magit-branch-unshelve)]]
    250   (interactive (list (magit-get-current-branch)))
    251   (transient-setup 'magit-branch nil nil :scope branch))
    252 
    253 (defun magit-branch-arguments ()
    254   (transient-args 'magit-branch))
    255 
    256 ;;;###autoload
    257 (defun magit-checkout (revision &optional args)
    258   "Checkout REVISION, updating the index and the working tree.
    259 If REVISION is a local branch, then that becomes the current
    260 branch.  If it is something else, then `HEAD' becomes detached.
    261 Checkout fails if the working tree or the staging area contain
    262 changes.
    263 \n(git checkout REVISION)."
    264   (declare (interactive-only magit--checkout))
    265   (interactive (list (magit-read-other-branch-or-commit "Checkout")
    266                      (magit-branch-arguments)))
    267   (when (string-match "\\`heads/\\(.+\\)" revision)
    268     (setq revision (match-string 1 revision)))
    269   (magit-run-git-async "checkout" args revision))
    270 
    271 (defun magit--checkout (revision &optional args)
    272   (when (string-match "\\`heads/\\(.+\\)" revision)
    273     (setq revision (match-string 1 revision)))
    274   (magit-call-git "checkout" args revision))
    275 
    276 ;;;###autoload
    277 (defun magit-branch-create (branch start-point)
    278   "Create BRANCH at branch or revision START-POINT."
    279   (declare (interactive-only magit-call-git))
    280   (interactive (magit-branch-read-args "Create branch"))
    281   (magit-run-git-async "branch" branch start-point)
    282   (set-process-sentinel
    283    magit-this-process
    284    (lambda (process event)
    285      (when (memq (process-status process) '(exit signal))
    286        (magit-branch-maybe-adjust-upstream branch start-point)
    287        (magit-process-sentinel process event)))))
    288 
    289 ;;;###autoload
    290 (defun magit-branch-and-checkout (branch start-point &optional args)
    291   "Create and checkout BRANCH at branch or revision START-POINT."
    292   (declare (interactive-only magit-call-git))
    293   (interactive (append (magit-branch-read-args "Create and checkout branch")
    294                        (list (magit-branch-arguments))))
    295   (if (string-match-p "^stash@{[0-9]+}$" start-point)
    296       (magit-run-git "stash" "branch" branch start-point)
    297     (magit-run-git-async "checkout" args "-b" branch start-point)
    298     (set-process-sentinel
    299      magit-this-process
    300      (lambda (process event)
    301        (when (memq (process-status process) '(exit signal))
    302          (magit-branch-maybe-adjust-upstream branch start-point)
    303          (magit-process-sentinel process event))))))
    304 
    305 ;;;###autoload
    306 (defun magit-branch-or-checkout (arg &optional start-point)
    307   "Hybrid between `magit-checkout' and `magit-branch-and-checkout'.
    308 
    309 Ask the user for an existing branch or revision.  If the user
    310 input actually can be resolved as a branch or revision, then
    311 check that out, just like `magit-checkout' would.
    312 
    313 Otherwise create and checkout a new branch using the input as
    314 its name.  Before doing so read the starting-point for the new
    315 branch.  This is similar to what `magit-branch-and-checkout'
    316 does."
    317   (declare (interactive-only magit-call-git))
    318   (interactive
    319    (let ((arg (magit-read-other-branch-or-commit "Checkout")))
    320      (list arg
    321            (and (not (magit-commit-p arg))
    322                 (magit-read-starting-point "Create and checkout branch" arg)))))
    323   (when (string-match "\\`heads/\\(.+\\)" arg)
    324     (setq arg (match-string 1 arg)))
    325   (if start-point
    326       (with-suppressed-warnings ((interactive-only magit-branch-and-checkout))
    327         (magit-branch-and-checkout arg start-point))
    328     (magit--checkout arg)
    329     (magit-refresh)))
    330 
    331 ;;;###autoload
    332 (defun magit-branch-checkout (branch &optional start-point)
    333   "Checkout an existing or new local branch.
    334 
    335 Read a branch name from the user offering all local branches and
    336 a subset of remote branches as candidates.  Omit remote branches
    337 for which a local branch by the same name exists from the list
    338 of candidates.  The user can also enter a completely new branch
    339 name.
    340 
    341 - If the user selects an existing local branch, then check that
    342   out.
    343 
    344 - If the user selects a remote branch, then create and checkout
    345   a new local branch with the same name.  Configure the selected
    346   remote branch as push target.
    347 
    348 - If the user enters a new branch name, then create and check
    349   that out, after also reading the starting-point from the user.
    350 
    351 In the latter two cases the upstream is also set.  Whether it is
    352 set to the chosen START-POINT or something else depends on the
    353 value of `magit-branch-adjust-remote-upstream-alist', just like
    354 when using `magit-branch-and-checkout'."
    355   (declare (interactive-only magit-call-git))
    356   (interactive
    357    (let* ((current (magit-get-current-branch))
    358           (local   (magit-list-local-branch-names))
    359           (remote  (--filter (and (string-match "[^/]+/" it)
    360                                   (not (member (substring it (match-end 0))
    361                                                (cons "HEAD" local))))
    362                              (magit-list-remote-branch-names)))
    363           (choices (nconc (delete current local) remote))
    364           (atpoint (magit-branch-at-point))
    365           (choice  (magit-completing-read
    366                     "Checkout branch" choices
    367                     nil nil nil 'magit-revision-history
    368                     (or (car (member atpoint choices))
    369                         (and atpoint
    370                              (car (member (and (string-match "[^/]+/" atpoint)
    371                                                (substring atpoint (match-end 0)))
    372                                           choices)))))))
    373      (cond ((member choice remote)
    374             (list (and (string-match "[^/]+/" choice)
    375                        (substring choice (match-end 0)))
    376                   choice))
    377            ((member choice local)
    378             (list choice))
    379            (t
    380             (list choice (magit-read-starting-point "Create" choice))))))
    381   (cond
    382    ((not start-point)
    383     (magit--checkout branch (magit-branch-arguments))
    384     (magit-refresh))
    385    (t
    386     (when (magit-anything-modified-p t)
    387       (user-error "Cannot checkout when there are uncommitted changes"))
    388     (magit-run-git-async "checkout" (magit-branch-arguments)
    389                          "-b" branch start-point)
    390     (set-process-sentinel
    391      magit-this-process
    392      (lambda (process event)
    393        (when (memq (process-status process) '(exit signal))
    394          (magit-branch-maybe-adjust-upstream branch start-point)
    395          (when (magit-remote-branch-p start-point)
    396            (pcase-let ((`(,remote . ,remote-branch)
    397                         (magit-split-branch-name start-point)))
    398              (when (and (equal branch remote-branch)
    399                         (not (equal remote (magit-get "remote.pushDefault"))))
    400                (magit-set remote "branch" branch "pushRemote"))))
    401          (magit-process-sentinel process event)))))))
    402 
    403 (defun magit-branch-maybe-adjust-upstream (branch start-point)
    404   (when-let ((upstream
    405               (or (and (magit-get-upstream-branch branch)
    406                        (magit-get-indirect-upstream-branch start-point))
    407                   (and (magit-remote-branch-p start-point)
    408                        (let ((name (cdr (magit-split-branch-name start-point))))
    409                          (seq-some
    410                           (pcase-lambda (`(,upstream . ,rule))
    411                             (and (magit-branch-p upstream)
    412                                  (if (listp rule)
    413                                      (not (member name rule))
    414                                    (string-match-p rule name))
    415                                  upstream))
    416                           magit-branch-adjust-remote-upstream-alist))))))
    417     (magit-call-git "branch" (concat "--set-upstream-to=" upstream) branch)))
    418 
    419 ;;;###autoload
    420 (defun magit-branch-orphan (branch start-point)
    421   "Create and checkout an orphan BRANCH with contents from revision START-POINT."
    422   (interactive (magit-branch-read-args "Create and checkout orphan branch"))
    423   (magit-run-git "checkout" "--orphan" branch start-point))
    424 
    425 (defun magit-branch-read-args (prompt &optional default-start)
    426   (if magit-branch-read-upstream-first
    427       (let ((choice (magit-read-starting-point prompt nil default-start)))
    428         (cond
    429          ((magit-rev-verify choice)
    430           (list (magit-read-string-ns
    431                  (if magit-completing-read--silent-default
    432                      (format "%s (starting at `%s')" prompt choice)
    433                    "Name for new branch")
    434                  (let ((def (string-join (cdr (split-string choice "/")) "/")))
    435                    (and (member choice (magit-list-remote-branch-names))
    436                         (not (member def (magit-list-local-branch-names)))
    437                         def)))
    438                 choice))
    439          ((eq magit-branch-read-upstream-first 'fallback)
    440           (list choice
    441                 (magit-read-starting-point prompt choice default-start)))
    442          ((user-error "Not a valid starting-point: %s" choice))))
    443     (let ((branch (magit-read-string-ns (concat prompt " named"))))
    444       (if (magit-branch-p branch)
    445           (magit-branch-read-args
    446            (format "Branch `%s' already exists; pick another name" branch)
    447            default-start)
    448         (list branch (magit-read-starting-point prompt branch default-start))))))
    449 
    450 ;;;###autoload
    451 (defun magit-branch-spinout (branch &optional from)
    452   "Create new branch from the unpushed commits.
    453 Like `magit-branch-spinoff' but remain on the current branch.
    454 If there are any uncommitted changes, then behave exactly like
    455 `magit-branch-spinoff'."
    456   (interactive (list (magit-read-string-ns "Spin out branch")
    457                      (car (last (magit-region-values 'commit)))))
    458   (magit--branch-spinoff branch from nil))
    459 
    460 ;;;###autoload
    461 (defun magit-branch-spinoff (branch &optional from)
    462   "Create new branch from the unpushed commits.
    463 
    464 Create and checkout a new branch starting at and tracking the
    465 current branch.  That branch in turn is reset to the last commit
    466 it shares with its upstream.  If the current branch has no
    467 upstream or no unpushed commits, then the new branch is created
    468 anyway and the previously current branch is not touched.
    469 
    470 This is useful to create a feature branch after work has already
    471 began on the old branch (likely but not necessarily \"master\").
    472 
    473 If the current branch is a member of the value of option
    474 `magit-branch-prefer-remote-upstream' (which see), then the
    475 current branch will be used as the starting point as usual, but
    476 the upstream of the starting-point may be used as the upstream
    477 of the new branch, instead of the starting-point itself.
    478 
    479 If optional FROM is non-nil, then the source branch is reset
    480 to `FROM~', instead of to the last commit it shares with its
    481 upstream.  Interactively, FROM is only ever non-nil, if the
    482 region selects some commits, and among those commits, FROM is
    483 the commit that is the fewest commits ahead of the source
    484 branch.
    485 
    486 The commit at the other end of the selection actually does not
    487 matter, all commits between FROM and `HEAD' are moved to the new
    488 branch.  If FROM is not reachable from `HEAD' or is reachable
    489 from the source branch's upstream, then an error is raised."
    490   (interactive (list (magit-read-string-ns "Spin off branch")
    491                      (car (last (magit-region-values 'commit)))))
    492   (magit--branch-spinoff branch from t))
    493 
    494 (defun magit--branch-spinoff (branch from checkout)
    495   (when (magit-branch-p branch)
    496     (user-error "Cannot spin off %s.  It already exists" branch))
    497   (when (and (not checkout)
    498              (magit-anything-modified-p))
    499     (message "Staying on HEAD due to uncommitted changes")
    500     (setq checkout t))
    501   (if-let ((current (magit-get-current-branch)))
    502       (let ((tracked (magit-get-upstream-branch current))
    503             base)
    504         (when from
    505           (unless (magit-rev-ancestor-p from current)
    506             (user-error "Cannot spin off %s.  %s is not reachable from %s"
    507                         branch from current))
    508           (when (and tracked
    509                      (magit-rev-ancestor-p from tracked))
    510             (user-error "Cannot spin off %s.  %s is ancestor of upstream %s"
    511                         branch from tracked)))
    512         (let ((magit-process-raise-error t))
    513           (if checkout
    514               (magit-call-git "checkout" "-b" branch current)
    515             (magit-call-git "branch" branch current)))
    516         (when-let ((upstream (magit-get-indirect-upstream-branch current)))
    517           (magit-call-git "branch" "--set-upstream-to" upstream branch))
    518         (when (and tracked
    519                    (setq base
    520                          (if from
    521                              (concat from "^")
    522                            (magit-git-string "merge-base" current tracked)))
    523                    (not (magit-rev-eq base current)))
    524           (if checkout
    525               (magit-call-git "update-ref" "-m"
    526                               (format "reset: moving to %s" base)
    527                               (concat "refs/heads/" current) base)
    528             (magit-call-git "reset" "--hard" base))))
    529     (if checkout
    530         (magit-call-git "checkout" "-b" branch)
    531       (magit-call-git "branch" branch)))
    532   (magit-refresh))
    533 
    534 ;;;###autoload
    535 (defun magit-branch-reset (branch to &optional set-upstream)
    536   "Reset a branch to the tip of another branch or any other commit.
    537 
    538 When the branch being reset is the current branch, then do a
    539 hard reset.  If there are any uncommitted changes, then the user
    540 has to confirm the reset because those changes would be lost.
    541 
    542 This is useful when you have started work on a feature branch but
    543 realize it's all crap and want to start over.
    544 
    545 When resetting to another branch and a prefix argument is used,
    546 then also set the target branch as the upstream of the branch
    547 that is being reset."
    548   (interactive
    549    (let ((branch (magit-read-local-branch "Reset branch"
    550                                           (magit-local-branch-at-point))))
    551      (list branch
    552            (magit-read-branch-or-commit (format "Reset %s to" branch)
    553                                         (magit-get-upstream-branch branch)
    554                                         branch)
    555            current-prefix-arg)))
    556   (let ((magit-inhibit-refresh t))
    557     (if (equal branch (magit-get-current-branch))
    558         (if (and (magit-anything-modified-p)
    559                  (not (yes-or-no-p
    560                        "Uncommitted changes will be lost.  Proceed? ")))
    561             (user-error "Abort")
    562           (magit-reset-hard to))
    563       (magit-call-git "update-ref"
    564                       "-m" (format "reset: moving to %s" to)
    565                       (magit-git-string "rev-parse" "--symbolic-full-name"
    566                                         branch)
    567                       to))
    568     (when (and set-upstream (magit-branch-p to))
    569       (magit-set-upstream-branch branch to)
    570       (magit-branch-maybe-adjust-upstream branch to)))
    571   (magit-refresh))
    572 
    573 (defvar magit-branch-delete-never-verify nil
    574   "Whether `magit-branch-delete' always pushes with \"--no-verify\".")
    575 
    576 ;;;###autoload
    577 (defun magit-branch-delete (branches &optional force)
    578   "Delete one or multiple branches.
    579 
    580 If the region marks multiple branches, then offer to delete
    581 those, otherwise prompt for a single branch to be deleted,
    582 defaulting to the branch at point.
    583 
    584 Require confirmation when deleting branches is dangerous in some
    585 way.  Option `magit-no-confirm' can be customized to not require
    586 confirmation in certain cases.  See its docstring to learn why
    587 confirmation is required by default in certain cases or if a
    588 prompt is confusing."
    589   ;; One would expect this to be a command as simple as, for example,
    590   ;; `magit-branch-rename'; but it turns out everyone wants to squeeze
    591   ;; a bit of extra functionality into this one, including myself.
    592   (interactive
    593    (let ((branches (magit-region-values 'branch t))
    594          (force current-prefix-arg))
    595      (if (length> branches 1)
    596          (magit-confirm t nil "Delete %d branches" nil branches)
    597        (setq branches
    598              (list (magit-read-branch-prefer-other
    599                     (if force "Force delete branch" "Delete branch")))))
    600      (when-let (((not force))
    601                 (unmerged (seq-remove #'magit-branch-merged-p branches)))
    602        (if (magit-confirm 'delete-unmerged-branch
    603              "Delete unmerged branch %s"
    604              "Delete %d unmerged branches"
    605              'noabort unmerged)
    606            (setq force branches)
    607          (or (setq branches
    608                    (cl-set-difference branches unmerged :test #'equal))
    609              (user-error "Abort"))))
    610      (list branches force)))
    611   (let ((refs (mapcar #'magit-ref-fullname branches)))
    612     (when-let ((ambiguous (--remove it refs)))
    613       (user-error
    614        "%s ambiguous.  Please cleanup using git directly."
    615        (let ((len (length ambiguous)))
    616          (cond
    617           ((= len 1)
    618            (format "%s is" (seq-find #'magit-ref-ambiguous-p branches)))
    619           ((= len (length refs))
    620            (format "These %s names are" len))
    621           (t
    622            (format "%s of these names are" len))))))
    623     (cond
    624      ((string-match "^refs/remotes/\\([^/]+\\)" (car refs))
    625       (let* ((remote (match-string 1 (car refs)))
    626              (offset (1+ (length remote))))
    627         (cond
    628          ((magit-confirm 'delete-branch-on-remote
    629             (list "Deleting local %s.  Also delete on %s"
    630                   (magit-ref-fullname (car branches))
    631                   remote)
    632             (list "Deleting %d local refs.  Also delete on %s"
    633                   (length refs)
    634                   remote)
    635             'noabort refs)
    636           ;; The ref may actually point at another rev on the remote,
    637           ;; but this is better than nothing.
    638           (dolist (ref refs)
    639             (message "Delete %s (was %s)" ref
    640                      (magit-rev-parse "--short" ref)))
    641           ;; Assume the branches actually still exist on the remote.
    642           (magit-run-git-async
    643            "push"
    644            (and (or force magit-branch-delete-never-verify) "--no-verify")
    645            remote
    646            (--map (concat ":" (substring it offset)) branches))
    647           ;; If that is not the case, then this deletes the tracking branches.
    648           (set-process-sentinel
    649            magit-this-process
    650            (apply-partially #'magit-delete-remote-branch-sentinel remote refs)))
    651          (t
    652           (dolist (ref refs)
    653             (message "Delete %s (was %s)" ref
    654                      (magit-rev-parse "--short" ref))
    655             (magit-call-git "update-ref" "-d" ref))
    656           (magit-refresh)))))
    657      ((length> branches 1)
    658       (setq branches (delete (magit-get-current-branch) branches))
    659       (mapc #'magit-branch-maybe-delete-pr-remote branches)
    660       (mapc #'magit-branch-unset-pushRemote branches)
    661       (magit-run-git "branch" (if force "-D" "-d") branches))
    662      (t ; And now for something completely different.
    663       (let* ((branch (car branches))
    664              (prompt (format "Branch %s is checked out.  " branch))
    665              (target (magit-get-indirect-upstream-branch branch t)))
    666         (when (equal branch (magit-get-current-branch))
    667           (when (or (equal branch target)
    668                     (not target))
    669             (setq target (magit-main-branch)))
    670           (pcase (if (or (equal branch target)
    671                          (not target))
    672                      (magit-read-char-case prompt nil
    673                        (?d "[d]etach HEAD & delete" 'detach)
    674                        (?a "[a]bort"                'abort))
    675                    (magit-read-char-case prompt nil
    676                      (?d "[d]etach HEAD & delete" 'detach)
    677                      (?c (format "[c]heckout %s & delete" target) 'target)
    678                      (?a "[a]bort" 'abort)))
    679             (`detach (unless (or (equal force '(4))
    680                                  (member branch force)
    681                                  (magit-branch-merged-p branch t))
    682                        (magit-confirm 'delete-unmerged-branch
    683                          "Delete unmerged branch %s" ""
    684                          nil (list branch)))
    685                      (magit-call-git "checkout" "--detach"))
    686             (`target (unless (or (equal force '(4))
    687                                  (member branch force)
    688                                  (magit-branch-merged-p branch target))
    689                        (magit-confirm 'delete-unmerged-branch
    690                          "Delete unmerged branch %s" ""
    691                          nil (list branch)))
    692                      (magit-call-git "checkout" target))
    693             (`abort  (user-error "Abort")))
    694           (setq force t))
    695         (magit-branch-maybe-delete-pr-remote branch)
    696         (magit-branch-unset-pushRemote branch)
    697         (magit-run-git "branch" (if force "-D" "-d") branch))))))
    698 
    699 (put 'magit-branch-delete 'interactive-only t)
    700 
    701 (defun magit-branch-maybe-delete-pr-remote (branch)
    702   (when-let ((remote (magit-get "branch" branch "pullRequestRemote")))
    703     (let* ((variable (format "remote.%s.fetch" remote))
    704            (refspecs (magit-get-all variable)))
    705       (unless (member (format "+refs/heads/*:refs/remotes/%s/*" remote)
    706                       refspecs)
    707         (let ((refspec
    708                (if (equal (magit-get "branch" branch "pushRemote") remote)
    709                    (format "+refs/heads/%s:refs/remotes/%s/%s"
    710                            branch remote branch)
    711                  (let ((merge (magit-get "branch" branch "merge")))
    712                    (and merge
    713                         (string-prefix-p "refs/heads/" merge)
    714                         (setq merge (substring merge 11))
    715                         (format "+refs/heads/%s:refs/remotes/%s/%s"
    716                                 merge remote merge))))))
    717           (when (member refspec refspecs)
    718             (if (and (length= refspecs 1)
    719                      (magit-confirm 'delete-pr-remote
    720                        (list "Also delete remote %s (%s)" remote
    721                              "no pull-request branch remains")
    722                        nil t))
    723                 (magit-call-git "remote" "rm" remote)
    724               (magit-call-git "config" "--unset-all" variable
    725                               (format "^%s$" (regexp-quote refspec))))))))))
    726 
    727 (defun magit-branch-unset-pushRemote (branch)
    728   (magit-set nil "branch" branch "pushRemote"))
    729 
    730 (defun magit-delete-remote-branch-sentinel (remote refs process event)
    731   (when (memq (process-status process) '(exit signal))
    732     (if (= (process-exit-status process) 1)
    733         (if-let ((on-remote (--map (concat "refs/remotes/" remote "/" it)
    734                                    (magit-remote-list-branches remote)))
    735                  (rest (--filter (and (not (member it on-remote))
    736                                       (magit-ref-exists-p it))
    737                                  refs)))
    738             (progn
    739               (process-put process 'inhibit-refresh t)
    740               (magit-process-sentinel process event)
    741               (setq magit-this-error nil)
    742               (message "Some remote branches no longer exist.  %s"
    743                        "Deleting just the local tracking refs instead...")
    744               (dolist (ref rest)
    745                 (magit-call-git "update-ref" "-d" ref))
    746               (magit-refresh)
    747               (message "Deleting local remote-tracking refs...done"))
    748           (magit-process-sentinel process event))
    749       (magit-process-sentinel process event))))
    750 
    751 ;;;###autoload
    752 (defun magit-branch-rename (old new &optional force)
    753   "Rename the branch named OLD to NEW.
    754 
    755 With a prefix argument FORCE, rename even if a branch named NEW
    756 already exists.
    757 
    758 If `branch.OLD.pushRemote' is set, then unset it.  Depending on
    759 the value of `magit-branch-rename-push-target' (which see) maybe
    760 set `branch.NEW.pushRemote' and maybe rename the push-target on
    761 the remote."
    762   (interactive
    763    (let ((branch (magit-read-local-branch "Rename branch")))
    764      (list branch
    765            (magit-read-string-ns (format "Rename branch '%s' to" branch)
    766                                  nil 'magit-revision-history)
    767            current-prefix-arg)))
    768   (when (string-match "\\`heads/\\(.+\\)" old)
    769     (setq old (match-string 1 old)))
    770   (when (equal old new)
    771     (user-error "Old and new branch names are the same"))
    772   (magit-call-git "branch" (if force "-M" "-m") old new)
    773   (when magit-branch-rename-push-target
    774     (let ((remote (magit-get-push-remote old))
    775           (old-specified (magit-get "branch" old "pushRemote"))
    776           (new-specified (magit-get "branch" new "pushRemote")))
    777       (when (and old-specified (or force (not new-specified)))
    778         ;; Keep the target setting branch specified, even if that is
    779         ;; redundant.  But if a branch by the same name existed before
    780         ;; and the rename isn't forced, then do not change a leftover
    781         ;; setting.  Such a leftover setting may or may not conform to
    782         ;; what we expect here...
    783         (magit-set old-specified "branch" new "pushRemote"))
    784       (when (and (equal (magit-get-push-remote new) remote)
    785                  ;; ...and if it does not, then we must abort.
    786                  (not (eq magit-branch-rename-push-target 'local-only))
    787                  (or (not (eq magit-branch-rename-push-target 'forge-only))
    788                      (and (require (quote forge) nil t)
    789                           (fboundp 'forge--split-forge-url)
    790                           (and-let* ((url (magit-git-string
    791                                            "remote" "get-url" remote)))
    792                             (forge--split-forge-url url)))))
    793         (let ((old-target (magit-get-push-branch old t))
    794               (new-target (magit-get-push-branch new t))
    795               (remote (magit-get-push-remote new)))
    796           (when (and old-target
    797                      (not new-target)
    798                      (magit-y-or-n-p (format "Also rename %S to %S on \"%s\""
    799                                              old new remote)))
    800             ;; Rename on (i.e., within) the remote, but only if the
    801             ;; destination ref doesn't exist yet.  If that ref already
    802             ;; exists, then it probably is of some value and we better
    803             ;; not touch it.  Ignore what the local ref points at,
    804             ;; i.e., if the local and the remote ref didn't point at
    805             ;; the same commit before the rename then keep it that way.
    806             (magit-call-git "push" "-v" remote
    807                             (format "%s:refs/heads/%s" old-target new)
    808                             (format ":refs/heads/%s" old)))))))
    809   (magit-branch-unset-pushRemote old)
    810   (magit-refresh))
    811 
    812 ;;;###autoload
    813 (defun magit-branch-shelve (branch)
    814   "Shelve a BRANCH.
    815 Rename \"refs/heads/BRANCH\" to \"refs/shelved/BRANCH\",
    816 and also rename the respective reflog file."
    817   (interactive (list (magit-read-other-local-branch "Shelve branch")))
    818   (let ((old (concat "refs/heads/"   branch))
    819         (new (concat "refs/shelved/" branch)))
    820     (magit-git "update-ref" new old "")
    821     (magit--rename-reflog-file old new)
    822     (magit-branch-unset-pushRemote branch)
    823     (magit-run-git "branch" "-D" branch)))
    824 
    825 ;;;###autoload
    826 (defun magit-branch-unshelve (branch)
    827   "Unshelve a BRANCH
    828 Rename \"refs/shelved/BRANCH\" to \"refs/heads/BRANCH\",
    829 and also rename the respective reflog file."
    830   (interactive
    831    (list (magit-completing-read
    832           "Unshelve branch"
    833           (--map (substring it 8)
    834                  (magit-list-refnames "refs/shelved"))
    835           nil t)))
    836   (let ((old (concat "refs/shelved/" branch))
    837         (new (concat "refs/heads/"   branch)))
    838     (magit-git "update-ref" new old "")
    839     (magit--rename-reflog-file old new)
    840     (magit-run-git "update-ref" "-d" old)))
    841 
    842 (defun magit--rename-reflog-file (old new)
    843   (let* ((dir (magit-gitdir))
    844          (old (expand-file-name (concat "logs/" old) dir))
    845          (new (expand-file-name (concat "logs/" new) dir)))
    846     (when (file-exists-p old)
    847       (make-directory (file-name-directory new) t)
    848       (rename-file old new t))))
    849 
    850 ;;; Configure
    851 
    852 ;;;###autoload (autoload 'magit-branch-configure "magit-branch" nil t)
    853 (transient-define-prefix magit-branch-configure (branch)
    854   "Configure a branch."
    855   :man-page "git-branch"
    856   [:description
    857    (lambda ()
    858      (concat (propertize "Configure " 'face 'transient-heading)
    859              (propertize (transient-scope) 'face 'magit-branch-local)))
    860    ("d" magit-branch.<branch>.description)
    861    ("u" magit-branch.<branch>.merge/remote)
    862    ("r" magit-branch.<branch>.rebase)
    863    ("p" magit-branch.<branch>.pushRemote)]
    864   ["Configure repository defaults"
    865    ("R" magit-pull.rebase)
    866    ("P" magit-remote.pushDefault)
    867    ("B" "Update default branch" magit-update-default-branch
    868     :inapt-if-not magit-get-some-remote)]
    869   ["Configure branch creation"
    870    ("a m" magit-branch.autoSetupMerge)
    871    ("a r" magit-branch.autoSetupRebase)]
    872   (interactive
    873    (list (or (and (not current-prefix-arg)
    874                   (not (and magit-branch-direct-configure
    875                             (eq transient-current-command 'magit-branch)))
    876                   (magit-get-current-branch))
    877              (magit--read-branch-scope))))
    878   (transient-setup 'magit-branch-configure nil nil :scope branch))
    879 
    880 (defun magit--read-branch-scope (&optional obj)
    881   (magit-read-local-branch
    882    (if obj
    883        (format "Set %s for branch"
    884                (format (oref obj variable) "<name>"))
    885      "Configure branch")))
    886 
    887 (transient-define-suffix magit-branch.<branch>.description (branch)
    888   "Edit the description of BRANCH."
    889   :class 'magit--git-variable
    890   :transient nil
    891   :variable "branch.%s.description"
    892   (interactive (list (oref transient-current-prefix scope)))
    893   (magit-run-git-with-editor "branch" "--edit-description" branch))
    894 
    895 (defclass magit--git-branch:upstream (magit--git-variable)
    896   ((format :initform " %k %m %M\n   %r %R")))
    897 
    898 (transient-define-infix magit-branch.<branch>.merge/remote ()
    899   :class 'magit--git-branch:upstream)
    900 
    901 (cl-defmethod transient-init-value ((obj magit--git-branch:upstream))
    902   (when-let* ((branch (transient-scope))
    903               (remote (magit-get "branch" branch "remote"))
    904               (merge  (magit-get "branch" branch "merge")))
    905     (oset obj value (list remote merge))))
    906 
    907 (cl-defmethod transient-infix-read ((obj magit--git-branch:upstream))
    908   (if (oref obj value)
    909       (oset obj value nil)
    910     (magit-read-upstream-branch (transient-scope) "Upstream")))
    911 
    912 (cl-defmethod transient-infix-set ((obj magit--git-branch:upstream) refname)
    913   (magit-set-upstream-branch (transient-scope) refname)
    914   (oset obj value
    915         (and-let* ((branch (transient-scope))
    916                    (r (magit-get "branch" branch "remote"))
    917                    (m (magit-get "branch" branch "merge")))
    918           (list r m)))
    919   (magit-refresh))
    920 
    921 (cl-defmethod transient-format ((obj magit--git-branch:upstream))
    922   (let ((branch (transient-scope)))
    923     (format-spec
    924      (oref obj format)
    925      `((?k . ,(transient-format-key obj))
    926        (?r . ,(format "branch.%s.remote" branch))
    927        (?m . ,(format "branch.%s.merge" branch))
    928        (?R . ,(transient-format-value obj #'car))
    929        (?M . ,(transient-format-value obj #'cadr))))))
    930 
    931 (cl-defmethod transient-format-value ((obj magit--git-branch:upstream) key)
    932   (if-let ((value (funcall key (oref obj value))))
    933       (propertize value 'face 'transient-argument)
    934     (propertize "unset" 'face 'transient-inactive-argument)))
    935 
    936 (transient-define-infix magit-branch.<branch>.rebase ()
    937   :class 'magit--git-variable:choices
    938   :scope #'magit--read-branch-scope
    939   :variable "branch.%s.rebase"
    940   :fallback "pull.rebase"
    941   :choices '("true" "false")
    942   :default "false")
    943 
    944 (transient-define-infix magit-branch.<branch>.pushRemote ()
    945   :class 'magit--git-variable:choices
    946   :scope #'magit--read-branch-scope
    947   :variable "branch.%s.pushRemote"
    948   :fallback "remote.pushDefault"
    949   :choices #'magit-list-remotes)
    950 
    951 (transient-define-infix magit-pull.rebase ()
    952   :class 'magit--git-variable:choices
    953   :variable "pull.rebase"
    954   :choices '("true" "false")
    955   :default "false")
    956 
    957 (transient-define-infix magit-remote.pushDefault ()
    958   :class 'magit--git-variable:choices
    959   :variable "remote.pushDefault"
    960   :choices #'magit-list-remotes)
    961 
    962 (transient-define-infix magit-branch.autoSetupMerge ()
    963   :class 'magit--git-variable:choices
    964   :variable "branch.autoSetupMerge"
    965   :choices '("always" "true" "false")
    966   :default "true")
    967 
    968 (transient-define-infix magit-branch.autoSetupRebase ()
    969   :class 'magit--git-variable:choices
    970   :variable "branch.autoSetupRebase"
    971   :choices '("always" "local" "remote" "never")
    972   :default "never")
    973 
    974 ;;; _
    975 (provide 'magit-branch)
    976 ;;; magit-branch.el ends here