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