]> code.delx.au - gnu-emacs/blob - lisp/vc/vc-git.el
Call `smerge-start-session' even when dealing with a stash conflict
[gnu-emacs] / lisp / vc / vc-git.el
1 ;;; vc-git.el --- VC backend for the git version control system -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2006-2015 Free Software Foundation, Inc.
4
5 ;; Author: Alexandre Julliard <julliard@winehq.org>
6 ;; Keywords: vc tools
7 ;; Package: vc
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25
26 ;; This file contains a VC backend for the git version control
27 ;; system.
28 ;;
29
30 ;;; Installation:
31
32 ;; To install: put this file on the load-path and add Git to the list
33 ;; of supported backends in `vc-handled-backends'; the following line,
34 ;; placed in your init file, will accomplish this:
35 ;;
36 ;; (add-to-list 'vc-handled-backends 'Git)
37
38 ;;; Todo:
39 ;; - check if more functions could use vc-git-command instead
40 ;; of start-process.
41 ;; - changelog generation
42
43 ;; Implement the rest of the vc interface. See the comment at the
44 ;; beginning of vc.el. The current status is:
45 ;; ("??" means: "figure out what to do about it")
46 ;;
47 ;; FUNCTION NAME STATUS
48 ;; BACKEND PROPERTIES
49 ;; * revision-granularity OK
50 ;; STATE-QUERYING FUNCTIONS
51 ;; * registered (file) OK
52 ;; * state (file) OK
53 ;; - dir-status-files (dir files uf) OK
54 ;; * working-revision (file) OK
55 ;; * checkout-model (files) OK
56 ;; - mode-line-string (file) OK
57 ;; STATE-CHANGING FUNCTIONS
58 ;; * create-repo () OK
59 ;; * register (files &optional rev comment) OK
60 ;; - responsible-p (file) OK
61 ;; - receive-file (file rev) NOT NEEDED
62 ;; - unregister (file) OK
63 ;; * checkin (files rev comment) OK
64 ;; * find-revision (file rev buffer) OK
65 ;; * checkout (file &optional rev) OK
66 ;; * revert (file &optional contents-done) OK
67 ;; - merge-file (file rev1 rev2) It would be possible to merge
68 ;; changes into a single file, but
69 ;; when committing they wouldn't
70 ;; be identified as a merge
71 ;; by git, so it's probably
72 ;; not a good idea.
73 ;; - merge-news (file) see `merge-file'
74 ;; - steal-lock (file &optional revision) NOT NEEDED
75 ;; HISTORY FUNCTIONS
76 ;; * print-log (files buffer &optional shortlog start-revision limit) OK
77 ;; - log-view-mode () OK
78 ;; - show-log-entry (revision) OK
79 ;; - comment-history (file) ??
80 ;; - update-changelog (files) COULD BE SUPPORTED
81 ;; * diff (file &optional rev1 rev2 buffer async) OK
82 ;; - revision-completion-table (files) OK
83 ;; - annotate-command (file buf &optional rev) OK
84 ;; - annotate-time () OK
85 ;; - annotate-current-time () NOT NEEDED
86 ;; - annotate-extract-revision-at-line () OK
87 ;; TAG SYSTEM
88 ;; - create-tag (dir name branchp) OK
89 ;; - retrieve-tag (dir name update) OK
90 ;; MISCELLANEOUS
91 ;; - make-version-backups-p (file) NOT NEEDED
92 ;; - previous-revision (file rev) OK
93 ;; - next-revision (file rev) OK
94 ;; - check-headers () COULD BE SUPPORTED
95 ;; - delete-file (file) OK
96 ;; - rename-file (old new) OK
97 ;; - find-file-hook () OK
98 ;; - conflicted-files OK
99
100 ;;; Code:
101
102 (eval-when-compile
103 (require 'cl-lib)
104 (require 'vc)
105 (require 'vc-dir)
106 (require 'grep))
107
108 (defgroup vc-git nil
109 "VC Git backend."
110 :version "24.1"
111 :group 'vc)
112
113 (defcustom vc-git-diff-switches t
114 "String or list of strings specifying switches for Git diff under VC.
115 If nil, use the value of `vc-diff-switches'. If t, use no switches."
116 :type '(choice (const :tag "Unspecified" nil)
117 (const :tag "None" t)
118 (string :tag "Argument String")
119 (repeat :tag "Argument List" :value ("") string))
120 :version "23.1"
121 :group 'vc-git)
122
123 (defcustom vc-git-annotate-switches nil
124 "String or list of strings specifying switches for Git blame under VC.
125 If nil, use the value of `vc-annotate-switches'. If t, use no switches."
126 :type '(choice (const :tag "Unspecified" nil)
127 (const :tag "None" t)
128 (string :tag "Argument String")
129 (repeat :tag "Argument List" :value ("") string))
130 :version "25.1"
131 :group 'vc-git)
132
133 (defcustom vc-git-program "git"
134 "Name of the Git executable (excluding any arguments)."
135 :version "24.1"
136 :type 'string
137 :group 'vc-git)
138
139 (defcustom vc-git-root-log-format
140 '("%d%h..: %an %ad %s"
141 ;; The first shy group matches the characters drawn by --graph.
142 ;; We use numbered groups because `log-view-message-re' wants the
143 ;; revision number to be group 1.
144 "^\\(?:[*/\\| ]+ \\)?\\(?2: ([^)]+)\\)?\\(?1:[0-9a-z]+\\)..: \
145 \\(?3:.*?\\)[ \t]+\\(?4:[0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\)"
146 ((1 'log-view-message-face)
147 (2 'change-log-list nil lax)
148 (3 'change-log-name)
149 (4 'change-log-date)))
150 "Git log format for `vc-print-root-log'.
151 This should be a list (FORMAT REGEXP KEYWORDS), where FORMAT is a
152 format string (which is passed to \"git log\" via the argument
153 \"--pretty=tformat:FORMAT\"), REGEXP is a regular expression
154 matching the resulting Git log output, and KEYWORDS is a list of
155 `font-lock-keywords' for highlighting the Log View buffer."
156 :type '(list string string (repeat sexp))
157 :group 'vc-git
158 :version "24.1")
159
160 (defvar vc-git-commits-coding-system 'utf-8
161 "Default coding system for git commits.")
162
163 ;; History of Git commands.
164 (defvar vc-git-history nil)
165
166 ;;; BACKEND PROPERTIES
167
168 (defun vc-git-revision-granularity () 'repository)
169 (defun vc-git-checkout-model (_files) 'implicit)
170
171 ;;; STATE-QUERYING FUNCTIONS
172
173 ;;;###autoload (defun vc-git-registered (file)
174 ;;;###autoload "Return non-nil if FILE is registered with git."
175 ;;;###autoload (if (vc-find-root file ".git") ; Short cut.
176 ;;;###autoload (progn
177 ;;;###autoload (load "vc-git" nil t)
178 ;;;###autoload (vc-git-registered file))))
179
180 (defun vc-git-registered (file)
181 "Check whether FILE is registered with git."
182 (let ((dir (vc-git-root file)))
183 (when dir
184 (with-temp-buffer
185 (let* (process-file-side-effects
186 ;; Do not use the `file-name-directory' here: git-ls-files
187 ;; sometimes fails to return the correct status for relative
188 ;; path specs.
189 ;; See also: http://marc.info/?l=git&m=125787684318129&w=2
190 (name (file-relative-name file dir))
191 (str (ignore-errors
192 (cd dir)
193 (vc-git--out-ok "ls-files" "-c" "-z" "--" name)
194 ;; If result is empty, use ls-tree to check for deleted
195 ;; file.
196 (when (eq (point-min) (point-max))
197 (vc-git--out-ok "ls-tree" "--name-only" "-z" "HEAD"
198 "--" name))
199 (buffer-string))))
200 (and str
201 (> (length str) (length name))
202 (string= (substring str 0 (1+ (length name)))
203 (concat name "\0"))))))))
204
205 (defun vc-git--state-code (code)
206 "Convert from a string to a added/deleted/modified state."
207 (pcase (string-to-char code)
208 (?M 'edited)
209 (?A 'added)
210 (?D 'removed)
211 (?U 'edited) ;; FIXME
212 (?T 'edited))) ;; FIXME
213
214 (defun vc-git-state (file)
215 "Git-specific version of `vc-state'."
216 ;; FIXME: This can't set 'ignored or 'conflict yet
217 ;; The 'ignored state could be detected with `git ls-files -i -o
218 ;; --exclude-standard` It also can't set 'needs-update or
219 ;; 'needs-merge. The rough equivalent would be that upstream branch
220 ;; for current branch is in fast-forward state i.e. current branch
221 ;; is direct ancestor of corresponding upstream branch, and the file
222 ;; was modified upstream. But we can't check that without a network
223 ;; operation.
224 ;; This assumes that status is known to be not `unregistered' because
225 ;; we've been successfully dispatched here from `vc-state', that
226 ;; means `vc-git-registered' returned t earlier once. Bug#11757
227 (let ((diff (vc-git--run-command-string
228 file "diff-index" "-p" "--raw" "-z" "HEAD" "--")))
229 (if (and diff
230 (string-match ":[0-7]\\{6\\} [0-7]\\{6\\} [0-9a-f]\\{40\\} [0-9a-f]\\{40\\} \\([ADMUT]\\)\0[^\0]+\0\\(.*\n.\\)?"
231 diff))
232 (let ((diff-letter (match-string 1 diff)))
233 (if (not (match-beginning 2))
234 ;; Empty diff: file contents is the same as the HEAD
235 ;; revision, but timestamps are different (eg, file
236 ;; was "touch"ed). Update timestamp in index:
237 (prog1 'up-to-date
238 (vc-git--call nil "add" "--refresh" "--"
239 (file-relative-name file)))
240 (vc-git--state-code diff-letter)))
241 (if (vc-git--empty-db-p) 'added 'up-to-date))))
242
243 (defun vc-git-working-revision (file)
244 "Git-specific version of `vc-working-revision'."
245 (let* (process-file-side-effects
246 (str (vc-git--run-command-string nil "symbolic-ref" "HEAD")))
247 (vc-file-setprop file 'vc-git-detached (null str))
248 (if str
249 (if (string-match "^\\(refs/heads/\\)?\\(.+\\)$" str)
250 (match-string 2 str)
251 str)
252 (vc-git--rev-parse "HEAD"))))
253
254 (defun vc-git-mode-line-string (file)
255 "Return a string for `vc-mode-line' to put in the mode line for FILE."
256 (let* ((rev (vc-working-revision file))
257 (detached (vc-file-getprop file 'vc-git-detached))
258 (def-ml (vc-default-mode-line-string 'Git file))
259 (help-echo (get-text-property 0 'help-echo def-ml)))
260 (propertize (if detached
261 (substring def-ml 0 (- 7 (length rev)))
262 def-ml)
263 'help-echo (concat help-echo "\nCurrent revision: " rev))))
264
265 (cl-defstruct (vc-git-extra-fileinfo
266 (:copier nil)
267 (:constructor vc-git-create-extra-fileinfo
268 (old-perm new-perm &optional rename-state orig-name))
269 (:conc-name vc-git-extra-fileinfo->))
270 old-perm new-perm ;; Permission flags.
271 rename-state ;; Rename or copy state.
272 orig-name) ;; Original name for renames or copies.
273
274 (defun vc-git-escape-file-name (name)
275 "Escape a file name if necessary."
276 (if (string-match "[\n\t\"\\]" name)
277 (concat "\""
278 (mapconcat (lambda (c)
279 (pcase c
280 (?\n "\\n")
281 (?\t "\\t")
282 (?\\ "\\\\")
283 (?\" "\\\"")
284 (_ (char-to-string c))))
285 name "")
286 "\"")
287 name))
288
289 (defun vc-git-file-type-as-string (old-perm new-perm)
290 "Return a string describing the file type based on its permissions."
291 (let* ((old-type (lsh (or old-perm 0) -9))
292 (new-type (lsh (or new-perm 0) -9))
293 (str (pcase new-type
294 (?\100 ;; File.
295 (pcase old-type
296 (?\100 nil)
297 (?\120 " (type change symlink -> file)")
298 (?\160 " (type change subproject -> file)")))
299 (?\120 ;; Symlink.
300 (pcase old-type
301 (?\100 " (type change file -> symlink)")
302 (?\160 " (type change subproject -> symlink)")
303 (t " (symlink)")))
304 (?\160 ;; Subproject.
305 (pcase old-type
306 (?\100 " (type change file -> subproject)")
307 (?\120 " (type change symlink -> subproject)")
308 (t " (subproject)")))
309 (?\110 nil) ;; Directory (internal, not a real git state).
310 (?\000 ;; Deleted or unknown.
311 (pcase old-type
312 (?\120 " (symlink)")
313 (?\160 " (subproject)")))
314 (_ (format " (unknown type %o)" new-type)))))
315 (cond (str (propertize str 'face 'font-lock-comment-face))
316 ((eq new-type ?\110) "/")
317 (t ""))))
318
319 (defun vc-git-rename-as-string (state extra)
320 "Return a string describing the copy or rename associated with INFO,
321 or an empty string if none."
322 (let ((rename-state (when extra
323 (vc-git-extra-fileinfo->rename-state extra))))
324 (if rename-state
325 (propertize
326 (concat " ("
327 (if (eq rename-state 'copy) "copied from "
328 (if (eq state 'added) "renamed from "
329 "renamed to "))
330 (vc-git-escape-file-name
331 (vc-git-extra-fileinfo->orig-name extra))
332 ")")
333 'face 'font-lock-comment-face)
334 "")))
335
336 (defun vc-git-permissions-as-string (old-perm new-perm)
337 "Format a permission change as string."
338 (propertize
339 (if (or (not old-perm)
340 (not new-perm)
341 (eq 0 (logand ?\111 (logxor old-perm new-perm))))
342 " "
343 (if (eq 0 (logand ?\111 old-perm)) "+x" "-x"))
344 'face 'font-lock-type-face))
345
346 (defun vc-git-dir-printer (info)
347 "Pretty-printer for the vc-dir-fileinfo structure."
348 (let* ((isdir (vc-dir-fileinfo->directory info))
349 (state (if isdir "" (vc-dir-fileinfo->state info)))
350 (extra (vc-dir-fileinfo->extra info))
351 (old-perm (when extra (vc-git-extra-fileinfo->old-perm extra)))
352 (new-perm (when extra (vc-git-extra-fileinfo->new-perm extra))))
353 (insert
354 " "
355 (propertize (format "%c" (if (vc-dir-fileinfo->marked info) ?* ? ))
356 'face 'font-lock-type-face)
357 " "
358 (propertize
359 (format "%-12s" state)
360 'face (cond ((eq state 'up-to-date) 'font-lock-builtin-face)
361 ((eq state 'missing) 'font-lock-warning-face)
362 (t 'font-lock-variable-name-face))
363 'mouse-face 'highlight)
364 " " (vc-git-permissions-as-string old-perm new-perm)
365 " "
366 (propertize (vc-git-escape-file-name (vc-dir-fileinfo->name info))
367 'face (if isdir 'font-lock-comment-delimiter-face
368 'font-lock-function-name-face)
369 'help-echo
370 (if isdir
371 "Directory\nVC operations can be applied to it\nmouse-3: Pop-up menu"
372 "File\nmouse-3: Pop-up menu")
373 'keymap vc-dir-filename-mouse-map
374 'mouse-face 'highlight)
375 (vc-git-file-type-as-string old-perm new-perm)
376 (vc-git-rename-as-string state extra))))
377
378 (defun vc-git-after-dir-status-stage (stage files update-function)
379 "Process sentinel for the various dir-status stages."
380 (let (next-stage result)
381 (goto-char (point-min))
382 (pcase stage
383 (`update-index
384 (setq next-stage (if (vc-git--empty-db-p) 'ls-files-added 'diff-index)))
385 (`ls-files-added
386 (setq next-stage 'ls-files-unknown)
387 (while (re-search-forward "\\([0-7]\\{6\\}\\) [0-9a-f]\\{40\\} 0\t\\([^\0]+\\)\0" nil t)
388 (let ((new-perm (string-to-number (match-string 1) 8))
389 (name (match-string 2)))
390 (push (list name 'added (vc-git-create-extra-fileinfo 0 new-perm))
391 result))))
392 (`ls-files-up-to-date
393 (setq next-stage 'ls-files-unknown)
394 (while (re-search-forward "\\([0-7]\\{6\\}\\) [0-9a-f]\\{40\\} 0\t\\([^\0]+\\)\0" nil t)
395 (let ((perm (string-to-number (match-string 1) 8))
396 (name (match-string 2)))
397 (push (list name 'up-to-date
398 (vc-git-create-extra-fileinfo perm perm))
399 result))))
400 (`ls-files-unknown
401 (when files (setq next-stage 'ls-files-ignored))
402 (while (re-search-forward "\\([^\0]*?\\)\0" nil t 1)
403 (push (list (match-string 1) 'unregistered
404 (vc-git-create-extra-fileinfo 0 0))
405 result)))
406 (`ls-files-ignored
407 (while (re-search-forward "\\([^\0]*?\\)\0" nil t 1)
408 (push (list (match-string 1) 'ignored
409 (vc-git-create-extra-fileinfo 0 0))
410 result)))
411 (`diff-index
412 (setq next-stage (if files 'ls-files-up-to-date 'ls-files-unknown))
413 (while (re-search-forward
414 ":\\([0-7]\\{6\\}\\) \\([0-7]\\{6\\}\\) [0-9a-f]\\{40\\} [0-9a-f]\\{40\\} \\(\\([ADMUT]\\)\0\\([^\0]+\\)\\|\\([CR]\\)[0-9]*\0\\([^\0]+\\)\0\\([^\0]+\\)\\)\0"
415 nil t 1)
416 (let ((old-perm (string-to-number (match-string 1) 8))
417 (new-perm (string-to-number (match-string 2) 8))
418 (state (or (match-string 4) (match-string 6)))
419 (name (or (match-string 5) (match-string 7)))
420 (new-name (match-string 8)))
421 (if new-name ; Copy or rename.
422 (if (eq ?C (string-to-char state))
423 (push (list new-name 'added
424 (vc-git-create-extra-fileinfo old-perm new-perm
425 'copy name))
426 result)
427 (push (list name 'removed
428 (vc-git-create-extra-fileinfo 0 0
429 'rename new-name))
430 result)
431 (push (list new-name 'added
432 (vc-git-create-extra-fileinfo old-perm new-perm
433 'rename name))
434 result))
435 (push (list name (vc-git--state-code state)
436 (vc-git-create-extra-fileinfo old-perm new-perm))
437 result))))))
438 (when result
439 (setq result (nreverse result))
440 (when files
441 (dolist (entry result) (setq files (delete (car entry) files)))
442 (unless files (setq next-stage nil))))
443 (when (or result (not next-stage))
444 (funcall update-function result next-stage))
445 (when next-stage
446 (vc-git-dir-status-goto-stage next-stage files update-function))))
447
448 ;; Follows vc-git-command (or vc-do-async-command), which uses vc-do-command
449 ;; from vc-dispatcher.
450 (declare-function vc-exec-after "vc-dispatcher" (code))
451 ;; Follows vc-exec-after.
452 (declare-function vc-set-async-update "vc-dispatcher" (process-buffer))
453
454 (defun vc-git-dir-status-goto-stage (stage files update-function)
455 (erase-buffer)
456 (pcase stage
457 (`update-index
458 (if files
459 (vc-git-command (current-buffer) 'async files "add" "--refresh" "--")
460 (vc-git-command (current-buffer) 'async nil
461 "update-index" "--refresh")))
462 (`ls-files-added
463 (vc-git-command (current-buffer) 'async files
464 "ls-files" "-z" "-c" "-s" "--"))
465 (`ls-files-up-to-date
466 (vc-git-command (current-buffer) 'async files
467 "ls-files" "-z" "-c" "-s" "--"))
468 (`ls-files-unknown
469 (vc-git-command (current-buffer) 'async files
470 "ls-files" "-z" "-o" "--directory"
471 "--no-empty-directory" "--exclude-standard" "--"))
472 (`ls-files-ignored
473 (vc-git-command (current-buffer) 'async files
474 "ls-files" "-z" "-o" "-i" "--directory"
475 "--no-empty-directory" "--exclude-standard" "--"))
476 ;; --relative added in Git 1.5.5.
477 (`diff-index
478 (vc-git-command (current-buffer) 'async files
479 "diff-index" "--relative" "-z" "-M" "HEAD" "--")))
480 (vc-run-delayed
481 (vc-git-after-dir-status-stage stage files update-function)))
482
483 (defun vc-git-dir-status-files (_dir files update-function)
484 "Return a list of (FILE STATE EXTRA) entries for DIR."
485 ;; Further things that would have to be fixed later:
486 ;; - how to handle unregistered directories
487 ;; - how to support vc-dir on a subdir of the project tree
488 (vc-git-dir-status-goto-stage 'update-index files update-function))
489
490 (defvar vc-git-stash-map
491 (let ((map (make-sparse-keymap)))
492 ;; Turn off vc-dir marking
493 (define-key map [mouse-2] 'ignore)
494
495 (define-key map [down-mouse-3] 'vc-git-stash-menu)
496 (define-key map "\C-k" 'vc-git-stash-delete-at-point)
497 (define-key map "=" 'vc-git-stash-show-at-point)
498 (define-key map "\C-m" 'vc-git-stash-show-at-point)
499 (define-key map "A" 'vc-git-stash-apply-at-point)
500 (define-key map "P" 'vc-git-stash-pop-at-point)
501 (define-key map "S" 'vc-git-stash-snapshot)
502 map))
503
504 (defvar vc-git-stash-menu-map
505 (let ((map (make-sparse-keymap "Git Stash")))
506 (define-key map [de]
507 '(menu-item "Delete Stash" vc-git-stash-delete-at-point
508 :help "Delete the current stash"))
509 (define-key map [ap]
510 '(menu-item "Apply Stash" vc-git-stash-apply-at-point
511 :help "Apply the current stash and keep it in the stash list"))
512 (define-key map [po]
513 '(menu-item "Apply and Remove Stash (Pop)" vc-git-stash-pop-at-point
514 :help "Apply the current stash and remove it"))
515 (define-key map [sh]
516 '(menu-item "Show Stash" vc-git-stash-show-at-point
517 :help "Show the contents of the current stash"))
518 map))
519
520 (defun vc-git-dir-extra-headers (dir)
521 (let ((str (with-output-to-string
522 (with-current-buffer standard-output
523 (vc-git--out-ok "symbolic-ref" "HEAD"))))
524 (stash (vc-git-stash-list))
525 (stash-help-echo "Use M-x vc-git-stash to create stashes.")
526 branch remote remote-url)
527 (if (string-match "^\\(refs/heads/\\)?\\(.+\\)$" str)
528 (progn
529 (setq branch (match-string 2 str))
530 (setq remote
531 (with-output-to-string
532 (with-current-buffer standard-output
533 (vc-git--out-ok "config"
534 (concat "branch." branch ".remote")))))
535 (when (string-match "\\([^\n]+\\)" remote)
536 (setq remote (match-string 1 remote)))
537 (when remote
538 (setq remote-url
539 (with-output-to-string
540 (with-current-buffer standard-output
541 (vc-git--out-ok "config"
542 (concat "remote." remote ".url"))))))
543 (when (string-match "\\([^\n]+\\)" remote-url)
544 (setq remote-url (match-string 1 remote-url))))
545 (setq branch "not (detached HEAD)"))
546 ;; FIXME: maybe use a different face when nothing is stashed.
547 (concat
548 (propertize "Branch : " 'face 'font-lock-type-face)
549 (propertize branch
550 'face 'font-lock-variable-name-face)
551 (when remote
552 (concat
553 "\n"
554 (propertize "Remote : " 'face 'font-lock-type-face)
555 (propertize remote-url
556 'face 'font-lock-variable-name-face)))
557 "\n"
558 ;; For now just a heading, key bindings can be added later for various bisect actions
559 (when (file-exists-p (expand-file-name ".git/BISECT_START" (vc-git-root dir)))
560 (propertize "Bisect : in progress\n" 'face 'font-lock-warning-face))
561 (when (file-exists-p (expand-file-name ".git/rebase-apply" (vc-git-root dir)))
562 (propertize "Rebase : in progress\n" 'face 'font-lock-warning-face))
563 (if stash
564 (concat
565 (propertize "Stash :\n" 'face 'font-lock-type-face
566 'help-echo stash-help-echo)
567 (mapconcat
568 (lambda (x)
569 (propertize x
570 'face 'font-lock-variable-name-face
571 'mouse-face 'highlight
572 'help-echo "mouse-3: Show stash menu\nRET: Show stash\nA: Apply stash\nP: Apply and remove stash (pop)\nC-k: Delete stash"
573 'keymap vc-git-stash-map))
574 stash "\n"))
575 (concat
576 (propertize "Stash : " 'face 'font-lock-type-face
577 'help-echo stash-help-echo)
578 (propertize "Nothing stashed"
579 'help-echo stash-help-echo
580 'face 'font-lock-variable-name-face))))))
581
582 (defun vc-git-branches ()
583 "Return the existing branches, as a list of strings.
584 The car of the list is the current branch."
585 (with-temp-buffer
586 (vc-git--call t "branch")
587 (goto-char (point-min))
588 (let (current-branch branches)
589 (while (not (eobp))
590 (when (looking-at "^\\([ *]\\) \\(.+\\)$")
591 (if (string-equal (match-string 1) "*")
592 (setq current-branch (match-string 2))
593 (push (match-string 2) branches)))
594 (forward-line 1))
595 (cons current-branch (nreverse branches)))))
596
597 ;;; STATE-CHANGING FUNCTIONS
598
599 (defun vc-git-create-repo ()
600 "Create a new Git repository."
601 (vc-git-command nil 0 nil "init"))
602
603 (defun vc-git-register (files &optional _comment)
604 "Register FILES into the git version-control system."
605 (let (flist dlist)
606 (dolist (crt files)
607 (if (file-directory-p crt)
608 (push crt dlist)
609 (push crt flist)))
610 (when flist
611 (vc-git-command nil 0 flist "update-index" "--add" "--"))
612 (when dlist
613 (vc-git-command nil 0 dlist "add"))))
614
615 (defalias 'vc-git-responsible-p 'vc-git-root)
616
617 (defun vc-git-unregister (file)
618 (vc-git-command nil 0 file "rm" "-f" "--cached" "--"))
619
620 (declare-function log-edit-mode "log-edit" ())
621 (declare-function log-edit-toggle-header "log-edit" (header value))
622 (declare-function log-edit-extract-headers "log-edit" (headers string))
623 (declare-function log-edit-set-header "log-edit" (header value &optional toggle))
624
625 (defun vc-git-log-edit-toggle-signoff ()
626 "Toggle whether to add the \"Signed-off-by\" line at the end of
627 the commit message."
628 (interactive)
629 (log-edit-toggle-header "Sign-Off" "yes"))
630
631 (defun vc-git-log-edit-toggle-amend ()
632 "Toggle whether this will amend the previous commit.
633 If toggling on, also insert its message into the buffer."
634 (interactive)
635 (when (log-edit-toggle-header "Amend" "yes")
636 (goto-char (point-max))
637 (unless (bolp) (insert "\n"))
638 (insert (with-output-to-string
639 (vc-git-command
640 standard-output 1 nil
641 "log" "--max-count=1" "--pretty=format:%B" "HEAD")))
642 (save-excursion
643 (rfc822-goto-eoh)
644 (forward-line 1)
645 (let ((pt (point)))
646 (and (zerop (forward-line 1))
647 (looking-at "\n\\|\\'")
648 (let ((summary (buffer-substring-no-properties pt (1- (point)))))
649 (skip-chars-forward " \n")
650 (delete-region pt (point))
651 (log-edit-set-header "Summary" summary)))))))
652
653 (defvar vc-git-log-edit-mode-map
654 (let ((map (make-sparse-keymap "Git-Log-Edit")))
655 (define-key map "\C-c\C-s" 'vc-git-log-edit-toggle-signoff)
656 (define-key map "\C-c\C-e" 'vc-git-log-edit-toggle-amend)
657 map))
658
659 (define-derived-mode vc-git-log-edit-mode log-edit-mode "Log-Edit/git"
660 "Major mode for editing Git log messages.
661 It is based on `log-edit-mode', and has Git-specific extensions.")
662
663 (defun vc-git-checkin (files comment)
664 (let* ((file1 (or (car files) default-directory))
665 (root (vc-git-root file1))
666 (default-directory (expand-file-name root))
667 (only (or (cdr files)
668 (not (equal root (abbreviate-file-name file1)))))
669 (coding-system-for-write vc-git-commits-coding-system))
670 (cl-flet ((boolean-arg-fn
671 (argument)
672 (lambda (value) (when (equal value "yes") (list argument)))))
673 ;; When operating on the whole tree, better pass "-a" than ".", since "."
674 ;; fails when we're committing a merge.
675 (apply 'vc-git-command nil 0 (if only files)
676 (nconc (list "commit" "-m")
677 (log-edit-extract-headers
678 `(("Author" . "--author")
679 ("Date" . "--date")
680 ("Amend" . ,(boolean-arg-fn "--amend"))
681 ("Sign-Off" . ,(boolean-arg-fn "--signoff")))
682 comment)
683 (if only (list "--only" "--") '("-a")))))))
684
685 (defun vc-git-find-revision (file rev buffer)
686 (let* (process-file-side-effects
687 (coding-system-for-read 'binary)
688 (coding-system-for-write 'binary)
689 (fullname
690 (let ((fn (vc-git--run-command-string
691 file "ls-files" "-z" "--full-name" "--")))
692 ;; ls-files does not return anything when looking for a
693 ;; revision of a file that has been renamed or removed.
694 (if (string= fn "")
695 (file-relative-name file (vc-git-root default-directory))
696 (substring fn 0 -1)))))
697 (vc-git-command
698 buffer 0
699 nil
700 "cat-file" "blob" (concat (if rev rev "HEAD") ":" fullname))))
701
702 (defun vc-git-find-ignore-file (file)
703 "Return the root directory of the repository of FILE."
704 (expand-file-name ".gitignore"
705 (vc-git-root file)))
706
707 (defun vc-git-checkout (file &optional rev)
708 (vc-git-command nil 0 file "checkout" (or rev "HEAD")))
709
710 (defun vc-git-revert (file &optional contents-done)
711 "Revert FILE to the version stored in the git repository."
712 (if contents-done
713 (vc-git-command nil 0 file "update-index" "--")
714 (vc-git-command nil 0 file "reset" "-q" "--")
715 (vc-git-command nil nil file "checkout" "-q" "--")))
716
717 (defvar vc-git-error-regexp-alist
718 '(("^ \\(.+\\) |" 1 nil nil 0))
719 "Value of `compilation-error-regexp-alist' in *vc-git* buffers.")
720
721 ;; To be called via vc-pull from vc.el, which requires vc-dispatcher.
722 (declare-function vc-compilation-mode "vc-dispatcher" (backend))
723
724 (defun vc-git-pull (prompt)
725 "Pull changes into the current Git branch.
726 Normally, this runs \"git pull\". If PROMPT is non-nil, prompt
727 for the Git command to run."
728 (let* ((root (vc-git-root default-directory))
729 (buffer (format "*vc-git : %s*" (expand-file-name root)))
730 (command "pull")
731 (git-program vc-git-program)
732 args)
733 ;; If necessary, prompt for the exact command.
734 (when prompt
735 (setq args (split-string
736 (read-shell-command "Git pull command: "
737 (format "%s pull" git-program)
738 'vc-git-history)
739 " " t))
740 (setq git-program (car args)
741 command (cadr args)
742 args (cddr args)))
743 (require 'vc-dispatcher)
744 (apply 'vc-do-async-command buffer root git-program command args)
745 (with-current-buffer buffer (vc-run-delayed (vc-compilation-mode 'git)))
746 (vc-set-async-update buffer)))
747
748 (defun vc-git-merge-branch ()
749 "Merge changes into the current Git branch.
750 This prompts for a branch to merge from."
751 (let* ((root (vc-git-root default-directory))
752 (buffer (format "*vc-git : %s*" (expand-file-name root)))
753 (branches (cdr (vc-git-branches)))
754 (merge-source
755 (completing-read "Merge from branch: "
756 (if (or (member "FETCH_HEAD" branches)
757 (not (file-readable-p
758 (expand-file-name ".git/FETCH_HEAD"
759 root))))
760 branches
761 (cons "FETCH_HEAD" branches))
762 nil t)))
763 (apply 'vc-do-async-command buffer root vc-git-program "merge"
764 (list merge-source))
765 (with-current-buffer buffer (vc-run-delayed (vc-compilation-mode 'git)))
766 (vc-set-async-update buffer)))
767
768 (defun vc-git-conflicted-files (directory)
769 "Return the list of files with conflicts in DIRECTORY."
770 (let* ((status
771 (vc-git--run-command-string directory "status" "--porcelain" "--"))
772 (lines (when status (split-string status "\n" 'omit-nulls)))
773 files)
774 (dolist (line lines files)
775 (when (string-match "\\([ MADRCU?!][ MADRCU?!]\\) \\(.+\\)\\(?: -> \\(.+\\)\\)?"
776 line)
777 (let ((state (match-string 1 line))
778 (file (match-string 2 line)))
779 ;; See git-status(1).
780 (when (member state '("AU" "UD" "UA" ;; "DD"
781 "DU" "AA" "UU"))
782 (push (expand-file-name file directory) files)))))))
783
784 (defun vc-git-resolve-when-done ()
785 "Call \"git add\" if the conflict markers have been removed."
786 (save-excursion
787 (goto-char (point-min))
788 (unless (re-search-forward "^<<<<<<< " nil t)
789 (vc-git-command nil 0 buffer-file-name "add")
790 ;; Remove the hook so that it is not called multiple times.
791 (remove-hook 'after-save-hook 'vc-git-resolve-when-done t))))
792
793 (defun vc-git-find-file-hook ()
794 "Activate `smerge-mode' if there is a conflict."
795 (let (stashed)
796 (when (and buffer-file-name
797 ;; FIXME
798 ;; 1) the net result is to call git twice per file.
799 ;; 2) v-g-c-f is documented to take a directory.
800 ;; http://lists.gnu.org/archive/html/emacs-devel/2014-01/msg01126.html
801 ;; XXX: Should we first look for the markers, and only
802 ;; call this function when see some?
803 (vc-git-conflicted-files buffer-file-name)
804 (save-excursion
805 (goto-char (point-min))
806 (when (re-search-forward "^>>>>>>> " nil 'noerror)
807 (setq stashed (looking-at "Stashed changes"))
808 t)))
809 (vc-file-setprop buffer-file-name 'vc-state 'conflict)
810 (smerge-start-session)
811 (unless stashed
812 ;; Stashes are tricky (bug#20292).
813 (add-hook 'after-save-hook 'vc-git-resolve-when-done nil 'local))
814 (message "There are unresolved conflicts in this file"))))
815
816 ;;; HISTORY FUNCTIONS
817
818 (autoload 'vc-setup-buffer "vc-dispatcher")
819
820 (defun vc-git-print-log (files buffer &optional shortlog start-revision limit)
821 "Print commit log associated with FILES into specified BUFFER.
822 If SHORTLOG is non-nil, use a short format based on `vc-git-root-log-format'.
823 \(This requires at least Git version 1.5.6, for the --graph option.)
824 If START-REVISION is non-nil, it is the newest revision to show.
825 If LIMIT is non-nil, show no more than this many entries."
826 (let ((coding-system-for-read vc-git-commits-coding-system))
827 ;; `vc-do-command' creates the buffer, but we need it before running
828 ;; the command.
829 (vc-setup-buffer buffer)
830 ;; If the buffer exists from a previous invocation it might be
831 ;; read-only.
832 (let ((inhibit-read-only t))
833 (with-current-buffer
834 buffer
835 (apply 'vc-git-command buffer
836 'async files
837 (append
838 '("log" "--no-color")
839 (when shortlog
840 `("--graph" "--decorate" "--date=short"
841 ,(format "--pretty=tformat:%s"
842 (car vc-git-root-log-format))
843 "--abbrev-commit"))
844 (when limit (list "-n" (format "%s" limit)))
845 (when start-revision (list start-revision))
846 '("--")))))))
847
848 (defun vc-git-log-outgoing (buffer remote-location)
849 (interactive)
850 (vc-git-command
851 buffer 0 nil
852 "log"
853 "--no-color" "--graph" "--decorate" "--date=short"
854 (format "--pretty=tformat:%s" (car vc-git-root-log-format))
855 "--abbrev-commit"
856 (concat (if (string= remote-location "")
857 "@{upstream}"
858 remote-location)
859 "..HEAD")))
860
861 (defun vc-git-log-incoming (buffer remote-location)
862 (interactive)
863 (vc-git-command nil 0 nil "fetch")
864 (vc-git-command
865 buffer 0 nil
866 "log"
867 "--no-color" "--graph" "--decorate" "--date=short"
868 (format "--pretty=tformat:%s" (car vc-git-root-log-format))
869 "--abbrev-commit"
870 (concat "HEAD.." (if (string= remote-location "")
871 "@{upstream}"
872 remote-location))))
873
874 (defvar log-view-message-re)
875 (defvar log-view-file-re)
876 (defvar log-view-font-lock-keywords)
877 (defvar log-view-per-file-logs)
878 (defvar log-view-expanded-log-entry-function)
879
880 (define-derived-mode vc-git-log-view-mode log-view-mode "Git-Log-View"
881 (require 'add-log) ;; We need the faces add-log.
882 ;; Don't have file markers, so use impossible regexp.
883 (set (make-local-variable 'log-view-file-re) "\\`a\\`")
884 (set (make-local-variable 'log-view-per-file-logs) nil)
885 (set (make-local-variable 'log-view-message-re)
886 (if (not (eq vc-log-view-type 'long))
887 (cadr vc-git-root-log-format)
888 "^commit *\\([0-9a-z]+\\)"))
889 ;; Allow expanding short log entries.
890 (when (eq vc-log-view-type 'short)
891 (setq truncate-lines t)
892 (set (make-local-variable 'log-view-expanded-log-entry-function)
893 'vc-git-expanded-log-entry))
894 (set (make-local-variable 'log-view-font-lock-keywords)
895 (if (not (eq vc-log-view-type 'long))
896 (list (cons (nth 1 vc-git-root-log-format)
897 (nth 2 vc-git-root-log-format)))
898 (append
899 `((,log-view-message-re (1 'change-log-acknowledgment)))
900 ;; Handle the case:
901 ;; user: foo@bar
902 '(("^Author:[ \t]+\\([A-Za-z0-9_.+-]+@[A-Za-z0-9_.-]+\\)"
903 (1 'change-log-email))
904 ;; Handle the case:
905 ;; user: FirstName LastName <foo@bar>
906 ("^Author:[ \t]+\\([^<(]+?\\)[ \t]*[(<]\\([A-Za-z0-9_.+-]+@[A-Za-z0-9_.-]+\\)[>)]"
907 (1 'change-log-name)
908 (2 'change-log-email))
909 ("^ +\\(?:\\(?:[Aa]cked\\|[Ss]igned-[Oo]ff\\)-[Bb]y:\\)[ \t]+\\([A-Za-z0-9_.+-]+@[A-Za-z0-9_.-]+\\)"
910 (1 'change-log-name))
911 ("^ +\\(?:\\(?:[Aa]cked\\|[Ss]igned-[Oo]ff\\)-[Bb]y:\\)[ \t]+\\([^<(]+?\\)[ \t]*[(<]\\([A-Za-z0-9_.+-]+@[A-Za-z0-9_.-]+\\)[>)]"
912 (1 'change-log-name)
913 (2 'change-log-email))
914 ("^Merge: \\([0-9a-z]+\\) \\([0-9a-z]+\\)"
915 (1 'change-log-acknowledgment)
916 (2 'change-log-acknowledgment))
917 ("^Date: \\(.+\\)" (1 'change-log-date))
918 ("^summary:[ \t]+\\(.+\\)" (1 'log-view-message)))))))
919
920
921 (defun vc-git-show-log-entry (revision)
922 "Move to the log entry for REVISION.
923 REVISION may have the form BRANCH, BRANCH~N,
924 or BRANCH^ (where \"^\" can be repeated)."
925 (goto-char (point-min))
926 (prog1
927 (when revision
928 (search-forward
929 (format "\ncommit %s" revision) nil t
930 (cond ((string-match "~\\([0-9]\\)\\'" revision)
931 (1+ (string-to-number (match-string 1 revision))))
932 ((string-match "\\^+\\'" revision)
933 (1+ (length (match-string 0 revision))))
934 (t nil))))
935 (beginning-of-line)))
936
937 (defun vc-git-expanded-log-entry (revision)
938 (with-temp-buffer
939 (apply 'vc-git-command t nil nil (list "log" revision "-1"))
940 (goto-char (point-min))
941 (unless (eobp)
942 ;; Indent the expanded log entry.
943 (indent-region (point-min) (point-max) 2)
944 (buffer-string))))
945
946
947 (defun vc-git-region-history (file buffer lfrom lto)
948 (vc-git-command buffer 'async nil "log" "-p" ;"--follow" ;FIXME: not supported?
949 (format "-L%d,%d:%s" lfrom lto (file-relative-name file))))
950
951 (require 'diff-mode)
952
953 (defvar vc-git-region-history-mode-map
954 (let ((map (make-composed-keymap
955 nil (make-composed-keymap
956 (list diff-mode-map vc-git-log-view-mode-map)))))
957 map))
958
959 (defvar vc-git--log-view-long-font-lock-keywords nil)
960 (defvar font-lock-keywords)
961 (defvar vc-git-region-history-font-lock-keywords
962 `((vc-git-region-history-font-lock)))
963
964 (defun vc-git-region-history-font-lock (limit)
965 (let ((in-diff (save-excursion
966 (beginning-of-line)
967 (or (looking-at "^\\(?:diff\\|commit\\)\\>")
968 (re-search-backward "^\\(?:diff\\|commit\\)\\>" nil t))
969 (eq ?d (char-after (match-beginning 0))))))
970 (while
971 (let ((end (save-excursion
972 (if (re-search-forward "\n\\(diff\\|commit\\)\\>"
973 limit t)
974 (match-beginning 1)
975 limit))))
976 (let ((font-lock-keywords (if in-diff diff-font-lock-keywords
977 vc-git--log-view-long-font-lock-keywords)))
978 (font-lock-fontify-keywords-region (point) end))
979 (goto-char end)
980 (prog1 (< (point) limit)
981 (setq in-diff (eq ?d (char-after))))))
982 nil))
983
984 (define-derived-mode vc-git-region-history-mode
985 vc-git-log-view-mode "Git-Region-History"
986 "Major mode to browse Git's \"log -p\" output."
987 (setq-local vc-git--log-view-long-font-lock-keywords
988 log-view-font-lock-keywords)
989 (setq-local font-lock-defaults
990 (cons 'vc-git-region-history-font-lock-keywords
991 (cdr font-lock-defaults))))
992
993
994 (autoload 'vc-switches "vc")
995
996 (defun vc-git-diff (files &optional rev1 rev2 buffer async)
997 "Get a difference report using Git between two revisions of FILES."
998 (let (process-file-side-effects)
999 (if vc-git-diff-switches
1000 (apply #'vc-git-command (or buffer "*vc-diff*")
1001 (if async 'async 1)
1002 files
1003 (if (and rev1 rev2) "diff-tree" "diff-index")
1004 "--exit-code"
1005 (append (vc-switches 'git 'diff)
1006 (list "-p" (or rev1 "HEAD") rev2 "--")))
1007 (vc-git-command (or buffer "*vc-diff*") 1 files
1008 "difftool" "--exit-code" "--no-prompt" "-x"
1009 (concat "diff "
1010 (mapconcat 'identity
1011 (vc-switches nil 'diff) " "))
1012 (or rev1 "HEAD") rev2 "--"))))
1013
1014 (defun vc-git-revision-table (_files)
1015 ;; What about `files'?!? --Stef
1016 (let (process-file-side-effects
1017 (table (list "HEAD")))
1018 (with-temp-buffer
1019 (vc-git-command t nil nil "for-each-ref" "--format=%(refname)")
1020 (goto-char (point-min))
1021 (while (re-search-forward "^refs/\\(heads\\|tags\\|remotes\\)/\\(.*\\)$"
1022 nil t)
1023 (push (match-string 2) table)))
1024 table))
1025
1026 (defun vc-git-revision-completion-table (files)
1027 (letrec ((table (lazy-completion-table
1028 table (lambda () (vc-git-revision-table files)))))
1029 table))
1030
1031 (defun vc-git-annotate-command (file buf &optional rev)
1032 (let ((name (file-relative-name file)))
1033 (apply #'vc-git-command buf 'async nil "blame" "--date=iso"
1034 (append (vc-switches 'git 'annotate)
1035 (list rev "--" name)))))
1036
1037 (declare-function vc-annotate-convert-time "vc-annotate" (time))
1038
1039 (defun vc-git-annotate-time ()
1040 (and (re-search-forward "[0-9a-f]+[^()]+(.* \\([0-9]+\\)-\\([0-9]+\\)-\\([0-9]+\\) \\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\) \\([-+0-9]+\\) +[0-9]+) " nil t)
1041 (vc-annotate-convert-time
1042 (apply #'encode-time (mapcar (lambda (match)
1043 (string-to-number (match-string match)))
1044 '(6 5 4 3 2 1 7))))))
1045
1046 (defun vc-git-annotate-extract-revision-at-line ()
1047 (save-excursion
1048 (beginning-of-line)
1049 (when (looking-at "\\([0-9a-f^][0-9a-f]+\\) \\(\\([^(]+\\) \\)?")
1050 (let ((revision (match-string-no-properties 1)))
1051 (if (match-beginning 2)
1052 (let ((fname (match-string-no-properties 3)))
1053 ;; Remove trailing whitespace from the file name.
1054 (when (string-match " +\\'" fname)
1055 (setq fname (substring fname 0 (match-beginning 0))))
1056 (cons revision
1057 (expand-file-name fname (vc-git-root default-directory))))
1058 revision)))))
1059
1060 ;;; TAG SYSTEM
1061
1062 (defun vc-git-create-tag (dir name branchp)
1063 (let ((default-directory dir))
1064 (and (vc-git-command nil 0 nil "update-index" "--refresh")
1065 (if branchp
1066 (vc-git-command nil 0 nil "checkout" "-b" name)
1067 (vc-git-command nil 0 nil "tag" name)))))
1068
1069 (defun vc-git-retrieve-tag (dir name _update)
1070 (let ((default-directory dir))
1071 (vc-git-command nil 0 nil "checkout" name)
1072 ;; FIXME: update buffers if `update' is true
1073 ))
1074
1075
1076 ;;; MISCELLANEOUS
1077
1078 (defun vc-git-previous-revision (file rev)
1079 "Git-specific version of `vc-previous-revision'."
1080 (if file
1081 (let* ((fname (file-relative-name file))
1082 (prev-rev (with-temp-buffer
1083 (and
1084 (vc-git--out-ok "rev-list" "-2" rev "--" fname)
1085 (goto-char (point-max))
1086 (bolp)
1087 (zerop (forward-line -1))
1088 (not (bobp))
1089 (buffer-substring-no-properties
1090 (point)
1091 (1- (point-max)))))))
1092 (or (vc-git-symbolic-commit prev-rev) prev-rev))
1093 ;; We used to use "^" here, but that fails on MS-Windows if git is
1094 ;; invoked via a batch file, in which case cmd.exe strips the "^"
1095 ;; because it is a special character for cmd which process-file
1096 ;; does not (and cannot) quote.
1097 (vc-git--rev-parse (concat rev "~1"))))
1098
1099 (defun vc-git--rev-parse (rev)
1100 (with-temp-buffer
1101 (and
1102 (vc-git--out-ok "rev-parse" rev)
1103 (buffer-substring-no-properties (point-min) (+ (point-min) 40)))))
1104
1105 (defun vc-git-next-revision (file rev)
1106 "Git-specific version of `vc-next-revision'."
1107 (let* ((default-directory (file-name-directory
1108 (expand-file-name file)))
1109 (file (file-name-nondirectory file))
1110 (current-rev
1111 (with-temp-buffer
1112 (and
1113 (vc-git--out-ok "rev-list" "-1" rev "--" file)
1114 (goto-char (point-max))
1115 (bolp)
1116 (zerop (forward-line -1))
1117 (bobp)
1118 (buffer-substring-no-properties
1119 (point)
1120 (1- (point-max))))))
1121 (next-rev
1122 (and current-rev
1123 (with-temp-buffer
1124 (and
1125 (vc-git--out-ok "rev-list" "HEAD" "--" file)
1126 (goto-char (point-min))
1127 (search-forward current-rev nil t)
1128 (zerop (forward-line -1))
1129 (buffer-substring-no-properties
1130 (point)
1131 (progn (forward-line 1) (1- (point)))))))))
1132 (or (vc-git-symbolic-commit next-rev) next-rev)))
1133
1134 (defun vc-git-delete-file (file)
1135 (vc-git-command nil 0 file "rm" "-f" "--"))
1136
1137 (defun vc-git-rename-file (old new)
1138 (vc-git-command nil 0 (list old new) "mv" "-f" "--"))
1139
1140 (defvar vc-git-extra-menu-map
1141 (let ((map (make-sparse-keymap)))
1142 (define-key map [git-grep]
1143 '(menu-item "Git grep..." vc-git-grep
1144 :help "Run the `git grep' command"))
1145 (define-key map [git-sn]
1146 '(menu-item "Stash a Snapshot" vc-git-stash-snapshot
1147 :help "Stash the current state of the tree and keep the current state"))
1148 (define-key map [git-st]
1149 '(menu-item "Create Stash..." vc-git-stash
1150 :help "Stash away changes"))
1151 (define-key map [git-ss]
1152 '(menu-item "Show Stash..." vc-git-stash-show
1153 :help "Show stash contents"))
1154 map))
1155
1156 (defun vc-git-extra-menu () vc-git-extra-menu-map)
1157
1158 (defun vc-git-extra-status-menu () vc-git-extra-menu-map)
1159
1160 (defun vc-git-root (file)
1161 (or (vc-file-getprop file 'git-root)
1162 (vc-file-setprop file 'git-root (vc-find-root file ".git"))))
1163
1164 ;; grep-compute-defaults autoloads grep.
1165 (declare-function grep-read-regexp "grep" ())
1166 (declare-function grep-read-files "grep" (regexp))
1167 (declare-function grep-expand-template "grep"
1168 (template &optional regexp files dir excl))
1169
1170 ;; Derived from `lgrep'.
1171 (defun vc-git-grep (regexp &optional files dir)
1172 "Run git grep, searching for REGEXP in FILES in directory DIR.
1173 The search is limited to file names matching shell pattern FILES.
1174 FILES may use abbreviations defined in `grep-files-aliases', e.g.
1175 entering `ch' is equivalent to `*.[ch]'.
1176
1177 With \\[universal-argument] prefix, you can edit the constructed shell command line
1178 before it is executed.
1179 With two \\[universal-argument] prefixes, directly edit and run `grep-command'.
1180
1181 Collect output in a buffer. While git grep runs asynchronously, you
1182 can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
1183 in the grep output buffer,
1184 to go to the lines where grep found matches.
1185
1186 This command shares argument histories with \\[rgrep] and \\[grep]."
1187 (interactive
1188 (progn
1189 (grep-compute-defaults)
1190 (cond
1191 ((equal current-prefix-arg '(16))
1192 (list (read-from-minibuffer "Run: " "git grep"
1193 nil nil 'grep-history)
1194 nil))
1195 (t (let* ((regexp (grep-read-regexp))
1196 (files (grep-read-files regexp))
1197 (dir (read-directory-name "In directory: "
1198 nil default-directory t)))
1199 (list regexp files dir))))))
1200 (require 'grep)
1201 (when (and (stringp regexp) (> (length regexp) 0))
1202 (let ((command regexp))
1203 (if (null files)
1204 (if (string= command "git grep")
1205 (setq command nil))
1206 (setq dir (file-name-as-directory (expand-file-name dir)))
1207 (setq command
1208 (grep-expand-template "git --no-pager grep -n -e <R> -- <F>"
1209 regexp files))
1210 (when command
1211 (if (equal current-prefix-arg '(4))
1212 (setq command
1213 (read-from-minibuffer "Confirm: "
1214 command nil nil 'grep-history))
1215 (add-to-history 'grep-history command))))
1216 (when command
1217 (let ((default-directory dir)
1218 (compilation-environment (cons "PAGER=" compilation-environment)))
1219 ;; Setting process-setup-function makes exit-message-function work
1220 ;; even when async processes aren't supported.
1221 (compilation-start command 'grep-mode))
1222 (if (eq next-error-last-buffer (current-buffer))
1223 (setq default-directory dir))))))
1224
1225 ;; Everywhere but here, follows vc-git-command, which uses vc-do-command
1226 ;; from vc-dispatcher.
1227 (autoload 'vc-resynch-buffer "vc-dispatcher")
1228
1229 (defun vc-git-stash (name)
1230 "Create a stash."
1231 (interactive "sStash name: ")
1232 (let ((root (vc-git-root default-directory)))
1233 (when root
1234 (vc-git--call nil "stash" "save" name)
1235 (vc-resynch-buffer root t t))))
1236
1237 (defun vc-git-stash-show (name)
1238 "Show the contents of stash NAME."
1239 (interactive "sStash name: ")
1240 (vc-setup-buffer "*vc-git-stash*")
1241 (vc-git-command "*vc-git-stash*" 'async nil "stash" "show" "-p" name)
1242 (set-buffer "*vc-git-stash*")
1243 (diff-mode)
1244 (setq buffer-read-only t)
1245 (pop-to-buffer (current-buffer)))
1246
1247 (defun vc-git-stash-apply (name)
1248 "Apply stash NAME."
1249 (interactive "sApply stash: ")
1250 (vc-git-command "*vc-git-stash*" 0 nil "stash" "apply" "-q" name)
1251 (vc-resynch-buffer (vc-git-root default-directory) t t))
1252
1253 (defun vc-git-stash-pop (name)
1254 "Pop stash NAME."
1255 (interactive "sPop stash: ")
1256 (vc-git-command "*vc-git-stash*" 0 nil "stash" "pop" "-q" name)
1257 (vc-resynch-buffer (vc-git-root default-directory) t t))
1258
1259 (defun vc-git-stash-snapshot ()
1260 "Create a stash with the current tree state."
1261 (interactive)
1262 (vc-git--call nil "stash" "save"
1263 (let ((ct (current-time)))
1264 (concat
1265 (format-time-string "Snapshot on %Y-%m-%d" ct)
1266 (format-time-string " at %H:%M" ct))))
1267 (vc-git-command "*vc-git-stash*" 0 nil "stash" "apply" "-q" "stash@{0}")
1268 (vc-resynch-buffer (vc-git-root default-directory) t t))
1269
1270 (defun vc-git-stash-list ()
1271 (delete
1272 ""
1273 (split-string
1274 (replace-regexp-in-string
1275 "^stash@" " " (vc-git--run-command-string nil "stash" "list"))
1276 "\n")))
1277
1278 (defun vc-git-stash-get-at-point (point)
1279 (save-excursion
1280 (goto-char point)
1281 (beginning-of-line)
1282 (if (looking-at "^ +\\({[0-9]+}\\):")
1283 (match-string 1)
1284 (error "Cannot find stash at point"))))
1285
1286 ;; vc-git-stash-delete-at-point must be called from a vc-dir buffer.
1287 (declare-function vc-dir-refresh "vc-dir" ())
1288
1289 (defun vc-git-stash-delete-at-point ()
1290 (interactive)
1291 (let ((stash (vc-git-stash-get-at-point (point))))
1292 (when (y-or-n-p (format "Remove stash %s ? " stash))
1293 (vc-git--run-command-string nil "stash" "drop" (format "stash@%s" stash))
1294 (vc-dir-refresh))))
1295
1296 (defun vc-git-stash-show-at-point ()
1297 (interactive)
1298 (vc-git-stash-show (format "stash@%s" (vc-git-stash-get-at-point (point)))))
1299
1300 (defun vc-git-stash-apply-at-point ()
1301 (interactive)
1302 (vc-git-stash-apply (format "stash@%s" (vc-git-stash-get-at-point (point)))))
1303
1304 (defun vc-git-stash-pop-at-point ()
1305 (interactive)
1306 (vc-git-stash-pop (format "stash@%s" (vc-git-stash-get-at-point (point)))))
1307
1308 (defun vc-git-stash-menu (e)
1309 (interactive "e")
1310 (vc-dir-at-event e (popup-menu vc-git-stash-menu-map e)))
1311
1312 \f
1313 ;;; Internal commands
1314
1315 (defun vc-git-command (buffer okstatus file-or-list &rest flags)
1316 "A wrapper around `vc-do-command' for use in vc-git.el.
1317 The difference to vc-do-command is that this function always invokes
1318 `vc-git-program'."
1319 (let ((coding-system-for-read vc-git-commits-coding-system)
1320 (coding-system-for-write vc-git-commits-coding-system))
1321 (apply 'vc-do-command (or buffer "*vc*") okstatus vc-git-program
1322 ;; http://debbugs.gnu.org/16897
1323 (unless (and (not (cdr-safe file-or-list))
1324 (let ((file (or (car-safe file-or-list)
1325 file-or-list)))
1326 (and file
1327 (eq ?/ (aref file (1- (length file))))
1328 (equal file (vc-git-root file)))))
1329 file-or-list)
1330 (cons "--no-pager" flags))))
1331
1332 (defun vc-git--empty-db-p ()
1333 "Check if the git db is empty (no commit done yet)."
1334 (let (process-file-side-effects)
1335 (not (eq 0 (vc-git--call nil "rev-parse" "--verify" "HEAD")))))
1336
1337 (defun vc-git--call (buffer command &rest args)
1338 ;; We don't need to care the arguments. If there is a file name, it
1339 ;; is always a relative one. This works also for remote
1340 ;; directories. We enable `inhibit-null-byte-detection', otherwise
1341 ;; Tramp's eol conversion might be confused.
1342 (let ((inhibit-null-byte-detection t)
1343 (coding-system-for-read vc-git-commits-coding-system)
1344 (coding-system-for-write vc-git-commits-coding-system)
1345 (process-environment (cons "PAGER=" process-environment)))
1346 (apply 'process-file vc-git-program nil buffer nil command args)))
1347
1348 (defun vc-git--out-ok (command &rest args)
1349 (zerop (apply 'vc-git--call '(t nil) command args)))
1350
1351 (defun vc-git--run-command-string (file &rest args)
1352 "Run a git command on FILE and return its output as string.
1353 FILE can be nil."
1354 (let* ((ok t)
1355 (str (with-output-to-string
1356 (with-current-buffer standard-output
1357 (unless (apply 'vc-git--out-ok
1358 (if file
1359 (append args (list (file-relative-name
1360 file)))
1361 args))
1362 (setq ok nil))))))
1363 (and ok str)))
1364
1365 (defun vc-git-symbolic-commit (commit)
1366 "Translate COMMIT string into symbolic form.
1367 Returns nil if not possible."
1368 (and commit
1369 (let ((name (with-temp-buffer
1370 (and
1371 (vc-git--out-ok "name-rev" "--name-only" commit)
1372 (goto-char (point-min))
1373 (= (forward-line 2) 1)
1374 (bolp)
1375 (buffer-substring-no-properties (point-min)
1376 (1- (point-max)))))))
1377 (and name (not (string= name "undefined")) name))))
1378
1379 (provide 'vc-git)
1380
1381 ;;; vc-git.el ends here