magit-sequence.el 37.9 KB
Newer Older
1
;;; magit-sequence.el --- history manipulation in Magit  -*- lexical-binding: t -*-
2

Jonas Bernoulli's avatar
Jonas Bernoulli committed
3
;; Copyright (C) 2011-2018  The Magit Project Contributors
4
;;
5 6
;; You should have received a copy of the AUTHORS.md file which
;; lists all contributors.  If not, see http://magit.vc/authors.
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75

;; Author: Jonas Bernoulli <jonas@bernoul.li>
;; Maintainer: Jonas Bernoulli <jonas@bernoul.li>

;; Magit is free software; you can redistribute it and/or modify it
;; under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3, or (at your option)
;; any later version.
;;
;; Magit is distributed in the hope that it will be useful, but WITHOUT
;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
;; or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
;; License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with Magit.  If not, see http://www.gnu.org/licenses.

;;; Commentary:

;; Support for Git commands that replay commits and help the user make
;; changes along the way.  Supports `cherry-pick', `revert', `rebase',
;; `rebase--interactive' and `am'.

;;; Code:

(require 'magit)

;;; Options
;;;; Faces

(defface magit-sequence-pick
  '((t :inherit default))
  "Face used in sequence sections."
  :group 'magit-faces)

(defface magit-sequence-stop
  '((((class color) (background light)) :foreground "DarkOliveGreen4")
    (((class color) (background dark))  :foreground "DarkSeaGreen2"))
  "Face used in sequence sections."
  :group 'magit-faces)

(defface magit-sequence-part
  '((((class color) (background light)) :foreground "Goldenrod4")
    (((class color) (background dark))  :foreground "LightGoldenrod2"))
  "Face used in sequence sections."
  :group 'magit-faces)

(defface magit-sequence-head
  '((((class color) (background light)) :foreground "SkyBlue4")
    (((class color) (background dark))  :foreground "LightSkyBlue1"))
  "Face used in sequence sections."
  :group 'magit-faces)

(defface magit-sequence-drop
  '((((class color) (background light)) :foreground "IndianRed")
    (((class color) (background dark))  :foreground "IndianRed"))
  "Face used in sequence sections."
  :group 'magit-faces)

(defface magit-sequence-done
  '((t :inherit magit-hash))
  "Face used in sequence sections."
  :group 'magit-faces)

(defface magit-sequence-onto
  '((t :inherit magit-sequence-done))
  "Face used in sequence sections."
  :group 'magit-faces)

76 77 78 79 80
(defface magit-sequence-exec
  '((t :inherit magit-hash))
  "Face used in sequence sections."
  :group 'magit-faces)

81 82 83 84
;;; Common

;;;###autoload
(defun magit-sequencer-continue ()
85
  "Resume the current cherry-pick or revert sequence."
86 87
  (interactive)
  (if (magit-sequencer-in-progress-p)
88
      (if (magit-anything-unstaged-p t)
89
          (user-error "Cannot continue due to unstaged changes")
90 91
        (magit-run-git-sequencer
         (if (magit-revert-in-progress-p) "revert" "cherry-pick") "--continue"))
92
    (user-error "No cherry-pick or revert in progress")))
93 94 95

;;;###autoload
(defun magit-sequencer-skip ()
96
  "Skip the stopped at commit during a cherry-pick or revert sequence."
97 98 99 100
  (interactive)
  (if (magit-sequencer-in-progress-p)
      (progn (magit-call-git "reset" "--hard")
             (magit-sequencer-continue))
101
    (user-error "No cherry-pick or revert in progress")))
102 103 104

;;;###autoload
(defun magit-sequencer-abort ()
105 106
  "Abort the current cherry-pick or revert sequence.
This discards all changes made since the sequence started."
107 108 109 110
  (interactive)
  (if (magit-sequencer-in-progress-p)
      (magit-run-git-sequencer
       (if (magit-revert-in-progress-p) "revert" "cherry-pick") "--abort")
111
    (user-error "No cherry-pick or revert in progress")))
112 113

(defun magit-sequencer-in-progress-p ()
114 115
  (or (magit-cherry-pick-in-progress-p)
      (magit-revert-in-progress-p)))
116 117 118

;;; Cherry-Pick

Jonas Bernoulli's avatar
Jonas Bernoulli committed
119
;;;###autoload (autoload 'magit-cherry-pick-popup "magit-sequence" nil t)
120 121 122 123 124 125
(magit-define-popup magit-cherry-pick-popup
  "Popup console for cherry-pick commands."
  :man-page "git-cherry-pick"
  :switches '((?s "Add Signed-off-by lines"            "--signoff")
              (?e "Edit commit messages"               "--edit")
              (?x "Reference cherry in commit message" "-x")
126 127 128
              (?F "Attempt fast-forward"               "--ff"))
  :options  '((?s "Strategy"                        "--strategy=")
              (?m "Replay merge relative to parent" "--mainline="))
129 130 131 132 133 134 135 136
  :actions  '("Apply here"
              (?A "Pick"    magit-cherry-pick)
              (?a "Apply"   magit-cherry-apply)
              (?h "Harvest" magit-cherry-harvest)
              "Apply elsewhere"
              (?d "Donate"  magit-cherry-donate)
              (?n "Spinout" magit-cherry-spinout)
              (?s "Spinoff" magit-cherry-spinoff))
137 138 139 140 141 142
  :sequence-actions '((?A "Continue" magit-sequencer-continue)
                      (?s "Skip"     magit-sequencer-skip)
                      (?a "Abort"    magit-sequencer-abort))
  :sequence-predicate 'magit-sequencer-in-progress-p
  :default-arguments '("--ff"))

143 144 145
(defun magit-cherry-pick-read-args (prompt)
  (list (or (nreverse (magit-region-values 'commit))
            (magit-read-other-branch-or-commit prompt))
146
        (magit-cherry-pick-arguments)))
147

148 149 150
(defun magit--cherry-move-read-args (verb away fn)
  (declare (indent defun))
   (let ((commits (or (nreverse (magit-region-values 'commit))
151 152 153 154
                      (list (funcall (if away
                                         'magit-read-branch-or-commit
                                       'magit-read-other-branch-or-commit)
                                     (format "%s cherry" (capitalize verb))))))
155 156 157 158 159 160 161 162
         (current (magit-get-current-branch)))
     (unless current
       (user-error "Cannot %s cherries while HEAD is detached" verb))
     (let ((reachable (magit-rev-ancestor-p (car commits) current))
           (msg "Cannot %s cherries that %s reachable from HEAD"))
       (pcase (list away reachable)
         (`(nil t) (user-error msg verb "are"))
         (`(t nil) (user-error msg verb "are not"))))
163
     `(,commits
164 165 166 167 168 169 170 171 172
       ,@(funcall fn commits)
       ,(magit-cherry-pick-arguments))))

(defun magit--cherry-spinoff-read-args (verb)
  (magit--cherry-move-read-args verb t
    (lambda (commits)
      (butlast (magit-branch-read-args
                (format "Create branch from %s cherries" commits))))))

173
;;;###autoload
174 175
(defun magit-cherry-pick (commits &optional args)
  "Copy COMMITS from another branch onto the current branch.
176 177 178
Prompt for a commit, defaulting to the commit at point.  If
the region selects multiple commits, then pick all of them,
without prompting."
179
  (interactive (magit-cherry-pick-read-args "Cherry-pick"))
180
  (magit--cherry-pick commits args))
181 182

;;;###autoload
183 184
(defun magit-cherry-apply (commits &optional args)
  "Apply the changes in COMMITS but do not commit them.
185 186 187
Prompt for a commit, defaulting to the commit at point.  If
the region selects multiple commits, then apply all of them,
without prompting."
188
  (interactive (magit-cherry-pick-read-args "Apply changes from commit"))
189
  (magit--cherry-pick commits (cons "--no-commit" (remove "--ff" args))))
190

191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
;;;###autoload
(defun magit-cherry-harvest (commits branch &optional args)
  "Move COMMITS from another BRANCH onto the current branch.
Remove the COMMITS from BRANCH and stay on the current branch.
If a conflict occurs, then you have to fix that and finish the
process manually."
  (interactive
   (magit--cherry-move-read-args "harvest" nil
     (lambda (commits)
       (list (let ((branches (magit-list-containing-branches (car commits))))
               (pcase (length branches)
                 (0 nil)
                 (1 (car branches))
                 (_ (magit-completing-read
                     (format "Remove %s cherries from branch" (length commits))
206
                     branches nil t))))))))
207
  (magit--cherry-move commits branch (magit-get-current-branch) args nil t))
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279

;;;###autoload
(defun magit-cherry-donate (commits branch &optional args)
  "Move COMMITS from the current branch onto another existing BRANCH.
Remove COMMITS from the current branch and stay on that branch.
If a conflict occurs, then you have to fix that and finish the
process manually."
  (interactive
   (magit--cherry-move-read-args "donate" t
     (lambda (commits)
       (list (magit-read-other-branch (format "Move %s cherries to branch"
                                              (length commits)))))))
  (magit--cherry-move commits (magit-get-current-branch) branch args))

;;;###autoload
(defun magit-cherry-spinout (commits branch start-point &optional args)
  "Move COMMITS from the current branch onto a new BRANCH.
Remove COMMITS from the current branch and stay on that branch.
If a conflict occurs, then you have to fix that and finish the
process manually."
  (interactive (magit--cherry-spinoff-read-args "spinout"))
  (magit--cherry-move commits (magit-get-current-branch) branch args
                      start-point))

;;;###autoload
(defun magit-cherry-spinoff (commits branch start-point &optional args)
  "Move COMMITS from the current branch onto a new BRANCH.
Remove COMMITS from the current branch and checkout BRANCH.
If a conflict occurs, then you have to fix that and finish
the process manually."
  (interactive (magit--cherry-spinoff-read-args "spinoff"))
  (magit--cherry-move commits (magit-get-current-branch) branch args
                      start-point t))

(defun magit--cherry-move (commits src dst args
                                   &optional start-point checkout-dst)
  (let ((current (magit-get-current-branch)))
    (unless (magit-branch-p dst)
      (let ((magit-process-raise-error t))
        (magit-call-git "branch" dst start-point))
      (--when-let (magit-get-indirect-upstream-branch start-point)
        (magit-call-git "branch" "--set-upstream-to" it dst)))
    (unless (equal dst current)
      (let ((magit-process-raise-error t))
        (magit-call-git "checkout" dst)))
    (if (not src) ; harvest only
        (magit--cherry-pick commits args)
      (let ((tip (car (last commits)))
            (keep (concat (car commits) "^")))
        (magit--cherry-pick commits args)
        (set-process-sentinel
         magit-this-process
         (lambda (process event)
           (when (memq (process-status process) '(exit signal))
             (if (> (process-exit-status process) 0)
                 (magit-process-sentinel process event)
               (process-put process 'inhibit-refresh t)
               (magit-process-sentinel process event)
               (cond
                ((magit-rev-equal tip src)
                 (magit-call-git "update-ref"
                                 "-m" (format "reset: moving to %s" keep)
                                 (magit-ref-fullname src)
                                 keep tip)
                 (if (not checkout-dst)
                     (magit-run-git "checkout" src)
                   (magit-refresh)))
                (t
                 (magit-call-git "checkout" src)
                 (let ((process-environment process-environment))
                   (push (format "%s=perl -i -ne '/^pick (%s)/ or print'"
                                 "GIT_SEQUENCE_EDITOR"
280
                                 (mapconcat #'magit-rev-abbrev commits "|"))
281 282 283 284 285 286 287 288 289 290 291 292 293
                         process-environment)
                   (magit-run-git-sequencer "rebase" "-i" keep))
                 (when checkout-dst
                   (set-process-sentinel
                    magit-this-process
                    (lambda (process event)
                      (when (memq (process-status process) '(exit signal))
                        (if (> (process-exit-status process) 0)
                            (magit-process-sentinel process event)
                          (process-put process 'inhibit-refresh t)
                          (magit-process-sentinel process event)
                          (magit-run-git "checkout" dst))))))))))))))))

294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
(defun magit--cherry-pick (commits args &optional revert)
  (let ((command (if revert "revert" "cherry-pick")))
    (when (stringp commits)
      (setq commits (if (string-match-p "\\.\\." commits)
                        (split-string commits "\\.\\.")
                      (list commits))))
    (magit-run-git-sequencer
     (if revert "revert" "cherry-pick")
     (pcase-let ((`(,merge ,non-merge)
                  (-separate 'magit-merge-commit-p commits)))
       (cond
        ((not merge)
         (--remove (string-prefix-p "--mainline=" it) args))
        (non-merge
         (user-error "Cannot %s merge and non-merge commits at once"
                     command))
        ((--first (string-prefix-p "--mainline=" it) args)
         args)
        (t
         (cons (format "--mainline=%s"
                       (read-number "Replay merges relative to parent: "))
               args))))
     commits)))
317 318

(defun magit-cherry-pick-in-progress-p ()
319 320
  ;; .git/sequencer/todo does not exist when there is only one commit left.
  (file-exists-p (magit-git-dir "CHERRY_PICK_HEAD")))
321 322 323

;;; Revert

Jonas Bernoulli's avatar
Jonas Bernoulli committed
324
;;;###autoload (autoload 'magit-revert-popup "magit-sequence" nil t)
325 326 327
(magit-define-popup magit-revert-popup
  "Popup console for revert commands."
  :man-page "git-revert"
328 329 330
  :switches '((?s "Add Signed-off-by lines"   "--signoff")
              (?e "Edit commit message"       "--edit")
              (?E "Don't edit commit message" "--no-edit"))
331
  :options  '((?s "Strategy"       "--strategy=")
332 333
              (?S "Sign using gpg" "--gpg-sign=" magit-read-gpg-secret-key)
              (?m "Replay merge relative to parent" "--mainline="))
334 335 336 337 338
  :actions  '((?V "Revert commit(s)" magit-revert)
              (?v "Revert changes"   magit-revert-no-commit))
  :sequence-actions '((?V "Continue" magit-sequencer-continue)
                      (?s "Skip"     magit-sequencer-skip)
                      (?a "Abort"    magit-sequencer-abort))
339 340
  :sequence-predicate 'magit-sequencer-in-progress-p
  :default-arguments '("--edit"))
341

342 343 344
(defun magit-revert-read-args (prompt)
  (list (or (magit-region-values 'commit)
            (magit-read-branch-or-commit prompt))
345
        (magit-revert-arguments)))
346

347 348
;;;###autoload
(defun magit-revert (commit &optional args)
349 350 351 352
  "Revert COMMIT by creating a new commit.
Prompt for a commit, defaulting to the commit at point.  If
the region selects multiple commits, then revert all of them,
without prompting."
353
  (interactive (magit-revert-read-args "Revert commit"))
354
  (magit--cherry-pick commit args t))
355 356 357

;;;###autoload
(defun magit-revert-no-commit (commit &optional args)
358 359 360 361
  "Revert COMMIT by applying it in reverse to the worktree.
Prompt for a commit, defaulting to the commit at point.  If
the region selects multiple commits, then revert all of them,
without prompting."
362
  (interactive (magit-revert-read-args "Revert changes"))
363
  (magit--cherry-pick commit (cons "--no-commit" args) t))
364 365

(defun magit-revert-in-progress-p ()
366 367
  ;; .git/sequencer/todo does not exist when there is only one commit left.
  (file-exists-p (magit-git-dir "REVERT_HEAD")))
368 369 370

;;; Patch

Jonas Bernoulli's avatar
Jonas Bernoulli committed
371
;;;###autoload (autoload 'magit-am-popup "magit-sequence" nil t)
372 373 374 375 376 377 378 379 380 381 382
(magit-define-popup magit-am-popup
  "Popup console for mailbox commands."
  :man-page "git-am"
  :switches '((?3 "Fall back on 3way merge"           "--3way")
              (?s "Add Signed-off-by lines"           "--signoff")
              (?c "Remove text before scissors line"  "--scissors")
              (?k "Inhibit removal of email cruft"    "--keep")
              (?b "Limit removal of email cruft"      "--keep-non-patch")
              (?d "Use author date as committer date"
                  "--committer-date-is-author-date")
              (?D "Use committer date as author date" "--ignore-date"))
383 384
  :options  '((?p "Remove leading slashes from paths" "-p"
                  magit-popup-read-number))
385 386 387
  :actions  '((?m "Apply maildir"     magit-am-apply-maildir)
              (?w "Apply patches"     magit-am-apply-patches)
              (?a "Apply plain patch" magit-patch-apply-popup))
388 389
  :default-arguments '("--3way")
  :default-actions 'magit-am-apply-patches
390
  :max-action-columns 1
391 392 393 394 395 396 397
  :sequence-actions '((?w "Continue" magit-am-continue)
                      (?s "Skip"     magit-am-skip)
                      (?a "Abort"    magit-am-abort))
  :sequence-predicate 'magit-am-in-progress-p)

