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>
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 <http://www.gnu.org/licenses/>.
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
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
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.
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"
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 (defconst gitmerge-default-branch
"origin/emacs-25"
71 "Default for branch that should be merged.")
73 (defconst gitmerge-buffer
"*gitmerge*"
74 "Working buffer for gitmerge.")
76 (defconst gitmerge-output-buffer
"*gitmerge output*"
77 "Buffer for displaying git output.")
79 (defconst gitmerge-warning-buffer
"*gitmerge warnings*"
80 "Buffer where gitmerge will display any warnings.")
82 (defvar gitmerge-log-regexp
83 "^\\([A-Z ]\\)\\s-*\\([0-9a-f]+\\) \\(.+?\\): \\(.*\\)$")
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
)
93 "Keymap for gitmerge major mode.")
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
))))
103 (defvar gitmerge--commits nil
)
104 (defvar gitmerge--from nil
)
106 (defun gitmerge-get-sha1 ()
107 "Get SHA1 from commit at point."
109 (goto-char (point-at-bol))
110 (when (looking-at "^[A-Z ]\\s-*\\([a-f0-9]+\\)")
113 (defun gitmerge-show-log ()
114 "Show log of commit at point."
116 (save-selected-window
117 (let ((commit (gitmerge-get-sha1)))
119 (pop-to-buffer (get-buffer-create gitmerge-output-buffer
))
122 (call-process "git" nil t nil
"log" "-1" commit
)
123 (goto-char (point-min))
124 (gitmerge-highlight-skip-regexp)))))
126 (defun gitmerge-show-diff ()
127 "Show diff of commit at point."
129 (save-selected-window
130 (let ((commit (gitmerge-get-sha1)))
132 (pop-to-buffer (get-buffer-create gitmerge-output-buffer
))
134 (call-process "git" nil t nil
"diff-tree" "-p" commit
)
135 (goto-char (point-min))
138 (defun gitmerge-show-files ()
139 "Show changed files of commit at point."
141 (save-selected-window
142 (let ((commit (gitmerge-get-sha1)))
144 (pop-to-buffer (get-buffer-create gitmerge-output-buffer
))
147 (call-process "git" nil t nil
"diff" "--name-only" (concat commit
"^!"))
148 (goto-char (point-min))))))
150 (defun gitmerge-toggle-skip ()
151 "Toggle skipping of commit at point."
153 (let ((commit (gitmerge-get-sha1))
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
)
168 (insert (if skip
"M" " "))
169 (setq buffer-read-only t
))))))
171 (defun gitmerge-highlight-skip-regexp ()
172 "Highlight strings that match `gitmerge-skip-regexp'."
174 (let ((case-fold-search t
))
175 (while (re-search-forward gitmerge-skip-regexp nil t
)
176 (put-text-property (match-beginning 0) (match-end 0)
177 'face
'font-lock-warning-face
)))))
179 (defun gitmerge-missing (from)
180 "Return the list of revisions that need to be merged from FROM.
181 Will detect a default set of skipped revision by looking at
182 cherry mark and search for `gitmerge-skip-regexp'. The result is
183 a list with entries of the form (SHA1 . SKIP), where SKIP denotes
184 if and why this commit should be skipped."
186 ;; Go through the log and remember all commits that match
187 ;; `gitmerge-skip-regexp' or are marked by --cherry-mark.
189 (call-process "git" nil t nil
"log" "--cherry-mark" "--left-only"
190 (concat from
"..." (car (vc-git-branches))))
191 (goto-char (point-max))
192 (while (re-search-backward "^commit \\(.+\\) \\([0-9a-f]+\\).*" nil t
)
193 (let ((cherrymark (match-string 1))
194 (commit (match-string 2)))
195 (push (list commit
) commits
)
196 (if (string= cherrymark
"=")
197 ;; Commit was recognized as backported by cherry-mark.
198 (setcdr (car commits
) "C")
200 (let ((case-fold-search t
))
201 (while (not (looking-at "^\\s-+[^ ]+"))
203 (when (re-search-forward gitmerge-skip-regexp nil t
)
204 (setcdr (car commits
) "R"))))))
205 (delete-region (point) (point-max))))
208 (defun gitmerge-setup-log-buffer (commits from
)
209 "Create the buffer for choosing commits."
210 (with-current-buffer (get-buffer-create gitmerge-buffer
)
212 (call-process "git" nil t nil
"log" "--left-only"
213 "--pretty=format:%h %<(20,trunc) %an: %<(100,trunc) %s"
214 (concat from
"..." (car (vc-git-branches))))
215 (goto-char (point-min))
216 (while (looking-at "^\\([a-f0-9]+\\)")
217 (let ((skipreason (gitmerge-skip-commit-p (match-string 1) commits
)))
218 (if (null skipreason
)
220 (insert skipreason
" ")
221 (gitmerge-handle-skip-overlay t
)))
225 (defun gitmerge-handle-skip-overlay (skip)
226 "Create or delete overlay on SHA1, depending on SKIP."
227 (when (looking-at "[0-9a-f]+")
229 (let ((ov (make-overlay (point)
231 (overlay-put ov
'face
'gitmerge-skip-face
))
232 (remove-overlays (point) (match-end 0)
233 'face
'gitmerge-skip-face
))))
235 (defun gitmerge-skip-commit-p (commit skips
)
236 "Tell whether COMMIT should be skipped.
237 COMMIT is an (possibly abbreviated) SHA1. SKIPS is list of
238 cons'es with commits that should be skipped and the reason.
239 Return value is string which denotes reason, or nil if commit
240 should not be skipped."
242 (while (and (setq skip
(pop skips
))
244 (when (string-match commit
(car skip
))
245 (setq found
(cdr skip
))))
248 (defun gitmerge-resolve (file)
249 "Try to resolve conflicts in FILE with smerge.
250 Returns non-nil if conflicts remain."
251 (unless (file-exists-p file
) (error "Gitmerge-resolve: Can't find %s" file
))
253 (let ((exists (find-buffer-visiting file
)))
254 (with-current-buffer (let ((enable-local-variables :safe
)
255 (enable-local-eval nil
))
256 (find-file-noselect file
))
257 (if (buffer-modified-p)
258 (user-error "Unsaved changes in %s" (current-buffer)))
261 ((derived-mode-p 'change-log-mode
)
262 ;; Fix up dates before resolving the conflicts.
263 (goto-char (point-min))
264 (let ((diff-auto-refine-mode nil
))
265 (while (re-search-forward smerge-begin-re nil t
)
266 (smerge-match-conflict)
267 (smerge-ensure-match 3)
268 (let ((start1 (match-beginning 1))
270 (start3 (match-beginning 3))
271 (end3 (copy-marker (match-end 3) t
)))
273 (while (re-search-forward change-log-start-entry-re end3 t
)
274 (let* ((str (match-string 0))
275 (newstr (save-match-data
276 (concat (add-log-iso8601-time-string)
277 (when (string-match " *\\'" str
)
278 (match-string 0 str
))))))
279 (replace-match newstr t t
)))
280 ;; change-log-resolve-conflict prefers to put match-1's
281 ;; elements first (for equal dates), whereas we want to put
283 (let ((match3 (buffer-substring start3 end3
))
284 (match1 (buffer-substring start1 end1
)))
285 (delete-region start3 end3
)
288 (delete-region start1 end1
)
291 ;; (pop-to-buffer (current-buffer)) (debug 'before-resolve)
293 ;; Try to resolve the conflicts.
295 ((member file
'("configure" "lisp/ldefs-boot.el"
296 "lisp/emacs-lisp/cl-loaddefs.el"))
297 ;; We are in the file's buffer, so names are relative.
298 (call-process "git" nil t nil
"checkout" "--"
299 (file-name-nondirectory file
))
300 (revert-buffer nil
'noconfirm
))
302 (goto-char (point-max))
303 (while (re-search-backward smerge-begin-re nil t
)
306 (smerge-match-conflict)
308 ;; (when (derived-mode-p 'change-log-mode)
309 ;; (pop-to-buffer (current-buffer)) (debug 'after-resolve))
311 (goto-char (point-min))
312 (prog1 (re-search-forward smerge-begin-re nil t
)
313 (unless exists
(kill-buffer))))))))
315 (defun gitmerge-commit-message (beg end skip branch
)
316 "Create commit message for merging BEG to END from BRANCH.
317 SKIP denotes whether those commits are actually skipped. If END
318 is nil, only the single commit BEG is merged."
320 ;; We do not insert "; " for non-skipped messages,
321 ;; because the date of those entries is helpful in figuring out
322 ;; when things got merged, since git does not track that.
323 (insert (if skip
"; " "")
324 "Merge from " branch
"\n\n"
326 (concat "The following commit"
327 (if end
"s were " " was ")
330 (apply 'call-process
"git" nil t nil
"log" "--oneline"
331 (if end
(list (concat beg
"~.." end
))
334 ;; Truncate to 72 chars so that the resulting ChangeLog line fits in 80.
335 (goto-char (point-min))
336 (while (re-search-forward "^\\(.\\{69\\}\\).\\{4,\\}" nil t
)
337 (replace-match "\\1..."))
340 (defun gitmerge-apply (missing from
)
341 "Merge commits in MISSING from branch FROM.
342 MISSING must be a list of SHA1 strings."
343 (with-current-buffer (get-buffer-create gitmerge-output-buffer
)
345 (let* ((skip (cdar missing
))
346 (beg (car (pop missing
)))
348 ;; Determine last revision with same boolean skip status.
350 (eq (null (cdar missing
))
352 (setq end
(car (pop missing
))))
354 (gitmerge-commit-message beg end skip from
))
356 (if skip
"Skipping" "Merging")
358 (if end
(concat ".." (substring end
0 6)) ""))
362 (apply 'call-process
"git" nil t nil
"merge" "--no-ff"
363 (append (when skip
'("-s" "ours"))
364 `("-m" ,commitmessage
,end
))))
365 (gitmerge-write-missing missing from
)
366 (gitmerge-resolve-unmerged)))
369 (defun gitmerge-resolve-unmerged ()
370 "Resolve all files that are unmerged.
371 Throw an user-error if we cannot resolve automatically."
372 (with-current-buffer (get-buffer-create gitmerge-output-buffer
)
374 (let (files conflicted
)
375 ;; List unmerged files
377 (call-process "git" nil t nil
378 "diff" "--name-only" "--diff-filter=U")))
379 (error "Error listing unmerged files. Resolve manually.")
380 (goto-char (point-min))
382 (push (buffer-substring (point) (line-end-position)) files
)
385 (if (gitmerge-resolve file
)
386 ;; File still has conflicts
389 (call-process "git" nil t nil
"add" file
)))
391 (with-current-buffer (get-buffer-create gitmerge-warning-buffer
)
393 (insert "For the following files, conflicts could\n"
394 "not be resolved automatically:\n\n")
395 (call-process "git" nil t nil
396 "diff" "--name-only" "--diff-filter=U")
397 (insert "\nResolve the conflicts manually, then run gitmerge again."
398 "\nNote:\n - You don't have to add resolved files or "
399 "commit the merge yourself (but you can)."
400 "\n - You can safely close this Emacs session and do this "
402 "\n - When running gitmerge again, remember that you must "
403 "that from within the Emacs repo.\n")
404 (pop-to-buffer (current-buffer)))
405 (user-error "Resolve the conflicts manually"))))))
407 (defun gitmerge-repo-clean ()
408 "Return non-nil if repository is clean."
410 (call-process "git" nil t nil
411 "diff" "--staged" "--name-only")
412 (call-process "git" nil t nil
413 "diff" "--name-only")
414 (zerop (buffer-size))))
416 (defun gitmerge-maybe-resume ()
417 "Check if we have to resume a merge.
418 If so, add no longer conflicted files and commit."
419 (let ((mergehead (file-exists-p
420 (expand-file-name ".git/MERGE_HEAD" default-directory
)))
421 (statusexist (file-exists-p gitmerge-status-file
)))
422 (when (and mergehead
(not statusexist
))
423 (user-error "Unfinished merge, but no record of a previous gitmerge run"))
424 (when (and (not mergehead
)
425 (not (gitmerge-repo-clean)))
426 (user-error "Repository is not clean"))
428 (if (not (y-or-n-p "Resume merge? "))
430 (delete-file gitmerge-status-file
)
433 (message "OK, resuming...")
434 (gitmerge-resolve-unmerged)
437 (with-current-buffer (get-buffer-create gitmerge-output-buffer
)
439 (unless (zerop (call-process "git" nil t nil
440 "commit" "--no-edit"))
441 (error "Git error during merge - fix it manually"))))
442 ;; Successfully resumed.
445 (defun gitmerge-get-all-branches ()
446 "Return list of all branches, including remotes."
448 (unless (zerop (call-process "git" nil t nil
450 (error "Git error listing remote branches"))
451 (goto-char (point-min))
452 (let (branches branch
)
454 (when (looking-at "^[^\\*]\\s-*\\(?:remotes/\\)?\\(.+\\)$")
455 (setq branch
(match-string 1))
456 (unless (string-match gitmerge-ignore-branches-regexp branch
)
457 (push branch branches
)))
459 (nreverse branches
))))
461 (defun gitmerge-write-missing (missing from
)
462 "Write list of commits MISSING into `gitmerge-status-file'.
463 Branch FROM will be prepended to the list."
465 (find-file-noselect gitmerge-status-file
)
468 (prin1-to-string (append (list from
) missing
))
473 (defun gitmerge-read-missing ()
474 "Read list of missing commits from `gitmerge-status-file'."
476 (find-file-noselect gitmerge-status-file
)
477 (unless (zerop (buffer-size))
478 (prog1 (read (buffer-string))
481 (define-derived-mode gitmerge-mode special-mode
"gitmerge"
482 "Major mode for Emacs branch merging."
483 (set-syntax-table text-mode-syntax-table
)
484 (setq buffer-read-only t
)
485 (setq-local truncate-lines t
)
486 (setq-local font-lock-defaults
'(gitmerge-mode-font-lock-keywords)))
488 (defun gitmerge (from)
489 "Merge from branch FROM into `default-directory'."
491 (if (not (vc-git-root default-directory
))
492 (user-error "Not in a git tree")
493 (let ((default-directory (vc-git-root default-directory
)))
495 (if (gitmerge-maybe-resume)
497 (completing-read "Merge branch: " (gitmerge-get-all-branches)
498 nil t gitmerge-default-branch
))))))
499 (let ((default-directory (vc-git-root default-directory
)))
500 (if (eq from
'resume
)
502 (setq gitmerge--commits
(gitmerge-read-missing))
503 (setq gitmerge--from
(pop gitmerge--commits
))
504 ;; Directly continue with the merge.
505 (gitmerge-start-merge))
506 (setq gitmerge--commits
(gitmerge-missing from
))
507 (setq gitmerge--from from
)
508 (when (null gitmerge--commits
)
509 (user-error "Nothing to merge"))
511 (gitmerge-setup-log-buffer gitmerge--commits gitmerge--from
)
512 (goto-char (point-min))
513 (insert (propertize "Commands: " 'font-lock-face
'bold
)
514 "(s) Toggle skip, (l) Show log, (d) Show diff, "
515 "(f) Show files, (m) Start merge\n"
516 (propertize "Flags: " 'font-lock-face
'bold
)
517 "(C) Detected backport (cherry-mark), (R) Log matches "
518 "regexp, (M) Manually picked\n\n")
520 (pop-to-buffer (current-buffer))))))
522 (defun gitmerge-start-merge ()
524 (when (not (vc-git-root default-directory
))
525 (user-error "Not in a git tree"))
526 (let ((default-directory (vc-git-root default-directory
)))
527 (while gitmerge--commits
528 (setq gitmerge--commits
529 (gitmerge-apply gitmerge--commits gitmerge--from
)))
530 (when (file-exists-p gitmerge-status-file
)
531 (delete-file gitmerge-status-file
))
532 (message "Merging from %s...done" gitmerge--from
)))
536 ;;; gitmerge.el ends here