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