;;;###autoload
(defun magit-am-apply-patches (&optional files args)
398
  "Apply the patches FILES."
399
  (interactive (list (or (magit-region-values 'file)
400 401 402 403 404 405
                         (list (let ((default (magit-file-at-point)))
                                 (read-file-name
                                  (if default
                                      (format "Apply patch (%s): " default)
                                    "Apply patch: ")
                                  nil default))))
406
                     (magit-am-arguments)))
407 408 409 410
  (magit-run-git-sequencer "am" args "--"
                           (--map (magit-convert-filename-for-git
                                   (expand-file-name it))
                                  files)))
411 412 413

;;;###autoload
(defun magit-am-apply-maildir (&optional maildir args)
414
  "Apply the patches from MAILDIR."
415
  (interactive (list (read-file-name "Apply mbox or Maildir: ")
416
                     (magit-am-arguments)))
417 418
  (magit-run-git-sequencer "am" args (magit-convert-filename-for-git
                                      (expand-file-name maildir))))
419 420 421

;;;###autoload
(defun magit-am-continue ()
422
  "Resume the current patch applying sequence."
423 424
  (interactive)
  (if (magit-am-in-progress-p)
425
      (if (magit-anything-unstaged-p t)
426 427 428 429 430 431
          (error "Cannot continue due to unstaged changes")
        (magit-run-git-sequencer "am" "--continue"))
    (user-error "Not applying any patches")))

;;;###autoload
(defun magit-am-skip ()
432
  "Skip the stopped at patch during a patch applying sequence."
433 434 435 436 437 438 439
  (interactive)
  (if (magit-am-in-progress-p)
      (magit-run-git-sequencer "am" "--skip")
    (user-error "Not applying any patches")))

;;;###autoload
(defun magit-am-abort ()
440 441
  "Abort the current patch applying sequence.
This discards all changes made since the sequence started."
442 443 444 445 446 447 448 449 450 451
  (interactive)
  (if (magit-am-in-progress-p)
      (magit-run-git "am" "--abort")
    (user-error "Not applying any patches")))

(defun magit-am-in-progress-p ()
  (file-exists-p (magit-git-dir "rebase-apply/applying")))

;;; Rebase

Jonas Bernoulli's avatar
Jonas Bernoulli committed
452
;;;###autoload (autoload 'magit-rebase-popup "magit-sequence" nil t)
453 454 455
(magit-define-popup magit-rebase-popup
  "Key menu for rebasing."
  :man-page "git-rebase"
456 457 458 459 460
  :switches '((?k "Keep empty commits"       "--keep-empty")
              (?p "Preserve merges"          "--preserve-merges")
              (?c "Lie about committer date" "--committer-date-is-author-date")
              (?a "Autosquash"               "--autosquash")
              (?A "Autostash"                "--autostash")
461 462
              (?i "Interactive"              "--interactive")
              (?h "Disable hooks"            "--no-verify"))
463 464 465 466 467
  :actions  '((lambda ()
                (concat (propertize "Rebase " 'face 'magit-popup-heading)
                        (propertize (or (magit-get-current-branch) "HEAD")
                                    'face 'magit-branch-local)
                        (propertize " onto" 'face 'magit-popup-heading)))
