Ibuffer: Don't truncate shell command output
[emacs.git] / admin / gitmerge.el
blob00c20ba7c673b32237dd9224c9f80145aa96b3c2
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 <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 ;; 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 not\\|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 (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)
92 map)
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."
108 (save-excursion
109 (goto-char (point-at-bol))
110 (when (looking-at "^[A-Z ]\\s-*\\([a-f0-9]+\\)")
111 (match-string 1))))
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)))))
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)))))
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))))))
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))))))
171 (defun gitmerge-highlight-skip-regexp ()
172 "Highlight strings that match `gitmerge-skip-regexp'."
173 (save-excursion
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."
185 (let (commits)
186 ;; Go through the log and remember all commits that match
187 ;; `gitmerge-skip-regexp' or are marked by --cherry-mark.
188 (with-temp-buffer
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")
199 (save-excursion
200 (let ((case-fold-search t))
201 (while (not (looking-at "^\\s-+[^ ]+"))
202 (forward-line))
203 (when (re-search-forward gitmerge-skip-regexp nil t)
204 (setcdr (car commits) "R"))))))
205 (delete-region (point) (point-max))))
206 (nreverse commits)))
208 (defun gitmerge-setup-log-buffer (commits from)
209 "Create the buffer for choosing commits."
210 (with-current-buffer (get-buffer-create gitmerge-buffer)
211 (erase-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)
219 (insert " ")
220 (insert skipreason " ")
221 (gitmerge-handle-skip-overlay t)))
222 (forward-line))
223 (current-buffer)))
225 (defun gitmerge-handle-skip-overlay (skip)
226 "Create or delete overlay on SHA1, depending on SKIP."
227 (when (looking-at "[0-9a-f]+")
228 (if skip
229 (let ((ov (make-overlay (point)
230 (match-end 0))))
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."
241 (let (found skip)
242 (while (and (setq skip (pop skips))
243 (not found))
244 (when (string-match commit (car skip))
245 (setq found (cdr skip))))
246 found))
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))
252 (with-demoted-errors
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)))
259 (save-excursion
260 (cond
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))
269 (end1 (match-end 1))
270 (start3 (match-beginning 3))
271 (end3 (copy-marker (match-end 3) t)))
272 (goto-char start3)
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
282 ;; match-3's first.
283 (let ((match3 (buffer-substring start3 end3))
284 (match1 (buffer-substring start1 end1)))
285 (delete-region start3 end3)
286 (goto-char start3)
287 (insert match1)
288 (delete-region start1 end1)
289 (goto-char start1)
290 (insert match3)))))
291 ;; (pop-to-buffer (current-buffer)) (debug 'before-resolve)
293 ;; Try to resolve the conflicts.
294 (cond
295 ((member file '("configure" "lisp/ldefs-boot-auto.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)
304 (save-excursion
305 (ignore-errors
306 (smerge-match-conflict)
307 (smerge-resolve))))
308 ;; (when (derived-mode-p 'change-log-mode)
309 ;; (pop-to-buffer (current-buffer)) (debug 'after-resolve))
310 (save-buffer)))
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."
319 (with-temp-buffer
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"
325 (if skip
326 (concat "The following commit"
327 (if end "s were " " was ")
328 "skipped:\n\n")
329 ""))
330 (apply 'call-process "git" nil t nil "log" "--oneline"
331 (if end (list (concat beg "~.." end))
332 `("-1" ,beg)))
333 (insert "\n")
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..."))
338 (buffer-string)))
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)
344 (erase-buffer)
345 (let* ((skip (cdar missing))
346 (beg (car (pop missing)))
347 end commitmessage)
348 ;; Determine last revision with same boolean skip status.
349 (while (and missing
350 (eq (null (cdar missing))
351 (null skip)))
352 (setq end (car (pop missing))))
353 (setq commitmessage
354 (gitmerge-commit-message beg end skip from))
355 (message "%s %s%s"
356 (if skip "Skipping" "Merging")
357 (substring beg 0 6)
358 (if end (concat ".." (substring end 0 6)) ""))
359 (unless end
360 (setq end beg))
361 (unless (zerop
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)))
367 missing))
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)
373 (erase-buffer)
374 (let (files conflicted)
375 ;; List unmerged files
376 (if (not (zerop
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))
381 (while (not (eobp))
382 (push (buffer-substring (point) (line-end-position)) files)
383 (forward-line))
384 (dolist (file files)
385 (if (gitmerge-resolve file)
386 ;; File still has conflicts
387 (setq conflicted t)
388 ;; Mark as resolved
389 (call-process "git" nil t nil "add" file)))
390 (when conflicted
391 (with-current-buffer (get-buffer-create gitmerge-warning-buffer)
392 (erase-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 "
401 "in a new one."
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."
409 (with-temp-buffer
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"))
427 (when statusexist
428 (if (not (y-or-n-p "Resume merge? "))
429 (progn
430 (delete-file gitmerge-status-file)
431 ;; No resume.
432 nil)
433 (message "OK, resuming...")
434 (gitmerge-resolve-unmerged)
435 ;; Commit the merge.
436 (when mergehead
437 (with-current-buffer (get-buffer-create gitmerge-output-buffer)
438 (erase-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.
443 t))))
445 (defun gitmerge-get-all-branches ()
446 "Return list of all branches, including remotes."
447 (with-temp-buffer
448 (unless (zerop (call-process "git" nil t nil
449 "branch" "-a"))
450 (error "Git error listing remote branches"))
451 (goto-char (point-min))
452 (let (branches branch)
453 (while (not (eobp))
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)))
458 (forward-line))
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."
464 (with-current-buffer
465 (find-file-noselect gitmerge-status-file)
466 (erase-buffer)
467 (insert
468 (prin1-to-string (append (list from) missing))
469 "\n")
470 (save-buffer)
471 (kill-buffer)))
473 (defun gitmerge-read-missing ()
474 "Read list of missing commits from `gitmerge-status-file'."
475 (with-current-buffer
476 (find-file-noselect gitmerge-status-file)
477 (unless (zerop (buffer-size))
478 (prog1 (read (buffer-string))
479 (kill-buffer)))))
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'."
490 (interactive
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)))
494 (list
495 (if (gitmerge-maybe-resume)
496 '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)
501 (progn
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"))
510 (with-current-buffer
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")
519 (gitmerge-mode)
520 (pop-to-buffer (current-buffer))))))
522 (defun gitmerge-start-merge ()
523 (interactive)
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)))
534 (provide 'gitmerge)
536 ;;; gitmerge.el ends here