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