]> code.delx.au - gnu-emacs/blob - lisp/vc/vc-git.el
Merge from emacs-24; up to 2014-06-29T18:32:35Z!michael.albinus@gmx.de
[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 editable 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 _rev 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 _editable 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 (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 (vc-git-conflicted-files buffer-file-name)
802 (save-excursion
803 (goto-char (point-min))
804 (re-search-forward "^<<<<<<< " nil 'noerror)))
805 (vc-file-setprop buffer-file-name 'vc-state 'conflict)
806 (smerge-start-session)
807 (add-hook 'after-save-hook 'vc-git-resolve-when-done nil 'local)
808 (message "There are unresolved conflicts in this file")))
809
810 ;;; HISTORY FUNCTIONS
811
812 (autoload 'vc-setup-buffer "vc-dispatcher")
813
814 (defun vc-git-print-log (files buffer &optional shortlog start-revision limit)
815 "Print commit log associated with FILES into specified BUFFER.
816 If SHORTLOG is non-nil, use a short format based on `vc-git-root-log-format'.
817 \(This requires at least Git version 1.5.6, for the --graph option.)
818 If START-REVISION is non-nil, it is the newest revision to show.
819 If LIMIT is non-nil, show no more than this many entries."
820 (let ((coding-system-for-read vc-git-commits-coding-system))
821 ;; `vc-do-command' creates the buffer, but we need it before running
822 ;; the command.
823 (vc-setup-buffer buffer)
824 ;; If the buffer exists from a previous invocation it might be
825 ;; read-only.
826 (let ((inhibit-read-only t))
827 (with-current-buffer
828 buffer
829 (apply 'vc-git-command buffer
830 'async files
831 (append
832 '("log" "--no-color")
833 (when shortlog
834 `("--graph" "--decorate" "--date=short"
835 ,(format "--pretty=tformat:%s"
836 (car vc-git-root-log-format))
837 "--abbrev-commit"))
838 (when limit (list "-n" (format "%s" limit)))
839 (when start-revision (list start-revision))
840 '("--")))))))
841
842 (defun vc-git-log-outgoing (buffer remote-location)
843 (interactive)
844 (vc-git-command
845 buffer 0 nil
846 "log"
847 "--no-color" "--graph" "--decorate" "--date=short"
848 (format "--pretty=tformat:%s" (car vc-git-root-log-format))
849 "--abbrev-commit"
850 (concat (if (string= remote-location "")
851 "@{upstream}"
852 remote-location)
853 "..HEAD")))
854
855 (defun vc-git-log-incoming (buffer remote-location)
856 (interactive)
857 (vc-git-command nil 0 nil "fetch")
858 (vc-git-command
859 buffer 0 nil
860 "log"
861 "--no-color" "--graph" "--decorate" "--date=short"
862 (format "--pretty=tformat:%s" (car vc-git-root-log-format))
863 "--abbrev-commit"
864 (concat "HEAD.." (if (string= remote-location "")
865 "@{upstream}"
866 remote-location))))
867
868 (defvar log-view-message-re)
869 (defvar log-view-file-re)
870 (defvar log-view-font-lock-keywords)
871 (defvar log-view-per-file-logs)
872 (defvar log-view-expanded-log-entry-function)
873
874 (define-derived-mode vc-git-log-view-mode log-view-mode "Git-Log-View"
875 (require 'add-log) ;; We need the faces add-log.
876 ;; Don't have file markers, so use impossible regexp.
877 (set (make-local-variable 'log-view-file-re) "\\`a\\`")
878 (set (make-local-variable 'log-view-per-file-logs) nil)
879 (set (make-local-variable 'log-view-message-re)
880 (if (not (eq vc-log-view-type 'long))
881 (cadr vc-git-root-log-format)
882 "^commit *\\([0-9a-z]+\\)"))
883 ;; Allow expanding short log entries
884 (when (eq vc-log-view-type 'short)
885 (setq truncate-lines t)
886 (set (make-local-variable 'log-view-expanded-log-entry-function)
887 'vc-git-expanded-log-entry))
888 (set (make-local-variable 'log-view-font-lock-keywords)
889 (if (not (eq vc-log-view-type 'long))
890 (list (cons (nth 1 vc-git-root-log-format)
891 (nth 2 vc-git-root-log-format)))
892 (append
893 `((,log-view-message-re (1 'change-log-acknowledgment)))
894 ;; Handle the case:
895 ;; user: foo@bar
896 '(("^Author:[ \t]+\\([A-Za-z0-9_.+-]+@[A-Za-z0-9_.-]+\\)"
897 (1 'change-log-email))
898 ;; Handle the case:
899 ;; user: FirstName LastName <foo@bar>
900 ("^Author:[ \t]+\\([^<(]+?\\)[ \t]*[(<]\\([A-Za-z0-9_.+-]+@[A-Za-z0-9_.-]+\\)[>)]"
901 (1 'change-log-name)
902 (2 'change-log-email))
903 ("^ +\\(?:\\(?:[Aa]cked\\|[Ss]igned-[Oo]ff\\)-[Bb]y:\\)[ \t]+\\([A-Za-z0-9_.+-]+@[A-Za-z0-9_.-]+\\)"
904 (1 'change-log-name))
905 ("^ +\\(?:\\(?:[Aa]cked\\|[Ss]igned-[Oo]ff\\)-[Bb]y:\\)[ \t]+\\([^<(]+?\\)[ \t]*[(<]\\([A-Za-z0-9_.+-]+@[A-Za-z0-9_.-]+\\)[>)]"
906 (1 'change-log-name)
907 (2 'change-log-email))
908 ("^Merge: \\([0-9a-z]+\\) \\([0-9a-z]+\\)"
909 (1 'change-log-acknowledgment)
910 (2 'change-log-acknowledgment))
911 ("^Date: \\(.+\\)" (1 'change-log-date))
912 ("^summary:[ \t]+\\(.+\\)" (1 'log-view-message)))))))
913
914
915 (defun vc-git-show-log-entry (revision)
916 "Move to the log entry for REVISION.
917 REVISION may have the form BRANCH, BRANCH~N,
918 or BRANCH^ (where \"^\" can be repeated)."
919 (goto-char (point-min))
920 (prog1
921 (when revision
922 (search-forward
923 (format "\ncommit %s" revision) nil t
924 (cond ((string-match "~\\([0-9]\\)\\'" revision)
925 (1+ (string-to-number (match-string 1 revision))))
926 ((string-match "\\^+\\'" revision)
927 (1+ (length (match-string 0 revision))))
928 (t nil))))
929 (beginning-of-line)))
930
931 (defun vc-git-expanded-log-entry (revision)
932 (with-temp-buffer
933 (apply 'vc-git-command t nil nil (list "log" revision "-1"))
934 (goto-char (point-min))
935 (unless (eobp)
936 ;; Indent the expanded log entry.
937 (indent-region (point-min) (point-max) 2)
938 (buffer-string))))
939
940 (autoload 'vc-switches "vc")
941
942 (defun vc-git-diff (files &optional rev1 rev2 buffer)
943 "Get a difference report using Git between two revisions of FILES."
944 (let (process-file-side-effects)
945 (apply #'vc-git-command (or buffer "*vc-diff*") 1 files
946 (if (and rev1 rev2) "diff-tree" "diff-index")
947 "--exit-code"
948 (append (vc-switches 'git 'diff)
949 (list "-p" (or rev1 "HEAD") rev2 "--")))))
950
951 (defun vc-git-revision-table (_files)
952 ;; What about `files'?!? --Stef
953 (let (process-file-side-effects
954 (table (list "HEAD")))
955 (with-temp-buffer
956 (vc-git-command t nil nil "for-each-ref" "--format=%(refname)")
957 (goto-char (point-min))
958 (while (re-search-forward "^refs/\\(heads\\|tags\\|remotes\\)/\\(.*\\)$"
959 nil t)
960 (push (match-string 2) table)))
961 table))
962
963 (defun vc-git-revision-completion-table (files)
964 (letrec ((table (lazy-completion-table
965 table (lambda () (vc-git-revision-table files)))))
966 table))
967
968 (defun vc-git-annotate-command (file buf &optional rev)
969 (let ((name (file-relative-name file)))
970 (vc-git-command buf 'async nil "blame" "--date=iso" "-C" "-C" rev "--" name)))
971
972 (declare-function vc-annotate-convert-time "vc-annotate" (time))
973
974 (defun vc-git-annotate-time ()
975 (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)
976 (vc-annotate-convert-time
977 (apply #'encode-time (mapcar (lambda (match)
978 (string-to-number (match-string match)))
979 '(6 5 4 3 2 1 7))))))
980
981 (defun vc-git-annotate-extract-revision-at-line ()
982 (save-excursion
983 (beginning-of-line)
984 (when (looking-at "\\([0-9a-f^][0-9a-f]+\\) \\(\\([^(]+\\) \\)?")
985 (let ((revision (match-string-no-properties 1)))
986 (if (match-beginning 2)
987 (let ((fname (match-string-no-properties 3)))
988 ;; Remove trailing whitespace from the file name.
989 (when (string-match " +\\'" fname)
990 (setq fname (substring fname 0 (match-beginning 0))))
991 (cons revision
992 (expand-file-name fname (vc-git-root default-directory))))
993 revision)))))
994
995 ;;; TAG SYSTEM
996
997 (defun vc-git-create-tag (dir name branchp)
998 (let ((default-directory dir))
999 (and (vc-git-command nil 0 nil "update-index" "--refresh")
1000 (if branchp
1001 (vc-git-command nil 0 nil "checkout" "-b" name)
1002 (vc-git-command nil 0 nil "tag" name)))))
1003
1004 (defun vc-git-retrieve-tag (dir name _update)
1005 (let ((default-directory dir))
1006 (vc-git-command nil 0 nil "checkout" name)
1007 ;; FIXME: update buffers if `update' is true
1008 ))
1009
1010
1011 ;;; MISCELLANEOUS
1012
1013 (defun vc-git-previous-revision (file rev)
1014 "Git-specific version of `vc-previous-revision'."
1015 (if file
1016 (let* ((fname (file-relative-name file))
1017 (prev-rev (with-temp-buffer
1018 (and
1019 (vc-git--out-ok "rev-list" "-2" rev "--" fname)
1020 (goto-char (point-max))
1021 (bolp)
1022 (zerop (forward-line -1))
1023 (not (bobp))
1024 (buffer-substring-no-properties
1025 (point)
1026 (1- (point-max)))))))
1027 (or (vc-git-symbolic-commit prev-rev) prev-rev))
1028 (vc-git--rev-parse (concat rev "^"))))
1029
1030 (defun vc-git--rev-parse (rev)
1031 (with-temp-buffer
1032 (and
1033 (vc-git--out-ok "rev-parse" rev)
1034 (buffer-substring-no-properties (point-min) (+ (point-min) 40)))))
1035
1036 (defun vc-git-next-revision (file rev)
1037 "Git-specific version of `vc-next-revision'."
1038 (let* ((default-directory (file-name-directory
1039 (expand-file-name file)))
1040 (file (file-name-nondirectory file))
1041 (current-rev
1042 (with-temp-buffer
1043 (and
1044 (vc-git--out-ok "rev-list" "-1" rev "--" file)
1045 (goto-char (point-max))
1046 (bolp)
1047 (zerop (forward-line -1))
1048 (bobp)
1049 (buffer-substring-no-properties
1050 (point)
1051 (1- (point-max))))))
1052 (next-rev
1053 (and current-rev
1054 (with-temp-buffer
1055 (and
1056 (vc-git--out-ok "rev-list" "HEAD" "--" file)
1057 (goto-char (point-min))
1058 (search-forward current-rev nil t)
1059 (zerop (forward-line -1))
1060 (buffer-substring-no-properties
1061 (point)
1062 (progn (forward-line 1) (1- (point)))))))))
1063 (or (vc-git-symbolic-commit next-rev) next-rev)))
1064
1065 (defun vc-git-delete-file (file)
1066 (vc-git-command nil 0 file "rm" "-f" "--"))
1067
1068 (defun vc-git-rename-file (old new)
1069 (vc-git-command nil 0 (list old new) "mv" "-f" "--"))
1070
1071 (defvar vc-git-extra-menu-map
1072 (let ((map (make-sparse-keymap)))
1073 (define-key map [git-grep]
1074 '(menu-item "Git grep..." vc-git-grep
1075 :help "Run the `git grep' command"))
1076 (define-key map [git-sn]
1077 '(menu-item "Stash a Snapshot" vc-git-stash-snapshot
1078 :help "Stash the current state of the tree and keep the current state"))
1079 (define-key map [git-st]
1080 '(menu-item "Create Stash..." vc-git-stash
1081 :help "Stash away changes"))
1082 (define-key map [git-ss]
1083 '(menu-item "Show Stash..." vc-git-stash-show
1084 :help "Show stash contents"))
1085 map))
1086
1087 (defun vc-git-extra-menu () vc-git-extra-menu-map)
1088
1089 (defun vc-git-extra-status-menu () vc-git-extra-menu-map)
1090
1091 (defun vc-git-root (file)
1092 (or (vc-file-getprop file 'git-root)
1093 (vc-file-setprop file 'git-root (vc-find-root file ".git"))))
1094
1095 ;; grep-compute-defaults autoloads grep.
1096 (declare-function grep-read-regexp "grep" ())
1097 (declare-function grep-read-files "grep" (regexp))
1098 (declare-function grep-expand-template "grep"
1099 (template &optional regexp files dir excl))
1100
1101 ;; Derived from `lgrep'.
1102 (defun vc-git-grep (regexp &optional files dir)
1103 "Run git grep, searching for REGEXP in FILES in directory DIR.
1104 The search is limited to file names matching shell pattern FILES.
1105 FILES may use abbreviations defined in `grep-files-aliases', e.g.
1106 entering `ch' is equivalent to `*.[ch]'.
1107
1108 With \\[universal-argument] prefix, you can edit the constructed shell command line
1109 before it is executed.
1110 With two \\[universal-argument] prefixes, directly edit and run `grep-command'.
1111
1112 Collect output in a buffer. While git grep runs asynchronously, you
1113 can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
1114 in the grep output buffer,
1115 to go to the lines where grep found matches.
1116
1117 This command shares argument histories with \\[rgrep] and \\[grep]."
1118 (interactive
1119 (progn
1120 (grep-compute-defaults)
1121 (cond
1122 ((equal current-prefix-arg '(16))
1123 (list (read-from-minibuffer "Run: " "git grep"
1124 nil nil 'grep-history)
1125 nil))
1126 (t (let* ((regexp (grep-read-regexp))
1127 (files (grep-read-files regexp))
1128 (dir (read-directory-name "In directory: "
1129 nil default-directory t)))
1130 (list regexp files dir))))))
1131 (require 'grep)
1132 (when (and (stringp regexp) (> (length regexp) 0))
1133 (let ((command regexp))
1134 (if (null files)
1135 (if (string= command "git grep")
1136 (setq command nil))
1137 (setq dir (file-name-as-directory (expand-file-name dir)))
1138 (setq command
1139 (grep-expand-template "git --no-pager grep -n -e <R> -- <F>"
1140 regexp files))
1141 (when command
1142 (if (equal current-prefix-arg '(4))
1143 (setq command
1144 (read-from-minibuffer "Confirm: "
1145 command nil nil 'grep-history))
1146 (add-to-history 'grep-history command))))
1147 (when command
1148 (let ((default-directory dir)
1149 (compilation-environment (cons "PAGER=" compilation-environment)))
1150 ;; Setting process-setup-function makes exit-message-function work
1151 ;; even when async processes aren't supported.
1152 (compilation-start command 'grep-mode))
1153 (if (eq next-error-last-buffer (current-buffer))
1154 (setq default-directory dir))))))
1155
1156 ;; Everywhere but here, follows vc-git-command, which uses vc-do-command
1157 ;; from vc-dispatcher.
1158 (autoload 'vc-resynch-buffer "vc-dispatcher")
1159
1160 (defun vc-git-stash (name)
1161 "Create a stash."
1162 (interactive "sStash name: ")
1163 (let ((root (vc-git-root default-directory)))
1164 (when root
1165 (vc-git--call nil "stash" "save" name)
1166 (vc-resynch-buffer root t t))))
1167
1168 (defun vc-git-stash-show (name)
1169 "Show the contents of stash NAME."
1170 (interactive "sStash name: ")
1171 (vc-setup-buffer "*vc-git-stash*")
1172 (vc-git-command "*vc-git-stash*" 'async nil "stash" "show" "-p" name)
1173 (set-buffer "*vc-git-stash*")
1174 (diff-mode)
1175 (setq buffer-read-only t)
1176 (pop-to-buffer (current-buffer)))
1177
1178 (defun vc-git-stash-apply (name)
1179 "Apply stash NAME."
1180 (interactive "sApply stash: ")
1181 (vc-git-command "*vc-git-stash*" 0 nil "stash" "apply" "-q" name)
1182 (vc-resynch-buffer (vc-git-root default-directory) t t))
1183
1184 (defun vc-git-stash-pop (name)
1185 "Pop stash NAME."
1186 (interactive "sPop stash: ")
1187 (vc-git-command "*vc-git-stash*" 0 nil "stash" "pop" "-q" name)
1188 (vc-resynch-buffer (vc-git-root default-directory) t t))
1189
1190 (defun vc-git-stash-snapshot ()
1191 "Create a stash with the current tree state."
1192 (interactive)
1193 (vc-git--call nil "stash" "save"
1194 (let ((ct (current-time)))
1195 (concat
1196 (format-time-string "Snapshot on %Y-%m-%d" ct)
1197 (format-time-string " at %H:%M" ct))))
1198 (vc-git-command "*vc-git-stash*" 0 nil "stash" "apply" "-q" "stash@{0}")
1199 (vc-resynch-buffer (vc-git-root default-directory) t t))
1200
1201 (defun vc-git-stash-list ()
1202 (delete
1203 ""
1204 (split-string
1205 (replace-regexp-in-string
1206 "^stash@" " " (vc-git--run-command-string nil "stash" "list"))
1207 "\n")))
1208
1209 (defun vc-git-stash-get-at-point (point)
1210 (save-excursion
1211 (goto-char point)
1212 (beginning-of-line)
1213 (if (looking-at "^ +\\({[0-9]+}\\):")
1214 (match-string 1)
1215 (error "Cannot find stash at point"))))
1216
1217 ;; vc-git-stash-delete-at-point must be called from a vc-dir buffer.
1218 (declare-function vc-dir-refresh "vc-dir" ())
1219
1220 (defun vc-git-stash-delete-at-point ()
1221 (interactive)
1222 (let ((stash (vc-git-stash-get-at-point (point))))
1223 (when (y-or-n-p (format "Remove stash %s ? " stash))
1224 (vc-git--run-command-string nil "stash" "drop" (format "stash@%s" stash))
1225 (vc-dir-refresh))))
1226
1227 (defun vc-git-stash-show-at-point ()
1228 (interactive)
1229 (vc-git-stash-show (format "stash@%s" (vc-git-stash-get-at-point (point)))))
1230
1231 (defun vc-git-stash-apply-at-point ()
1232 (interactive)
1233 (vc-git-stash-apply (format "stash@%s" (vc-git-stash-get-at-point (point)))))
1234
1235 (defun vc-git-stash-pop-at-point ()
1236 (interactive)
1237 (vc-git-stash-pop (format "stash@%s" (vc-git-stash-get-at-point (point)))))
1238
1239 (defun vc-git-stash-menu (e)
1240 (interactive "e")
1241 (vc-dir-at-event e (popup-menu vc-git-stash-menu-map e)))
1242
1243 \f
1244 ;;; Internal commands
1245
1246 (defun vc-git-command (buffer okstatus file-or-list &rest flags)
1247 "A wrapper around `vc-do-command' for use in vc-git.el.
1248 The difference to vc-do-command is that this function always invokes
1249 `vc-git-program'."
1250 (apply 'vc-do-command (or buffer "*vc*") okstatus vc-git-program
1251 ;; http://debbugs.gnu.org/16897
1252 (unless (and (not (cdr-safe file-or-list))
1253 (let ((file (or (car-safe file-or-list)
1254 file-or-list)))
1255 (and file
1256 (eq ?/ (aref file (1- (length file))))
1257 (equal file (vc-git-root file)))))
1258 file-or-list)
1259 (cons "--no-pager" flags)))
1260
1261 (defun vc-git--empty-db-p ()
1262 "Check if the git db is empty (no commit done yet)."
1263 (let (process-file-side-effects)
1264 (not (eq 0 (vc-git--call nil "rev-parse" "--verify" "HEAD")))))
1265
1266 (defun vc-git--call (buffer command &rest args)
1267 ;; We don't need to care the arguments. If there is a file name, it
1268 ;; is always a relative one. This works also for remote
1269 ;; directories. We enable `inhibit-null-byte-detection', otherwise
1270 ;; Tramp's eol conversion might be confused.
1271 (let ((inhibit-null-byte-detection t)
1272 (process-environment (cons "PAGER=" process-environment)))
1273 (apply 'process-file vc-git-program nil buffer nil command args)))
1274
1275 (defun vc-git--out-ok (command &rest args)
1276 (zerop (apply 'vc-git--call '(t nil) command args)))
1277
1278 (defun vc-git--run-command-string (file &rest args)
1279 "Run a git command on FILE and return its output as string.
1280 FILE can be nil."
1281 (let* ((ok t)
1282 (str (with-output-to-string
1283 (with-current-buffer standard-output
1284 (unless (apply 'vc-git--out-ok
1285 (if file
1286 (append args (list (file-relative-name
1287 file)))
1288 args))
1289 (setq ok nil))))))
1290 (and ok str)))
1291
1292 (defun vc-git-symbolic-commit (commit)
1293 "Translate COMMIT string into symbolic form.
1294 Returns nil if not possible."
1295 (and commit
1296 (let ((name (with-temp-buffer
1297 (and
1298 (vc-git--out-ok "name-rev" "--name-only" commit)
1299 (goto-char (point-min))
1300 (= (forward-line 2) 1)
1301 (bolp)
1302 (buffer-substring-no-properties (point-min)
1303 (1- (point-max)))))))
1304 (and name (not (string= name "undefined")) name))))
1305
1306 (provide 'vc-git)
1307
1308 ;;; vc-git.el ends here