* vc/vc-git.el (vc-git-registered): Use cache property
[emacs.git] / lisp / vc / vc-git.el
blob8b48efbfd247941ec27eec907f6e83fee68b40bf
1 ;;; vc-git.el --- VC backend for the git version control system -*- lexical-binding: t -*-
3 ;; Copyright (C) 2006-2012 Free Software Foundation, Inc.
5 ;; Author: Alexandre Julliard <julliard@winehq.org>
6 ;; Keywords: vc tools
7 ;; Package: vc
9 ;; This file is part of GNU Emacs.
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.
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.
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/>.
24 ;;; Commentary:
26 ;; This file contains a VC backend for the git version control
27 ;; system.
30 ;;; Installation:
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 ~/.emacs, will accomplish this:
36 ;; (add-to-list 'vc-handled-backends 'Git)
38 ;;; Todo:
39 ;; - check if more functions could use vc-git-command instead
40 ;; of start-process.
41 ;; - changelog generation
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")
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 () NOT NEEDED
106 (eval-when-compile
107 (require 'cl)
108 (require 'vc)
109 (require 'vc-dir)
110 (require 'grep))
112 (defgroup vc-git nil
113 "VC Git backend."
114 :version "24.1"
115 :group 'vc)
117 (defcustom vc-git-diff-switches t
118 "String or list of strings specifying switches for Git diff under VC.
119 If nil, use the value of `vc-diff-switches'. If t, use no switches."
120 :type '(choice (const :tag "Unspecified" nil)
121 (const :tag "None" t)
122 (string :tag "Argument String")
123 (repeat :tag "Argument List" :value ("") string))
124 :version "23.1"
125 :group 'vc-git)
127 (defcustom vc-git-program "git"
128 "Name of the Git executable (excluding any arguments)."
129 :version "24.1"
130 :type 'string
131 :group 'vc-git)
133 (defcustom vc-git-root-log-format
134 '("%d%h..: %an %ad %s"
135 ;; The first shy group matches the characters drawn by --graph.
136 ;; We use numbered groups because `log-view-message-re' wants the
137 ;; revision number to be group 1.
138 "^\\(?:[*/\\| ]+ \\)?\\(?2: ([^)]+)\\)?\\(?1:[0-9a-z]+\\)..: \
139 \\(?3:.*?\\)[ \t]+\\(?4:[0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\)"
140 ((1 'log-view-message-face)
141 (2 'change-log-list nil lax)
142 (3 'change-log-name)
143 (4 'change-log-date)))
144 "Git log format for `vc-print-root-log'.
145 This should be a list (FORMAT REGEXP KEYWORDS), where FORMAT is a
146 format string (which is passed to \"git log\" via the argument
147 \"--pretty=tformat:FORMAT\"), REGEXP is a regular expression
148 matching the resulting Git log output, and KEYWORDS is a list of
149 `font-lock-keywords' for highlighting the Log View buffer."
150 :type '(list string string (repeat sexp))
151 :group 'vc-git
152 :version "24.1")
154 (defvar vc-git-commits-coding-system 'utf-8
155 "Default coding system for git commits.")
157 ;; History of Git commands.
158 (defvar vc-git-history nil)
160 ;;; BACKEND PROPERTIES
162 (defun vc-git-revision-granularity () 'repository)
163 (defun vc-git-checkout-model (_files) 'implicit)
165 ;;; STATE-QUERYING FUNCTIONS
167 ;;;###autoload (defun vc-git-registered (file)
168 ;;;###autoload "Return non-nil if FILE is registered with git."
169 ;;;###autoload (if (vc-find-root file ".git") ; Short cut.
170 ;;;###autoload (progn
171 ;;;###autoload (load "vc-git")
172 ;;;###autoload (vc-git-registered file))))
174 (defun vc-git-registered (file)
175 "Check whether FILE is registered with git."
176 (or (vc-file-getprop file 'git-registered)
177 (vc-file-setprop
178 file 'git-registered
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"))))))))))
202 (defun vc-git--state-code (code)
203 "Convert from a string to a added/deleted/modified state."
204 (case (string-to-char code)
205 (?M 'edited)
206 (?A 'added)
207 (?D 'removed)
208 (?U 'edited) ;; FIXME
209 (?T 'edited))) ;; FIXME
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 (if (not (vc-git-registered file))
222 'unregistered
223 (let ((diff (vc-git--run-command-string
224 file "diff-index" "-p" "--raw" "-z" "HEAD" "--")))
225 (if (and diff
226 (string-match ":[0-7]\\{6\\} [0-7]\\{6\\} [0-9a-f]\\{40\\} [0-9a-f]\\{40\\} \\([ADMUT]\\)\0[^\0]+\0\\(.*\n.\\)?"
227 diff))
228 (let ((diff-letter (match-string 1 diff)))
229 (if (not (match-beginning 2))
230 ;; Empty diff: file contents is the same as the HEAD
231 ;; revision, but timestamps are different (eg, file
232 ;; was "touch"ed). Update timestamp in index:
233 (prog1 'up-to-date
234 (vc-git--call nil "add" "--refresh" "--"
235 (file-relative-name file)))
236 (vc-git--state-code diff-letter)))
237 (if (vc-git--empty-db-p) 'added 'up-to-date)))))
239 (defun vc-git-working-revision (_file)
240 "Git-specific version of `vc-working-revision'."
241 (let* (process-file-side-effects
242 (str (with-output-to-string
243 (with-current-buffer standard-output
244 (vc-git--out-ok "symbolic-ref" "HEAD")))))
245 (if (string-match "^\\(refs/heads/\\)?\\(.+\\)$" str)
246 (match-string 2 str)
247 str)))
249 (defun vc-git-workfile-unchanged-p (file)
250 (eq 'up-to-date (vc-git-state file)))
252 (defun vc-git-mode-line-string (file)
253 "Return a string for `vc-mode-line' to put in the mode line for FILE."
254 (let* ((branch (vc-working-revision file))
255 (def-ml (vc-default-mode-line-string 'Git file))
256 (help-echo (get-text-property 0 'help-echo def-ml)))
257 (if (zerop (length branch))
258 (propertize
259 (concat def-ml "!")
260 'help-echo (concat help-echo "\nNo current branch (detached HEAD)"))
261 (propertize def-ml
262 'help-echo (concat help-echo "\nCurrent branch: " branch)))))
264 (defstruct (vc-git-extra-fileinfo
265 (:copier nil)
266 (:constructor vc-git-create-extra-fileinfo
267 (old-perm new-perm &optional rename-state orig-name))
268 (:conc-name vc-git-extra-fileinfo->))
269 old-perm new-perm ;; Permission flags.
270 rename-state ;; Rename or copy state.
271 orig-name) ;; Original name for renames or copies.
273 (defun vc-git-escape-file-name (name)
274 "Escape a file name if necessary."
275 (if (string-match "[\n\t\"\\]" name)
276 (concat "\""
277 (mapconcat (lambda (c)
278 (case c
279 (?\n "\\n")
280 (?\t "\\t")
281 (?\\ "\\\\")
282 (?\" "\\\"")
283 (t (char-to-string c))))
284 name "")
285 "\"")
286 name))
288 (defun vc-git-file-type-as-string (old-perm new-perm)
289 "Return a string describing the file type based on its permissions."
290 (let* ((old-type (lsh (or old-perm 0) -9))
291 (new-type (lsh (or new-perm 0) -9))
292 (str (case new-type
293 (?\100 ;; File.
294 (case old-type
295 (?\100 nil)
296 (?\120 " (type change symlink -> file)")
297 (?\160 " (type change subproject -> file)")))
298 (?\120 ;; Symlink.
299 (case old-type
300 (?\100 " (type change file -> symlink)")
301 (?\160 " (type change subproject -> symlink)")
302 (t " (symlink)")))
303 (?\160 ;; Subproject.
304 (case old-type
305 (?\100 " (type change file -> subproject)")
306 (?\120 " (type change symlink -> subproject)")
307 (t " (subproject)")))
308 (?\110 nil) ;; Directory (internal, not a real git state).
309 (?\000 ;; Deleted or unknown.
310 (case old-type
311 (?\120 " (symlink)")
312 (?\160 " (subproject)")))
313 (t (format " (unknown type %o)" new-type)))))
314 (cond (str (propertize str 'face 'font-lock-comment-face))
315 ((eq new-type ?\110) "/")
316 (t ""))))
318 (defun vc-git-rename-as-string (state extra)
319 "Return a string describing the copy or rename associated with INFO,
320 or an empty string if none."
321 (let ((rename-state (when extra
322 (vc-git-extra-fileinfo->rename-state extra))))
323 (if rename-state
324 (propertize
325 (concat " ("
326 (if (eq rename-state 'copy) "copied from "
327 (if (eq state 'added) "renamed from "
328 "renamed to "))
329 (vc-git-escape-file-name
330 (vc-git-extra-fileinfo->orig-name extra))
331 ")")
332 'face 'font-lock-comment-face)
333 "")))
335 (defun vc-git-permissions-as-string (old-perm new-perm)
336 "Format a permission change as string."
337 (propertize
338 (if (or (not old-perm)
339 (not new-perm)
340 (eq 0 (logand ?\111 (logxor old-perm new-perm))))
342 (if (eq 0 (logand ?\111 old-perm)) "+x" "-x"))
343 'face 'font-lock-type-face))
345 (defun vc-git-dir-printer (info)
346 "Pretty-printer for the vc-dir-fileinfo structure."
347 (let* ((isdir (vc-dir-fileinfo->directory info))
348 (state (if isdir "" (vc-dir-fileinfo->state info)))
349 (extra (vc-dir-fileinfo->extra info))
350 (old-perm (when extra (vc-git-extra-fileinfo->old-perm extra)))
351 (new-perm (when extra (vc-git-extra-fileinfo->new-perm extra))))
352 (insert
354 (propertize (format "%c" (if (vc-dir-fileinfo->marked info) ?* ? ))
355 'face 'font-lock-type-face)
357 (propertize
358 (format "%-12s" state)
359 'face (cond ((eq state 'up-to-date) 'font-lock-builtin-face)
360 ((eq state 'missing) 'font-lock-warning-face)
361 (t 'font-lock-variable-name-face))
362 'mouse-face 'highlight)
363 " " (vc-git-permissions-as-string old-perm new-perm)
365 (propertize (vc-git-escape-file-name (vc-dir-fileinfo->name info))
366 'face (if isdir 'font-lock-comment-delimiter-face
367 'font-lock-function-name-face)
368 'help-echo
369 (if isdir
370 "Directory\nVC operations can be applied to it\nmouse-3: Pop-up menu"
371 "File\nmouse-3: Pop-up menu")
372 'keymap vc-dir-filename-mouse-map
373 'mouse-face 'highlight)
374 (vc-git-file-type-as-string old-perm new-perm)
375 (vc-git-rename-as-string state extra))))
377 (defun vc-git-after-dir-status-stage (stage files update-function)
378 "Process sentinel for the various dir-status stages."
379 (let (next-stage result)
380 (goto-char (point-min))
381 (case stage
382 (update-index
383 (setq next-stage (if (vc-git--empty-db-p) 'ls-files-added
384 (if files 'ls-files-up-to-date 'diff-index))))
385 (ls-files-added
386 (setq next-stage 'ls-files-unknown)
387 (while (re-search-forward "\\([0-7]\\{6\\}\\) [0-9a-f]\\{40\\} 0\t\\([^\0]+\\)\0" nil t)
388 (let ((new-perm (string-to-number (match-string 1) 8))
389 (name (match-string 2)))
390 (push (list name 'added (vc-git-create-extra-fileinfo 0 new-perm))
391 result))))
392 (ls-files-up-to-date
393 (setq next-stage 'diff-index)
394 (while (re-search-forward "\\([0-7]\\{6\\}\\) [0-9a-f]\\{40\\} 0\t\\([^\0]+\\)\0" nil t)
395 (let ((perm (string-to-number (match-string 1) 8))
396 (name (match-string 2)))
397 (push (list name 'up-to-date
398 (vc-git-create-extra-fileinfo perm perm))
399 result))))
400 (ls-files-unknown
401 (when files (setq next-stage 'ls-files-ignored))
402 (while (re-search-forward "\\([^\0]*?\\)\0" nil t 1)
403 (push (list (match-string 1) 'unregistered
404 (vc-git-create-extra-fileinfo 0 0))
405 result)))
406 (ls-files-ignored
407 (while (re-search-forward "\\([^\0]*?\\)\0" nil t 1)
408 (push (list (match-string 1) 'ignored
409 (vc-git-create-extra-fileinfo 0 0))
410 result)))
411 (diff-index
412 (setq next-stage 'ls-files-unknown)
413 (while (re-search-forward
414 ":\\([0-7]\\{6\\}\\) \\([0-7]\\{6\\}\\) [0-9a-f]\\{40\\} [0-9a-f]\\{40\\} \\(\\([ADMUT]\\)\0\\([^\0]+\\)\\|\\([CR]\\)[0-9]*\0\\([^\0]+\\)\0\\([^\0]+\\)\\)\0"
415 nil t 1)
416 (let ((old-perm (string-to-number (match-string 1) 8))
417 (new-perm (string-to-number (match-string 2) 8))
418 (state (or (match-string 4) (match-string 6)))
419 (name (or (match-string 5) (match-string 7)))
420 (new-name (match-string 8)))
421 (if new-name ; Copy or rename.
422 (if (eq ?C (string-to-char state))
423 (push (list new-name 'added
424 (vc-git-create-extra-fileinfo old-perm new-perm
425 'copy name))
426 result)
427 (push (list name 'removed
428 (vc-git-create-extra-fileinfo 0 0
429 'rename new-name))
430 result)
431 (push (list new-name 'added
432 (vc-git-create-extra-fileinfo old-perm new-perm
433 'rename name))
434 result))
435 (push (list name (vc-git--state-code state)
436 (vc-git-create-extra-fileinfo old-perm new-perm))
437 result))))))
438 (when result
439 (setq result (nreverse result))
440 (when files
441 (dolist (entry result) (setq files (delete (car entry) files)))
442 (unless files (setq next-stage nil))))
443 (when (or result (not next-stage))
444 (funcall update-function result next-stage))
445 (when next-stage
446 (vc-git-dir-status-goto-stage next-stage files update-function))))
448 (defun vc-git-dir-status-goto-stage (stage files update-function)
449 (erase-buffer)
450 (case stage
451 (update-index
452 (if files
453 (vc-git-command (current-buffer) 'async files "add" "--refresh" "--")
454 (vc-git-command (current-buffer) 'async nil
455 "update-index" "--refresh")))
456 (ls-files-added
457 (vc-git-command (current-buffer) 'async files
458 "ls-files" "-z" "-c" "-s" "--"))
459 (ls-files-up-to-date
460 (vc-git-command (current-buffer) 'async files
461 "ls-files" "-z" "-c" "-s" "--"))
462 (ls-files-unknown
463 (vc-git-command (current-buffer) 'async files
464 "ls-files" "-z" "-o" "--directory"
465 "--no-empty-directory" "--exclude-standard" "--"))
466 (ls-files-ignored
467 (vc-git-command (current-buffer) 'async files
468 "ls-files" "-z" "-o" "-i" "--directory"
469 "--no-empty-directory" "--exclude-standard" "--"))
470 ;; --relative added in Git 1.5.5.
471 (diff-index
472 (vc-git-command (current-buffer) 'async files
473 "diff-index" "--relative" "-z" "-M" "HEAD" "--")))
474 (vc-exec-after
475 `(vc-git-after-dir-status-stage ',stage ',files ',update-function)))
477 (defun vc-git-dir-status (_dir update-function)
478 "Return a list of (FILE STATE EXTRA) entries for DIR."
479 ;; Further things that would have to be fixed later:
480 ;; - how to handle unregistered directories
481 ;; - how to support vc-dir on a subdir of the project tree
482 (vc-git-dir-status-goto-stage 'update-index nil update-function))
484 (defun vc-git-dir-status-files (_dir files _default-state update-function)
485 "Return a list of (FILE STATE EXTRA) entries for FILES in DIR."
486 (vc-git-dir-status-goto-stage 'update-index files update-function))
488 (defvar vc-git-stash-map
489 (let ((map (make-sparse-keymap)))
490 ;; Turn off vc-dir marking
491 (define-key map [mouse-2] 'ignore)
493 (define-key map [down-mouse-3] 'vc-git-stash-menu)
494 (define-key map "\C-k" 'vc-git-stash-delete-at-point)
495 (define-key map "=" 'vc-git-stash-show-at-point)
496 (define-key map "\C-m" 'vc-git-stash-show-at-point)
497 (define-key map "A" 'vc-git-stash-apply-at-point)
498 (define-key map "P" 'vc-git-stash-pop-at-point)
499 (define-key map "S" 'vc-git-stash-snapshot)
500 map))
502 (defvar vc-git-stash-menu-map
503 (let ((map (make-sparse-keymap "Git Stash")))
504 (define-key map [de]
505 '(menu-item "Delete Stash" vc-git-stash-delete-at-point
506 :help "Delete the current stash"))
507 (define-key map [ap]
508 '(menu-item "Apply Stash" vc-git-stash-apply-at-point
509 :help "Apply the current stash and keep it in the stash list"))
510 (define-key map [po]
511 '(menu-item "Apply and Remove Stash (Pop)" vc-git-stash-pop-at-point
512 :help "Apply the current stash and remove it"))
513 (define-key map [sh]
514 '(menu-item "Show Stash" vc-git-stash-show-at-point
515 :help "Show the contents of the current stash"))
516 map))
518 (defun vc-git-dir-extra-headers (_dir)
519 (let ((str (with-output-to-string
520 (with-current-buffer standard-output
521 (vc-git--out-ok "symbolic-ref" "HEAD"))))
522 (stash (vc-git-stash-list))
523 (stash-help-echo "Use M-x vc-git-stash to create stashes.")
524 branch remote remote-url)
525 (if (string-match "^\\(refs/heads/\\)?\\(.+\\)$" str)
526 (progn
527 (setq branch (match-string 2 str))
528 (setq remote
529 (with-output-to-string
530 (with-current-buffer standard-output
531 (vc-git--out-ok "config"
532 (concat "branch." branch ".remote")))))
533 (when (string-match "\\([^\n]+\\)" remote)
534 (setq remote (match-string 1 remote)))
535 (when remote
536 (setq remote-url
537 (with-output-to-string
538 (with-current-buffer standard-output
539 (vc-git--out-ok "config"
540 (concat "remote." remote ".url"))))))
541 (when (string-match "\\([^\n]+\\)" remote-url)
542 (setq remote-url (match-string 1 remote-url))))
543 (setq branch "not (detached HEAD)"))
544 ;; FIXME: maybe use a different face when nothing is stashed.
545 (concat
546 (propertize "Branch : " 'face 'font-lock-type-face)
547 (propertize branch
548 'face 'font-lock-variable-name-face)
549 (when remote
550 (concat
551 "\n"
552 (propertize "Remote : " 'face 'font-lock-type-face)
553 (propertize remote-url
554 'face 'font-lock-variable-name-face)))
555 "\n"
556 (if stash
557 (concat
558 (propertize "Stash :\n" 'face 'font-lock-type-face
559 'help-echo stash-help-echo)
560 (mapconcat
561 (lambda (x)
562 (propertize x
563 'face 'font-lock-variable-name-face
564 'mouse-face 'highlight
565 'help-echo "mouse-3: Show stash menu\nRET: Show stash\nA: Apply stash\nP: Apply and remove stash (pop)\nC-k: Delete stash"
566 'keymap vc-git-stash-map))
567 stash "\n"))
568 (concat
569 (propertize "Stash : " 'face 'font-lock-type-face
570 'help-echo stash-help-echo)
571 (propertize "Nothing stashed"
572 'help-echo stash-help-echo
573 'face 'font-lock-variable-name-face))))))
575 (defun vc-git-branches ()
576 "Return the existing branches, as a list of strings.
577 The car of the list is the current branch."
578 (with-temp-buffer
579 (call-process vc-git-program nil t nil "branch")
580 (goto-char (point-min))
581 (let (current-branch branches)
582 (while (not (eobp))
583 (when (looking-at "^\\([ *]\\) \\(.+\\)$")
584 (if (string-equal (match-string 1) "*")
585 (setq current-branch (match-string 2))
586 (push (match-string 2) branches)))
587 (forward-line 1))
588 (cons current-branch (nreverse branches)))))
590 ;;; STATE-CHANGING FUNCTIONS
592 (defun vc-git-create-repo ()
593 "Create a new Git repository."
594 (vc-git-command nil 0 nil "init"))
596 (defun vc-git-register (files &optional _rev _comment)
597 "Register FILES into the git version-control system."
598 (let (flist dlist)
599 (dolist (crt files)
600 (if (file-directory-p crt)
601 (push crt dlist)
602 (push crt flist)))
603 (when flist
604 (vc-git-command nil 0 flist "update-index" "--add" "--"))
605 (when dlist
606 (vc-git-command nil 0 dlist "add"))))
608 (defalias 'vc-git-responsible-p 'vc-git-root)
610 (defun vc-git-unregister (file)
611 (vc-git-command nil 0 file "rm" "-f" "--cached" "--"))
613 (declare-function log-edit-extract-headers "log-edit" (headers string))
615 (defun vc-git-checkin (files _rev comment)
616 (let ((coding-system-for-write vc-git-commits-coding-system))
617 (apply 'vc-git-command nil 0 files
618 (nconc (list "commit" "-m")
619 (log-edit-extract-headers '(("Author" . "--author")
620 ("Date" . "--date"))
621 comment)
622 (list "--only" "--")))))
624 (defun vc-git-find-revision (file rev buffer)
625 (let* (process-file-side-effects
626 (coding-system-for-read 'binary)
627 (coding-system-for-write 'binary)
628 (fullname
629 (let ((fn (vc-git--run-command-string
630 file "ls-files" "-z" "--full-name" "--")))
631 ;; ls-files does not return anything when looking for a
632 ;; revision of a file that has been renamed or removed.
633 (if (string= fn "")
634 (file-relative-name file (vc-git-root default-directory))
635 (substring fn 0 -1)))))
636 (vc-git-command
637 buffer 0
639 "cat-file" "blob" (concat (if rev rev "HEAD") ":" fullname))))
641 (defun vc-git-checkout (file &optional _editable rev)
642 (vc-git-command nil 0 file "checkout" (or rev "HEAD")))
644 (defun vc-git-revert (file &optional contents-done)
645 "Revert FILE to the version stored in the git repository."
646 (if contents-done
647 (vc-git-command nil 0 file "update-index" "--")
648 (vc-git-command nil 0 file "reset" "-q" "--")
649 (vc-git-command nil nil file "checkout" "-q" "--")))
651 (defun vc-git-pull (prompt)
652 "Pull changes into the current Git branch.
653 Normally, this runs \"git pull\". If PROMPT is non-nil, prompt
654 for the Git command to run."
655 (let* ((root (vc-git-root default-directory))
656 (buffer (format "*vc-git : %s*" (expand-file-name root)))
657 (command "pull")
658 (git-program vc-git-program)
659 args)
660 ;; If necessary, prompt for the exact command.
661 (when prompt
662 (setq args (split-string
663 (read-shell-command "Git pull command: "
664 (format "%s pull" git-program)
665 'vc-git-history)
666 " " t))
667 (setq git-program (car args)
668 command (cadr args)
669 args (cddr args)))
670 (apply 'vc-do-async-command buffer root git-program command args)
671 (vc-set-async-update buffer)))
673 (defun vc-git-merge-branch ()
674 "Merge changes into the current Git branch.
675 This prompts for a branch to merge from."
676 (let* ((root (vc-git-root default-directory))
677 (buffer (format "*vc-git : %s*" (expand-file-name root)))
678 (branches (cdr (vc-git-branches)))
679 (merge-source
680 (completing-read "Merge from branch: "
681 (if (or (member "FETCH_HEAD" branches)
682 (not (file-readable-p
683 (expand-file-name ".git/FETCH_HEAD"
684 root))))
685 branches
686 (cons "FETCH_HEAD" branches))
687 nil t)))
688 (apply 'vc-do-async-command buffer root vc-git-program "merge"
689 (list merge-source))
690 (vc-set-async-update buffer)))
692 ;;; HISTORY FUNCTIONS
694 (defun vc-git-print-log (files buffer &optional shortlog start-revision limit)
695 "Get change log associated with FILES.
696 Note that using SHORTLOG requires at least Git version 1.5.6,
697 for the --graph option."
698 (let ((coding-system-for-read vc-git-commits-coding-system))
699 ;; `vc-do-command' creates the buffer, but we need it before running
700 ;; the command.
701 (vc-setup-buffer buffer)
702 ;; If the buffer exists from a previous invocation it might be
703 ;; read-only.
704 (let ((inhibit-read-only t))
705 (with-current-buffer
706 buffer
707 (apply 'vc-git-command buffer
708 'async files
709 (append
710 '("log" "--no-color")
711 (when shortlog
712 `("--graph" "--decorate" "--date=short"
713 ,(format "--pretty=tformat:%s"
714 (car vc-git-root-log-format))
715 "--abbrev-commit"))
716 (when limit (list "-n" (format "%s" limit)))
717 (when start-revision (list start-revision))
718 '("--")))))))
720 (defun vc-git-log-outgoing (buffer remote-location)
721 (interactive)
722 (vc-git-command
723 buffer 0 nil
724 "log"
725 "--no-color" "--graph" "--decorate" "--date=short"
726 (format "--pretty=tformat:%s" (car vc-git-root-log-format))
727 "--abbrev-commit"
728 (concat (if (string= remote-location "")
729 "@{upstream}"
730 remote-location)
731 "..HEAD")))
733 (defun vc-git-log-incoming (buffer remote-location)
734 (interactive)
735 (vc-git-command nil 0 nil "fetch")
736 (vc-git-command
737 buffer 0 nil
738 "log"
739 "--no-color" "--graph" "--decorate" "--date=short"
740 (format "--pretty=tformat:%s" (car vc-git-root-log-format))
741 "--abbrev-commit"
742 (concat "HEAD.." (if (string= remote-location "")
743 "@{upstream}"
744 remote-location))))
746 (defvar log-view-message-re)
747 (defvar log-view-file-re)
748 (defvar log-view-font-lock-keywords)
749 (defvar log-view-per-file-logs)
750 (defvar log-view-expanded-log-entry-function)
752 (define-derived-mode vc-git-log-view-mode log-view-mode "Git-Log-View"
753 (require 'add-log) ;; We need the faces add-log.
754 ;; Don't have file markers, so use impossible regexp.
755 (set (make-local-variable 'log-view-file-re) "\\`a\\`")
756 (set (make-local-variable 'log-view-per-file-logs) nil)
757 (set (make-local-variable 'log-view-message-re)
758 (if (not (eq vc-log-view-type 'long))
759 (cadr vc-git-root-log-format)
760 "^commit *\\([0-9a-z]+\\)"))
761 ;; Allow expanding short log entries
762 (when (eq vc-log-view-type 'short)
763 (setq truncate-lines t)
764 (set (make-local-variable 'log-view-expanded-log-entry-function)
765 'vc-git-expanded-log-entry))
766 (set (make-local-variable 'log-view-font-lock-keywords)
767 (if (not (eq vc-log-view-type 'long))
768 (list (cons (nth 1 vc-git-root-log-format)
769 (nth 2 vc-git-root-log-format)))
770 (append
771 `((,log-view-message-re (1 'change-log-acknowledgement)))
772 ;; Handle the case:
773 ;; user: foo@bar
774 '(("^Author:[ \t]+\\([A-Za-z0-9_.+-]+@[A-Za-z0-9_.-]+\\)"
775 (1 'change-log-email))
776 ;; Handle the case:
777 ;; user: FirstName LastName <foo@bar>
778 ("^Author:[ \t]+\\([^<(]+?\\)[ \t]*[(<]\\([A-Za-z0-9_.+-]+@[A-Za-z0-9_.-]+\\)[>)]"
779 (1 'change-log-name)
780 (2 'change-log-email))
781 ("^ +\\(?:\\(?:[Aa]cked\\|[Ss]igned-[Oo]ff\\)-[Bb]y:\\)[ \t]+\\([A-Za-z0-9_.+-]+@[A-Za-z0-9_.-]+\\)"
782 (1 'change-log-name))
783 ("^ +\\(?:\\(?:[Aa]cked\\|[Ss]igned-[Oo]ff\\)-[Bb]y:\\)[ \t]+\\([^<(]+?\\)[ \t]*[(<]\\([A-Za-z0-9_.+-]+@[A-Za-z0-9_.-]+\\)[>)]"
784 (1 'change-log-name)
785 (2 'change-log-email))
786 ("^Merge: \\([0-9a-z]+\\) \\([0-9a-z]+\\)"
787 (1 'change-log-acknowledgement)
788 (2 'change-log-acknowledgement))
789 ("^Date: \\(.+\\)" (1 'change-log-date))
790 ("^summary:[ \t]+\\(.+\\)" (1 'log-view-message)))))))
793 (defun vc-git-show-log-entry (revision)
794 "Move to the log entry for REVISION.
795 REVISION may have the form BRANCH, BRANCH~N,
796 or BRANCH^ (where \"^\" can be repeated)."
797 (goto-char (point-min))
798 (prog1
799 (when revision
800 (search-forward
801 (format "\ncommit %s" revision) nil t
802 (cond ((string-match "~\\([0-9]\\)\\'" revision)
803 (1+ (string-to-number (match-string 1 revision))))
804 ((string-match "\\^+\\'" revision)
805 (1+ (length (match-string 0 revision))))
806 (t nil))))
807 (beginning-of-line)))
809 (defun vc-git-expanded-log-entry (revision)
810 (with-temp-buffer
811 (apply 'vc-git-command t nil nil (list "log" revision "-1"))
812 (goto-char (point-min))
813 (unless (eobp)
814 ;; Indent the expanded log entry.
815 (indent-region (point-min) (point-max) 2)
816 (buffer-string))))
818 (defun vc-git-diff (files &optional rev1 rev2 buffer)
819 "Get a difference report using Git between two revisions of FILES."
820 (let (process-file-side-effects)
821 (apply #'vc-git-command (or buffer "*vc-diff*") 1 files
822 (if (and rev1 rev2) "diff-tree" "diff-index")
823 "--exit-code"
824 (append (vc-switches 'git 'diff)
825 (list "-p" (or rev1 "HEAD") rev2 "--")))))
827 (defun vc-git-revision-table (_files)
828 ;; What about `files'?!? --Stef
829 (let (process-file-side-effects
830 (table (list "HEAD")))
831 (with-temp-buffer
832 (vc-git-command t nil nil "for-each-ref" "--format=%(refname)")
833 (goto-char (point-min))
834 (while (re-search-forward "^refs/\\(heads\\|tags\\|remotes\\)/\\(.*\\)$"
835 nil t)
836 (push (match-string 2) table)))
837 table))
839 (defun vc-git-revision-completion-table (files)
840 (letrec ((table (lazy-completion-table
841 table (lambda () (vc-git-revision-table files)))))
842 table))
844 (defun vc-git-annotate-command (file buf &optional rev)
845 (let ((name (file-relative-name file)))
846 (vc-git-command buf 'async nil "blame" "--date=iso" "-C" "-C" rev "--" name)))
848 (declare-function vc-annotate-convert-time "vc-annotate" (time))
850 (defun vc-git-annotate-time ()
851 (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)
852 (vc-annotate-convert-time
853 (apply #'encode-time (mapcar (lambda (match)
854 (string-to-number (match-string match)))
855 '(6 5 4 3 2 1 7))))))
857 (defun vc-git-annotate-extract-revision-at-line ()
858 (save-excursion
859 (move-beginning-of-line 1)
860 (when (looking-at "\\([0-9a-f^][0-9a-f]+\\) \\(\\([^(]+\\) \\)?")
861 (let ((revision (match-string-no-properties 1)))
862 (if (match-beginning 2)
863 (let ((fname (match-string-no-properties 3)))
864 ;; Remove trailing whitespace from the file name.
865 (when (string-match " +\\'" fname)
866 (setq fname (substring fname 0 (match-beginning 0))))
867 (cons revision
868 (expand-file-name fname (vc-git-root default-directory))))
869 revision)))))
871 ;;; TAG SYSTEM
873 (defun vc-git-create-tag (dir name branchp)
874 (let ((default-directory dir))
875 (and (vc-git-command nil 0 nil "update-index" "--refresh")
876 (if branchp
877 (vc-git-command nil 0 nil "checkout" "-b" name)
878 (vc-git-command nil 0 nil "tag" name)))))
880 (defun vc-git-retrieve-tag (dir name _update)
881 (let ((default-directory dir))
882 (vc-git-command nil 0 nil "checkout" name)
883 ;; FIXME: update buffers if `update' is true
887 ;;; MISCELLANEOUS
889 (defun vc-git-previous-revision (file rev)
890 "Git-specific version of `vc-previous-revision'."
891 (if file
892 (let* ((fname (file-relative-name file))
893 (prev-rev (with-temp-buffer
894 (and
895 (vc-git--out-ok "rev-list" "-2" rev "--" fname)
896 (goto-char (point-max))
897 (bolp)
898 (zerop (forward-line -1))
899 (not (bobp))
900 (buffer-substring-no-properties
901 (point)
902 (1- (point-max)))))))
903 (or (vc-git-symbolic-commit prev-rev) prev-rev))
904 (with-temp-buffer
905 (and
906 (vc-git--out-ok "rev-parse" (concat rev "^"))
907 (buffer-substring-no-properties (point-min) (+ (point-min) 40))))))
909 (defun vc-git-next-revision (file rev)
910 "Git-specific version of `vc-next-revision'."
911 (let* ((default-directory (file-name-directory
912 (expand-file-name file)))
913 (file (file-name-nondirectory file))
914 (current-rev
915 (with-temp-buffer
916 (and
917 (vc-git--out-ok "rev-list" "-1" rev "--" file)
918 (goto-char (point-max))
919 (bolp)
920 (zerop (forward-line -1))
921 (bobp)
922 (buffer-substring-no-properties
923 (point)
924 (1- (point-max))))))
925 (next-rev
926 (and current-rev
927 (with-temp-buffer
928 (and
929 (vc-git--out-ok "rev-list" "HEAD" "--" file)
930 (goto-char (point-min))
931 (search-forward current-rev nil t)
932 (zerop (forward-line -1))
933 (buffer-substring-no-properties
934 (point)
935 (progn (forward-line 1) (1- (point)))))))))
936 (or (vc-git-symbolic-commit next-rev) next-rev)))
938 (defun vc-git-delete-file (file)
939 (vc-git-command nil 0 file "rm" "-f" "--"))
941 (defun vc-git-rename-file (old new)
942 (vc-git-command nil 0 (list old new) "mv" "-f" "--"))
944 (defvar vc-git-extra-menu-map
945 (let ((map (make-sparse-keymap)))
946 (define-key map [git-grep]
947 '(menu-item "Git grep..." vc-git-grep
948 :help "Run the `git grep' command"))
949 (define-key map [git-sn]
950 '(menu-item "Stash a Snapshot" vc-git-stash-snapshot
951 :help "Stash the current state of the tree and keep the current state"))
952 (define-key map [git-st]
953 '(menu-item "Create Stash..." vc-git-stash
954 :help "Stash away changes"))
955 (define-key map [git-ss]
956 '(menu-item "Show Stash..." vc-git-stash-show
957 :help "Show stash contents"))
958 map))
960 (defun vc-git-extra-menu () vc-git-extra-menu-map)
962 (defun vc-git-extra-status-menu () vc-git-extra-menu-map)
964 (defun vc-git-root (file)
965 (or (vc-file-getprop file 'git-root)
966 (vc-file-setprop file 'git-root (vc-find-root file ".git"))))
968 ;; Derived from `lgrep'.
969 (defun vc-git-grep (regexp &optional files dir)
970 "Run git grep, searching for REGEXP in FILES in directory DIR.
971 The search is limited to file names matching shell pattern FILES.
972 FILES may use abbreviations defined in `grep-files-aliases', e.g.
973 entering `ch' is equivalent to `*.[ch]'.
975 With \\[universal-argument] prefix, you can edit the constructed shell command line
976 before it is executed.
977 With two \\[universal-argument] prefixes, directly edit and run `grep-command'.
979 Collect output in a buffer. While git grep runs asynchronously, you
980 can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
981 in the grep output buffer,
982 to go to the lines where grep found matches.
984 This command shares argument histories with \\[rgrep] and \\[grep]."
985 (interactive
986 (progn
987 (grep-compute-defaults)
988 (cond
989 ((equal current-prefix-arg '(16))
990 (list (read-from-minibuffer "Run: " "git grep"
991 nil nil 'grep-history)
992 nil))
993 (t (let* ((regexp (grep-read-regexp))
994 (files (grep-read-files regexp))
995 (dir (read-directory-name "In directory: "
996 nil default-directory t)))
997 (list regexp files dir))))))
998 (require 'grep)
999 (when (and (stringp regexp) (> (length regexp) 0))
1000 (let ((command regexp))
1001 (if (null files)
1002 (if (string= command "git grep")
1003 (setq command nil))
1004 (setq dir (file-name-as-directory (expand-file-name dir)))
1005 (setq command
1006 (grep-expand-template "git grep -n -e <R> -- <F>"
1007 regexp files))
1008 (when command
1009 (if (equal current-prefix-arg '(4))
1010 (setq command
1011 (read-from-minibuffer "Confirm: "
1012 command nil nil 'grep-history))
1013 (add-to-history 'grep-history command))))
1014 (when command
1015 (let ((default-directory dir)
1016 (compilation-environment (cons "PAGER=" compilation-environment)))
1017 ;; Setting process-setup-function makes exit-message-function work
1018 ;; even when async processes aren't supported.
1019 (compilation-start command 'grep-mode))
1020 (if (eq next-error-last-buffer (current-buffer))
1021 (setq default-directory dir))))))
1023 (defun vc-git-stash (name)
1024 "Create a stash."
1025 (interactive "sStash name: ")
1026 (let ((root (vc-git-root default-directory)))
1027 (when root
1028 (vc-git--call nil "stash" "save" name)
1029 (vc-resynch-buffer root t t))))
1031 (defun vc-git-stash-show (name)
1032 "Show the contents of stash NAME."
1033 (interactive "sStash name: ")
1034 (vc-setup-buffer "*vc-git-stash*")
1035 (vc-git-command "*vc-git-stash*" 'async nil "stash" "show" "-p" name)
1036 (set-buffer "*vc-git-stash*")
1037 (diff-mode)
1038 (setq buffer-read-only t)
1039 (pop-to-buffer (current-buffer)))
1041 (defun vc-git-stash-apply (name)
1042 "Apply stash NAME."
1043 (interactive "sApply stash: ")
1044 (vc-git-command "*vc-git-stash*" 0 nil "stash" "apply" "-q" name)
1045 (vc-resynch-buffer (vc-git-root default-directory) t t))
1047 (defun vc-git-stash-pop (name)
1048 "Pop stash NAME."
1049 (interactive "sPop stash: ")
1050 (vc-git-command "*vc-git-stash*" 0 nil "stash" "pop" "-q" name)
1051 (vc-resynch-buffer (vc-git-root default-directory) t t))
1053 (defun vc-git-stash-snapshot ()
1054 "Create a stash with the current tree state."
1055 (interactive)
1056 (vc-git--call nil "stash" "save"
1057 (let ((ct (current-time)))
1058 (concat
1059 (format-time-string "Snapshot on %Y-%m-%d" ct)
1060 (format-time-string " at %H:%M" ct))))
1061 (vc-git-command "*vc-git-stash*" 0 nil "stash" "apply" "-q" "stash@{0}")
1062 (vc-resynch-buffer (vc-git-root default-directory) t t))
1064 (defun vc-git-stash-list ()
1065 (delete
1067 (split-string
1068 (replace-regexp-in-string
1069 "^stash@" " " (vc-git--run-command-string nil "stash" "list"))
1070 "\n")))
1072 (defun vc-git-stash-get-at-point (point)
1073 (save-excursion
1074 (goto-char point)
1075 (beginning-of-line)
1076 (if (looking-at "^ +\\({[0-9]+}\\):")
1077 (match-string 1)
1078 (error "Cannot find stash at point"))))
1080 (defun vc-git-stash-delete-at-point ()
1081 (interactive)
1082 (let ((stash (vc-git-stash-get-at-point (point))))
1083 (when (y-or-n-p (format "Remove stash %s ? " stash))
1084 (vc-git--run-command-string nil "stash" "drop" (format "stash@%s" stash))
1085 (vc-dir-refresh))))
1087 (defun vc-git-stash-show-at-point ()
1088 (interactive)
1089 (vc-git-stash-show (format "stash@%s" (vc-git-stash-get-at-point (point)))))
1091 (defun vc-git-stash-apply-at-point ()
1092 (interactive)
1093 (vc-git-stash-apply (format "stash@%s" (vc-git-stash-get-at-point (point)))))
1095 (defun vc-git-stash-pop-at-point ()
1096 (interactive)
1097 (vc-git-stash-pop (format "stash@%s" (vc-git-stash-get-at-point (point)))))
1099 (defun vc-git-stash-menu (e)
1100 (interactive "e")
1101 (vc-dir-at-event e (popup-menu vc-git-stash-menu-map e)))
1104 ;;; Internal commands
1106 (defun vc-git-command (buffer okstatus file-or-list &rest flags)
1107 "A wrapper around `vc-do-command' for use in vc-git.el.
1108 The difference to vc-do-command is that this function always invokes
1109 `vc-git-program'."
1110 (apply 'vc-do-command (or buffer "*vc*") okstatus vc-git-program
1111 file-or-list flags))
1113 (defun vc-git--empty-db-p ()
1114 "Check if the git db is empty (no commit done yet)."
1115 (let (process-file-side-effects)
1116 (not (eq 0 (vc-git--call nil "rev-parse" "--verify" "HEAD")))))
1118 (defun vc-git--call (buffer command &rest args)
1119 ;; We don't need to care the arguments. If there is a file name, it
1120 ;; is always a relative one. This works also for remote
1121 ;; directories. We enable `inhibit-null-byte-detection', otherwise
1122 ;; Tramp's eol conversion might be confused.
1123 (let ((inhibit-null-byte-detection t)
1124 (process-environment (cons "PAGER=" process-environment)))
1125 (apply 'process-file vc-git-program nil buffer nil command args)))
1127 (defun vc-git--out-ok (command &rest args)
1128 (zerop (apply 'vc-git--call '(t nil) command args)))
1130 (defun vc-git--run-command-string (file &rest args)
1131 "Run a git command on FILE and return its output as string.
1132 FILE can be nil."
1133 (let* ((ok t)
1134 (str (with-output-to-string
1135 (with-current-buffer standard-output
1136 (unless (apply 'vc-git--out-ok
1137 (if file
1138 (append args (list (file-relative-name
1139 file)))
1140 args))
1141 (setq ok nil))))))
1142 (and ok str)))
1144 (defun vc-git-symbolic-commit (commit)
1145 "Translate COMMIT string into symbolic form.
1146 Returns nil if not possible."
1147 (and commit
1148 (let ((name (with-temp-buffer
1149 (and
1150 (vc-git--out-ok "name-rev" "--name-only" commit)
1151 (goto-char (point-min))
1152 (= (forward-line 2) 1)
1153 (bolp)
1154 (buffer-substring-no-properties (point-min)
1155 (1- (point-max)))))))
1156 (and name (not (string= name "undefined")) name))))
1158 (provide 'vc-git)
1160 ;;; vc-git.el ends here