468 469 470 471 472 473
              (?p (lambda ()
                    (--when-let (magit-get-push-branch) (concat it "\n")))
                  magit-rebase-onto-pushremote)
              (?u (lambda ()
                    (--when-let (magit-get-upstream-branch) (concat it "\n")))
                  magit-rebase-onto-upstream)
474
              (?e "elsewhere"               magit-rebase)
475 476
              "Rebase"
              (?i "interactively"      magit-rebase-interactive)
477
              (?m "to modify a commit" magit-rebase-edit-commit)
478
              (?s "a subset"           magit-rebase-subset)
479
              (?w "to reword a commit" magit-rebase-reword-commit) nil
480
              (?k "to remove a commit" magit-rebase-remove-commit) nil
481
              (?f "to autosquash"      magit-rebase-autosquash))
482 483 484 485 486
  :sequence-actions '((?r "Continue" magit-rebase-continue)
                      (?s "Skip"     magit-rebase-skip)
                      (?e "Edit"     magit-rebase-edit)
                      (?a "Abort"    magit-rebase-abort))
  :sequence-predicate 'magit-rebase-in-progress-p
487
  :max-action-columns 2)
488

489 490 491
(defun magit-git-rebase (target args)
  (magit-run-git-sequencer "rebase" target args))

492
;;;###autoload
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
(defun magit-rebase-onto-pushremote (args)
  "Rebase the current branch onto `branch.<name>.pushRemote'.
If that variable is unset, then rebase onto `remote.pushDefault'."
  (interactive (list (magit-rebase-arguments)))
  (--if-let (magit-get-current-branch)
      (-if-let (remote (magit-get-push-remote it))
          (if (member remote (magit-list-remotes))
              (magit-git-rebase (concat remote "/" it) args)
            (user-error "Remote `%s' doesn't exist" remote))
        (user-error "No push-remote is configured for %s" it))
    (user-error "No branch is checked out")))

