* admin/gitmerge.el (gitmerge-missing):
[emacs.git] / admin / gitmerge.el
blob5e7d8c3e33fd977a7423e27567afe19ebce98938
1 ;;; gitmerge.el --- help merge one Emacs branch into another
3 ;; Copyright (C) 2010-2017 Free Software Foundation, Inc.
5 ;; Authors: David Engster <deng@randomsample.de>
6 ;; Stefan Monnier <monnier@iro.umontreal.ca>
8 ;; Keywords: maint
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it 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.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
23 ;;; Commentary:
25 ;; Rewrite of bzrmerge.el, but using git.
27 ;; In a nutshell: For merging foo into master, do
29 ;; - 'git checkout master' in Emacs repository
30 ;; - Start Emacs, cd to Emacs repository
31 ;; - M-x gitmerge
32 ;; - Choose branch 'foo' or 'origin/foo', depending on whether you
33 ;; like to merge from a local tracking branch or from the remote
34 ;; (does not make a difference if the local tracking branch is
35 ;; up-to-date).
36 ;; - Mark commits you'd like to skip, meaning to only merge their
37 ;; metadata (merge strategy 'ours').
38 ;; - Hit 'm' to start merging. Skipped commits will be merged separately.
39 ;; - If conflicts cannot be resolved automatically, you'll have to do
40 ;; it manually. In that case, resolve the conflicts and restart
41 ;; gitmerge, which will automatically resume. It will add resolved
42 ;; files, commit the pending merge and continue merging the rest.
43 ;; - Inspect master branch, and if everything looks OK, push.
45 ;;; Code:
47 (require 'vc-git)
48 (require 'smerge-mode)
50 (defvar gitmerge-skip-regexp
51 ;; We used to include "sync" in there, but in my experience it only
52 ;; caused false positives. --Stef
53 "back[- ]?port\\|cherry picked from commit\\|\\(do\\( no\\|n['’]\\)t\\|no need to\\) merge\\|\
54 re-?generate\\|bump version\\|from trunk\\|Auto-commit"
55 "Regexp matching logs of revisions that might be skipped.
56 `gitmerge-missing' will ask you if it should skip any matches.")
58 (defvar gitmerge-status-file (expand-file-name "gitmerge-status"
59 user-emacs-directory)
60 "File where missing commits will be saved between sessions.")
62 (defvar gitmerge-ignore-branches-regexp
63 "origin/\\(\\(HEAD\\|master\\)$\\|\\(old-branches\\|other-branches\\)/\\)"
64 "Regexp matching branches we want to ignore.")
66 (defface gitmerge-skip-face
67 '((t (:strike-through t)))
68 "Face for skipped commits.")
70 (defvar gitmerge-default-branch nil
71 "Default for branch that should be merged.
72 If nil, the function `gitmerge-default-branch' guesses.")
74 (defconst gitmerge-buffer "*gitmerge*"
75 "Working buffer for gitmerge.")
77 (defconst gitmerge-output-buffer "*gitmerge output*"
78 "Buffer for displaying git output.")
80 (defconst gitmerge-warning-buffer "*gitmerge warnings*"
81 "Buffer where gitmerge will display any warnings.")
83 (defvar gitmerge-log-regexp
84 "^\\([A-Z ]\\)\\s-*\\([0-9a-f]+\\) \\(.+?\\): \\(.*\\)$")
86 (defvar gitmerge-mode-map
87 (let ((map (make-keymap)))
88 (define-key map [(l)] 'gitmerge-show-log)
89 (define-key map [(d)] 'gitmerge-show-diff)
90 (define-key map [(f)] 'gitmerge-show-files)
91 (define-key map [(s)] 'gitmerge-toggle-skip)
92 (define-key map [(m)] 'gitmerge-start-merge)
93 map)
94 "Keymap for gitmerge major mode.")
97 (defvar gitmerge-mode-font-lock-keywords
98 `((,gitmerge-log-regexp
99 (1 font-lock-warning-face)
100 (2 font-lock-constant-face)
101 (3 font-lock-builtin-face)
102 (4 font-lock-comment-face))))
104 (defvar gitmerge--commits nil)
105 (defvar gitmerge--from nil)
107 (defun gitmerge-emacs-version (&optional branch)
108 "Return the major version of Emacs, optionally in BRANCH."
109 (with-temp-buffer
110 (if (not branch)
111 (insert-file-contents "configure.ac")
112 (call-process "git" nil t nil "show" (format "%s:configure.ac" branch))
113 (goto-char (point-min)))
114 (re-search-forward "^AC_INIT([^,]+, \\([0-9]+\\)\\.")
115 (string-to-number (match-string 1))))
117 (defun gitmerge-default-branch ()
118 "Default for branch that should be merged; eg \"origin/emacs-26\"."
119 (or gitmerge-default-branch
120 (format "origin/emacs-%s" (1- (gitmerge-emacs-version)))))
122 (defun gitmerge-get-sha1 ()
123 "Get SHA1 from commit at point."
124 (save-excursion
125 (goto-char (point-at-bol))
126 (when (looking-at "^[A-Z ]\\s-*\\([a-f0-9]+\\)")
127 (match-string 1))))
129 (defun gitmerge-show-log ()
130 "Show log of commit at point."
131 (interactive)
132 (save-selected-window
133 (let ((commit (gitmerge-get-sha1)))
134 (when commit
135 (pop-to-buffer (get-buffer-create gitmerge-output-buffer))
136 (fundamental-mode)
137 (erase-buffer)
138 (call-process "git" nil t nil "log" "-1" commit)
139 (goto-char (point-min))
140 (gitmerge-highlight-skip-regexp)))))
142 (defun gitmerge-show-diff ()
143 "Show diff of commit at point."
144 (interactive)
145 (save-selected-window
146 (let ((commit (gitmerge-get-sha1)))
147 (when commit
148 (pop-to-buffer (get-buffer-create gitmerge-output-buffer))
149 (erase-buffer)
150 (call-process "git" nil t nil "diff-tree" "-p" commit)
151 (goto-char (point-min))
152 (diff-mode)))))
154 (defun gitmerge-show-files ()
155 "Show changed files of commit at point."
156 (interactive)
157 (save-selected-window
158 (let ((commit (gitmerge-get-sha1)))
159 (when commit
160 (pop-to-buffer (get-buffer-create gitmerge-output-buffer))
161 (erase-buffer)
162 (fundamental-mode)
163 (call-process "git" nil t nil "diff" "--name-only" (concat commit "^!"))
164 (goto-char (point-min))))))
166 (defun gitmerge-toggle-skip ()
167 "Toggle skipping of commit at point."
168 (interactive)
169 (let ((commit (gitmerge-get-sha1))
170 skip)
171 (when commit
172 (save-excursion
173 (goto-char (point-at-bol))
174 (when (looking-at "^\\([A-Z ]\\)\\s-*\\([a-f0-9]+\\)")
175 (setq skip (string= (match-string 1) " "))
176 (goto-char (match-beginning 2))
177 (gitmerge-handle-skip-overlay skip)
178 (dolist (ct gitmerge--commits)
179 (when (string-match commit (car ct))
180 (setcdr ct (when skip "M"))))
181 (goto-char (point-at-bol))
182 (setq buffer-read-only nil)
183 (delete-char 1)
184 (insert (if skip "M" " "))
185 (setq buffer-read-only t))))))
187 (defun gitmerge-highlight-skip-regexp ()
188 "Highlight strings that match `gitmerge-skip-regexp'."
189 (save-excursion
190 (let ((case-fold-search t))
191 (while (re-search-forward gitmerge-skip-regexp nil t)
192 (put-text-property (match-beginning 0) (match-end 0)
193 'face 'font-lock-warning-face)))))
195 (defun gitmerge-missing (from)
196 "Return the list of revisions that need to be merged from FROM.
197 Will detect a default set of skipped revision by looking at
198 cherry mark and search for `gitmerge-skip-regexp'. The result is
199 a list with entries of the form (SHA1 . SKIP), where SKIP denotes
200 if and why this commit should be skipped."
201 (let (commits)
202 ;; Go through the log and remember all commits that match
203 ;; `gitmerge-skip-regexp' or are marked by --cherry-mark.
204 (with-temp-buffer
205 (call-process "git" nil t nil "log" "--cherry-mark" "--left-only"
206 "--no-decorate"
207 (concat from "..." (car (vc-git-branches))))
208 (goto-char (point-max))
209 (while (re-search-backward "^commit \\(.+\\) \\([0-9a-f]+\\).*" nil t)
210 (let ((cherrymark (match-string 1))
211 (commit (match-string 2)))
212 (push (list commit) commits)
213 (if (string= cherrymark "=")
214 ;; Commit was recognized as backported by cherry-mark.
215 (setcdr (car commits) "C")
216 (save-excursion
217 (let ((case-fold-search t))
218 (while (not (looking-at "^\\s-+[^ ]+"))
219 (forward-line))
220 (when (re-search-forward gitmerge-skip-regexp nil t)
221 (setcdr (car commits) "R"))))))
222 (delete-region (point) (point-max))))
223 (nreverse commits)))
225 (defun gitmerge-setup-log-buffer (commits from)
226 "Create the buffer for choosing commits."
227 (with-current-buffer (get-buffer-create gitmerge-buffer)
228 (erase-buffer)
229 (call-process "git" nil t nil "log" "--left-only"
230 "--pretty=format:%h %<(20,trunc) %an: %<(100,trunc) %s"
231 (concat from "..." (car (vc-git-branches))))
232 (goto-char (point-min))
233 (while (looking-at "^\\([a-f0-9]+\\)")
234 (let ((skipreason (gitmerge-skip-commit-p (match-string 1) commits)))
235 (if (null skipreason)
236 (insert " ")
237 (insert skipreason " ")
238 (gitmerge-handle-skip-overlay t)))
239 (forward-line))
240 (current-buffer)))
242 (defun gitmerge-handle-skip-overlay (skip)
243 "Create or delete overlay on SHA1, depending on SKIP."
244 (when (looking-at "[0-9a-f]+")
245 (if skip
246 (let ((ov (make-overlay (point)
247 (match-end 0))))
248 (overlay-put ov 'face 'gitmerge-skip-face))
249 (remove-overlays (point) (match-end 0)
250 'face 'gitmerge-skip-face))))
252 (defun gitmerge-skip-commit-p (commit skips)
253 "Tell whether COMMIT should be skipped.
254 COMMIT is an (possibly abbreviated) SHA1. SKIPS is list of
255 cons'es with commits that should be skipped and the reason.
256 Return value is string which denotes reason, or nil if commit
257 should not be skipped."
258 (let (found skip)
259 (while (and (setq skip (pop skips))
260 (not found))
261 (when (string-match commit (car skip))
262 (setq found (cdr skip))))
263 found))
265 (defun gitmerge-resolve (file)
266 "Try to resolve conflicts in FILE with smerge.
267 Returns non-nil if conflicts remain."
268 (unless (file-exists-p file) (error "Gitmerge-resolve: Can't find %s" file))
269 (with-demoted-errors
270 (let ((exists (find-buffer-visiting file)))
271 (with-current-buffer (let ((enable-local-variables :safe)
272 (enable-local-eval nil))
273 (find-file-noselect file))
274 (if (buffer-modified-p)
275 (user-error "Unsaved changes in %s" (current-buffer)))
276 (save-excursion
277 (cond
278 ((derived-mode-p 'change-log-mode)
279 ;; Fix up dates before resolving the conflicts.
280 (goto-char (point-min))
281 (let ((diff-auto-refine-mode nil))
282 (while (re-search-forward smerge-begin-re nil t)
283 (smerge-match-conflict)
284 (smerge-ensure-match 3)
285 (let ((start1 (match-beginning 1))
286 (end1 (match-end 1))
287 (start3 (match-beginning 3))
288 (end3 (copy-marker (match-end 3) t)))
289 (goto-char start3)
290 (while (re-search-forward change-log-start-entry-re end3 t)
291 (let* ((str (match-string 0))
292 (newstr (save-match-data
293 (concat (add-log-iso8601-time-string)
294 (when (string-match " *\\'" str)
295 (match-string 0 str))))))
296 (replace-match newstr t t)))
297 ;; change-log-resolve-conflict prefers to put match-1's
298 ;; elements first (for equal dates), whereas we want to put
299 ;; match-3's first.
300 (let ((match3 (buffer-substring start3 end3))
301 (match1 (buffer-substring start1 end1)))
302 (delete-region start3 end3)
303 (goto-char start3)
304 (insert match1)
305 (delete-region start1 end1)
306 (goto-char start1)
307 (insert match3)))))
308 ;; (pop-to-buffer (current-buffer)) (debug 'before-resolve)
310 ;; Try to resolve the conflicts.
311 (let (temp)
312 (cond
313 ((and (equal file "etc/NEWS")
314 (ignore-errors
315 (setq temp
316 (format "NEWS.%s"
317 (gitmerge-emacs-version gitmerge--from))))
318 (file-exists-p temp)
319 (or noninteractive
320 (y-or-n-p "Try to fix NEWS conflict? ")))
321 (let ((relfile (file-name-nondirectory file))
322 (tempfile (make-temp-file "gitmerge")))
323 (unwind-protect
324 (progn
325 (call-process "git" nil `(:file ,tempfile) nil "diff"
326 (format ":1:%s" file)
327 (format ":3:%s" file))
328 (call-process "git" nil t nil "reset" "--" relfile)
329 (call-process "git" nil t nil "checkout" "--" relfile)
330 (revert-buffer nil 'noconfirm)
331 (call-process "patch" tempfile nil nil temp)
332 (call-process "git" nil t nil "add" "--" temp))
333 (delete-file tempfile))))
334 ;; Generated files.
335 ((member file '("lisp/ldefs-boot.el"))
336 ;; We are in the file's buffer, so names are relative.
337 (call-process "git" nil t nil "reset" "--"
338 (file-name-nondirectory file))
339 (call-process "git" nil t nil "checkout" "--"
340 (file-name-nondirectory file))
341 (revert-buffer nil 'noconfirm))
343 (goto-char (point-max))
344 (while (re-search-backward smerge-begin-re nil t)
345 (save-excursion
346 (ignore-errors
347 (smerge-match-conflict)
348 (smerge-resolve))))
349 ;; (when (derived-mode-p 'change-log-mode)
350 ;; (pop-to-buffer (current-buffer)) (debug 'after-resolve))
351 (save-buffer))))
352 (goto-char (point-min))
353 (prog1 (re-search-forward smerge-begin-re nil t)
354 (unless exists (kill-buffer))))))))
356 (defun gitmerge-commit-message (beg end skip branch)
357 "Create commit message for merging BEG to END from BRANCH.
358 SKIP denotes whether those commits are actually skipped. If END
359 is nil, only the single commit BEG is merged."
360 (with-temp-buffer
361 ;; We do not insert "; " for non-skipped messages,
362 ;; because the date of those entries is helpful in figuring out
363 ;; when things got merged, since git does not track that.
364 (insert (if skip "; " "")
365 "Merge from " branch "\n\n"
366 (if skip
367 (concat "The following commit"
368 (if end "s were " " was ")
369 "skipped:\n\n")
370 ""))
371 (apply 'call-process "git" nil t nil "log" "--oneline"
372 (if end (list (concat beg "~.." end))
373 `("-1" ,beg)))
374 (insert "\n")
375 ;; Truncate to 72 chars so that the resulting ChangeLog line fits in 80.
376 (goto-char (point-min))
377 (while (re-search-forward "^\\(.\\{69\\}\\).\\{4,\\}" nil t)
378 (replace-match "\\1..."))
379 (buffer-string)))
381 (defun gitmerge-apply (missing from)
382 "Merge commits in MISSING from branch FROM.
383 MISSING must be a list of SHA1 strings."
384 (with-current-buffer (get-buffer-create gitmerge-output-buffer)
385 (erase-buffer)
386 (let* ((skip (cdar missing))
387 (beg (car (pop missing)))
388 end commitmessage)
389 ;; Determine last revision with same boolean skip status.
390 (while (and missing
391 (eq (null (cdar missing))
392 (null skip)))
393 (setq end (car (pop missing))))
394 (setq commitmessage
395 (gitmerge-commit-message beg end skip from))
396 (message "%s %s%s"
397 (if skip "Skipping" "Merging")
398 (substring beg 0 6)
399 (if end (concat ".." (substring end 0 6)) ""))
400 (unless end
401 (setq end beg))
402 (unless (zerop
403 (apply 'call-process "git" nil t nil "merge" "--no-ff"
404 (append (when skip '("-s" "ours"))
405 `("-m" ,commitmessage ,end))))
406 (gitmerge-write-missing missing from)
407 (gitmerge-resolve-unmerged)))
408 missing))
410 (defun gitmerge-resolve-unmerged ()
411 "Resolve all files that are unmerged.
412 Throw an user-error if we cannot resolve automatically."
413 (with-current-buffer (get-buffer-create gitmerge-output-buffer)
414 (erase-buffer)
415 (let (files conflicted)
416 ;; List unmerged files
417 (if (not (zerop
418 (call-process "git" nil t nil
419 "diff" "--name-only" "--diff-filter=U")))
420 (error "Error listing unmerged files. Resolve manually.")
421 (goto-char (point-min))
422 (while (not (eobp))
423 (push (buffer-substring (point) (line-end-position)) files)
424 (forward-line))
425 (dolist (file files)
426 (if (gitmerge-resolve file)
427 ;; File still has conflicts
428 (setq conflicted t)
429 ;; Mark as resolved
430 (call-process "git" nil t nil "add" file)))
431 (if (not conflicted)
432 (and files (not (gitmerge-commit))
433 (error "Error committing resolution - fix it manually"))
434 (with-current-buffer (get-buffer-create gitmerge-warning-buffer)
435 (erase-buffer)
436 (insert "For the following files, conflicts could\n"
437 "not be resolved automatically:\n\n")
438 (call-process "git" nil t nil
439 "diff" "--name-only" "--diff-filter=U")
440 (insert "\nResolve the conflicts manually, then run gitmerge again."
441 "\nNote:\n - You don't have to add resolved files or "
442 "commit the merge yourself (but you can)."
443 "\n - You can safely close this Emacs session and do this "
444 "in a new one."
445 "\n - When running gitmerge again, remember that you must "
446 "do that from within the Emacs repo.\n")
447 (pop-to-buffer (current-buffer)))
448 (user-error "Resolve the conflicts manually"))))))
450 (defun gitmerge-repo-clean ()
451 "Return non-nil if repository is clean."
452 (with-temp-buffer
453 (call-process "git" nil t nil
454 "diff" "--staged" "--name-only")
455 (call-process "git" nil t nil
456 "diff" "--name-only")
457 (zerop (buffer-size))))
459 (defun gitmerge-commit ()
460 "Commit, and return non-nil if it succeeds."
461 (with-current-buffer (get-buffer-create gitmerge-output-buffer)
462 (erase-buffer)
463 (eq 0 (call-process "git" nil t nil "commit" "--no-edit"))))
465 (defun gitmerge-maybe-resume ()
466 "Check if we have to resume a merge.
467 If so, add no longer conflicted files and commit."
468 (let ((mergehead (file-exists-p
469 (expand-file-name ".git/MERGE_HEAD" default-directory)))
470 (statusexist (file-exists-p gitmerge-status-file)))
471 (when (and mergehead (not statusexist))
472 (user-error "Unfinished merge, but no record of a previous gitmerge run"))
473 (when (and (not mergehead)
474 (not (gitmerge-repo-clean)))
475 (user-error "Repository is not clean"))
476 (when statusexist
477 (if (not (y-or-n-p "Resume merge? "))
478 (progn
479 (delete-file gitmerge-status-file)
480 ;; No resume.
481 nil)
482 (message "OK, resuming...")
483 (gitmerge-resolve-unmerged)
484 ;; Commit the merge.
485 (when mergehead
486 (or (gitmerge-commit)
487 (error "Git error during merge - fix it manually")))
488 ;; Successfully resumed.
489 t))))
491 (defun gitmerge-get-all-branches ()
492 "Return list of all branches, including remotes."
493 (with-temp-buffer
494 (unless (zerop (call-process "git" nil t nil
495 "branch" "-a"))
496 (error "Git error listing remote branches"))
497 (goto-char (point-min))
498 (let (branches branch)
499 (while (not (eobp))
500 (when (looking-at "^[^\\*]\\s-*\\(?:remotes/\\)?\\(.+\\)$")
501 (setq branch (match-string 1))
502 (unless (string-match gitmerge-ignore-branches-regexp branch)
503 (push branch branches)))
504 (forward-line))
505 (nreverse branches))))
507 (defun gitmerge-write-missing (missing from)
508 "Write list of commits MISSING into `gitmerge-status-file'.
509 Branch FROM will be prepended to the list."
510 (with-current-buffer
511 (find-file-noselect gitmerge-status-file)
512 (erase-buffer)
513 (insert
514 (prin1-to-string (append (list from) missing))
515 "\n")
516 (save-buffer)
517 (kill-buffer)))
519 (defun gitmerge-read-missing ()
520 "Read list of missing commits from `gitmerge-status-file'."
521 (with-current-buffer
522 (find-file-noselect gitmerge-status-file)
523 (unless (zerop (buffer-size))
524 (prog1 (read (buffer-string))
525 (kill-buffer)))))
527 (define-derived-mode gitmerge-mode special-mode "gitmerge"
528 "Major mode for Emacs branch merging."
529 (set-syntax-table text-mode-syntax-table)
530 (setq buffer-read-only t)
531 (setq-local truncate-lines t)
532 (setq-local font-lock-defaults '(gitmerge-mode-font-lock-keywords)))
534 (defun gitmerge (from)
535 "Merge from branch FROM into `default-directory'."
536 (interactive
537 (if (not (vc-git-root default-directory))
538 (user-error "Not in a git tree")
539 (let ((default-directory (vc-git-root default-directory)))
540 (list
541 (if (gitmerge-maybe-resume)
542 'resume
543 (completing-read "Merge branch: " (gitmerge-get-all-branches)
544 nil t (gitmerge-default-branch)))))))
545 (let ((default-directory (vc-git-root default-directory)))
546 (if (eq from 'resume)
547 (progn
548 (setq gitmerge--commits (gitmerge-read-missing))
549 (setq gitmerge--from (pop gitmerge--commits))
550 ;; Directly continue with the merge.
551 (gitmerge-start-merge))
552 (setq gitmerge--commits (gitmerge-missing from))
553 (setq gitmerge--from from)
554 (when (null gitmerge--commits)
555 (user-error "Nothing to merge"))
556 (with-current-buffer
557 (gitmerge-setup-log-buffer gitmerge--commits gitmerge--from)
558 (goto-char (point-min))
559 (insert (propertize "Commands: " 'font-lock-face 'bold)
560 "(s) Toggle skip, (l) Show log, (d) Show diff, "
561 "(f) Show files, (m) Start merge\n"
562 (propertize "Flags: " 'font-lock-face 'bold)
563 "(C) Detected backport (cherry-mark), (R) Log matches "
564 "regexp, (M) Manually picked\n\n")
565 (gitmerge-mode)
566 (pop-to-buffer (current-buffer))))))
568 (defun gitmerge-start-merge ()
569 (interactive)
570 (when (not (vc-git-root default-directory))
571 (user-error "Not in a git tree"))
572 (let ((default-directory (vc-git-root default-directory)))
573 (while gitmerge--commits
574 (setq gitmerge--commits
575 (gitmerge-apply gitmerge--commits gitmerge--from)))
576 (when (file-exists-p gitmerge-status-file)
577 (delete-file gitmerge-status-file))
578 (message "Merging from %s...done" gitmerge--from)))
580 (provide 'gitmerge)
582 ;;; gitmerge.el ends here