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