1 ;;; vc-git.el --- VC backend for the git version control system -*- lexical-binding: t -*-
3 ;; Copyright (C) 2006-2017 Free Software Foundation, Inc.
5 ;; Author: Alexandre Julliard <julliard@winehq.org>
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/>.
26 ;; This file contains a VC backend for the git version control
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:
36 ;; (add-to-list 'vc-handled-backends 'Git)
39 ;; - check if more functions could use vc-git-command instead
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
49 ;; * revision-granularity OK
50 ;; STATE-QUERYING FUNCTIONS
51 ;; * registered (file) OK
53 ;; - dir-status-files (dir files uf) OK
54 ;; * working-revision (file) OK
55 ;; * checkout-model (files) OK
56 ;; - mode-line-string (file) OK
57 ;; STATE-CHANGING FUNCTIONS
58 ;; * create-repo () OK
59 ;; * register (files &optional rev comment) OK
60 ;; - responsible-p (file) OK
61 ;; - receive-file (file rev) NOT NEEDED
62 ;; - unregister (file) OK
63 ;; * checkin (files rev comment) OK
64 ;; * find-revision (file rev buffer) OK
65 ;; * checkout (file &optional rev) OK
66 ;; * revert (file &optional contents-done) OK
67 ;; - merge-file (file rev1 rev2) It would be possible to merge
68 ;; changes into a single file, but
69 ;; when committing they wouldn't
70 ;; be identified as a merge
71 ;; by git, so it's probably
73 ;; - merge-news (file) see `merge-file'
74 ;; - steal-lock (file &optional revision) NOT NEEDED
76 ;; * print-log (files buffer &optional shortlog start-revision limit) OK
77 ;; - log-view-mode () OK
78 ;; - show-log-entry (revision) OK
79 ;; - comment-history (file) ??
80 ;; - update-changelog (files) COULD BE SUPPORTED
81 ;; * diff (file &optional rev1 rev2 buffer async) OK
82 ;; - revision-completion-table (files) OK
83 ;; - annotate-command (file buf &optional rev) OK
84 ;; - annotate-time () OK
85 ;; - annotate-current-time () NOT NEEDED
86 ;; - annotate-extract-revision-at-line () OK
88 ;; - create-tag (dir name branchp) OK
89 ;; - retrieve-tag (dir name update) OK
91 ;; - make-version-backups-p (file) NOT NEEDED
92 ;; - previous-revision (file rev) OK
93 ;; - next-revision (file rev) OK
94 ;; - check-headers () COULD BE SUPPORTED
95 ;; - delete-file (file) OK
96 ;; - rename-file (old new) OK
97 ;; - find-file-hook () OK
98 ;; - conflicted-files OK
113 (defcustom vc-git-diff-switches t
114 "String or list of strings specifying switches for Git diff under VC.
115 If nil, use the value of `vc-diff-switches'. If t, use no switches."
116 :type
'(choice (const :tag
"Unspecified" nil
)
117 (const :tag
"None" t
)
118 (string :tag
"Argument String")
119 (repeat :tag
"Argument List" :value
("") string
))
122 (defcustom vc-git-annotate-switches nil
123 "String or list of strings specifying switches for Git blame under VC.
124 If nil, use the value of `vc-annotate-switches'. If t, use no switches."
125 :type
'(choice (const :tag
"Unspecified" nil
)
126 (const :tag
"None" t
)
127 (string :tag
"Argument String")
128 (repeat :tag
"Argument List" :value
("") string
))
131 (defcustom vc-git-resolve-conflicts t
132 "When non-nil, mark conflicted file as resolved upon saving.
133 That is performed after all conflict markers in it have been
134 removed. If the value is `unstage-maybe', and no merge is in
135 progress, then after the last conflict is resolved, also clear
137 :type
'(choice (const :tag
"Don't resolve" nil
)
138 (const :tag
"Resolve" t
)
139 (const :tag
"Resolve and maybe unstage all files"
143 (defcustom vc-git-program
"git"
144 "Name of the Git executable (excluding any arguments)."
148 (defcustom vc-git-root-log-format
149 '("%d%h..: %an %ad %s"
150 ;; The first shy group matches the characters drawn by --graph.
151 ;; We use numbered groups because `log-view-message-re' wants the
152 ;; revision number to be group 1.
153 "^\\(?:[*/\\| ]+ \\)?\\(?2: ([^)]+)\\)?\\(?1:[0-9a-z]+\\)..: \
154 \\(?3:.*?\\)[ \t]+\\(?4:[0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\)"
155 ((1 'log-view-message
)
156 (2 'change-log-list nil lax
)
158 (4 'change-log-date
)))
159 "Git log format for `vc-print-root-log'.
160 This should be a list (FORMAT REGEXP KEYWORDS), where FORMAT is a
161 format string (which is passed to \"git log\" via the argument
162 \"--pretty=tformat:FORMAT\"), REGEXP is a regular expression
163 matching the resulting Git log output, and KEYWORDS is a list of
164 `font-lock-keywords' for highlighting the Log View buffer."
165 :type
'(list string string
(repeat sexp
))
168 (defcustom vc-git-commits-coding-system
'utf-8
169 "Default coding system for sending commit log messages to Git.
171 Should be consistent with the Git config value i18n.commitEncoding,
172 and should also be consistent with `locale-coding-system'."
173 :type
'(coding-system :tag
"Coding system to encode Git commit logs")
176 (defcustom vc-git-log-output-coding-system
'utf-8
177 "Default coding system for receiving log output from Git.
179 Should be consistent with the Git config value i18n.logOutputEncoding."
180 :type
'(coding-system :tag
"Coding system to decode Git log output")
183 ;; History of Git commands.
184 (defvar vc-git-history nil
)
186 ;;; BACKEND PROPERTIES
188 (defun vc-git-revision-granularity () 'repository
)
189 (defun vc-git-checkout-model (_files) 'implicit
)
191 ;;; STATE-QUERYING FUNCTIONS
193 ;;;###autoload (defun vc-git-registered (file)
194 ;;;###autoload "Return non-nil if FILE is registered with git."
195 ;;;###autoload (if (vc-find-root file ".git") ; Short cut.
196 ;;;###autoload (progn
197 ;;;###autoload (load "vc-git" nil t)
198 ;;;###autoload (vc-git-registered file))))
200 (defun vc-git-registered (file)
201 "Check whether FILE is registered with git."
202 (let ((dir (vc-git-root file
)))
205 (let* (process-file-side-effects
206 ;; Do not use the `file-name-directory' here: git-ls-files
207 ;; sometimes fails to return the correct status for relative
209 ;; See also: http://marc.info/?l=git&m=125787684318129&w=2
210 (name (file-relative-name file dir
))
213 (vc-git--out-ok "ls-files" "-c" "-z" "--" name
)
214 ;; If result is empty, use ls-tree to check for deleted
216 (when (eq (point-min) (point-max))
217 (vc-git--out-ok "ls-tree" "--name-only" "-z" "HEAD"
221 (> (length str
) (length name
))
222 (string= (substring str
0 (1+ (length name
)))
223 (concat name
"\0"))))))))
225 (defun vc-git--state-code (code)
226 "Convert from a string to a added/deleted/modified state."
227 (pcase (string-to-char code
)
231 (?U
'edited
) ;; FIXME
232 (?T
'edited
))) ;; FIXME
234 (defun vc-git-state (file)
235 "Git-specific version of `vc-state'."
236 ;; FIXME: This can't set 'ignored or 'conflict yet
237 ;; The 'ignored state could be detected with `git ls-files -i -o
238 ;; --exclude-standard` It also can't set 'needs-update or
239 ;; 'needs-merge. The rough equivalent would be that upstream branch
240 ;; for current branch is in fast-forward state i.e. current branch
241 ;; is direct ancestor of corresponding upstream branch, and the file
242 ;; was modified upstream. But we can't check that without a network
244 ;; This assumes that status is known to be not `unregistered' because
245 ;; we've been successfully dispatched here from `vc-state', that
246 ;; means `vc-git-registered' returned t earlier once. Bug#11757
247 (let ((diff (vc-git--run-command-string
248 file
"diff-index" "-p" "--raw" "-z" "HEAD" "--")))
250 (string-match ":[0-7]\\{6\\} [0-7]\\{6\\} [0-9a-f]\\{40\\} [0-9a-f]\\{40\\} \\([ADMUT]\\)\0[^\0]+\0\\(.*\n.\\)?"
252 (let ((diff-letter (match-string 1 diff
)))
253 (if (not (match-beginning 2))
254 ;; Empty diff: file contents is the same as the HEAD
255 ;; revision, but timestamps are different (eg, file
256 ;; was "touch"ed). Update timestamp in index:
258 (vc-git--call nil
"add" "--refresh" "--"
259 (file-relative-name file
)))
260 (vc-git--state-code diff-letter
)))
261 (if (vc-git--empty-db-p) 'added
'up-to-date
))))
263 (defun vc-git-working-revision (_file)
264 "Git-specific version of `vc-working-revision'."
265 (let (process-file-side-effects)
266 (vc-git--rev-parse "HEAD")))
268 (defun vc-git--symbolic-ref (file)
270 (vc-file-getprop file
'vc-git-symbolic-ref
)
271 (let* (process-file-side-effects
272 (str (vc-git--run-command-string nil
"symbolic-ref" "HEAD")))
273 (vc-file-setprop file
'vc-git-symbolic-ref
275 (if (string-match "^\\(refs/heads/\\)?\\(.+\\)$" str
)
279 (defun vc-git-mode-line-string (file)
280 "Return a string for `vc-mode-line' to put in the mode line for FILE."
281 (let* ((rev (vc-working-revision file
'Git
))
282 (disp-rev (or (vc-git--symbolic-ref file
)
283 (substring rev
0 7)))
284 (def-ml (vc-default-mode-line-string 'Git file
))
285 (help-echo (get-text-property 0 'help-echo def-ml
))
286 (face (get-text-property 0 'face def-ml
)))
287 (propertize (concat (substring def-ml
0 4) disp-rev
)
289 'help-echo
(concat help-echo
"\nCurrent revision: " rev
))))
291 (cl-defstruct (vc-git-extra-fileinfo
293 (:constructor vc-git-create-extra-fileinfo
294 (old-perm new-perm
&optional rename-state orig-name
))
295 (:conc-name vc-git-extra-fileinfo-
>))
296 old-perm new-perm
;; Permission flags.
297 rename-state
;; Rename or copy state.
298 orig-name
) ;; Original name for renames or copies.
300 (defun vc-git-escape-file-name (name)
301 "Escape a file name if necessary."
302 (if (string-match "[\n\t\"\\]" name
)
304 (mapconcat (lambda (c)
310 (_ (char-to-string c
))))
315 (defun vc-git-file-type-as-string (old-perm new-perm
)
316 "Return a string describing the file type based on its permissions."
317 (let* ((old-type (lsh (or old-perm
0) -
9))
318 (new-type (lsh (or new-perm
0) -
9))
323 (?
\120 " (type change symlink -> file)")
324 (?
\160 " (type change subproject -> file)")))
327 (?
\100 " (type change file -> symlink)")
328 (?
\160 " (type change subproject -> symlink)")
330 (?
\160 ;; Subproject.
332 (?
\100 " (type change file -> subproject)")
333 (?
\120 " (type change symlink -> subproject)")
334 (_ " (subproject)")))
335 (?
\110 nil
) ;; Directory (internal, not a real git state).
336 (?
\000 ;; Deleted or unknown.
339 (?
\160 " (subproject)")))
340 (_ (format " (unknown type %o)" new-type
)))))
341 (cond (str (propertize str
'face
'font-lock-comment-face
))
342 ((eq new-type ?
\110) "/")
345 (defun vc-git-rename-as-string (state extra
)
346 "Return a string describing the copy or rename associated with INFO,
347 or an empty string if none."
348 (let ((rename-state (when extra
349 (vc-git-extra-fileinfo->rename-state extra
))))
353 (if (eq rename-state
'copy
) "copied from "
354 (if (eq state
'added
) "renamed from "
356 (vc-git-escape-file-name
357 (vc-git-extra-fileinfo->orig-name extra
))
359 'face
'font-lock-comment-face
)
362 (defun vc-git-permissions-as-string (old-perm new-perm
)
363 "Format a permission change as string."
365 (if (or (not old-perm
)
367 (eq 0 (logand ?
\111 (logxor old-perm new-perm
))))
369 (if (eq 0 (logand ?
\111 old-perm
)) "+x" "-x"))
370 'face
'font-lock-type-face
))
372 (defun vc-git-dir-printer (info)
373 "Pretty-printer for the vc-dir-fileinfo structure."
374 (let* ((isdir (vc-dir-fileinfo->directory info
))
375 (state (if isdir
"" (vc-dir-fileinfo->state info
)))
376 (extra (vc-dir-fileinfo->extra info
))
377 (old-perm (when extra
(vc-git-extra-fileinfo->old-perm extra
)))
378 (new-perm (when extra
(vc-git-extra-fileinfo->new-perm extra
))))
381 (propertize (format "%c" (if (vc-dir-fileinfo->marked info
) ?
* ?
))
382 'face
'font-lock-type-face
)
385 (format "%-12s" state
)
386 'face
(cond ((eq state
'up-to-date
) 'font-lock-builtin-face
)
387 ((eq state
'missing
) 'font-lock-warning-face
)
388 (t 'font-lock-variable-name-face
))
389 'mouse-face
'highlight
)
390 " " (vc-git-permissions-as-string old-perm new-perm
)
392 (propertize (vc-git-escape-file-name (vc-dir-fileinfo->name info
))
393 'face
(if isdir
'font-lock-comment-delimiter-face
394 'font-lock-function-name-face
)
397 "Directory\nVC operations can be applied to it\nmouse-3: Pop-up menu"
398 "File\nmouse-3: Pop-up menu")
399 'keymap vc-dir-filename-mouse-map
400 'mouse-face
'highlight
)
401 (vc-git-file-type-as-string old-perm new-perm
)
402 (vc-git-rename-as-string state extra
))))
404 (cl-defstruct (vc-git-dir-status-state
406 (:conc-name vc-git-dir-status-state-
>))
409 ;; List of files still to be processed.
411 ;; Update function to be called at the end.
413 ;; Hash table of entries for files we've computed so far.
414 (hash (make-hash-table :test
'equal
)))
416 (defsubst vc-git-dir-status-update-file
(state filename file-state file-info
)
417 (puthash filename
(list file-state file-info
)
418 (vc-git-dir-status-state->hash state
))
419 (setf (vc-git-dir-status-state->files state
)
420 (delete filename
(vc-git-dir-status-state->files state
))))
422 (defun vc-git-after-dir-status-stage (git-state)
423 "Process sentinel for the various dir-status stages."
425 (files (vc-git-dir-status-state->files git-state
)))
426 (goto-char (point-min))
427 (pcase (vc-git-dir-status-state->stage git-state
)
429 (setq next-stage
(if (vc-git--empty-db-p) 'ls-files-added
'diff-index
)))
431 (setq next-stage
'ls-files-unknown
)
432 (while (re-search-forward "\\([0-7]\\{6\\}\\) [0-9a-f]\\{40\\} 0\t\\([^\0]+\\)\0" nil t
)
433 (let ((new-perm (string-to-number (match-string 1) 8))
434 (name (match-string 2)))
435 (vc-git-dir-status-update-file
436 git-state name
'added
437 (vc-git-create-extra-fileinfo 0 new-perm
)))))
438 (`ls-files-up-to-date
439 (setq next-stage
'ls-files-unknown
)
440 (while (re-search-forward "\\([0-7]\\{6\\}\\) [0-9a-f]\\{40\\} \\([0-3]\\)\t\\([^\0]+\\)\0" nil t
)
441 (let ((perm (string-to-number (match-string 1) 8))
442 (state (match-string 2))
443 (name (match-string 3)))
444 (vc-git-dir-status-update-file
445 git-state name
(if (equal state
"0")
448 (vc-git-create-extra-fileinfo perm perm
)))))
450 (setq next-stage
'ls-files-unknown
)
451 ;; It's enough to look for "3" to notice a conflict.
452 (while (re-search-forward "\\([0-7]\\{6\\}\\) [0-9a-f]\\{40\\} 3\t\\([^\0]+\\)\0" nil t
)
453 (let ((perm (string-to-number (match-string 1) 8))
454 (name (match-string 2)))
455 (vc-git-dir-status-update-file
456 git-state name
'conflict
457 (vc-git-create-extra-fileinfo perm perm
)))))
459 (when files
(setq next-stage
'ls-files-ignored
))
460 (while (re-search-forward "\\([^\0]*?\\)\0" nil t
1)
461 (vc-git-dir-status-update-file git-state
(match-string 1) 'unregistered
462 (vc-git-create-extra-fileinfo 0 0))))
464 (while (re-search-forward "\\([^\0]*?\\)\0" nil t
1)
465 (vc-git-dir-status-update-file git-state
(match-string 1) 'ignored
466 (vc-git-create-extra-fileinfo 0 0))))
468 (setq next-stage
(if files
'ls-files-up-to-date
'ls-files-conflict
))
469 (while (re-search-forward
470 ":\\([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"
472 (let ((old-perm (string-to-number (match-string 1) 8))
473 (new-perm (string-to-number (match-string 2) 8))
474 (state (or (match-string 4) (match-string 6)))
475 (name (or (match-string 5) (match-string 7)))
476 (new-name (match-string 8)))
477 (if new-name
; Copy or rename.
478 (if (eq ?C
(string-to-char state
))
479 (vc-git-dir-status-update-file
480 git-state new-name
'added
481 (vc-git-create-extra-fileinfo old-perm new-perm
483 (vc-git-dir-status-update-file
484 git-state name
'removed
485 (vc-git-create-extra-fileinfo 0 0 'rename new-name
))
486 (vc-git-dir-status-update-file
487 git-state new-name
'added
488 (vc-git-create-extra-fileinfo old-perm new-perm
490 (vc-git-dir-status-update-file
491 git-state name
(vc-git--state-code state
)
492 (vc-git-create-extra-fileinfo old-perm new-perm
)))))))
493 ;; If we had files but now we don't, it's time to stop.
494 (when (and files
(not (vc-git-dir-status-state->files git-state
)))
495 (setq next-stage nil
))
496 (setf (vc-git-dir-status-state->stage git-state
) next-stage
)
497 (setf (vc-git-dir-status-state->files git-state
) files
)
499 (vc-git-dir-status-goto-stage git-state
)
500 (funcall (vc-git-dir-status-state->update-function git-state
)
502 (maphash (lambda (key value
)
503 (push (cons key value
) result
))
504 (vc-git-dir-status-state->hash git-state
))
508 ;; Follows vc-git-command (or vc-do-async-command), which uses vc-do-command
509 ;; from vc-dispatcher.
510 (declare-function vc-exec-after
"vc-dispatcher" (code))
511 ;; Follows vc-exec-after.
512 (declare-function vc-set-async-update
"vc-dispatcher" (process-buffer))
514 (defun vc-git-dir-status-goto-stage (git-state)
515 (let ((files (vc-git-dir-status-state->files git-state
)))
517 (pcase (vc-git-dir-status-state->stage git-state
)
520 (vc-git-command (current-buffer) 'async files
"add" "--refresh" "--")
521 (vc-git-command (current-buffer) 'async nil
522 "update-index" "--refresh")))
524 (vc-git-command (current-buffer) 'async files
525 "ls-files" "-z" "-c" "-s" "--"))
526 (`ls-files-up-to-date
527 (vc-git-command (current-buffer) 'async files
528 "ls-files" "-z" "-c" "-s" "--"))
530 (vc-git-command (current-buffer) 'async files
531 "ls-files" "-z" "-c" "-s" "--"))
533 (vc-git-command (current-buffer) 'async files
534 "ls-files" "-z" "-o" "--directory"
535 "--no-empty-directory" "--exclude-standard" "--"))
537 (vc-git-command (current-buffer) 'async files
538 "ls-files" "-z" "-o" "-i" "--directory"
539 "--no-empty-directory" "--exclude-standard" "--"))
540 ;; --relative added in Git 1.5.5.
542 (vc-git-command (current-buffer) 'async files
543 "diff-index" "--relative" "-z" "-M" "HEAD" "--")))
545 (vc-git-after-dir-status-stage git-state
))))
547 (defun vc-git-dir-status-files (_dir files update-function
)
548 "Return a list of (FILE STATE EXTRA) entries for DIR."
549 ;; Further things that would have to be fixed later:
550 ;; - how to handle unregistered directories
551 ;; - how to support vc-dir on a subdir of the project tree
552 (vc-git-dir-status-goto-stage
553 (make-vc-git-dir-status-state :stage
'update-index
555 :update-function update-function
)))
557 (defvar vc-git-stash-map
558 (let ((map (make-sparse-keymap)))
559 ;; Turn off vc-dir marking
560 (define-key map
[mouse-2
] 'ignore
)
562 (define-key map
[down-mouse-3
] 'vc-git-stash-menu
)
563 (define-key map
"\C-k" 'vc-git-stash-delete-at-point
)
564 (define-key map
"=" 'vc-git-stash-show-at-point
)
565 (define-key map
"\C-m" 'vc-git-stash-show-at-point
)
566 (define-key map
"A" 'vc-git-stash-apply-at-point
)
567 (define-key map
"P" 'vc-git-stash-pop-at-point
)
568 (define-key map
"S" 'vc-git-stash-snapshot
)
571 (defvar vc-git-stash-menu-map
572 (let ((map (make-sparse-keymap "Git Stash")))
574 '(menu-item "Delete Stash" vc-git-stash-delete-at-point
575 :help "Delete the current stash"))
577 '(menu-item "Apply Stash" vc-git-stash-apply-at-point
578 :help "Apply the current stash and keep it in the stash list"))
580 '(menu-item "Apply and Remove Stash (Pop)" vc-git-stash-pop-at-point
581 :help "Apply the current stash and remove it"))
583 '(menu-item "Show Stash" vc-git-stash-show-at-point
584 :help "Show the contents of the current stash"))
587 (defun vc-git-dir-extra-headers (dir)
588 (let ((str (with-output-to-string
589 (with-current-buffer standard-output
590 (vc-git--out-ok "symbolic-ref" "HEAD"))))
591 (stash (vc-git-stash-list))
592 (stash-help-echo "Use M-x vc-git-stash to create stashes.")
593 branch remote remote-url)
594 (if (string-match "^\\(refs/heads/\\)?\\(.+\\)$" str)
596 (setq branch (match-string 2 str))
598 (with-output-to-string
599 (with-current-buffer standard-output
600 (vc-git--out-ok "config"
601 (concat "branch." branch ".remote")))))
602 (when (string-match "\\([^\n]+\\)" remote)
603 (setq remote (match-string 1 remote)))
606 (with-output-to-string
607 (with-current-buffer standard-output
608 (vc-git--out-ok "config"
609 (concat "remote." remote ".url"))))))
610 (when (string-match "\\([^\n]+\\)" remote-url)
611 (setq remote-url (match-string 1 remote-url))))
612 (setq branch "not (detached HEAD)"))
613 ;; FIXME: maybe use a different face when nothing is stashed.
615 (propertize "Branch : " 'face 'font-lock-type-face)
617 'face 'font-lock-variable-name-face)
621 (propertize "Remote : " 'face 'font-lock-type-face)
622 (propertize remote-url
623 'face 'font-lock-variable-name-face)))
625 ;; For now just a heading, key bindings can be added later for various bisect actions
626 (when (file-exists-p (expand-file-name ".git/BISECT_START" (vc-git-root dir)))
627 (propertize "Bisect : in progress\n" 'face 'font-lock-warning-face))
628 (when (file-exists-p (expand-file-name ".git/rebase-apply" (vc-git-root dir)))
629 (propertize "Rebase : in progress\n" 'face 'font-lock-warning-face))
632 (propertize "Stash :\n" 'face 'font-lock-type-face
633 'help-echo stash-help-echo)
637 'face 'font-lock-variable-name-face
638 'mouse-face 'highlight
639 'help-echo "mouse-3: Show stash menu\nRET: Show stash\nA: Apply stash\nP: Apply and remove stash (pop)\nC-k: Delete stash"
640 'keymap vc-git-stash-map))
643 (propertize "Stash : " 'face 'font-lock-type-face
644 'help-echo stash-help-echo)
645 (propertize "Nothing stashed"
646 'help-echo stash-help-echo
647 'face 'font-lock-variable-name-face))))))
649 (defun vc-git-branches ()
650 "Return the existing branches, as a list of strings.
651 The car of the list is the current branch."
653 (vc-git--call t "branch")
654 (goto-char (point-min))
655 (let (current-branch branches)
657 (when (looking-at "^\\([ *]\\) \\(.+\\)$")
658 (if (string-equal (match-string 1) "*")
659 (setq current-branch (match-string 2))
660 (push (match-string 2) branches)))
662 (cons current-branch (nreverse branches)))))
664 ;;; STATE-CHANGING FUNCTIONS
666 (defun vc-git-create-repo ()
667 "Create a new Git repository."
668 (vc-git-command nil 0 nil "init"))
670 (defun vc-git-register (files &optional _comment)
671 "Register FILES into the git version-control system."
674 (if (file-directory-p crt)
678 (vc-git-command nil 0 flist "update-index" "--add" "--"))
680 (vc-git-command nil 0 dlist "add"))))
682 (defalias 'vc-git-responsible-p 'vc-git-root)
684 (defun vc-git-unregister (file)
685 (vc-git-command nil 0 file "rm" "-f" "--cached" "--"))
687 (declare-function log-edit-mode "log-edit" ())
688 (declare-function log-edit-toggle-header "log-edit" (header value))
689 (declare-function log-edit-extract-headers "log-edit" (headers string))
690 (declare-function log-edit-set-header "log-edit" (header value &optional toggle))
692 (defun vc-git-log-edit-toggle-signoff ()
693 "Toggle whether to add the \"Signed-off-by\" line at the end of
696 (log-edit-toggle-header "Sign-Off" "yes"))
698 (defun vc-git-log-edit-toggle-amend ()
699 "Toggle whether this will amend the previous commit.
700 If toggling on, also insert its message into the buffer."
702 (when (log-edit-toggle-header "Amend" "yes")
703 (goto-char (point-max))
704 (unless (bolp) (insert "\n"))
705 (insert (with-output-to-string
707 standard-output 1 nil
708 "log" "--max-count=1" "--pretty=format:%B" "HEAD")))
713 (and (zerop (forward-line 1))
714 (looking-at "\n\\|\\'")
715 (let ((summary (buffer-substring-no-properties pt (1- (point)))))
716 (skip-chars-forward " \n")
717 (delete-region pt (point))
718 (log-edit-set-header "Summary" summary)))))))
720 (defvar vc-git-log-edit-mode-map
721 (let ((map (make-sparse-keymap "Git-Log-Edit")))
722 (define-key map "\C-c\C-s" 'vc-git-log-edit-toggle-signoff)
723 (define-key map "\C-c\C-e" 'vc-git-log-edit-toggle-amend)
726 (define-derived-mode vc-git-log-edit-mode log-edit-mode "Log-Edit/git"
727 "Major mode for editing Git log messages.
728 It is based on `log-edit-mode', and has Git-specific extensions.")
730 (defun vc-git-checkin (files comment &optional _rev)
731 (let* ((file1 (or (car files) default-directory))
732 (root (vc-git-root file1))
733 (default-directory (expand-file-name root))
734 (only (or (cdr files)
735 (not (equal root (abbreviate-file-name file1)))))
736 (pcsw coding-system-for-write)
737 (coding-system-for-write
738 ;; On MS-Windows, we must encode command-line arguments in
739 ;; the system codepage.
740 (if (eq system-type 'windows-nt)
742 (or coding-system-for-write vc-git-commits-coding-system)))
744 ;; On MS-Windows, pass the commit log message through a
745 ;; file, to work around the limitation that command-line
746 ;; arguments must be in the system codepage, and therefore
747 ;; might not support the non-ASCII characters in the log
748 ;; message. Handle also remote files.
749 (if (eq system-type 'windows-nt)
750 (let ((default-directory (file-name-directory file1)))
751 (file-local-name (make-nearby-temp-file "git-msg"))))))
752 (cl-flet ((boolean-arg-fn
754 (lambda (value) (when (equal value "yes") (list argument)))))
755 ;; When operating on the whole tree, better pass "-a" than ".", since "."
756 ;; fails when we're committing a merge.
757 (apply 'vc-git-command nil 0 (if only files)
758 (nconc (if msg-file (list "commit" "-F" msg-file)
759 (list "commit" "-m"))
761 (log-edit-extract-headers
762 `(("Author" . "--author")
764 ("Amend" . ,(boolean-arg-fn "--amend"))
765 ("Sign-Off" . ,(boolean-arg-fn "--signoff")))
768 (let ((coding-system-for-write
769 (or pcsw vc-git-commits-coding-system)))
770 (write-region (car args) nil msg-file))
771 (setq args (cdr args)))
773 (if only (list "--only" "--") '("-a")))))
774 (if (and msg-file (file-exists-p msg-file)) (delete-file msg-file))))
776 (defun vc-git-find-revision (file rev buffer)
777 (let* (process-file-side-effects
778 (coding-system-for-read 'binary)
779 (coding-system-for-write 'binary)
781 (let ((fn (vc-git--run-command-string
782 file "ls-files" "-z" "--full-name" "--")))
783 ;; ls-files does not return anything when looking for a
784 ;; revision of a file that has been renamed or removed.
786 (file-relative-name file (vc-git-root default-directory))
787 (substring fn 0 -1)))))
791 "cat-file" "blob" (concat (if rev rev "HEAD") ":" fullname))))
793 (defun vc-git-find-ignore-file (file)
794 "Return the git ignore file that controls FILE."
795 (expand-file-name ".gitignore"
798 (defun vc-git-checkout (file &optional rev)
799 (vc-git-command nil 0 file "checkout" (or rev "HEAD")))
801 (defun vc-git-revert (file &optional contents-done)
802 "Revert FILE to the version stored in the git repository."
804 (vc-git-command nil 0 file "update-index" "--")
805 (vc-git-command nil 0 file "reset" "-q" "--")
806 (vc-git-command nil nil file "checkout" "-q" "--")))
808 (defvar vc-git-error-regexp-alist
809 '(("^ \\(.+\\) |" 1 nil nil 0))
810 "Value of `compilation-error-regexp-alist' in *vc-git* buffers.")
812 ;; To be called via vc-pull from vc.el, which requires vc-dispatcher.
813 (declare-function vc-compilation-mode "vc-dispatcher" (backend))
815 (defun vc-git--pushpull (command prompt)
816 "Run COMMAND (a string; either push or pull) on the current Git branch.
817 If PROMPT is non-nil, prompt for the Git command to run."
818 (let* ((root (vc-git-root default-directory))
819 (buffer (format "*vc-git : %s*" (expand-file-name root)))
820 (git-program vc-git-program)
822 ;; If necessary, prompt for the exact command.
823 ;; TODO if pushing, prompt if no default push location - cf bzr.
825 (setq args (split-string
827 (format "Git %s command: " command)
828 (format "%s %s" git-program command)
831 (setq git-program (car args)
834 (require 'vc-dispatcher)
835 (apply 'vc-do-async-command buffer root git-program command args)
836 (with-current-buffer buffer
838 (vc-compilation-mode 'git)
839 (setq-local compile-command
840 (concat git-program " " command " "
841 (if args (mapconcat 'identity args " ") "")))))
842 (vc-set-async-update buffer)))
844 (defun vc-git-pull (prompt)
845 "Pull changes into the current Git branch.
846 Normally, this runs \"git pull\". If PROMPT is non-nil, prompt
847 for the Git command to run."
848 (vc-git--pushpull "pull" prompt))
850 (defun vc-git-push (prompt)
851 "Push changes from the current Git branch.
852 Normally, this runs \"git push\". If PROMPT is non-nil, prompt
853 for the Git command to run."
854 (vc-git--pushpull "push" prompt))
856 (defun vc-git-merge-branch ()
857 "Merge changes into the current Git branch.
858 This prompts for a branch to merge from."
859 (let* ((root (vc-git-root default-directory))
860 (buffer (format "*vc-git : %s*" (expand-file-name root)))
861 (branches (cdr (vc-git-branches)))
863 (completing-read "Merge from branch: "
864 (if (or (member "FETCH_HEAD" branches)
865 (not (file-readable-p
866 (expand-file-name ".git/FETCH_HEAD"
869 (cons "FETCH_HEAD" branches))
871 (apply 'vc-do-async-command buffer root vc-git-program "merge"
873 (with-current-buffer buffer (vc-run-delayed (vc-compilation-mode 'git)))
874 (vc-set-async-update buffer)))
876 (defun vc-git-conflicted-files (directory)
877 "Return the list of files with conflicts in DIRECTORY."
879 (vc-git--run-command-string directory "status" "--porcelain" "--"))
880 (lines (when status (split-string status "\n" 'omit-nulls)))
882 ;; TODO: Look into reimplementing `vc-git-state', as well as
883 ;; `vc-git-dir-status-files', based on this output, thus making the
884 ;; extra process call in `vc-git-find-file-hook' unnecessary.
885 (dolist (line lines files)
886 (when (string-match "\\([ MADRCU?!][ MADRCU?!]\\) \\(.+\\)\\(?: -> \\(.+\\)\\)?"
888 (let ((state (match-string 1 line))
889 (file (match-string 2 line)))
890 ;; See git-status(1).
891 (when (member state '("AU" "UD" "UA" ;; "DD"
893 (push (expand-file-name file directory) files)))))))
895 (defun vc-git-resolve-when-done ()
896 "Call \"git add\" if the conflict markers have been removed."
898 (goto-char (point-min))
899 (unless (re-search-forward "^<<<<<<< " nil t)
900 (vc-git-command nil 0 buffer-file-name "add")
902 (not (eq vc-git-resolve-conflicts 'unstage-maybe))
903 ;; Doing a merge, so bug#20292 doesn't apply.
904 (file-exists-p (expand-file-name ".git/MERGE_HEAD"
905 (vc-git-root buffer-file-name)))
906 (vc-git-conflicted-files (vc-git-root buffer-file-name)))
907 (vc-git-command nil 0 nil "reset"))
908 ;; Remove the hook so that it is not called multiple times.
909 (remove-hook 'after-save-hook 'vc-git-resolve-when-done t))))
911 (defun vc-git-find-file-hook ()
912 "Activate `smerge-mode' if there is a conflict."
913 (when (and buffer-file-name
915 ;; 1) the net result is to call git twice per file.
916 ;; 2) v-g-c-f is documented to take a directory.
917 ;; http://lists.gnu.org/archive/html/emacs-devel/2014-01/msg01126.html
918 (vc-git-conflicted-files buffer-file-name)
920 (goto-char (point-min))
921 (re-search-forward "^<<<<<<< " nil 'noerror)))
922 (vc-file-setprop buffer-file-name 'vc-state 'conflict)
923 (smerge-start-session)
924 (when vc-git-resolve-conflicts
925 (add-hook 'after-save-hook 'vc-git-resolve-when-done nil 'local))
926 (vc-message-unresolved-conflicts buffer-file-name)))
928 ;;; HISTORY FUNCTIONS
930 (autoload 'vc-setup-buffer "vc-dispatcher")
932 (defcustom vc-git-print-log-follow nil
933 "If true, follow renames in Git logs for files."
937 (defun vc-git-print-log (files buffer &optional shortlog start-revision limit)
938 "Print commit log associated with FILES into specified BUFFER.
939 If SHORTLOG is non-nil, use a short format based on `vc-git-root-log-format'.
940 \(This requires at least Git version 1.5.6, for the --graph option.)
941 If START-REVISION is non-nil, it is the newest revision to show.
942 If LIMIT is non-nil, show no more than this many entries."
943 (let ((coding-system-for-read
944 (or coding-system-for-read vc-git-log-output-coding-system)))
945 ;; `vc-do-command' creates the buffer, but we need it before running
947 (vc-setup-buffer buffer)
948 ;; If the buffer exists from a previous invocation it might be
950 (let ((inhibit-read-only t))
953 (apply 'vc-git-command buffer
956 '("log" "--no-color")
957 (when (and vc-git-print-log-follow
958 (not (cl-some #'file-directory-p files)))
959 ;; "--follow" on directories is broken
960 ;; https://debbugs.gnu.org/cgi/bugreport.cgi?bug=8756
961 ;; https://debbugs.gnu.org/cgi/bugreport.cgi?bug=16422
964 `("--graph" "--decorate" "--date=short"
965 ,(format "--pretty=tformat:%s"
966 (car vc-git-root-log-format))
968 (when limit (list "-n" (format "%s" limit)))
969 (when start-revision (list start-revision))
972 (defun vc-git-log-outgoing (buffer remote-location)
977 "--no-color" "--graph" "--decorate" "--date=short"
978 (format "--pretty=tformat:%s" (car vc-git-root-log-format))
980 (concat (if (string= remote-location "")
985 (defun vc-git-log-incoming (buffer remote-location)
987 (vc-git-command nil 0 nil "fetch")
991 "--no-color" "--graph" "--decorate" "--date=short"
992 (format "--pretty=tformat:%s" (car vc-git-root-log-format))
994 (concat "HEAD.." (if (string= remote-location "")
998 (defvar log-view-message-re)
999 (defvar log-view-file-re)
1000 (defvar log-view-font-lock-keywords)
1001 (defvar log-view-per-file-logs)
1002 (defvar log-view-expanded-log-entry-function)
1004 (define-derived-mode vc-git-log-view-mode log-view-mode "Git-Log-View"
1005 (require 'add-log) ;; We need the faces add-log.
1006 ;; Don't have file markers, so use impossible regexp.
1007 (set (make-local-variable 'log-view-file-re) "\\`a\\`")
1008 (set (make-local-variable 'log-view-per-file-logs) nil)
1009 (set (make-local-variable 'log-view-message-re)
1010 (if (not (eq vc-log-view-type 'long))
1011 (cadr vc-git-root-log-format)
1012 "^commit *\\([0-9a-z]+\\)"))
1013 ;; Allow expanding short log entries.
1014 (when (memq vc-log-view-type '(short log-outgoing log-incoming))
1015 (setq truncate-lines t)
1016 (set (make-local-variable 'log-view-expanded-log-entry-function)
1017 'vc-git-expanded-log-entry))
1018 (set (make-local-variable 'log-view-font-lock-keywords)
1019 (if (not (eq vc-log-view-type 'long))
1020 (list (cons (nth 1 vc-git-root-log-format)
1021 (nth 2 vc-git-root-log-format)))
1023 `((,log-view-message-re (1 'change-log-acknowledgment)))
1026 '(("^Author:[ \t]+\\([A-Za-z0-9_.+-]+@[A-Za-z0-9_.-]+\\)"
1027 (1 'change-log-email))
1029 ;; user: FirstName LastName <foo@bar>
1030 ("^Author:[ \t]+\\([^<(]+?\\)[ \t]*[(<]\\([A-Za-z0-9_.+-]+@[A-Za-z0-9_.-]+\\)[>)]"
1031 (1 'change-log-name)
1032 (2 'change-log-email))
1033 ("^ +\\(?:\\(?:[Aa]cked\\|[Ss]igned-[Oo]ff\\)-[Bb]y:\\)[ \t]+\\([A-Za-z0-9_.+-]+@[A-Za-z0-9_.-]+\\)"
1034 (1 'change-log-name))
1035 ("^ +\\(?:\\(?:[Aa]cked\\|[Ss]igned-[Oo]ff\\)-[Bb]y:\\)[ \t]+\\([^<(]+?\\)[ \t]*[(<]\\([A-Za-z0-9_.+-]+@[A-Za-z0-9_.-]+\\)[>)]"
1036 (1 'change-log-name)
1037 (2 'change-log-email))
1038 ("^Merge: \\([0-9a-z]+\\) \\([0-9a-z]+\\)"
1039 (1 'change-log-acknowledgment)
1040 (2 'change-log-acknowledgment))
1041 ("^Date: \\(.+\\)" (1 'change-log-date))
1042 ("^summary:[ \t]+\\(.+\\)" (1 'log-view-message)))))))
1045 (defun vc-git-show-log-entry (revision)
1046 "Move to the log entry for REVISION.
1047 REVISION may have the form BRANCH, BRANCH~N,
1048 or BRANCH^ (where \"^\" can be repeated)."
1049 (goto-char (point-min))
1053 (format "\ncommit %s" revision) nil t
1054 (cond ((string-match "~\\([0-9]\\)\\'" revision)
1055 (1+ (string-to-number (match-string 1 revision))))
1056 ((string-match "\\^+\\'" revision)
1057 (1+ (length (match-string 0 revision))))
1059 (beginning-of-line)))
1061 (defun vc-git-expanded-log-entry (revision)
1063 (apply 'vc-git-command t nil nil (list "log" revision "-1" "--"))
1064 (goto-char (point-min))
1066 ;; Indent the expanded log entry.
1067 (while (re-search-forward "^ " nil t)
1072 (defun vc-git-region-history (file buffer lfrom lto)
1073 "Insert into BUFFER the history of FILE for lines LFROM to LTO.
1074 This requires git 1.8.4 or later, for the \"-L\" option of \"git log\"."
1075 ;; The "git log" command below interprets the line numbers as applying
1076 ;; to the HEAD version of the file, not to the current state of the file.
1077 ;; So we need to look at all the local changes and adjust lfrom/lto
1079 ;; FIXME: Maybe this should be done in vc.el (i.e. for all backends), but
1080 ;; since Git is the only backend to support this operation so far, it's hard
1083 (vc-call-backend 'git 'diff file "HEAD" nil (current-buffer))
1084 (goto-char (point-min))
1085 (let ((last-offset 0)
1088 (while (re-search-forward
1089 "^@@ -\\([0-9]+\\),\\([0-9]+\\) \\+\\([0-9]+\\),\\([0-9]+\\) @@" nil t)
1090 (let ((headno (string-to-number (match-string 1)))
1091 (headcnt (string-to-number (match-string 2)))
1092 (curno (string-to-number (match-string 3)))
1093 (curcnt (string-to-number (match-string 4))))
1094 (cl-assert (equal (- curno headno) last-offset))
1095 (and (null from-offset) (> curno lfrom)
1096 (setq from-offset last-offset))
1097 (and (null to-offset) (> curno lto)
1098 (setq to-offset last-offset))
1100 (- (+ curno curcnt) (+ headno headcnt)))))
1101 (setq lto (- lto (or to-offset last-offset)))
1102 (setq lfrom (- lfrom (or to-offset last-offset)))))
1103 (vc-git-command buffer 'async nil "log" "-p" ;"--follow" ;FIXME: not supported?
1104 (format "-L%d,%d:%s" lfrom lto (file-relative-name file))))
1106 (require 'diff-mode)
1108 (defvar vc-git-region-history-mode-map
1109 (let ((map (make-composed-keymap
1110 nil (make-composed-keymap
1111 (list diff-mode-map vc-git-log-view-mode-map)))))
1114 (defvar vc-git--log-view-long-font-lock-keywords nil)
1115 (defvar font-lock-keywords)
1116 (defvar vc-git-region-history-font-lock-keywords
1117 `((vc-git-region-history-font-lock)))
1119 (defun vc-git-region-history-font-lock (limit)
1120 (let ((in-diff (save-excursion
1122 (or (looking-at "^\\(?:diff\\|commit\\)\\>")
1123 (re-search-backward "^\\(?:diff\\|commit\\)\\>" nil t))
1124 (eq ?d (char-after (match-beginning 0))))))
1126 (let ((end (save-excursion
1127 (if (re-search-forward "\n\\(diff\\|commit\\)\\>"
1131 (let ((font-lock-keywords (if in-diff diff-font-lock-keywords
1132 vc-git--log-view-long-font-lock-keywords)))
1133 (font-lock-fontify-keywords-region (point) end))
1135 (prog1 (< (point) limit)
1136 (setq in-diff (eq ?d (char-after))))))
1139 (define-derived-mode vc-git-region-history-mode
1140 vc-git-log-view-mode "Git-Region-History"
1141 "Major mode to browse Git's \"log -p\" output."
1142 (setq-local vc-git--log-view-long-font-lock-keywords
1143 log-view-font-lock-keywords)
1144 (setq-local font-lock-defaults
1145 (cons 'vc-git-region-history-font-lock-keywords
1146 (cdr font-lock-defaults))))
1148 (defun vc-git--asciify-coding-system ()
1149 ;; Try to reconcile the content encoding with the encoding of Git's
1150 ;; auxiliary output (which is ASCII or ASCII-compatible), bug#23595.
1151 (unless (let ((samp "Binary files differ"))
1152 (string-equal samp (decode-coding-string
1153 samp coding-system-for-read t)))
1154 (setq coding-system-for-read 'undecided)))
1156 (autoload 'vc-switches "vc")
1158 (defun vc-git-diff (files &optional rev1 rev2 buffer _async)
1159 "Get a difference report using Git between two revisions of FILES."
1160 (let (process-file-side-effects
1161 (command "diff-tree"))
1162 (vc-git--asciify-coding-system)
1164 ;; Diffing against the empty tree.
1165 (unless rev1 (setq rev1 "4b825dc642cb6eb9a060e54bf8d69288fbee4904"))
1166 (setq command "diff-index")
1167 (unless rev1 (setq rev1 "HEAD")))
1168 (if vc-git-diff-switches
1169 (apply #'vc-git-command (or buffer "*vc-diff*")
1174 (append (vc-switches 'git 'diff)
1175 (list "-p" (or rev1 "HEAD") rev2 "--")))
1176 (vc-git-command (or buffer "*vc-diff*") 1 files
1177 "difftool" "--exit-code" "--no-prompt" "-x"
1179 (mapconcat 'identity
1180 (vc-switches nil 'diff) " "))
1183 (defun vc-git-revision-table (_files)
1184 ;; What about `files'?!? --Stef
1185 (let (process-file-side-effects
1186 (table (list "HEAD")))
1188 (vc-git-command t nil nil "for-each-ref" "--format=%(refname)")
1189 (goto-char (point-min))
1190 (while (re-search-forward "^refs/\\(heads\\|tags\\|remotes\\)/\\(.*\\)$"
1192 (push (match-string 2) table)))
1195 (defun vc-git-revision-completion-table (files)
1196 (letrec ((table (lazy-completion-table
1197 table (lambda () (vc-git-revision-table files)))))
1200 (defun vc-git-annotate-command (file buf &optional rev)
1201 (vc-git--asciify-coding-system)
1202 (let ((name (file-relative-name file)))
1203 (apply #'vc-git-command buf 'async nil "blame" "--date=short"
1204 (append (vc-switches 'git 'annotate)
1205 (list rev "--" name)))))
1207 (declare-function vc-annotate-convert-time "vc-annotate" (&optional time))
1209 (defun vc-git-annotate-time ()
1210 (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)
1211 (vc-annotate-convert-time
1212 (apply #'encode-time (mapcar (lambda (match)
1213 (if (match-beginning match)
1214 (string-to-number (match-string match))
1216 '(6 5 4 3 2 1 7))))))
1218 (defun vc-git-annotate-extract-revision-at-line ()
1221 (when (looking-at "\\^?\\([0-9a-f]+\\) \\(\\([^(]+\\) \\)?")
1222 (let ((revision (match-string-no-properties 1)))
1223 (if (match-beginning 2)
1224 (let ((fname (match-string-no-properties 3)))
1225 ;; Remove trailing whitespace from the file name.
1226 (when (string-match " +\\'" fname)
1227 (setq fname (substring fname 0 (match-beginning 0))))
1229 (expand-file-name fname (vc-git-root default-directory))))
1234 (defun vc-git-create-tag (dir name branchp)
1235 (let ((default-directory dir))
1236 (and (vc-git-command nil 0 nil "update-index" "--refresh")
1238 (vc-git-command nil 0 nil "checkout" "-b" name)
1239 (vc-git-command nil 0 nil "tag" name)))))
1241 (defun vc-git-retrieve-tag (dir name _update)
1242 (let ((default-directory dir))
1243 (vc-git-command nil 0 nil "checkout" name)))
1248 (defun vc-git-previous-revision (file rev)
1249 "Git-specific version of `vc-previous-revision'."
1251 (let* ((fname (file-relative-name file))
1252 (prev-rev (with-temp-buffer
1254 (vc-git--out-ok "rev-list" "-2" rev "--" fname)
1255 (goto-char (point-max))
1257 (zerop (forward-line -1))
1259 (buffer-substring-no-properties
1261 (1- (point-max)))))))
1262 (or (vc-git-symbolic-commit prev-rev) prev-rev))
1263 ;; We used to use "^" here, but that fails on MS-Windows if git is
1264 ;; invoked via a batch file, in which case cmd.exe strips the "^"
1265 ;; because it is a special character for cmd which process-file
1266 ;; does not (and cannot) quote.
1267 (vc-git--rev-parse (concat rev "~1"))))
1269 (defun vc-git--rev-parse (rev)
1272 (vc-git--out-ok "rev-parse" rev)
1273 (buffer-substring-no-properties (point-min) (+ (point-min) 40)))))
1275 (defun vc-git-next-revision (file rev)
1276 "Git-specific version of `vc-next-revision'."
1277 (let* ((default-directory (vc-git-root file))
1278 (file (file-relative-name file))
1282 (vc-git--out-ok "rev-list" "-1" rev "--" file)
1283 (goto-char (point-max))
1285 (zerop (forward-line -1))
1287 (buffer-substring-no-properties
1289 (1- (point-max))))))
1294 (vc-git--out-ok "rev-list" "HEAD" "--" file)
1295 (goto-char (point-min))
1296 (search-forward current-rev nil t)
1297 (zerop (forward-line -1))
1298 (buffer-substring-no-properties
1300 (progn (forward-line 1) (1- (point)))))))))
1301 (or (vc-git-symbolic-commit next-rev) next-rev)))
1303 (defun vc-git-delete-file (file)
1304 (vc-git-command nil 0 file "rm" "-f" "--"))
1306 (defun vc-git-rename-file (old new)
1307 (vc-git-command nil 0 (list old new) "mv" "-f" "--"))
1309 (defvar vc-git-extra-menu-map
1310 (let ((map (make-sparse-keymap)))
1311 (define-key map [git-grep]
1312 '(menu-item "Git grep..." vc-git-grep
1313 :help "Run the `git grep' command"))
1314 (define-key map [git-sn]
1315 '(menu-item "Stash a Snapshot" vc-git-stash-snapshot
1316 :help "Stash the current state of the tree and keep the current state"))
1317 (define-key map [git-st]
1318 '(menu-item "Create Stash..." vc-git-stash
1319 :help "Stash away changes"))
1320 (define-key map [git-ss]
1321 '(menu-item "Show Stash..." vc-git-stash-show
1322 :help "Show stash contents"))
1325 (defun vc-git-extra-menu () vc-git-extra-menu-map)
1327 (defun vc-git-extra-status-menu () vc-git-extra-menu-map)
1329 (defun vc-git-root (file)
1330 (or (vc-file-getprop file 'git-root)
1331 (vc-file-setprop file 'git-root (vc-find-root file ".git"))))
1333 ;; grep-compute-defaults autoloads grep.
1334 (declare-function grep-read-regexp "grep" ())
1335 (declare-function grep-read-files "grep" (regexp))
1336 (declare-function grep-expand-template "grep"
1337 (template &optional regexp files dir excl))
1339 ;; Derived from `lgrep'.
1340 (defun vc-git-grep (regexp &optional files dir)
1341 "Run git grep, searching for REGEXP in FILES in directory DIR.
1342 The search is limited to file names matching shell pattern FILES.
1343 FILES may use abbreviations defined in `grep-files-aliases', e.g.
1344 entering `ch' is equivalent to `*.[ch]'.
1346 With \\[universal-argument] prefix, you can edit the constructed shell command line
1347 before it is executed.
1348 With two \\[universal-argument] prefixes, directly edit and run `grep-command'.
1350 Collect output in a buffer. While git grep runs asynchronously, you
1351 can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
1352 in the grep output buffer,
1353 to go to the lines where grep found matches.
1355 This command shares argument histories with \\[rgrep] and \\[grep]."
1358 (grep-compute-defaults)
1360 ((equal current-prefix-arg '(16))
1361 (list (read-from-minibuffer "Run: " "git grep"
1362 nil nil 'grep-history)
1364 (t (let* ((regexp (grep-read-regexp))
1365 (files (grep-read-files regexp))
1366 (dir (read-directory-name "In directory: "
1367 nil default-directory t)))
1368 (list regexp files dir))))))
1370 (when (and (stringp regexp) (> (length regexp) 0))
1371 (let ((command regexp))
1373 (if (string= command "git grep")
1375 (setq dir (file-name-as-directory (expand-file-name dir)))
1377 (grep-expand-template "git --no-pager grep -n -e <R> -- <F>"
1380 (if (equal current-prefix-arg '(4))
1382 (read-from-minibuffer "Confirm: "
1383 command nil nil 'grep-history))
1384 (add-to-history 'grep-history command))))
1386 (let ((default-directory dir)
1387 (compilation-environment (cons "PAGER=" compilation-environment)))
1388 ;; Setting process-setup-function makes exit-message-function work
1389 ;; even when async processes aren't supported.
1390 (compilation-start command 'grep-mode))
1391 (if (eq next-error-last-buffer (current-buffer))
1392 (setq default-directory dir))))))
1394 ;; Everywhere but here, follows vc-git-command, which uses vc-do-command
1395 ;; from vc-dispatcher.
1396 (autoload 'vc-resynch-buffer "vc-dispatcher")
1398 (defun vc-git-stash (name)
1400 (interactive "sStash name: ")
1401 (let ((root (vc-git-root default-directory)))
1403 (vc-git--call nil "stash" "save" name)
1404 (vc-resynch-buffer root t t))))
1406 (defun vc-git-stash-show (name)
1407 "Show the contents of stash NAME."
1408 (interactive "sStash name: ")
1409 (vc-setup-buffer "*vc-git-stash*")
1410 (vc-git-command "*vc-git-stash*" 'async nil "stash" "show" "-p" name)
1411 (set-buffer "*vc-git-stash*")
1413 (setq buffer-read-only t)
1414 (pop-to-buffer (current-buffer)))
1416 (defun vc-git-stash-apply (name)
1418 (interactive "sApply stash: ")
1419 (vc-git-command "*vc-git-stash*" 0 nil "stash" "apply" "-q" name)
1420 (vc-resynch-buffer (vc-git-root default-directory) t t))
1422 (defun vc-git-stash-pop (name)
1424 (interactive "sPop stash: ")
1425 (vc-git-command "*vc-git-stash*" 0 nil "stash" "pop" "-q" name)
1426 (vc-resynch-buffer (vc-git-root default-directory) t t))
1428 (defun vc-git-stash-snapshot ()
1429 "Create a stash with the current tree state."
1431 (vc-git--call nil "stash" "save"
1432 (let ((ct (current-time)))
1434 (format-time-string "Snapshot on %Y-%m-%d" ct)
1435 (format-time-string " at %H:%M" ct))))
1436 (vc-git-command "*vc-git-stash*" 0 nil "stash" "apply" "-q" "stash@{0}")
1437 (vc-resynch-buffer (vc-git-root default-directory) t t))
1439 (defun vc-git-stash-list ()
1443 (replace-regexp-in-string
1444 "^stash@" " " (vc-git--run-command-string nil "stash" "list"))
1447 (defun vc-git-stash-get-at-point (point)
1451 (if (looking-at "^ +\\({[0-9]+}\\):")
1453 (error "Cannot find stash at point"))))
1455 ;; vc-git-stash-delete-at-point must be called from a vc-dir buffer.
1456 (declare-function vc-dir-refresh "vc-dir" ())
1458 (defun vc-git-stash-delete-at-point ()
1460 (let ((stash (vc-git-stash-get-at-point (point))))
1461 (when (y-or-n-p (format "Remove stash %s ? " stash))
1462 (vc-git--run-command-string nil "stash" "drop" (format "stash@%s" stash))
1465 (defun vc-git-stash-show-at-point ()
1467 (vc-git-stash-show (format "stash@%s" (vc-git-stash-get-at-point (point)))))
1469 (defun vc-git-stash-apply-at-point ()
1471 (let (vc-dir-buffers) ; Small optimization.
1472 (vc-git-stash-apply (format "stash@%s" (vc-git-stash-get-at-point (point)))))
1475 (defun vc-git-stash-pop-at-point ()
1477 (let (vc-dir-buffers) ; Likewise.
1478 (vc-git-stash-pop (format "stash@%s" (vc-git-stash-get-at-point (point)))))
1481 (defun vc-git-stash-menu (e)
1483 (vc-dir-at-event e (popup-menu vc-git-stash-menu-map e)))
1486 ;;; Internal commands
1488 (defun vc-git-command (buffer okstatus file-or-list &rest flags)
1489 "A wrapper around `vc-do-command' for use in vc-git.el.
1490 The difference to vc-do-command is that this function always invokes
1492 (let ((coding-system-for-read
1493 (or coding-system-for-read vc-git-log-output-coding-system))
1494 (coding-system-for-write
1495 (or coding-system-for-write vc-git-commits-coding-system))
1496 (process-environment (cons "GIT_DIR" process-environment)))
1497 (apply 'vc-do-command (or buffer "*vc*") okstatus vc-git-program
1498 ;; http://debbugs.gnu.org/16897
1499 (unless (and (not (cdr-safe file-or-list))
1500 (let ((file (or (car-safe file-or-list)
1503 (eq ?/ (aref file (1- (length file))))
1504 (equal file (vc-git-root file)))))
1506 (cons "--no-pager" flags))))
1508 (defun vc-git--empty-db-p ()
1509 "Check if the git db is empty (no commit done yet)."
1510 (let (process-file-side-effects)
1511 (not (eq 0 (vc-git--call nil "rev-parse" "--verify" "HEAD")))))
1513 (defun vc-git--call (buffer command &rest args)
1514 ;; We don't need to care the arguments. If there is a file name, it
1515 ;; is always a relative one. This works also for remote
1516 ;; directories. We enable `inhibit-null-byte-detection', otherwise
1517 ;; Tramp's eol conversion might be confused.
1518 (let ((inhibit-null-byte-detection t)
1519 (coding-system-for-read
1520 (or coding-system-for-read vc-git-log-output-coding-system))
1521 (coding-system-for-write
1522 (or coding-system-for-write vc-git-commits-coding-system))
1523 (process-environment (cons "PAGER=" process-environment)))
1524 (push "GIT_DIR" process-environment)
1525 (apply 'process-file vc-git-program nil buffer nil command args)))
1527 (defun vc-git--out-ok (command &rest args)
1528 (zerop (apply 'vc-git--call '(t nil) command args)))
1530 (defun vc-git--run-command-string (file &rest args)
1531 "Run a git command on FILE and return its output as string.
1534 (str (with-output-to-string
1535 (with-current-buffer standard-output
1536 (unless (apply 'vc-git--out-ok
1538 (append args (list (file-relative-name
1544 (defun vc-git-symbolic-commit (commit)
1545 "Translate COMMIT string into symbolic form.
1546 Returns nil if not possible."
1548 (let ((name (with-temp-buffer
1550 (vc-git--out-ok "name-rev" "--name-only" commit)
1551 (goto-char (point-min))
1552 (= (forward-line 2) 1)
1554 (buffer-substring-no-properties (point-min)
1555 (1- (point-max)))))))
1556 (and name (not (string= name "undefined")) name))))
1560 ;;; vc-git.el ends here