;;;###autoload
(defun magit-rebase-onto-upstream (args)
  "Rebase the current branch onto its upstream branch."
  (interactive (list (magit-rebase-arguments)))
  (--if-let (magit-get-current-branch)
510
      (-if-let (target (magit-get-upstream-branch it))
511 512 513 514 515 516 517
          (magit-git-rebase target args)
        (user-error "No upstream is configured for %s" it))
    (user-error "No branch is checked out")))

;;;###autoload
(defun magit-rebase (target args)
  "Rebase the current branch onto a branch read in the minibuffer.
518
All commits that are reachable from `HEAD' but not from the
519
selected branch TARGET are being rebased."
520
  (interactive (list (magit-read-other-branch-or-commit "Rebase onto")
521
                     (magit-rebase-arguments)))
522
  (message "Rebasing...")
523
  (magit-git-rebase target args)
524
  (message "Rebasing...done"))
525 526

;;;###autoload
527
(defun magit-rebase-subset (newbase start args)
528
  "Rebase a subset of the current branch's history onto a new base.
529 530
Rebase commits from START to `HEAD' onto NEWBASE.
START has to be selected from a list of recent commits."
531
  (interactive (list (magit-read-other-branch-or-commit
532
                      "Rebase subset onto" nil
533
                      (magit-get-upstream-branch))
534
                     nil
535
                     (magit-rebase-arguments)))
536
  (if start
537
      (progn (message "Rebasing...")
538
             (magit-run-git-sequencer "rebase" "--onto" newbase start args)
539 540 541
             (message "Rebasing...done"))
    (magit-log-select
      `(lambda (commit)
542
         (magit-rebase-subset ,newbase (concat commit "^") (list ,@args)))
543
      (concat "Type %p on a commit to rebase it "
544
              "and commits above it onto " newbase ","))))
545

546
(defun magit-rebase-interactive-1
547
    (commit args message &optional editor delay-edit-confirm noassert confirm)
548
  (declare (indent 2))
549 550
  (when commit
    (if (eq commit :merge-base)
551
        (setq commit (--if-let (magit-get-upstream-branch)
552 553
                         (magit-git-string "merge-base" it "HEAD")
                       nil))
554
      (unless (magit-rev-ancestor-p commit "HEAD")
555
        (user-error "%s isn't an ancestor of HEAD" commit))
556 557 558
      (if (magit-commit-parents commit)
          (setq commit (concat commit "^"))
        (setq args (cons "--root" args)))))
559
  (when (and commit (not noassert))
560
    (setq commit (magit-rebase-interactive-assert commit delay-edit-confirm)))
561
  (if (and commit (not confirm))
562 563
      (let ((process-environment process-environment))
        (when editor
564
          (push (concat "GIT_SEQUENCE_EDITOR=" editor) process-environment))
565
        (magit-run-git-sequencer "rebase" "-i" args
566
                                 (unless (member "--root" args) commit)))
567
    (magit-log-select
568
      `(lambda (commit)
569
         (magit-rebase-interactive-1 commit (list ,@args)
570
           ,message ,editor ,delay-edit-confirm ,noassert))
571 572
      message)))

