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