1 ;;; vc-git.el --- VC backend for the git version control system -*- lexical-binding: t -*-
3 ;; Copyright (C) 2006-2018 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 <https://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
112 (defcustom vc-git-diff-switches t
113 "String or list of strings specifying switches for Git diff under VC.
114 If nil, use the value of `vc-diff-switches'. If t, use no switches."
115 :type
'(choice (const :tag
"Unspecified" nil
)
116 (const :tag
"None" t
)
117 (string :tag
"Argument String")
118 (repeat :tag
"Argument List" :value
("") string
))
121 (defcustom vc-git-annotate-switches nil
122 "String or list of strings specifying switches for Git blame under VC.
123 If nil, use the value of `vc-annotate-switches'. If t, use no switches."
124 :type
'(choice (const :tag
"Unspecified" nil
)
125 (const :tag
"None" t
)
126 (string :tag
"Argument String")
127 (repeat :tag
"Argument List" :value
("") string
))
130 (defcustom vc-git-resolve-conflicts t
131 "When non-nil, mark conflicted file as resolved upon saving.
132 That is performed after all conflict markers in it have been
133 removed. If the value is `unstage-maybe', and no merge is in
134 progress, then after the last conflict is resolved, also clear
136 :type
'(choice (const :tag
"Don't resolve" nil
)
137 (const :tag
"Resolve" t
)
138 (const :tag
"Resolve and maybe unstage all files"
142 (defcustom vc-git-program
"git"
143 "Name of the Git executable (excluding any arguments)."
147 (defcustom vc-git-root-log-format
148 '("%d%h..: %an %ad %s"
149 ;; The first shy group matches the characters drawn by --graph.
150 ;; We use numbered groups because `log-view-message-re' wants the
151 ;; revision number to be group 1.
152 "^\\(?:[*/\\| ]+ \\)?\\(?2: ([^)]+)\\)?\\(?1:[0-9a-z]+\\)..: \
153 \\(?3:.*?\\)[ \t]+\\(?4:[0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\)"
154 ((1 'log-view-message
)
155 (2 'change-log-list nil lax
)
157 (4 'change-log-date
)))
158 "Git log format for `vc-print-root-log'.
159 This should be a list (FORMAT REGEXP KEYWORDS), where FORMAT is a
160 format string (which is passed to \"git log\" via the argument
161 \"--pretty=tformat:FORMAT\"), REGEXP is a regular expression
162 matching the resulting Git log output, and KEYWORDS is a list of
163 `font-lock-keywords' for highlighting the Log View buffer."
164 :type
'(list string string
(repeat sexp
))
167 (defcustom vc-git-commits-coding-system
'utf-8
168 "Default coding system for sending commit log messages to Git.
170 Should be consistent with the Git config value i18n.commitEncoding,
171 and should also be consistent with `locale-coding-system'."
172 :type
'(coding-system :tag
"Coding system to encode Git commit logs")
175 (defcustom vc-git-log-output-coding-system
'utf-8
176 "Default coding system for receiving log output from Git.
178 Should be consistent with the Git config value i18n.logOutputEncoding."
179 :type
'(coding-system :tag
"Coding system to decode Git log output")
182 ;; History of Git commands.
183 (defvar vc-git-history nil
)
185 ;; Clear up the cache to force vc-call to check again and discover
186 ;; new functions when we reload this file.
187 (put 'Git
'vc-functions nil
)
189 ;;; BACKEND PROPERTIES
191 (defun vc-git-revision-granularity () 'repository
)
192 (defun vc-git-checkout-model (_files) 'implicit
)
194 ;;; STATE-QUERYING FUNCTIONS
196 ;;;###autoload (defun vc-git-registered (file)
197 ;;;###autoload "Return non-nil if FILE is registered with git."
198 ;;;###autoload (if (vc-find-root file ".git") ; Short cut.
199 ;;;###autoload (progn
200 ;;;###autoload (load "vc-git" nil t)
201 ;;;###autoload (vc-git-registered file))))
203 (defun vc-git-registered (file)
204 "Check whether FILE is registered with git."
205 (let ((dir (vc-git-root file
)))
208 (let* (process-file-side-effects
209 ;; Do not use the `file-name-directory' here: git-ls-files
210 ;; sometimes fails to return the correct status for relative
212 ;; See also: http://marc.info/?l=git&m=125787684318129&w=2
213 (name (file-relative-name file dir
))
216 (vc-git--out-ok "ls-files" "-c" "-z" "--" name
)
217 ;; If result is empty, use ls-tree to check for deleted
219 (when (eq (point-min) (point-max))
220 (vc-git--out-ok "ls-tree" "--name-only" "-z" "HEAD"
224 (> (length str
) (length name
))
225 (string= (substring str
0 (1+ (length name
)))
226 (concat name
"\0"))))))))
228 (defun vc-git--state-code (code)
229 "Convert from a string to an added/deleted/modified state."
230 (pcase (string-to-char code
)
234 (?U
'edited
) ;; FIXME
235 (?T
'edited
))) ;; FIXME
237 (defvar vc-git--program-version nil
)
239 (defun vc-git--program-version ()
240 (or vc-git--program-version
241 (let ((version-string
242 (vc-git--run-command-string nil
"version")))
243 (setq vc-git--program-version
244 (if (and version-string
245 ;; Git for Windows appends ".windows.N" to the
246 ;; numerical version reported by Git.
248 "git version \\([0-9.]+\\)\\(\.windows.[0-9]+\\)?$"
250 (match-string 1 version-string
)
253 (defun vc-git--git-status-to-vc-state (code-list)
254 "Convert CODE-LIST to a VC status.
256 Each element of CODE-LIST comes from the first two characters of
257 a line returned by 'git status --porcelain' and should be passed
258 in the order given by 'git status'."
259 ;; It is necessary to allow CODE-LIST to be a list because sometimes git
260 ;; status returns multiple lines, e.g. for a file that is removed from
261 ;; the index but is present in the HEAD and working tree.
268 ;; I have only seen this with a file that is only present in the
269 ;; index. Let us call this `removed'.
272 ((string-match-p "^[ RD]+$" code
) 'removed
)
273 ((string-match-p "^[ M]+$" code
) 'edited
)
274 ((string-match-p "^[ A]+$" code
) 'added
)
275 ((string-match-p "^[ U]+$" code
) 'conflict
)
277 ;; I know of two cases when git state returns more than one element,
278 ;; in both cases returning '("D " "??")':
279 ;; 1. When a file is removed from the index but present in the
280 ;; HEAD and working tree.
281 ;; 2. When a file A is renamed to B in the index and then back to A
282 ;; in the working tree.
283 ;; In both of these instances, `unregistered' is a reasonable response.
284 (`("D " "??") 'unregistered
)
285 ;; In other cases, let us return `edited'.
288 (defun vc-git-state (file)
289 "Git-specific version of `vc-state'."
290 ;; It can't set `needs-update' or `needs-merge'. The rough
291 ;; equivalent would be that upstream branch for current branch is in
292 ;; fast-forward state i.e. current branch is direct ancestor of
293 ;; corresponding upstream branch, and the file was modified
294 ;; upstream. We'd need to check against the upstream tracking
295 ;; branch for that (an extra process call or two).
297 `("status" "--porcelain" "-z"
298 ;; Just to be explicit, it's the default anyway.
300 ,@(when (version<= "1.7.6.3" (vc-git--program-version))
303 (status (apply #'vc-git--run-command-string file args
)))
304 ;; Alternatively, the `ignored' state could be detected with 'git
305 ;; ls-files -i -o --exclude-standard', but that's an extra process
306 ;; call, and the `ignored' state is rarely needed.
308 ;; If status is nil, there was an error calling git, likely because
309 ;; the file is not in a git repo.
311 ;; If this code is adapted to parse 'git status' for a directory,
312 ;; note that a renamed file takes up two null values and needs to be
313 ;; treated slightly more carefully.
314 (vc-git--git-status-to-vc-state
317 (split-string status
"\0" t
))))))
319 (defun vc-git-working-revision (_file)
320 "Git-specific version of `vc-working-revision'."
321 (let (process-file-side-effects)
322 (vc-git--rev-parse "HEAD")))
324 (defun vc-git--symbolic-ref (file)
326 (vc-file-getprop file
'vc-git-symbolic-ref
)
327 (let* (process-file-side-effects
328 (str (vc-git--run-command-string nil
"symbolic-ref" "HEAD")))
329 (vc-file-setprop file
'vc-git-symbolic-ref
331 (if (string-match "^\\(refs/heads/\\)?\\(.+\\)$" str
)
335 (defun vc-git-mode-line-string (file)
336 "Return a string for `vc-mode-line' to put in the mode line for FILE."
337 (let* ((rev (vc-working-revision file
'Git
))
338 (disp-rev (or (vc-git--symbolic-ref file
)
339 (substring rev
0 7)))
340 (def-ml (vc-default-mode-line-string 'Git file
))
341 (help-echo (get-text-property 0 'help-echo def-ml
))
342 (face (get-text-property 0 'face def-ml
)))
343 (propertize (concat (substring def-ml
0 4) disp-rev
)
345 'help-echo
(concat help-echo
"\nCurrent revision: " rev
))))
347 (cl-defstruct (vc-git-extra-fileinfo
349 (:constructor vc-git-create-extra-fileinfo
350 (old-perm new-perm
&optional rename-state orig-name
))
351 (:conc-name vc-git-extra-fileinfo-
>))
352 old-perm new-perm
;; Permission flags.
353 rename-state
;; Rename or copy state.
354 orig-name
) ;; Original name for renames or copies.
356 (defun vc-git-escape-file-name (name)
357 "Escape a file name if necessary."
358 (if (string-match "[\n\t\"\\]" name
)
360 (mapconcat (lambda (c)
366 (_ (char-to-string c
))))
371 (defun vc-git-file-type-as-string (old-perm new-perm
)
372 "Return a string describing the file type based on its permissions."
373 (let* ((old-type (lsh (or old-perm
0) -
9))
374 (new-type (lsh (or new-perm
0) -
9))
379 (?
\120 " (type change symlink -> file)")
380 (?
\160 " (type change subproject -> file)")))
383 (?
\100 " (type change file -> symlink)")
384 (?
\160 " (type change subproject -> symlink)")
386 (?
\160 ;; Subproject.
388 (?
\100 " (type change file -> subproject)")
389 (?
\120 " (type change symlink -> subproject)")
390 (_ " (subproject)")))
391 (?
\110 nil
) ;; Directory (internal, not a real git state).
392 (?
\000 ;; Deleted or unknown.
395 (?
\160 " (subproject)")))
396 (_ (format " (unknown type %o)" new-type
)))))
397 (cond (str (propertize str
'face
'font-lock-comment-face
))
398 ((eq new-type ?
\110) "/")
401 (defun vc-git-rename-as-string (state extra
)
402 "Return a string describing the copy or rename associated with INFO,
403 or an empty string if none."
404 (let ((rename-state (when extra
405 (vc-git-extra-fileinfo->rename-state extra
))))
409 (if (eq rename-state
'copy
) "copied from "
410 (if (eq state
'added
) "renamed from "
412 (vc-git-escape-file-name
413 (vc-git-extra-fileinfo->orig-name extra
))
415 'face
'font-lock-comment-face
)
418 (defun vc-git-permissions-as-string (old-perm new-perm
)
419 "Format a permission change as string."
421 (if (or (not old-perm
)
423 (eq 0 (logand ?
\111 (logxor old-perm new-perm
))))
425 (if (eq 0 (logand ?
\111 old-perm
)) "+x" "-x"))
426 'face
'font-lock-type-face
))
428 (defun vc-git-dir-printer (info)
429 "Pretty-printer for the vc-dir-fileinfo structure."
430 (let* ((isdir (vc-dir-fileinfo->directory info
))
431 (state (if isdir
"" (vc-dir-fileinfo->state info
)))
432 (extra (vc-dir-fileinfo->extra info
))
433 (old-perm (when extra
(vc-git-extra-fileinfo->old-perm extra
)))
434 (new-perm (when extra
(vc-git-extra-fileinfo->new-perm extra
))))
437 (propertize (format "%c" (if (vc-dir-fileinfo->marked info
) ?
* ?
))
438 'face
'font-lock-type-face
)
441 (format "%-12s" state
)
442 'face
(cond ((eq state
'up-to-date
) 'font-lock-builtin-face
)
443 ((eq state
'missing
) 'font-lock-warning-face
)
444 (t 'font-lock-variable-name-face
))
445 'mouse-face
'highlight
)
446 " " (vc-git-permissions-as-string old-perm new-perm
)
448 (propertize (vc-git-escape-file-name (vc-dir-fileinfo->name info
))
449 'face
(if isdir
'font-lock-comment-delimiter-face
450 'font-lock-function-name-face
)
453 "Directory\nVC operations can be applied to it\nmouse-3: Pop-up menu"
454 "File\nmouse-3: Pop-up menu")
455 'keymap vc-dir-filename-mouse-map
456 'mouse-face
'highlight
)
457 (vc-git-file-type-as-string old-perm new-perm
)
458 (vc-git-rename-as-string state extra
))))
460 (cl-defstruct (vc-git-dir-status-state
462 (:conc-name vc-git-dir-status-state-
>))
465 ;; List of files still to be processed.
467 ;; Update function to be called at the end.
469 ;; Hash table of entries for files we've computed so far.
470 (hash (make-hash-table :test
'equal
)))
472 (defsubst vc-git-dir-status-update-file
(state filename file-state file-info
)
473 (puthash filename
(list file-state file-info
)
474 (vc-git-dir-status-state->hash state
))
475 (setf (vc-git-dir-status-state->files state
)
476 (delete filename
(vc-git-dir-status-state->files state
))))
478 (defun vc-git-after-dir-status-stage (git-state)
479 "Process sentinel for the various dir-status stages."
481 (files (vc-git-dir-status-state->files git-state
)))
482 (goto-char (point-min))
483 (pcase (vc-git-dir-status-state->stage git-state
)
485 (setq next-stage
(if (vc-git--empty-db-p) 'ls-files-added
'diff-index
)))
487 (setq next-stage
'ls-files-unknown
)
488 (while (re-search-forward "\\([0-7]\\{6\\}\\) [0-9a-f]\\{40\\} 0\t\\([^\0]+\\)\0" nil t
)
489 (let ((new-perm (string-to-number (match-string 1) 8))
490 (name (match-string 2)))
491 (vc-git-dir-status-update-file
492 git-state name
'added
493 (vc-git-create-extra-fileinfo 0 new-perm
)))))
494 (`ls-files-up-to-date
495 (setq next-stage
'ls-files-unknown
)
496 (while (re-search-forward "\\([0-7]\\{6\\}\\) [0-9a-f]\\{40\\} \\([0-3]\\)\t\\([^\0]+\\)\0" nil t
)
497 (let ((perm (string-to-number (match-string 1) 8))
498 (state (match-string 2))
499 (name (match-string 3)))
500 (vc-git-dir-status-update-file
501 git-state name
(if (equal state
"0")
504 (vc-git-create-extra-fileinfo perm perm
)))))
506 (setq next-stage
'ls-files-unknown
)
507 ;; It's enough to look for "3" to notice a conflict.
508 (while (re-search-forward "\\([0-7]\\{6\\}\\) [0-9a-f]\\{40\\} 3\t\\([^\0]+\\)\0" nil t
)
509 (let ((perm (string-to-number (match-string 1) 8))
510 (name (match-string 2)))
511 (vc-git-dir-status-update-file
512 git-state name
'conflict
513 (vc-git-create-extra-fileinfo perm perm
)))))
515 (when files
(setq next-stage
'ls-files-ignored
))
516 (while (re-search-forward "\\([^\0]*?\\)\0" nil t
1)
517 (vc-git-dir-status-update-file git-state
(match-string 1) 'unregistered
518 (vc-git-create-extra-fileinfo 0 0))))
520 (while (re-search-forward "\\([^\0]*?\\)\0" nil t
1)
521 (vc-git-dir-status-update-file git-state
(match-string 1) 'ignored
522 (vc-git-create-extra-fileinfo 0 0))))
524 (setq next-stage
(if files
'ls-files-up-to-date
'ls-files-conflict
))
525 (while (re-search-forward
526 ":\\([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"
528 (let ((old-perm (string-to-number (match-string 1) 8))
529 (new-perm (string-to-number (match-string 2) 8))
530 (state (or (match-string 4) (match-string 6)))
531 (name (or (match-string 5) (match-string 7)))
532 (new-name (match-string 8)))
533 (if new-name
; Copy or rename.
534 (if (eq ?C
(string-to-char state
))
535 (vc-git-dir-status-update-file
536 git-state new-name
'added
537 (vc-git-create-extra-fileinfo old-perm new-perm
539 (vc-git-dir-status-update-file
540 git-state name
'removed
541 (vc-git-create-extra-fileinfo 0 0 'rename new-name
))
542 (vc-git-dir-status-update-file
543 git-state new-name
'added
544 (vc-git-create-extra-fileinfo old-perm new-perm
546 (vc-git-dir-status-update-file
547 git-state name
(vc-git--state-code state
)
548 (vc-git-create-extra-fileinfo old-perm new-perm
)))))))
549 ;; If we had files but now we don't, it's time to stop.
550 (when (and files
(not (vc-git-dir-status-state->files git-state
)))
551 (setq next-stage nil
))
552 (setf (vc-git-dir-status-state->stage git-state
) next-stage
)
553 (setf (vc-git-dir-status-state->files git-state
) files
)
555 (vc-git-dir-status-goto-stage git-state
)
556 (funcall (vc-git-dir-status-state->update-function git-state
)
558 (maphash (lambda (key value
)
559 (push (cons key value
) result
))
560 (vc-git-dir-status-state->hash git-state
))
564 ;; Follows vc-git-command (or vc-do-async-command), which uses vc-do-command
565 ;; from vc-dispatcher.
566 (declare-function vc-exec-after
"vc-dispatcher" (code))
567 ;; Follows vc-exec-after.
568 (declare-function vc-set-async-update
"vc-dispatcher" (process-buffer))
570 (defun vc-git-dir-status-goto-stage (git-state)
571 (let ((files (vc-git-dir-status-state->files git-state
)))
573 (pcase (vc-git-dir-status-state->stage git-state
)
576 (vc-git-command (current-buffer) 'async files
"add" "--refresh" "--")
577 (vc-git-command (current-buffer) 'async nil
578 "update-index" "--refresh")))
580 (vc-git-command (current-buffer) 'async files
581 "ls-files" "-z" "-c" "-s" "--"))
582 (`ls-files-up-to-date
583 (vc-git-command (current-buffer) 'async files
584 "ls-files" "-z" "-c" "-s" "--"))
586 (vc-git-command (current-buffer) 'async files
587 "ls-files" "-z" "-c" "-s" "--"))
589 (vc-git-command (current-buffer) 'async files
590 "ls-files" "-z" "-o" "--directory"
591 "--no-empty-directory" "--exclude-standard" "--"))
593 (vc-git-command (current-buffer) 'async files
594 "ls-files" "-z" "-o" "-i" "--directory"
595 "--no-empty-directory" "--exclude-standard" "--"))
596 ;; --relative added in Git 1.5.5.
598 (vc-git-command (current-buffer) 'async files
599 "diff-index" "--relative" "-z" "-M" "HEAD" "--")))
601 (vc-git-after-dir-status-stage git-state
))))
603 (defun vc-git-dir-status-files (_dir files update-function
)
604 "Return a list of (FILE STATE EXTRA) entries for DIR."
605 ;; Further things that would have to be fixed later:
606 ;; - how to handle unregistered directories
607 ;; - how to support vc-dir on a subdir of the project tree
608 (vc-git-dir-status-goto-stage
609 (make-vc-git-dir-status-state :stage
'update-index
611 :update-function update-function
)))
613 (defvar vc-git-stash-map
614 (let ((map (make-sparse-keymap)))
615 ;; Turn off vc-dir marking
616 (define-key map
[mouse-2
] 'ignore
)
618 (define-key map
[down-mouse-3
] 'vc-git-stash-menu
)
619 (define-key map
"\C-k" 'vc-git-stash-delete-at-point
)
620 (define-key map
"=" 'vc-git-stash-show-at-point
)
621 (define-key map
"\C-m" 'vc-git-stash-show-at-point
)
622 (define-key map
"A" 'vc-git-stash-apply-at-point
)
623 (define-key map
"P" 'vc-git-stash-pop-at-point
)
624 (define-key map
"S" 'vc-git-stash-snapshot
)
627 (defvar vc-git-stash-menu-map
628 (let ((map (make-sparse-keymap "Git Stash")))
630 '(menu-item "Delete Stash" vc-git-stash-delete-at-point
631 :help "Delete the current stash"))
633 '(menu-item "Apply Stash" vc-git-stash-apply-at-point
634 :help "Apply the current stash and keep it in the stash list"))
636 '(menu-item "Apply and Remove Stash (Pop)" vc-git-stash-pop-at-point
637 :help "Apply the current stash and remove it"))
639 '(menu-item "Show Stash" vc-git-stash-show-at-point
640 :help "Show the contents of the current stash"))
643 (defun vc-git-dir-extra-headers (dir)
644 (let ((str (with-output-to-string
645 (with-current-buffer standard-output
646 (vc-git--out-ok "symbolic-ref" "HEAD"))))
647 (stash (vc-git-stash-list))
648 (stash-help-echo "Use M-x vc-git-stash to create stashes.")
649 branch remote remote-url)
650 (if (string-match "^\\(refs/heads/\\)?\\(.+\\)$" str)
652 (setq branch (match-string 2 str))
654 (with-output-to-string
655 (with-current-buffer standard-output
656 (vc-git--out-ok "config"
657 (concat "branch." branch ".remote")))))
658 (when (string-match "\\([^\n]+\\)" remote)
659 (setq remote (match-string 1 remote)))
662 (with-output-to-string
663 (with-current-buffer standard-output
664 (vc-git--out-ok "config"
665 (concat "remote." remote ".url"))))))
666 (when (string-match "\\([^\n]+\\)" remote-url)
667 (setq remote-url (match-string 1 remote-url))))
668 (setq branch "not (detached HEAD)"))
669 ;; FIXME: maybe use a different face when nothing is stashed.
671 (propertize "Branch : " 'face 'font-lock-type-face)
673 'face 'font-lock-variable-name-face)
677 (propertize "Remote : " 'face 'font-lock-type-face)
678 (propertize remote-url
679 'face 'font-lock-variable-name-face)))
681 ;; For now just a heading, key bindings can be added later for various bisect actions
682 (when (file-exists-p (expand-file-name ".git/BISECT_START" (vc-git-root dir)))
683 (propertize "Bisect : in progress\n" 'face 'font-lock-warning-face))
684 (when (file-exists-p (expand-file-name ".git/rebase-apply" (vc-git-root dir)))
685 (propertize "Rebase : in progress\n" 'face 'font-lock-warning-face))
688 (propertize "Stash :\n" 'face 'font-lock-type-face
689 'help-echo stash-help-echo)
693 'face 'font-lock-variable-name-face
694 'mouse-face 'highlight
695 'help-echo "mouse-3: Show stash menu\nRET: Show stash\nA: Apply stash\nP: Apply and remove stash (pop)\nC-k: Delete stash"
696 'keymap vc-git-stash-map))
699 (propertize "Stash : " 'face 'font-lock-type-face
700 'help-echo stash-help-echo)
701 (propertize "Nothing stashed"
702 'help-echo stash-help-echo
703 'face 'font-lock-variable-name-face))))))
705 (defun vc-git-branches ()
706 "Return the existing branches, as a list of strings.
707 The car of the list is the current branch."
709 (vc-git--call t "branch")
710 (goto-char (point-min))
711 (let (current-branch branches)
713 (when (looking-at "^\\([ *]\\) \\(.+\\)$")
714 (if (string-equal (match-string 1) "*")
715 (setq current-branch (match-string 2))
716 (push (match-string 2) branches)))
718 (cons current-branch (nreverse branches)))))
720 ;;; STATE-CHANGING FUNCTIONS
722 (defun vc-git-create-repo ()
723 "Create a new Git repository."
724 (vc-git-command nil 0 nil "init"))
726 (defun vc-git-register (files &optional _comment)
727 "Register FILES into the git version-control system."
730 (if (file-directory-p crt)
734 (vc-git-command nil 0 flist "update-index" "--add" "--"))
736 (vc-git-command nil 0 dlist "add"))))
738 (defalias 'vc-git-responsible-p 'vc-git-root)
740 (defun vc-git-unregister (file)
741 (vc-git-command nil 0 file "rm" "-f" "--cached" "--"))
743 (declare-function log-edit-mode "log-edit" ())
744 (declare-function log-edit-toggle-header "log-edit" (header value))
745 (declare-function log-edit-extract-headers "log-edit" (headers string))
746 (declare-function log-edit-set-header "log-edit" (header value &optional toggle))
748 (defun vc-git-log-edit-toggle-signoff ()
749 "Toggle whether to add the \"Signed-off-by\" line at the end of
752 (log-edit-toggle-header "Sign-Off" "yes"))
754 (defun vc-git-log-edit-toggle-amend ()
755 "Toggle whether this will amend the previous commit.
756 If toggling on, also insert its message into the buffer."
758 (when (log-edit-toggle-header "Amend" "yes")
759 (goto-char (point-max))
760 (unless (bolp) (insert "\n"))
761 (insert (with-output-to-string
763 standard-output 1 nil
764 "log" "--max-count=1" "--pretty=format:%B" "HEAD")))
769 (and (zerop (forward-line 1))
770 (looking-at "\n\\|\\'")
771 (let ((summary (buffer-substring-no-properties pt (1- (point)))))
772 (skip-chars-forward " \n")
773 (delete-region pt (point))
774 (log-edit-set-header "Summary" summary)))))))
776 (defvar vc-git-log-edit-mode-map
777 (let ((map (make-sparse-keymap "Git-Log-Edit")))
778 (define-key map "\C-c\C-s" 'vc-git-log-edit-toggle-signoff)
779 (define-key map "\C-c\C-e" 'vc-git-log-edit-toggle-amend)
782 (define-derived-mode vc-git-log-edit-mode log-edit-mode "Log-Edit/git"
783 "Major mode for editing Git log messages.
784 It is based on `log-edit-mode', and has Git-specific extensions.")
786 (defun vc-git-checkin (files comment &optional _rev)
787 (let* ((file1 (or (car files) default-directory))
788 (root (vc-git-root file1))
789 (default-directory (expand-file-name root))
790 (only (or (cdr files)
791 (not (equal root (abbreviate-file-name file1)))))
792 (pcsw coding-system-for-write)
793 (coding-system-for-write
794 ;; On MS-Windows, we must encode command-line arguments in
795 ;; the system codepage.
796 (if (eq system-type 'windows-nt)
798 (or coding-system-for-write vc-git-commits-coding-system)))
800 ;; On MS-Windows, pass the commit log message through a
801 ;; file, to work around the limitation that command-line
802 ;; arguments must be in the system codepage, and therefore
803 ;; might not support the non-ASCII characters in the log
804 ;; message. Handle also remote files.
805 (if (eq system-type 'windows-nt)
806 (let ((default-directory (file-name-directory file1)))
807 (make-nearby-temp-file "git-msg")))))
808 (cl-flet ((boolean-arg-fn
810 (lambda (value) (when (equal value "yes") (list argument)))))
811 ;; When operating on the whole tree, better pass "-a" than ".", since "."
812 ;; fails when we're committing a merge.
813 (apply 'vc-git-command nil 0 (if only files)
814 (nconc (if msg-file (list "commit" "-F"
815 (file-local-name msg-file))
816 (list "commit" "-m"))
818 (log-edit-extract-headers
819 `(("Author" . "--author")
821 ("Amend" . ,(boolean-arg-fn "--amend"))
822 ("Sign-Off" . ,(boolean-arg-fn "--signoff")))
825 (let ((coding-system-for-write
826 (or pcsw vc-git-commits-coding-system)))
827 (write-region (car args) nil msg-file))
828 (setq args (cdr args)))
830 (if only (list "--only" "--") '("-a")))))
831 (if (and msg-file (file-exists-p msg-file)) (delete-file msg-file))))
833 (defun vc-git-find-revision (file rev buffer)
834 (let* (process-file-side-effects
835 (coding-system-for-read 'binary)
836 (coding-system-for-write 'binary)
838 (let ((fn (vc-git--run-command-string
839 file "ls-files" "-z" "--full-name" "--")))
840 ;; ls-files does not return anything when looking for a
841 ;; revision of a file that has been renamed or removed.
843 (file-relative-name file (vc-git-root default-directory))
844 (substring fn 0 -1)))))
848 "cat-file" "blob" (concat (if rev rev "HEAD") ":" fullname))))
850 (defun vc-git-find-ignore-file (file)
851 "Return the git ignore file that controls FILE."
852 (expand-file-name ".gitignore"
855 (defun vc-git-checkout (file &optional rev)
856 (vc-git-command nil 0 file "checkout" (or rev "HEAD")))
858 (defun vc-git-revert (file &optional contents-done)
859 "Revert FILE to the version stored in the git repository."
861 (vc-git-command nil 0 file "update-index" "--")
862 (vc-git-command nil 0 file "reset" "-q" "--")
863 (vc-git-command nil nil file "checkout" "-q" "--")))
865 (defvar vc-git-error-regexp-alist
866 '(("^ \\(.+\\)\\> *|" 1 nil nil 0))
867 "Value of `compilation-error-regexp-alist' in *vc-git* buffers.")
869 ;; To be called via vc-pull from vc.el, which requires vc-dispatcher.
870 (declare-function vc-compilation-mode "vc-dispatcher" (backend))
871 (defvar compilation-directory)
872 (defvar compilation-arguments)
874 (defun vc-git--pushpull (command prompt extra-args)
875 "Run COMMAND (a string; either push or pull) on the current Git branch.
876 If PROMPT is non-nil, prompt for the Git command to run."
877 (let* ((root (vc-git-root default-directory))
878 (buffer (format "*vc-git : %s*" (expand-file-name root)))
879 (git-program vc-git-program)
881 ;; If necessary, prompt for the exact command.
882 ;; TODO if pushing, prompt if no default push location - cf bzr.
884 (setq args (split-string
886 (format "Git %s command: " command)
887 (format "%s %s" git-program command)
890 (setq git-program (car args)
893 (setq args (nconc args extra-args))
894 (require 'vc-dispatcher)
895 (apply 'vc-do-async-command buffer root git-program command args)
896 (with-current-buffer buffer
898 (vc-compilation-mode 'git)
899 (setq-local compile-command
900 (concat git-program " " command " "
901 (mapconcat 'identity args " ")))
902 (setq-local compilation-directory root)
903 ;; Either set `compilation-buffer-name-function' locally to nil
904 ;; or use `compilation-arguments' to set `name-function'.
905 ;; See `compilation-buffer-name'.
906 (setq-local compilation-arguments
907 (list compile-command nil
908 (lambda (_name-of-mode) buffer)
910 (vc-set-async-update buffer)))
912 (defun vc-git-pull (prompt)
913 "Pull changes into the current Git branch.
914 Normally, this runs \"git pull\". If PROMPT is non-nil, prompt
915 for the Git command to run."
916 (vc-git--pushpull "pull" prompt '("--stat")))
918 (defun vc-git-push (prompt)
919 "Push changes from the current Git branch.
920 Normally, this runs \"git push\". If PROMPT is non-nil, prompt
921 for the Git command to run."
922 (vc-git--pushpull "push" prompt nil))
924 (defun vc-git-merge-branch ()
925 "Merge changes into the current Git branch.
926 This prompts for a branch to merge from."
927 (let* ((root (vc-git-root default-directory))
928 (buffer (format "*vc-git : %s*" (expand-file-name root)))
929 (branches (cdr (vc-git-branches)))
931 (completing-read "Merge from branch: "
932 (if (or (member "FETCH_HEAD" branches)
933 (not (file-readable-p
934 (expand-file-name ".git/FETCH_HEAD"
937 (cons "FETCH_HEAD" branches))
939 (apply 'vc-do-async-command buffer root vc-git-program "merge"
941 (with-current-buffer buffer (vc-run-delayed (vc-compilation-mode 'git)))
942 (vc-set-async-update buffer)))
944 (defun vc-git-conflicted-files (directory)
945 "Return the list of files with conflicts in DIRECTORY."
947 (vc-git--run-command-string directory "status" "--porcelain" "--"))
948 (lines (when status (split-string status "\n" 'omit-nulls)))
950 ;; TODO: Look into reimplementing `vc-git-state', as well as
951 ;; `vc-git-dir-status-files', based on this output, thus making the
952 ;; extra process call in `vc-git-find-file-hook' unnecessary.
953 (dolist (line lines files)
954 (when (string-match "\\([ MADRCU?!][ MADRCU?!]\\) \\(.+\\)\\(?: -> \\(.+\\)\\)?"
956 (let ((state (match-string 1 line))
957 (file (match-string 2 line)))
958 ;; See git-status(1).
959 (when (member state '("AU" "UD" "UA" ;; "DD"
961 (push (expand-file-name file directory) files)))))))
963 ;; Everywhere but here, follows vc-git-command, which uses vc-do-command
964 ;; from vc-dispatcher.
965 (autoload 'vc-resynch-buffer "vc-dispatcher")
967 (defun vc-git-resolve-when-done ()
968 "Call \"git add\" if the conflict markers have been removed."
970 (goto-char (point-min))
971 (unless (re-search-forward "^<<<<<<< " nil t)
972 (vc-git-command nil 0 buffer-file-name "add")
974 (not (eq vc-git-resolve-conflicts 'unstage-maybe))
975 ;; Doing a merge, so bug#20292 doesn't apply.
976 (file-exists-p (expand-file-name ".git/MERGE_HEAD"
977 (vc-git-root buffer-file-name)))
978 (vc-git-conflicted-files (vc-git-root buffer-file-name)))
979 (vc-git-command nil 0 nil "reset"))
980 (vc-resynch-buffer buffer-file-name t t)
981 ;; Remove the hook so that it is not called multiple times.
982 (remove-hook 'after-save-hook 'vc-git-resolve-when-done t))))
984 (defun vc-git-find-file-hook ()
985 "Activate `smerge-mode' if there is a conflict."
986 (when (and buffer-file-name
988 ;; 1) the net result is to call git twice per file.
989 ;; 2) v-g-c-f is documented to take a directory.
990 ;; https://lists.gnu.org/r/emacs-devel/2014-01/msg01126.html
991 (vc-git-conflicted-files buffer-file-name)
993 (goto-char (point-min))
994 (re-search-forward "^<<<<<<< " nil 'noerror)))
995 (vc-file-setprop buffer-file-name 'vc-state 'conflict)
996 (smerge-start-session)
997 (when vc-git-resolve-conflicts
998 (add-hook 'after-save-hook 'vc-git-resolve-when-done nil 'local))
999 (vc-message-unresolved-conflicts buffer-file-name)))
1001 ;;; HISTORY FUNCTIONS
1003 (autoload 'vc-setup-buffer "vc-dispatcher")
1005 (defcustom vc-git-print-log-follow nil
1006 "If true, follow renames in Git logs for a single file."
1010 (defun vc-git-print-log (files buffer &optional shortlog start-revision limit)
1011 "Print commit log associated with FILES into specified BUFFER.
1012 If SHORTLOG is non-nil, use a short format based on `vc-git-root-log-format'.
1013 \(This requires at least Git version 1.5.6, for the --graph option.)
1014 If START-REVISION is non-nil, it is the newest revision to show.
1015 If LIMIT is non-nil, show no more than this many entries."
1016 (let ((coding-system-for-read
1017 (or coding-system-for-read vc-git-log-output-coding-system)))
1018 ;; `vc-do-command' creates the buffer, but we need it before running
1020 (vc-setup-buffer buffer)
1021 ;; If the buffer exists from a previous invocation it might be
1023 (let ((inhibit-read-only t))
1024 (with-current-buffer
1026 (apply 'vc-git-command buffer
1029 '("log" "--no-color")
1030 (when (and vc-git-print-log-follow
1033 (not (file-directory-p (car files))))
1034 ;; "--follow" on directories or multiple files is broken
1035 ;; https://debbugs.gnu.org/cgi/bugreport.cgi?bug=8756
1036 ;; https://debbugs.gnu.org/cgi/bugreport.cgi?bug=16422
1039 `("--graph" "--decorate" "--date=short"
1040 ,(format "--pretty=tformat:%s"
1041 (car vc-git-root-log-format))
1043 (when limit (list "-n" (format "%s" limit)))
1044 (when start-revision (list start-revision))
1047 (defun vc-git-log-outgoing (buffer remote-location)
1049 (vc-setup-buffer buffer)
1053 "--no-color" "--graph" "--decorate" "--date=short"
1054 (format "--pretty=tformat:%s" (car vc-git-root-log-format))
1056 (concat (if (string= remote-location "")
1061 (defun vc-git-log-incoming (buffer remote-location)
1063 (vc-setup-buffer buffer)
1064 (vc-git-command nil 0 nil "fetch")
1068 "--no-color" "--graph" "--decorate" "--date=short"
1069 (format "--pretty=tformat:%s" (car vc-git-root-log-format))
1071 (concat "HEAD.." (if (string= remote-location "")
1075 (defvar log-view-message-re)
1076 (defvar log-view-file-re)
1077 (defvar log-view-font-lock-keywords)
1078 (defvar log-view-per-file-logs)
1079 (defvar log-view-expanded-log-entry-function)
1081 (define-derived-mode vc-git-log-view-mode log-view-mode "Git-Log-View"
1082 (require 'add-log) ;; We need the faces add-log.
1083 ;; Don't have file markers, so use impossible regexp.
1084 (set (make-local-variable 'log-view-file-re) "\\`a\\`")
1085 (set (make-local-variable 'log-view-per-file-logs) nil)
1086 (set (make-local-variable 'log-view-message-re)
1087 (if (not (eq vc-log-view-type 'long))
1088 (cadr vc-git-root-log-format)
1089 "^commit *\\([0-9a-z]+\\)"))
1090 ;; Allow expanding short log entries.
1091 (when (memq vc-log-view-type '(short log-outgoing log-incoming))
1092 (setq truncate-lines t)
1093 (set (make-local-variable 'log-view-expanded-log-entry-function)
1094 'vc-git-expanded-log-entry))
1095 (set (make-local-variable 'log-view-font-lock-keywords)
1096 (if (not (eq vc-log-view-type 'long))
1097 (list (cons (nth 1 vc-git-root-log-format)
1098 (nth 2 vc-git-root-log-format)))
1100 `((,log-view-message-re (1 'change-log-acknowledgment)))
1103 '(("^Author:[ \t]+\\([A-Za-z0-9_.+-]+@[A-Za-z0-9_.-]+\\)"
1104 (1 'change-log-email))
1106 ;; user: FirstName LastName <foo@bar>
1107 ("^Author:[ \t]+\\([^<(]+?\\)[ \t]*[(<]\\([A-Za-z0-9_.+-]+@[A-Za-z0-9_.-]+\\)[>)]"
1108 (1 'change-log-name)
1109 (2 'change-log-email))
1110 ("^ +\\(?:\\(?:[Aa]cked\\|[Ss]igned-[Oo]ff\\)-[Bb]y:\\)[ \t]+\\([A-Za-z0-9_.+-]+@[A-Za-z0-9_.-]+\\)"
1111 (1 'change-log-name))
1112 ("^ +\\(?:\\(?:[Aa]cked\\|[Ss]igned-[Oo]ff\\)-[Bb]y:\\)[ \t]+\\([^<(]+?\\)[ \t]*[(<]\\([A-Za-z0-9_.+-]+@[A-Za-z0-9_.-]+\\)[>)]"
1113 (1 'change-log-name)
1114 (2 'change-log-email))
1115 ("^Merge: \\([0-9a-z]+\\) \\([0-9a-z]+\\)"
1116 (1 'change-log-acknowledgment)
1117 (2 'change-log-acknowledgment))
1118 ("^Date: \\(.+\\)" (1 'change-log-date))
1119 ("^summary:[ \t]+\\(.+\\)" (1 'log-view-message)))))))
1122 (defun vc-git-show-log-entry (revision)
1123 "Move to the log entry for REVISION.
1124 REVISION may have the form BRANCH, BRANCH~N,
1125 or BRANCH^ (where \"^\" can be repeated)."
1126 (goto-char (point-min))
1130 (format "\ncommit %s" revision) nil t
1131 (cond ((string-match "~\\([0-9]\\)\\'" revision)
1132 (1+ (string-to-number (match-string 1 revision))))
1133 ((string-match "\\^+\\'" revision)
1134 (1+ (length (match-string 0 revision))))
1136 (beginning-of-line)))
1138 (defun vc-git-expanded-log-entry (revision)
1140 (apply 'vc-git-command t nil nil (list "log" revision "-1" "--"))
1141 (goto-char (point-min))
1143 ;; Indent the expanded log entry.
1144 (while (re-search-forward "^ " nil t)
1149 (defun vc-git-region-history (file buffer lfrom lto)
1150 "Insert into BUFFER the history of FILE for lines LFROM to LTO.
1151 This requires git 1.8.4 or later, for the \"-L\" option of \"git log\"."
1152 ;; The "git log" command below interprets the line numbers as applying
1153 ;; to the HEAD version of the file, not to the current state of the file.
1154 ;; So we need to look at all the local changes and adjust lfrom/lto
1156 ;; FIXME: Maybe this should be done in vc.el (i.e. for all backends), but
1157 ;; since Git is the only backend to support this operation so far, it's hard
1160 (vc-call-backend 'git 'diff file "HEAD" nil (current-buffer))
1161 (goto-char (point-min))
1162 (let ((last-offset 0)
1165 (while (re-search-forward
1166 "^@@ -\\([0-9]+\\),\\([0-9]+\\) \\+\\([0-9]+\\),\\([0-9]+\\) @@" nil t)
1167 (let ((headno (string-to-number (match-string 1)))
1168 (headcnt (string-to-number (match-string 2)))
1169 (curno (string-to-number (match-string 3)))
1170 (curcnt (string-to-number (match-string 4))))
1171 (cl-assert (equal (- curno headno) last-offset))
1172 (and (null from-offset) (> curno lfrom)
1173 (setq from-offset last-offset))
1174 (and (null to-offset) (> curno lto)
1175 (setq to-offset last-offset))
1177 (- (+ curno curcnt) (+ headno headcnt)))))
1178 (setq lto (- lto (or to-offset last-offset)))
1179 (setq lfrom (- lfrom (or to-offset last-offset)))))
1180 (vc-git-command buffer 'async nil "log" "-p" ;"--follow" ;FIXME: not supported?
1181 (format "-L%d,%d:%s" lfrom lto (file-relative-name file))))
1183 (require 'diff-mode)
1185 (defvar vc-git-region-history-mode-map
1186 (let ((map (make-composed-keymap
1187 nil (make-composed-keymap
1188 (list diff-mode-map vc-git-log-view-mode-map)))))
1191 (defvar vc-git--log-view-long-font-lock-keywords nil)
1192 (defvar font-lock-keywords)
1193 (defvar vc-git-region-history-font-lock-keywords
1194 `((vc-git-region-history-font-lock)))
1196 (defun vc-git-region-history-font-lock (limit)
1197 (let ((in-diff (save-excursion
1199 (or (looking-at "^\\(?:diff\\|commit\\)\\>")
1200 (re-search-backward "^\\(?:diff\\|commit\\)\\>" nil t))
1201 (eq ?d (char-after (match-beginning 0))))))
1203 (let ((end (save-excursion
1204 (if (re-search-forward "\n\\(diff\\|commit\\)\\>"
1208 (let ((font-lock-keywords (if in-diff diff-font-lock-keywords
1209 vc-git--log-view-long-font-lock-keywords)))
1210 (font-lock-fontify-keywords-region (point) end))
1212 (prog1 (< (point) limit)
1213 (setq in-diff (eq ?d (char-after))))))
1216 (define-derived-mode vc-git-region-history-mode
1217 vc-git-log-view-mode "Git-Region-History"
1218 "Major mode to browse Git's \"log -p\" output."
1219 (setq-local vc-git--log-view-long-font-lock-keywords
1220 log-view-font-lock-keywords)
1221 (setq-local font-lock-defaults
1222 (cons 'vc-git-region-history-font-lock-keywords
1223 (cdr font-lock-defaults))))
1225 (defun vc-git--asciify-coding-system ()
1226 ;; Try to reconcile the content encoding with the encoding of Git's
1227 ;; auxiliary output (which is ASCII or ASCII-compatible), bug#23595.
1228 (unless (let ((samp "Binary files differ"))
1229 (string-equal samp (decode-coding-string
1230 samp coding-system-for-read t)))
1231 (setq coding-system-for-read 'undecided)))
1233 (autoload 'vc-switches "vc")
1235 (defun vc-git-diff (files &optional rev1 rev2 buffer _async)
1236 "Get a difference report using Git between two revisions of FILES."
1237 (let (process-file-side-effects
1238 (command "diff-tree"))
1239 (vc-git--asciify-coding-system)
1241 ;; Diffing against the empty tree.
1242 (unless rev1 (setq rev1 "4b825dc642cb6eb9a060e54bf8d69288fbee4904"))
1243 (setq command "diff-index")
1244 (unless rev1 (setq rev1 "HEAD")))
1245 (if vc-git-diff-switches
1246 (apply #'vc-git-command (or buffer "*vc-diff*")
1251 (append (vc-switches 'git 'diff)
1252 (list "-p" (or rev1 "HEAD") rev2 "--")))
1253 (vc-git-command (or buffer "*vc-diff*") 1 files
1254 "difftool" "--exit-code" "--no-prompt" "-x"
1256 (mapconcat 'identity
1257 (vc-switches nil 'diff) " "))
1260 (defun vc-git-revision-table (_files)
1261 ;; What about `files'?!? --Stef
1262 (let (process-file-side-effects
1263 (table (list "HEAD")))
1265 (vc-git-command t nil nil "for-each-ref" "--format=%(refname)")
1266 (goto-char (point-min))
1267 (while (re-search-forward "^refs/\\(heads\\|tags\\|remotes\\)/\\(.*\\)$"
1269 (push (match-string 2) table)))
1272 (defun vc-git-revision-completion-table (files)
1273 (letrec ((table (lazy-completion-table
1274 table (lambda () (vc-git-revision-table files)))))
1277 (defun vc-git-annotate-command (file buf &optional rev)
1278 (vc-git--asciify-coding-system)
1279 (let ((name (file-relative-name file)))
1280 (apply #'vc-git-command buf 'async nil "blame" "--date=short"
1281 (append (vc-switches 'git 'annotate)
1282 (list rev "--" name)))))
1284 (declare-function vc-annotate-convert-time "vc-annotate" (&optional time))
1286 (defun vc-git-annotate-time ()
1287 (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)
1288 (vc-annotate-convert-time
1289 (apply #'encode-time (mapcar (lambda (match)
1290 (if (match-beginning match)
1291 (string-to-number (match-string match))
1293 '(6 5 4 3 2 1 7))))))
1295 (defun vc-git-annotate-extract-revision-at-line ()
1298 (when (looking-at "\\^?\\([0-9a-f]+\\) \\(\\([^(]+\\) \\)?")
1299 (let ((revision (match-string-no-properties 1)))
1300 (if (match-beginning 2)
1301 (let ((fname (match-string-no-properties 3)))
1302 ;; Remove trailing whitespace from the file name.
1303 (when (string-match " +\\'" fname)
1304 (setq fname (substring fname 0 (match-beginning 0))))
1306 (expand-file-name fname (vc-git-root default-directory))))
1311 (defun vc-git-create-tag (dir name branchp)
1312 (let ((default-directory dir))
1313 (and (vc-git-command nil 0 nil "update-index" "--refresh")
1315 (vc-git-command nil 0 nil "checkout" "-b" name)
1316 (vc-git-command nil 0 nil "tag" name)))))
1318 (defun vc-git-retrieve-tag (dir name _update)
1319 (let ((default-directory dir))
1320 (vc-git-command nil 0 nil "checkout" name)))
1325 (defun vc-git-previous-revision (file rev)
1326 "Git-specific version of `vc-previous-revision'."
1328 (let* ((fname (file-relative-name file))
1329 (prev-rev (with-temp-buffer
1331 (vc-git--out-ok "rev-list" "-2" rev "--" fname)
1332 (goto-char (point-max))
1334 (zerop (forward-line -1))
1336 (buffer-substring-no-properties
1338 (1- (point-max)))))))
1339 (or (vc-git-symbolic-commit prev-rev) prev-rev))
1340 ;; We used to use "^" here, but that fails on MS-Windows if git is
1341 ;; invoked via a batch file, in which case cmd.exe strips the "^"
1342 ;; because it is a special character for cmd which process-file
1343 ;; does not (and cannot) quote.
1344 (vc-git--rev-parse (concat rev "~1"))))
1346 (defun vc-git--rev-parse (rev)
1349 (vc-git--out-ok "rev-parse" rev)
1350 (buffer-substring-no-properties (point-min) (+ (point-min) 40)))))
1352 (defun vc-git-next-revision (file rev)
1353 "Git-specific version of `vc-next-revision'."
1354 (let* ((default-directory (vc-git-root file))
1355 (file (file-relative-name file))
1359 (vc-git--out-ok "rev-list" "-1" rev "--" file)
1360 (goto-char (point-max))
1362 (zerop (forward-line -1))
1364 (buffer-substring-no-properties
1366 (1- (point-max))))))
1371 (vc-git--out-ok "rev-list" "HEAD" "--" file)
1372 (goto-char (point-min))
1373 (search-forward current-rev nil t)
1374 (zerop (forward-line -1))
1375 (buffer-substring-no-properties
1377 (progn (forward-line 1) (1- (point)))))))))
1378 (or (vc-git-symbolic-commit next-rev) next-rev)))
1380 (defun vc-git-delete-file (file)
1381 (vc-git-command nil 0 file "rm" "-f" "--"))
1383 (defun vc-git-rename-file (old new)
1384 (vc-git-command nil 0 (list old new) "mv" "-f" "--"))
1386 (defvar vc-git-extra-menu-map
1387 (let ((map (make-sparse-keymap)))
1388 (define-key map [git-grep]
1389 '(menu-item "Git grep..." vc-git-grep
1390 :help "Run the `git grep' command"))
1391 (define-key map [git-sn]
1392 '(menu-item "Stash a Snapshot" vc-git-stash-snapshot
1393 :help "Stash the current state of the tree and keep the current state"))
1394 (define-key map [git-st]
1395 '(menu-item "Create Stash..." vc-git-stash
1396 :help "Stash away changes"))
1397 (define-key map [git-ss]
1398 '(menu-item "Show Stash..." vc-git-stash-show
1399 :help "Show stash contents"))
1402 (defun vc-git-extra-menu () vc-git-extra-menu-map)
1404 (defun vc-git-extra-status-menu () vc-git-extra-menu-map)
1406 (defun vc-git-root (file)
1407 (or (vc-file-getprop file 'git-root)
1408 (vc-file-setprop file 'git-root (vc-find-root file ".git"))))
1410 ;; grep-compute-defaults autoloads grep.
1411 (declare-function grep-read-regexp "grep" ())
1412 (declare-function grep-read-files "grep" (regexp))
1413 (declare-function grep-expand-template "grep"
1414 (template &optional regexp files dir excl))
1415 (defvar compilation-environment)
1417 ;; Derived from `lgrep'.
1418 (defun vc-git-grep (regexp &optional files dir)
1419 "Run git grep, searching for REGEXP in FILES in directory DIR.
1420 The search is limited to file names matching shell pattern FILES.
1421 FILES may use abbreviations defined in `grep-files-aliases', e.g.
1422 entering `ch' is equivalent to `*.[ch]'. As whitespace triggers
1423 completion when entering a pattern, including it requires
1424 quoting, e.g. `\\[quoted-insert]<space>'.
1426 With \\[universal-argument] prefix, you can edit the constructed shell command line
1427 before it is executed.
1428 With two \\[universal-argument] prefixes, directly edit and run `grep-command'.
1430 Collect output in a buffer. While git grep runs asynchronously, you
1431 can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
1432 in the grep output buffer,
1433 to go to the lines where grep found matches.
1435 This command shares argument histories with \\[rgrep] and \\[grep]."
1438 (grep-compute-defaults)
1440 ((equal current-prefix-arg '(16))
1441 (list (read-from-minibuffer "Run: " "git grep"
1442 nil nil 'grep-history)
1444 (t (let* ((regexp (grep-read-regexp))
1446 (mapconcat #'shell-quote-argument
1447 (split-string (grep-read-files regexp)) " "))
1448 (dir (read-directory-name "In directory: "
1449 nil default-directory t)))
1450 (list regexp files dir))))))
1452 (when (and (stringp regexp) (> (length regexp) 0))
1453 (let ((command regexp))
1455 (if (string= command "git grep")
1457 (setq dir (file-name-as-directory (expand-file-name dir)))
1459 (grep-expand-template "git --no-pager grep -n -e <R> -- <F>"
1462 (if (equal current-prefix-arg '(4))
1464 (read-from-minibuffer "Confirm: "
1465 command nil nil 'grep-history))
1466 (add-to-history 'grep-history command))))
1468 (let ((default-directory dir)
1469 (compilation-environment (cons "PAGER=" compilation-environment)))
1470 ;; Setting process-setup-function makes exit-message-function work
1471 ;; even when async processes aren't supported.
1472 (compilation-start command 'grep-mode))
1473 (if (eq next-error-last-buffer (current-buffer))
1474 (setq default-directory dir))))))
1476 (defun vc-git-stash (name)
1478 (interactive "sStash name: ")
1479 (let ((root (vc-git-root default-directory)))
1481 (vc-git--call nil "stash" "save" name)
1482 (vc-resynch-buffer root t t))))
1484 (defun vc-git-stash-show (name)
1485 "Show the contents of stash NAME."
1486 (interactive "sStash name: ")
1487 (vc-setup-buffer "*vc-git-stash*")
1488 (vc-git-command "*vc-git-stash*" 'async nil "stash" "show" "-p" name)
1489 (set-buffer "*vc-git-stash*")
1491 (setq buffer-read-only t)
1492 (pop-to-buffer (current-buffer)))
1494 (defun vc-git-stash-apply (name)
1496 (interactive "sApply stash: ")
1497 (vc-git-command "*vc-git-stash*" 0 nil "stash" "apply" "-q" name)
1498 (vc-resynch-buffer (vc-git-root default-directory) t t))
1500 (defun vc-git-stash-pop (name)
1502 (interactive "sPop stash: ")
1503 (vc-git-command "*vc-git-stash*" 0 nil "stash" "pop" "-q" name)
1504 (vc-resynch-buffer (vc-git-root default-directory) t t))
1506 (defun vc-git-stash-snapshot ()
1507 "Create a stash with the current tree state."
1509 (vc-git--call nil "stash" "save"
1510 (let ((ct (current-time)))
1512 (format-time-string "Snapshot on %Y-%m-%d" ct)
1513 (format-time-string " at %H:%M" ct))))
1514 (vc-git-command "*vc-git-stash*" 0 nil "stash" "apply" "-q" "stash@{0}")
1515 (vc-resynch-buffer (vc-git-root default-directory) t t))
1517 (defun vc-git-stash-list ()
1521 (replace-regexp-in-string
1522 "^stash@" " " (vc-git--run-command-string nil "stash" "list"))
1525 (defun vc-git-stash-get-at-point (point)
1529 (if (looking-at "^ +\\({[0-9]+}\\):")
1531 (error "Cannot find stash at point"))))
1533 ;; vc-git-stash-delete-at-point must be called from a vc-dir buffer.
1534 (declare-function vc-dir-refresh "vc-dir" ())
1536 (defun vc-git-stash-delete-at-point ()
1538 (let ((stash (vc-git-stash-get-at-point (point))))
1539 (when (y-or-n-p (format "Remove stash %s ? " stash))
1540 (vc-git--run-command-string nil "stash" "drop" (format "stash@%s" stash))
1543 (defun vc-git-stash-show-at-point ()
1545 (vc-git-stash-show (format "stash@%s" (vc-git-stash-get-at-point (point)))))
1547 (defun vc-git-stash-apply-at-point ()
1549 (let (vc-dir-buffers) ; Small optimization.
1550 (vc-git-stash-apply (format "stash@%s" (vc-git-stash-get-at-point (point)))))
1553 (defun vc-git-stash-pop-at-point ()
1555 (let (vc-dir-buffers) ; Likewise.
1556 (vc-git-stash-pop (format "stash@%s" (vc-git-stash-get-at-point (point)))))
1559 (defun vc-git-stash-menu (e)
1561 (vc-dir-at-event e (popup-menu vc-git-stash-menu-map e)))
1564 ;;; Internal commands
1566 (defun vc-git-command (buffer okstatus file-or-list &rest flags)
1567 "A wrapper around `vc-do-command' for use in vc-git.el.
1568 The difference to vc-do-command is that this function always invokes
1570 (let ((coding-system-for-read
1571 (or coding-system-for-read vc-git-log-output-coding-system))
1572 (coding-system-for-write
1573 (or coding-system-for-write vc-git-commits-coding-system))
1574 (process-environment
1577 ;; Avoid repository locking during background operations
1579 ,@(when revert-buffer-in-progress-p
1580 '("GIT_OPTIONAL_LOCKS=0")))
1581 process-environment)))
1582 (apply 'vc-do-command (or buffer "*vc*") okstatus vc-git-program
1583 ;; https://debbugs.gnu.org/16897
1584 (unless (and (not (cdr-safe file-or-list))
1585 (let ((file (or (car-safe file-or-list)
1588 (eq ?/ (aref file (1- (length file))))
1589 (equal file (vc-git-root file)))))
1591 (cons "--no-pager" flags))))
1593 (defun vc-git--empty-db-p ()
1594 "Check if the git db is empty (no commit done yet)."
1595 (let (process-file-side-effects)
1596 (not (eq 0 (vc-git--call nil "rev-parse" "--verify" "HEAD")))))
1598 (defun vc-git--call (buffer command &rest args)
1599 ;; We don't need to care the arguments. If there is a file name, it
1600 ;; is always a relative one. This works also for remote
1601 ;; directories. We enable `inhibit-null-byte-detection', otherwise
1602 ;; Tramp's eol conversion might be confused.
1603 (let ((inhibit-null-byte-detection t)
1604 (coding-system-for-read
1605 (or coding-system-for-read vc-git-log-output-coding-system))
1606 (coding-system-for-write
1607 (or coding-system-for-write vc-git-commits-coding-system))
1608 (process-environment (cons "PAGER=" process-environment)))
1609 (push "GIT_DIR" process-environment)
1610 (apply 'process-file vc-git-program nil buffer nil command args)))
1612 (defun vc-git--out-ok (command &rest args)
1613 (zerop (apply 'vc-git--call '(t nil) command args)))
1615 (defun vc-git--run-command-string (file &rest args)
1616 "Run a git command on FILE and return its output as string.
1619 (str (with-output-to-string
1620 (with-current-buffer standard-output
1621 (unless (apply 'vc-git--out-ok
1623 (append args (list (file-relative-name
1629 (defun vc-git-symbolic-commit (commit)
1630 "Translate COMMIT string into symbolic form.
1631 Returns nil if not possible."
1633 (let ((name (with-temp-buffer
1635 (vc-git--out-ok "name-rev" "--name-only" commit)
1636 (goto-char (point-min))
1637 (= (forward-line 2) 1)
1639 (buffer-substring-no-properties (point-min)
1640 (1- (point-max)))))))
1641 (and name (not (string= name "undefined")) name))))
1645 ;;; vc-git.el ends here