573
(defvar magit--rebase-published-symbol nil)
574
(defvar magit--rebase-public-edit-confirmed nil)
575

576 577 578 579 580 581 582 583 584
(defun magit-rebase-interactive-assert (since &optional delay-edit-confirm)
  (let* ((commit (if (string-suffix-p "^" since)
                     ;; If SINCE is "REV^", then the user selected
                     ;; "REV", which is the first commit that will
                     ;; be replaced. (from^..to] <=> [from..to].
                     (substring since 0 -1)
                   ;; The "--root" argument is being used.
                   since))
         (branches (magit-list-publishing-branches commit)))
585 586
    (setq magit--rebase-public-edit-confirmed
          (delete (magit-toplevel) magit--rebase-public-edit-confirmed))
587 588 589 590 591 592 593 594 595
    (when (and branches
               (or (not delay-edit-confirm)
                   ;; The user might have stopped at a published commit
                   ;; merely to add new commits *after* it.  Try not to
                   ;; ask users whether they really want to edit public
                   ;; commits, when they don't actually intend to do so.
                   (not (--all-p (magit-rev-equal it commit) branches))))
      (let ((m1 "Some of these commits have already been published to ")
            (m2 ".\nDo you really want to modify them"))
596
        (magit-confirm (or magit--rebase-published-symbol 'rebase-published)
597
          (concat m1 "%s" m2)
598 599
          (concat m1 "%i public branches" m2)))
      (push (magit-toplevel) magit--rebase-public-edit-confirmed)))
600 601 602 603 604 605 606
  (if (magit-git-lines "rev-list" "--merges" (concat since "..HEAD"))
      (magit-read-char-case "Proceed despite merge in rebase range?  " nil
        (?c "[c]ontinue" since)
        (?s "[s]elect other" nil)
        (?a "[a]bort" (user-error "Quit")))
    since))

607
;;;###autoload
608
(defun magit-rebase-interactive (commit args)
609
  "Start an interactive rebase sequence."
610 611 612
  (interactive (list (magit-commit-at-point)
                     (magit-rebase-arguments)))
  (magit-rebase-interactive-1 commit args
613 614
    "Type %p on a commit to rebase it and all commits above it,"
    nil t))
615 616

;;;###autoload
617
(defun magit-rebase-autosquash (args)
618
  "Combine squash and fixup commits with their intended targets."
619 620
  (interactive (list (magit-rebase-arguments)))
  (magit-rebase-interactive-1 :merge-base (cons "--autosquash" args)
621
    "Type %p on a commit to squash into it and then rebase as necessary,"
622
    "true"))
623 624

;;;###autoload
625
(defun magit-rebase-edit-commit (commit args)
626
  "Edit a single older commit using rebase."
627 628 629
  (interactive (list (magit-commit-at-point)
                     (magit-rebase-arguments)))
  (magit-rebase-interactive-1 commit args
630
    "Type %p on a commit to edit it,"
631 632
    "perl -i -p -e '++$x if not $x and s/^pick/edit/'"
    t))
633 634

;;;###autoload
635
(defun magit-rebase-reword-commit (commit args)
636
  "Reword a single older commit using rebase."
637 638 639
  (interactive (list (magit-commit-at-point)
                     (magit-rebase-arguments)))
  (magit-rebase-interactive-1 commit args
640 641 642
    "Type %p on a commit to reword its message,"
    "perl -i -p -e '++$x if not $x and s/^pick/reword/'"))

643 644 645 646 647 648 649 650
;;;###autoload
(defun magit-rebase-remove-commit (commit args)
  "Remove a single older commit using rebase."
  (interactive (list (magit-commit-at-point)
                     (magit-rebase-arguments)))
  (magit-rebase-interactive-1 commit args
    "Type %p on a commit to remove it,"
    "perl -i -p -e '++$x if not $x and s/^pick/# pick/'"
651
    nil nil t))
652

653
;;;###autoload
654 655 656 657 658
(defun magit-rebase-continue (&optional noedit)
  "Restart the current rebasing operation.
In some cases this pops up a commit message buffer for you do
edit.  With a prefix argument the old message is reused as-is."
  (interactive "P")
659
  (if (magit-rebase-in-progress-p)
660
      (if (magit-anything-unstaged-p t)
661
          (user-error "Cannot continue rebase with unstaged changes")
662 663
        (when (and (magit-anything-staged-p)
                   (file-exists-p (magit-git-dir "rebase-merge"))
664 665
                   (not (member (magit-toplevel)
                                magit--rebase-public-edit-confirmed)))
666
          (magit-commit-amend-assert))
667 668 669 670 671 672 673 674
        (if noedit
            (let ((process-environment process-environment))
              (push "GIT_EDITOR=true" process-environment)
              (magit-run-git-async "rebase" "--continue")
              (set-process-sentinel magit-this-process
                                    #'magit-sequencer-process-sentinel)
              magit-this-process)
          (magit-run-git-sequencer "rebase" "--continue")))
675 676 677 678 679 680
    (user-error "No rebase in progress")))

;;;###autoload
(defun magit-rebase-skip ()
  "Skip the current commit and restart the current rebase operation."
  (interactive)
681 682 683
  (unless (magit-rebase-in-progress-p)
    (user-error "No rebase in progress"))
  (magit-run-git-sequencer "rebase" "--skip"))
684 685 686 687 688

;;;###autoload
(defun magit-rebase-edit ()
  "Edit the todo list of the current rebase operation."
  (interactive)
689 690 691
  (unless (magit-rebase-in-progress-p)
    (user-error "No rebase in progress"))
  (magit-run-git-sequencer "rebase" "--edit-todo"))
692 693 694 695 696

;;;###autoload
(defun magit-rebase-abort ()
  "Abort the current rebase operation, restoring the original branch."
  (interactive)
697 698
  (unless (magit-rebase-in-progress-p)
    (user-error "No rebase in progress"))
699 700
  (magit-confirm 'abort-rebase "Abort this rebase")
  (magit-run-git "rebase" "--abort"))
701 702 703 704 705 706 707 708 709

(defun magit-rebase-in-progress-p ()
  "Return t if a rebase is in progress."
  (or (file-exists-p (magit-git-dir "rebase-merge"))
      (file-exists-p (magit-git-dir "rebase-apply/onto"))))

;;; Sections

(defun magit-insert-sequencer-sequence ()
710 711
  "Insert section for the on-going cherry-pick or revert sequence.
If no such sequence is in progress, do nothing."
712 713 714 715
  (let ((picking (magit-cherry-pick-in-progress-p)))
    (when (or picking (magit-revert-in-progress-p))
      (magit-insert-section (sequence)
        (magit-insert-heading (if picking "Cherry Picking" "Reverting"))
716 717 718
        (-when-let (lines (cdr (magit-file-lines (magit-git-dir "sequencer/todo"))))
          (dolist (line (nreverse lines))
            (when (string-match "^\\(pick\\|revert\\) \\([^ ]+\\) \\(.*\\)$" line)
719 720 721 722 723 724 725 726 727 728 729 730 731
              (magit-bind-match-strings (cmd hash msg) line
                (magit-insert-section (commit hash)
                  (insert (propertize cmd 'face 'magit-sequence-pick)
                          " " (propertize hash 'face 'magit-hash)
                          " " msg "\n"))))))
        (magit-sequence-insert-sequence
         (magit-file-line (magit-git-dir (if picking
                                             "CHERRY_PICK_HEAD"
                                           "REVERT_HEAD")))
         (magit-file-line (magit-git-dir "sequencer/head")))
        (insert "\n")))))

(defun magit-insert-am-sequence ()
732 733
  "Insert section for the on-going patch applying sequence.
If no such sequence is in progress, do nothing."
734 735 736
  (when (magit-am-in-progress-p)
    (magit-insert-section (rebase-sequence)
      (magit-insert-heading "Applying patches")
737 738 739
      (let ((patches (nreverse (magit-rebase-patches)))
            patch commit)
        (while patches
740 741
          (setq patch (pop patches))
          (setq commit (magit-rev-verify-commit
742 743 744 745 746 747 748 749 750 751 752 753 754
                        (cadr (split-string (magit-file-line patch)))))
          (cond ((and commit patches)
                 (magit-sequence-insert-commit
                  "pick" commit 'magit-sequence-pick))
                (patches
                 (magit-sequence-insert-am-patch
                  "pick" patch 'magit-sequence-pick))
                (commit
                 (magit-sequence-insert-sequence commit "ORIG_HEAD"))
                (t
                 (magit-sequence-insert-am-patch
                  "stop" patch 'magit-sequence-stop)
                 (magit-sequence-insert-sequence nil "ORIG_HEAD")))))
755 756
      (insert ?\n))))

757 758
(defun magit-sequence-insert-am-patch (type patch face)
  (magit-insert-section (file patch)
759 760 761 762 763 764 765 766 767 768
    (let ((title
           (with-temp-buffer
             (insert-file-contents patch nil nil 4096)
             (unless (re-search-forward "^Subject: " nil t)
               (goto-char (point-min)))
             (buffer-substring (point) (line-end-position)))))
      (insert (propertize type 'face face)
              ?\s (propertize (file-name-nondirectory patch) 'face 'magit-hash)
              ?\s title
              ?\n))))
769

770
(defun magit-insert-rebase-sequence ()
771 772
  "Insert section for the on-going rebase sequence.
If no such sequence is in progress, do nothing."
773 774 775 776 777 778 779 780 781 782 783
  (when (magit-rebase-in-progress-p)
    (let* ((interactive (file-directory-p (magit-git-dir "rebase-merge")))
           (dir  (if interactive "rebase-merge/" "rebase-apply/"))
           (name (-> (concat dir "head-name") magit-git-dir magit-file-line))
           (onto (-> (concat dir "onto")      magit-git-dir magit-file-line))
           (onto (or (magit-rev-name onto name)
                     (magit-rev-name onto "refs/heads/*") onto))
           (name (or (magit-rev-name name "refs/heads/*") name)))
      (magit-insert-section (rebase-sequence)
        (magit-insert-heading (format "Rebasing %s onto %s" name onto))
        (if interactive
784 785
            (magit-rebase-insert-merge-sequence onto)
          (magit-rebase-insert-apply-sequence onto))
786 787
        (insert ?\n)))))

788
(defun magit-rebase-insert-merge-sequence (onto)
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803
  (let (exec)
    (dolist (line (nreverse
                   (magit-file-lines
                    (magit-git-dir "rebase-merge/git-rebase-todo"))))
      (cond ((string-prefix-p "exec" line)
             (setq exec (substring line 5)))
            ((string-match (format "^\\([^%c ]+\\) \\([^ ]+\\) .*$"
                                   (string-to-char
                                    (or (magit-get "core.commentChar") "#")))
                           line)
             (magit-bind-match-strings (action hash) line
               (unless (equal action "exec")
                 (magit-sequence-insert-commit
                  action hash 'magit-sequence-pick exec)))
             (setq exec nil)))))
804 805 806
  (magit-sequence-insert-sequence
   (magit-file-line (magit-git-dir "rebase-merge/stopped-sha"))
   onto
807 808
   (--when-let (magit-file-lines (magit-git-dir "rebase-merge/done"))
     (cadr (split-string (car (last it)))))))
809 810 811 812 813 814 815 816 817 818 819 820 821 822

(defun magit-rebase-insert-apply-sequence (onto)
  (let ((rewritten
         (--map (car (split-string it))
                (magit-file-lines (magit-git-dir "rebase-apply/rewritten"))))
        (stop (magit-file-line (magit-git-dir "rebase-apply/original-commit"))))
    (dolist (patch (nreverse (cdr (magit-rebase-patches))))
      (let ((hash (cadr (split-string (magit-file-line patch)))))
        (unless (or (member hash rewritten)
                    (equal hash stop))
          (magit-sequence-insert-commit "pick" hash 'magit-sequence-pick)))))
  (magit-sequence-insert-sequence
   (magit-file-line (magit-git-dir "rebase-apply/original-commit"))
   onto))
823 824 825 826 827

(defun magit-rebase-patches ()
  (directory-files (magit-git-dir "rebase-apply") t "^[0-9]\\{4\\}$"))

(defun magit-sequence-insert-sequence (stop onto &optional orig)
828
  (let ((head (magit-rev-parse "HEAD")) done)
829 830
    (setq onto (if onto (magit-rev-parse onto) head))
    (setq done (magit-git-lines "log" "--format=%H" (concat onto "..HEAD")))
831 832 833 834 835 836 837 838 839 840 841 842
    (when (and stop (not (member stop done)))
      (let ((id (magit-patch-id stop)))
        (--if-let (--first (equal (magit-patch-id it) id) done)
            (setq stop it)
          (cond
           ((--first (magit-rev-equal it stop) done)
            ;; The commit's testament has been executed.
            (magit-sequence-insert-commit "void" stop 'magit-sequence-drop))
           ;; The faith of the commit is still undecided...
           ((magit-anything-unmerged-p)
            ;; ...and time travel isn't for the faint of heart.
            (magit-sequence-insert-commit "join" stop 'magit-sequence-part))
843
           ((magit-anything-modified-p t)
844 845
            ;; ...and the dust hasn't settled yet...
            (magit-sequence-insert-commit
846 847 848
             (let* ((magit--refresh-cache nil)
                    (staged   (magit-commit-tree "oO" nil "HEAD"))
                    (unstaged (magit-commit-worktree "oO" "--reset")))
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872
               (cond
                ;; ...but we could end up at the same tree just by committing.
                ((or (magit-rev-equal staged   stop)
                     (magit-rev-equal unstaged stop)) "goal")
                ;; ...but the changes are still there, untainted.
                ((or (equal (magit-patch-id staged)   id)
                     (equal (magit-patch-id unstaged) id)) "same")
                ;; ...and some changes are gone and/or others were added.
                (t "work")))
             stop 'magit-sequence-part))
           ;; The commit is definitely gone...
           ((--first (magit-rev-equal it stop) done)
            ;; ...but all of its changes are still in effect.
            (magit-sequence-insert-commit "poof" stop 'magit-sequence-drop))
           (t
            ;; ...and some changes are gone and/or other changes were added.
            (magit-sequence-insert-commit "gone" stop 'magit-sequence-drop)))
          (setq stop nil))))
    (dolist (rev done)
      (apply 'magit-sequence-insert-commit
             (cond ((equal rev stop)
                    ;; ...but its reincarnation lives on.
                    ;; Or it didn't die in the first place.
                    (list (if (and (equal rev head)
873
                                   (equal (magit-patch-id rev)
874
                                          (magit-patch-id orig)))
875
                              "stop" ; We haven't done anything yet.
876
                            "like")  ; There are new commits.
877 878 879 880 881 882 883 884 885 886 887 888
                          rev (if (equal rev head)
                                  'magit-sequence-head
                                'magit-sequence-stop)))
                   ((equal rev head)
                    (list "done" rev 'magit-sequence-head))
                   (t
                    (list "done" rev 'magit-sequence-done)))))
    (magit-sequence-insert-commit "onto" onto
                                (if (equal onto head)
                                    'magit-sequence-head
                                  'magit-sequence-onto))))

889
(defun magit-sequence-insert-commit (type hash face &optional exec)
890
  (magit-insert-section (commit hash)
891 892 893 894 895
    (magit-insert-heading
      (concat (propertize type 'face face)    "\s"
              (magit-format-rev-summary hash) "\n"))
    (when exec
      (insert (propertize "exec" 'face 'magit-sequence-onto) "\s" exec "\n"))))
896 897 898

(provide 'magit-sequence)
;;; magit-sequence.el ends here