* lisp/vc/vc-hg.el, lisp/vc/vc-git.el: Flush the 'vc-functions' cache.
[emacs.git] / lisp / vc / vc-git.el
blob2d6ca1386a359d708629bc96ae69bc3dab9e1aeb
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>
6 ;; Keywords: vc tools
7 ;; Package: vc
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
24 ;;; Commentary:
26 ;; This file contains a VC backend for the git version control
27 ;; system.
30 ;;; Installation:
32 ;; To install: put this file on the load-path and add Git to the list
33 ;; of supported backends in `vc-handled-backends'; the following line,
34 ;; placed in your init file, will accomplish this:
36 ;; (add-to-list 'vc-handled-backends 'Git)
38 ;;; Todo:
39 ;; - check if more functions could use vc-git-command instead
40 ;; of start-process.
41 ;; - changelog generation
43 ;; Implement the rest of the vc interface. See the comment at the
44 ;; beginning of vc.el. The current status is:
45 ;; ("??" means: "figure out what to do about it")
47 ;; FUNCTION NAME STATUS
48 ;; BACKEND PROPERTIES
49 ;; * revision-granularity OK
50 ;; STATE-QUERYING FUNCTIONS
51 ;; * registered (file) OK
52 ;; * state (file) OK
53 ;; - 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
72 ;; not a good idea.
73 ;; - merge-news (file) see `merge-file'
74 ;; - steal-lock (file &optional revision) NOT NEEDED
75 ;; HISTORY FUNCTIONS
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
87 ;; TAG SYSTEM
88 ;; - create-tag (dir name branchp) OK
89 ;; - retrieve-tag (dir name update) OK
90 ;; MISCELLANEOUS
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
100 ;;; Code:
102 (eval-when-compile
103 (require 'cl-lib)
104 (require 'vc)
105 (require 'vc-dir)
106 (require 'grep))
108 (defgroup vc-git nil
109 "VC Git backend."
110 :version "24.1"
111 :group 'vc)
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))
120 :version "23.1")
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))
129 :version "25.1")
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
136 the staging area."
137 :type '(choice (const :tag "Don't resolve" nil)
138 (const :tag "Resolve" t)
139 (const :tag "Resolve and maybe unstage all files"
140 unstage-maybe))
141 :version "25.1")
143 (defcustom vc-git-program "git"
144 "Name of the Git executable (excluding any arguments)."
145 :version "24.1"
146 :type 'string)
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)
157 (3 'change-log-name)
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))
166 :version "24.1")
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")
174 :version "25.1")
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")
181 :version "25.1")
183 ;; History of Git commands.
184 (defvar vc-git-history nil)
186 ;; Clear up the cache to force vc-call to check again and discover
187 ;; new functions when we reload this file.
188 (put 'Git 'vc-functions nil)
190 ;;; BACKEND PROPERTIES
192 (defun vc-git-revision-granularity () 'repository)
193 (defun vc-git-checkout-model (_files) 'implicit)
195 ;;; STATE-QUERYING FUNCTIONS
197 ;;;###autoload (defun vc-git-registered (file)
198 ;;;###autoload "Return non-nil if FILE is registered with git."
199 ;;;###autoload (if (vc-find-root file ".git") ; Short cut.
200 ;;;###autoload (progn
201 ;;;###autoload (load "vc-git" nil t)
202 ;;;###autoload (vc-git-registered file))))
204 (defun vc-git-registered (file)
205 "Check whether FILE is registered with git."
206 (let ((dir (vc-git-root file)))
207 (when dir
208 (with-temp-buffer
209 (let* (process-file-side-effects
210 ;; Do not use the `file-name-directory' here: git-ls-files
211 ;; sometimes fails to return the correct status for relative
212 ;; path specs.
213 ;; See also: http://marc.info/?l=git&m=125787684318129&w=2
214 (name (file-relative-name file dir))
215 (str (ignore-errors
216 (cd dir)
217 (vc-git--out-ok "ls-files" "-c" "-z" "--" name)
218 ;; If result is empty, use ls-tree to check for deleted
219 ;; file.
220 (when (eq (point-min) (point-max))
221 (vc-git--out-ok "ls-tree" "--name-only" "-z" "HEAD"
222 "--" name))
223 (buffer-string))))
224 (and str
225 (> (length str) (length name))
226 (string= (substring str 0 (1+ (length name)))
227 (concat name "\0"))))))))
229 (defun vc-git--state-code (code)
230 "Convert from a string to a added/deleted/modified state."
231 (pcase (string-to-char code)
232 (?M 'edited)
233 (?A 'added)
234 (?D 'removed)
235 (?U 'edited) ;; FIXME
236 (?T 'edited))) ;; FIXME
238 (defvar vc-git--program-version nil)
240 (defun vc-git--program-version ()
241 (or vc-git--program-version
242 (let ((version-string
243 (vc-git--run-command-string nil "version")))
244 (setq vc-git--program-version
245 (if (and version-string
246 (string-match "git version \\([0-9.]+\\)$"
247 version-string))
248 (match-string 1 version-string)
249 "0")))))
251 (defun vc-git--git-status-to-vc-state (code-list)
252 "Convert CODE-LIST to a VC status.
254 Each element of CODE-LIST comes from the first two characters of
255 a line returned by 'git status --porcelain' and should be passed
256 in the order given by 'git status'."
257 ;; It is necessary to allow CODE-LIST to be a list because sometimes git
258 ;; status returns multiple lines, e.g. for a file that is removed from
259 ;; the index but is present in the HEAD and working tree.
260 (pcase code-list
261 ('nil 'up-to-date)
262 (`(,code)
263 (pcase code
264 ("!!" 'ignored)
265 ("??" 'unregistered)
266 ;; I have only seen this with a file that is only present in the
267 ;; index. Let us call this `removed'.
268 ("AD" 'removed)
269 (_ (cond
270 ((string-match-p "^[ RD]+$" code) 'removed)
271 ((string-match-p "^[ M]+$" code) 'edited)
272 ((string-match-p "^[ A]+$" code) 'added)
273 ((string-match-p "^[ U]+$" code) 'conflict)
274 (t 'edited)))))
275 ;; I know of two cases when git state returns more than one element,
276 ;; in both cases returning '("D " "??")':
277 ;; 1. When a file is removed from the index but present in the
278 ;; HEAD and working tree.
279 ;; 2. When a file A is renamed to B in the index and then back to A
280 ;; in the working tree.
281 ;; In both of these instances, `unregistered' is a reasonable response.
282 (`("D " "??") 'unregistered)
283 ;; In other cases, let us return `edited'.
284 (_ 'edited)))
286 (defun vc-git-state (file)
287 "Git-specific version of `vc-state'."
288 ;; It can't set `needs-update' or `needs-merge'. The rough
289 ;; equivalent would be that upstream branch for current branch is in
290 ;; fast-forward state i.e. current branch is direct ancestor of
291 ;; corresponding upstream branch, and the file was modified
292 ;; upstream. We'd need to check against the upstream tracking
293 ;; branch for that (an extra process call or two).
294 (let* ((args
295 `("status" "--porcelain" "-z"
296 ;; Just to be explicit, it's the default anyway.
297 "--untracked-files"
298 ,@(when (version<= "1.7.6.3" (vc-git--program-version))
299 '("--ignored"))
300 "--"))
301 (status (apply #'vc-git--run-command-string file args)))
302 ;; Alternatively, the `ignored' state could be detected with 'git
303 ;; ls-files -i -o --exclude-standard', but that's an extra process
304 ;; call, and the `ignored' state is rarely needed.
305 (if (null status)
306 ;; If status is nil, there was an error calling git, likely because
307 ;; the file is not in a git repo.
308 'unregistered
309 ;; If this code is adapted to parse 'git status' for a directory,
310 ;; note that a renamed file takes up two null values and needs to be
311 ;; treated slightly more carefully.
312 (vc-git--git-status-to-vc-state
313 (mapcar (lambda (s)
314 (substring s 0 2))
315 (split-string status "\0" t))))))
317 (defun vc-git-working-revision (_file)
318 "Git-specific version of `vc-working-revision'."
319 (let (process-file-side-effects)
320 (vc-git--rev-parse "HEAD")))
322 (defun vc-git--symbolic-ref (file)
324 (vc-file-getprop file 'vc-git-symbolic-ref)
325 (let* (process-file-side-effects
326 (str (vc-git--run-command-string nil "symbolic-ref" "HEAD")))
327 (vc-file-setprop file 'vc-git-symbolic-ref
328 (if str
329 (if (string-match "^\\(refs/heads/\\)?\\(.+\\)$" str)
330 (match-string 2 str)
331 str))))))
333 (defun vc-git-mode-line-string (file)
334 "Return a string for `vc-mode-line' to put in the mode line for FILE."
335 (let* ((rev (vc-working-revision file 'Git))
336 (disp-rev (or (vc-git--symbolic-ref file)
337 (substring rev 0 7)))
338 (def-ml (vc-default-mode-line-string 'Git file))
339 (help-echo (get-text-property 0 'help-echo def-ml))
340 (face (get-text-property 0 'face def-ml)))
341 (propertize (concat (substring def-ml 0 4) disp-rev)
342 'face face
343 'help-echo (concat help-echo "\nCurrent revision: " rev))))
345 (cl-defstruct (vc-git-extra-fileinfo
346 (:copier nil)
347 (:constructor vc-git-create-extra-fileinfo
348 (old-perm new-perm &optional rename-state orig-name))
349 (:conc-name vc-git-extra-fileinfo->))
350 old-perm new-perm ;; Permission flags.
351 rename-state ;; Rename or copy state.
352 orig-name) ;; Original name for renames or copies.
354 (defun vc-git-escape-file-name (name)
355 "Escape a file name if necessary."
356 (if (string-match "[\n\t\"\\]" name)
357 (concat "\""
358 (mapconcat (lambda (c)
359 (pcase c
360 (?\n "\\n")
361 (?\t "\\t")
362 (?\\ "\\\\")
363 (?\" "\\\"")
364 (_ (char-to-string c))))
365 name "")
366 "\"")
367 name))
369 (defun vc-git-file-type-as-string (old-perm new-perm)
370 "Return a string describing the file type based on its permissions."
371 (let* ((old-type (lsh (or old-perm 0) -9))
372 (new-type (lsh (or new-perm 0) -9))
373 (str (pcase new-type
374 (?\100 ;; File.
375 (pcase old-type
376 (?\100 nil)
377 (?\120 " (type change symlink -> file)")
378 (?\160 " (type change subproject -> file)")))
379 (?\120 ;; Symlink.
380 (pcase old-type
381 (?\100 " (type change file -> symlink)")
382 (?\160 " (type change subproject -> symlink)")
383 (_ " (symlink)")))
384 (?\160 ;; Subproject.
385 (pcase old-type
386 (?\100 " (type change file -> subproject)")
387 (?\120 " (type change symlink -> subproject)")
388 (_ " (subproject)")))
389 (?\110 nil) ;; Directory (internal, not a real git state).
390 (?\000 ;; Deleted or unknown.
391 (pcase old-type
392 (?\120 " (symlink)")
393 (?\160 " (subproject)")))
394 (_ (format " (unknown type %o)" new-type)))))
395 (cond (str (propertize str 'face 'font-lock-comment-face))
396 ((eq new-type ?\110) "/")
397 (t ""))))
399 (defun vc-git-rename-as-string (state extra)
400 "Return a string describing the copy or rename associated with INFO,
401 or an empty string if none."
402 (let ((rename-state (when extra
403 (vc-git-extra-fileinfo->rename-state extra))))
404 (if rename-state
405 (propertize
406 (concat " ("
407 (if (eq rename-state 'copy) "copied from "
408 (if (eq state 'added) "renamed from "
409 "renamed to "))
410 (vc-git-escape-file-name
411 (vc-git-extra-fileinfo->orig-name extra))
412 ")")
413 'face 'font-lock-comment-face)
414 "")))
416 (defun vc-git-permissions-as-string (old-perm new-perm)
417 "Format a permission change as string."
418 (propertize
419 (if (or (not old-perm)
420 (not new-perm)
421 (eq 0 (logand ?\111 (logxor old-perm new-perm))))
423 (if (eq 0 (logand ?\111 old-perm)) "+x" "-x"))
424 'face 'font-lock-type-face))
426 (defun vc-git-dir-printer (info)
427 "Pretty-printer for the vc-dir-fileinfo structure."
428 (let* ((isdir (vc-dir-fileinfo->directory info))
429 (state (if isdir "" (vc-dir-fileinfo->state info)))
430 (extra (vc-dir-fileinfo->extra info))
431 (old-perm (when extra (vc-git-extra-fileinfo->old-perm extra)))
432 (new-perm (when extra (vc-git-extra-fileinfo->new-perm extra))))
433 (insert
435 (propertize (format "%c" (if (vc-dir-fileinfo->marked info) ?* ? ))
436 'face 'font-lock-type-face)
438 (propertize
439 (format "%-12s" state)
440 'face (cond ((eq state 'up-to-date) 'font-lock-builtin-face)
441 ((eq state 'missing) 'font-lock-warning-face)
442 (t 'font-lock-variable-name-face))
443 'mouse-face 'highlight)
444 " " (vc-git-permissions-as-string old-perm new-perm)
446 (propertize (vc-git-escape-file-name (vc-dir-fileinfo->name info))
447 'face (if isdir 'font-lock-comment-delimiter-face
448 'font-lock-function-name-face)
449 'help-echo
450 (if isdir
451 "Directory\nVC operations can be applied to it\nmouse-3: Pop-up menu"
452 "File\nmouse-3: Pop-up menu")
453 'keymap vc-dir-filename-mouse-map
454 'mouse-face 'highlight)
455 (vc-git-file-type-as-string old-perm new-perm)
456 (vc-git-rename-as-string state extra))))
458 (cl-defstruct (vc-git-dir-status-state
459 (:copier nil)
460 (:conc-name vc-git-dir-status-state->))
461 ;; Current stage.
462 stage
463 ;; List of files still to be processed.
464 files
465 ;; Update function to be called at the end.
466 update-function
467 ;; Hash table of entries for files we've computed so far.
468 (hash (make-hash-table :test 'equal)))
470 (defsubst vc-git-dir-status-update-file (state filename file-state file-info)
471 (puthash filename (list file-state file-info)
472 (vc-git-dir-status-state->hash state))
473 (setf (vc-git-dir-status-state->files state)
474 (delete filename (vc-git-dir-status-state->files state))))
476 (defun vc-git-after-dir-status-stage (git-state)
477 "Process sentinel for the various dir-status stages."
478 (let (next-stage
479 (files (vc-git-dir-status-state->files git-state)))
480 (goto-char (point-min))
481 (pcase (vc-git-dir-status-state->stage git-state)
482 (`update-index
483 (setq next-stage (if (vc-git--empty-db-p) 'ls-files-added 'diff-index)))
484 (`ls-files-added
485 (setq next-stage 'ls-files-unknown)
486 (while (re-search-forward "\\([0-7]\\{6\\}\\) [0-9a-f]\\{40\\} 0\t\\([^\0]+\\)\0" nil t)
487 (let ((new-perm (string-to-number (match-string 1) 8))
488 (name (match-string 2)))
489 (vc-git-dir-status-update-file
490 git-state name 'added
491 (vc-git-create-extra-fileinfo 0 new-perm)))))
492 (`ls-files-up-to-date
493 (setq next-stage 'ls-files-unknown)
494 (while (re-search-forward "\\([0-7]\\{6\\}\\) [0-9a-f]\\{40\\} \\([0-3]\\)\t\\([^\0]+\\)\0" nil t)
495 (let ((perm (string-to-number (match-string 1) 8))
496 (state (match-string 2))
497 (name (match-string 3)))
498 (vc-git-dir-status-update-file
499 git-state name (if (equal state "0")
500 'up-to-date
501 'conflict)
502 (vc-git-create-extra-fileinfo perm perm)))))
503 (`ls-files-conflict
504 (setq next-stage 'ls-files-unknown)
505 ;; It's enough to look for "3" to notice a conflict.
506 (while (re-search-forward "\\([0-7]\\{6\\}\\) [0-9a-f]\\{40\\} 3\t\\([^\0]+\\)\0" nil t)
507 (let ((perm (string-to-number (match-string 1) 8))
508 (name (match-string 2)))
509 (vc-git-dir-status-update-file
510 git-state name 'conflict
511 (vc-git-create-extra-fileinfo perm perm)))))
512 (`ls-files-unknown
513 (when files (setq next-stage 'ls-files-ignored))
514 (while (re-search-forward "\\([^\0]*?\\)\0" nil t 1)
515 (vc-git-dir-status-update-file git-state (match-string 1) 'unregistered
516 (vc-git-create-extra-fileinfo 0 0))))
517 (`ls-files-ignored
518 (while (re-search-forward "\\([^\0]*?\\)\0" nil t 1)
519 (vc-git-dir-status-update-file git-state (match-string 1) 'ignored
520 (vc-git-create-extra-fileinfo 0 0))))
521 (`diff-index
522 (setq next-stage (if files 'ls-files-up-to-date 'ls-files-conflict))
523 (while (re-search-forward
524 ":\\([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"
525 nil t 1)
526 (let ((old-perm (string-to-number (match-string 1) 8))
527 (new-perm (string-to-number (match-string 2) 8))
528 (state (or (match-string 4) (match-string 6)))
529 (name (or (match-string 5) (match-string 7)))
530 (new-name (match-string 8)))
531 (if new-name ; Copy or rename.
532 (if (eq ?C (string-to-char state))
533 (vc-git-dir-status-update-file
534 git-state new-name 'added
535 (vc-git-create-extra-fileinfo old-perm new-perm
536 'copy name))
537 (vc-git-dir-status-update-file
538 git-state name 'removed
539 (vc-git-create-extra-fileinfo 0 0 'rename new-name))
540 (vc-git-dir-status-update-file
541 git-state new-name 'added
542 (vc-git-create-extra-fileinfo old-perm new-perm
543 'rename name)))
544 (vc-git-dir-status-update-file
545 git-state name (vc-git--state-code state)
546 (vc-git-create-extra-fileinfo old-perm new-perm)))))))
547 ;; If we had files but now we don't, it's time to stop.
548 (when (and files (not (vc-git-dir-status-state->files git-state)))
549 (setq next-stage nil))
550 (setf (vc-git-dir-status-state->stage git-state) next-stage)
551 (setf (vc-git-dir-status-state->files git-state) files)
552 (if next-stage
553 (vc-git-dir-status-goto-stage git-state)
554 (funcall (vc-git-dir-status-state->update-function git-state)
555 (let ((result nil))
556 (maphash (lambda (key value)
557 (push (cons key value) result))
558 (vc-git-dir-status-state->hash git-state))
559 result)
560 nil))))
562 ;; Follows vc-git-command (or vc-do-async-command), which uses vc-do-command
563 ;; from vc-dispatcher.
564 (declare-function vc-exec-after "vc-dispatcher" (code))
565 ;; Follows vc-exec-after.
566 (declare-function vc-set-async-update "vc-dispatcher" (process-buffer))
568 (defun vc-git-dir-status-goto-stage (git-state)
569 (let ((files (vc-git-dir-status-state->files git-state)))
570 (erase-buffer)
571 (pcase (vc-git-dir-status-state->stage git-state)
572 (`update-index
573 (if files
574 (vc-git-command (current-buffer) 'async files "add" "--refresh" "--")
575 (vc-git-command (current-buffer) 'async nil
576 "update-index" "--refresh")))
577 (`ls-files-added
578 (vc-git-command (current-buffer) 'async files
579 "ls-files" "-z" "-c" "-s" "--"))
580 (`ls-files-up-to-date
581 (vc-git-command (current-buffer) 'async files
582 "ls-files" "-z" "-c" "-s" "--"))
583 (`ls-files-conflict
584 (vc-git-command (current-buffer) 'async files
585 "ls-files" "-z" "-c" "-s" "--"))
586 (`ls-files-unknown
587 (vc-git-command (current-buffer) 'async files
588 "ls-files" "-z" "-o" "--directory"
589 "--no-empty-directory" "--exclude-standard" "--"))
590 (`ls-files-ignored
591 (vc-git-command (current-buffer) 'async files
592 "ls-files" "-z" "-o" "-i" "--directory"
593 "--no-empty-directory" "--exclude-standard" "--"))
594 ;; --relative added in Git 1.5.5.
595 (`diff-index
596 (vc-git-command (current-buffer) 'async files
597 "diff-index" "--relative" "-z" "-M" "HEAD" "--")))
598 (vc-run-delayed
599 (vc-git-after-dir-status-stage git-state))))
601 (defun vc-git-dir-status-files (_dir files update-function)
602 "Return a list of (FILE STATE EXTRA) entries for DIR."
603 ;; Further things that would have to be fixed later:
604 ;; - how to handle unregistered directories
605 ;; - how to support vc-dir on a subdir of the project tree
606 (vc-git-dir-status-goto-stage
607 (make-vc-git-dir-status-state :stage 'update-index
608 :files files
609 :update-function update-function)))
611 (defvar vc-git-stash-map
612 (let ((map (make-sparse-keymap)))
613 ;; Turn off vc-dir marking
614 (define-key map [mouse-2] 'ignore)
616 (define-key map [down-mouse-3] 'vc-git-stash-menu)
617 (define-key map "\C-k" 'vc-git-stash-delete-at-point)
618 (define-key map "=" 'vc-git-stash-show-at-point)
619 (define-key map "\C-m" 'vc-git-stash-show-at-point)
620 (define-key map "A" 'vc-git-stash-apply-at-point)
621 (define-key map "P" 'vc-git-stash-pop-at-point)
622 (define-key map "S" 'vc-git-stash-snapshot)
623 map))
625 (defvar vc-git-stash-menu-map
626 (let ((map (make-sparse-keymap "Git Stash")))
627 (define-key map [de]
628 '(menu-item "Delete Stash" vc-git-stash-delete-at-point
629 :help "Delete the current stash"))
630 (define-key map [ap]
631 '(menu-item "Apply Stash" vc-git-stash-apply-at-point
632 :help "Apply the current stash and keep it in the stash list"))
633 (define-key map [po]
634 '(menu-item "Apply and Remove Stash (Pop)" vc-git-stash-pop-at-point
635 :help "Apply the current stash and remove it"))
636 (define-key map [sh]
637 '(menu-item "Show Stash" vc-git-stash-show-at-point
638 :help "Show the contents of the current stash"))
639 map))
641 (defun vc-git-dir-extra-headers (dir)
642 (let ((str (with-output-to-string
643 (with-current-buffer standard-output
644 (vc-git--out-ok "symbolic-ref" "HEAD"))))
645 (stash (vc-git-stash-list))
646 (stash-help-echo "Use M-x vc-git-stash to create stashes.")
647 branch remote remote-url)
648 (if (string-match "^\\(refs/heads/\\)?\\(.+\\)$" str)
649 (progn
650 (setq branch (match-string 2 str))
651 (setq remote
652 (with-output-to-string
653 (with-current-buffer standard-output
654 (vc-git--out-ok "config"
655 (concat "branch." branch ".remote")))))
656 (when (string-match "\\([^\n]+\\)" remote)
657 (setq remote (match-string 1 remote)))
658 (when remote
659 (setq remote-url
660 (with-output-to-string
661 (with-current-buffer standard-output
662 (vc-git--out-ok "config"
663 (concat "remote." remote ".url"))))))
664 (when (string-match "\\([^\n]+\\)" remote-url)
665 (setq remote-url (match-string 1 remote-url))))
666 (setq branch "not (detached HEAD)"))
667 ;; FIXME: maybe use a different face when nothing is stashed.
668 (concat
669 (propertize "Branch : " 'face 'font-lock-type-face)
670 (propertize branch
671 'face 'font-lock-variable-name-face)
672 (when remote
673 (concat
674 "\n"
675 (propertize "Remote : " 'face 'font-lock-type-face)
676 (propertize remote-url
677 'face 'font-lock-variable-name-face)))
678 "\n"
679 ;; For now just a heading, key bindings can be added later for various bisect actions
680 (when (file-exists-p (expand-file-name ".git/BISECT_START" (vc-git-root dir)))
681 (propertize "Bisect : in progress\n" 'face 'font-lock-warning-face))
682 (when (file-exists-p (expand-file-name ".git/rebase-apply" (vc-git-root dir)))
683 (propertize "Rebase : in progress\n" 'face 'font-lock-warning-face))
684 (if stash
685 (concat
686 (propertize "Stash :\n" 'face 'font-lock-type-face
687 'help-echo stash-help-echo)
688 (mapconcat
689 (lambda (x)
690 (propertize x
691 'face 'font-lock-variable-name-face
692 'mouse-face 'highlight
693 'help-echo "mouse-3: Show stash menu\nRET: Show stash\nA: Apply stash\nP: Apply and remove stash (pop)\nC-k: Delete stash"
694 'keymap vc-git-stash-map))
695 stash "\n"))
696 (concat
697 (propertize "Stash : " 'face 'font-lock-type-face
698 'help-echo stash-help-echo)
699 (propertize "Nothing stashed"
700 'help-echo stash-help-echo
701 'face 'font-lock-variable-name-face))))))
703 (defun vc-git-branches ()
704 "Return the existing branches, as a list of strings.
705 The car of the list is the current branch."
706 (with-temp-buffer
707 (vc-git--call t "branch")
708 (goto-char (point-min))
709 (let (current-branch branches)
710 (while (not (eobp))
711 (when (looking-at "^\\([ *]\\) \\(.+\\)$")
712 (if (string-equal (match-string 1) "*")
713 (setq current-branch (match-string 2))
714 (push (match-string 2) branches)))
715 (forward-line 1))
716 (cons current-branch (nreverse branches)))))
718 ;;; STATE-CHANGING FUNCTIONS
720 (defun vc-git-create-repo ()
721 "Create a new Git repository."
722 (vc-git-command nil 0 nil "init"))
724 (defun vc-git-register (files &optional _comment)
725 "Register FILES into the git version-control system."
726 (let (flist dlist)
727 (dolist (crt files)
728 (if (file-directory-p crt)
729 (push crt dlist)
730 (push crt flist)))
731 (when flist
732 (vc-git-command nil 0 flist "update-index" "--add" "--"))
733 (when dlist
734 (vc-git-command nil 0 dlist "add"))))
736 (defalias 'vc-git-responsible-p 'vc-git-root)
738 (defun vc-git-unregister (file)
739 (vc-git-command nil 0 file "rm" "-f" "--cached" "--"))
741 (declare-function log-edit-mode "log-edit" ())
742 (declare-function log-edit-toggle-header "log-edit" (header value))
743 (declare-function log-edit-extract-headers "log-edit" (headers string))
744 (declare-function log-edit-set-header "log-edit" (header value &optional toggle))
746 (defun vc-git-log-edit-toggle-signoff ()
747 "Toggle whether to add the \"Signed-off-by\" line at the end of
748 the commit message."
749 (interactive)
750 (log-edit-toggle-header "Sign-Off" "yes"))
752 (defun vc-git-log-edit-toggle-amend ()
753 "Toggle whether this will amend the previous commit.
754 If toggling on, also insert its message into the buffer."
755 (interactive)
756 (when (log-edit-toggle-header "Amend" "yes")
757 (goto-char (point-max))
758 (unless (bolp) (insert "\n"))
759 (insert (with-output-to-string
760 (vc-git-command
761 standard-output 1 nil
762 "log" "--max-count=1" "--pretty=format:%B" "HEAD")))
763 (save-excursion
764 (rfc822-goto-eoh)
765 (forward-line 1)
766 (let ((pt (point)))
767 (and (zerop (forward-line 1))
768 (looking-at "\n\\|\\'")
769 (let ((summary (buffer-substring-no-properties pt (1- (point)))))
770 (skip-chars-forward " \n")
771 (delete-region pt (point))
772 (log-edit-set-header "Summary" summary)))))))
774 (defvar vc-git-log-edit-mode-map
775 (let ((map (make-sparse-keymap "Git-Log-Edit")))
776 (define-key map "\C-c\C-s" 'vc-git-log-edit-toggle-signoff)
777 (define-key map "\C-c\C-e" 'vc-git-log-edit-toggle-amend)
778 map))
780 (define-derived-mode vc-git-log-edit-mode log-edit-mode "Log-Edit/git"
781 "Major mode for editing Git log messages.
782 It is based on `log-edit-mode', and has Git-specific extensions.")
784 (defun vc-git-checkin (files comment &optional _rev)
785 (let* ((file1 (or (car files) default-directory))
786 (root (vc-git-root file1))
787 (default-directory (expand-file-name root))
788 (only (or (cdr files)
789 (not (equal root (abbreviate-file-name file1)))))
790 (pcsw coding-system-for-write)
791 (coding-system-for-write
792 ;; On MS-Windows, we must encode command-line arguments in
793 ;; the system codepage.
794 (if (eq system-type 'windows-nt)
795 locale-coding-system
796 (or coding-system-for-write vc-git-commits-coding-system)))
797 (msg-file
798 ;; On MS-Windows, pass the commit log message through a
799 ;; file, to work around the limitation that command-line
800 ;; arguments must be in the system codepage, and therefore
801 ;; might not support the non-ASCII characters in the log
802 ;; message. Handle also remote files.
803 (if (eq system-type 'windows-nt)
804 (let ((default-directory (file-name-directory file1)))
805 (make-nearby-temp-file "git-msg")))))
806 (cl-flet ((boolean-arg-fn
807 (argument)
808 (lambda (value) (when (equal value "yes") (list argument)))))
809 ;; When operating on the whole tree, better pass "-a" than ".", since "."
810 ;; fails when we're committing a merge.
811 (apply 'vc-git-command nil 0 (if only files)
812 (nconc (if msg-file (list "commit" "-F"
813 (file-local-name msg-file))
814 (list "commit" "-m"))
815 (let ((args
816 (log-edit-extract-headers
817 `(("Author" . "--author")
818 ("Date" . "--date")
819 ("Amend" . ,(boolean-arg-fn "--amend"))
820 ("Sign-Off" . ,(boolean-arg-fn "--signoff")))
821 comment)))
822 (when msg-file
823 (let ((coding-system-for-write
824 (or pcsw vc-git-commits-coding-system)))
825 (write-region (car args) nil msg-file))
826 (setq args (cdr args)))
827 args)
828 (if only (list "--only" "--") '("-a")))))
829 (if (and msg-file (file-exists-p msg-file)) (delete-file msg-file))))
831 (defun vc-git-find-revision (file rev buffer)
832 (let* (process-file-side-effects
833 (coding-system-for-read 'binary)
834 (coding-system-for-write 'binary)
835 (fullname
836 (let ((fn (vc-git--run-command-string
837 file "ls-files" "-z" "--full-name" "--")))
838 ;; ls-files does not return anything when looking for a
839 ;; revision of a file that has been renamed or removed.
840 (if (string= fn "")
841 (file-relative-name file (vc-git-root default-directory))
842 (substring fn 0 -1)))))
843 (vc-git-command
844 buffer 0
846 "cat-file" "blob" (concat (if rev rev "HEAD") ":" fullname))))
848 (defun vc-git-find-ignore-file (file)
849 "Return the git ignore file that controls FILE."
850 (expand-file-name ".gitignore"
851 (vc-git-root file)))
853 (defun vc-git-checkout (file &optional rev)
854 (vc-git-command nil 0 file "checkout" (or rev "HEAD")))
856 (defun vc-git-revert (file &optional contents-done)
857 "Revert FILE to the version stored in the git repository."
858 (if contents-done
859 (vc-git-command nil 0 file "update-index" "--")
860 (vc-git-command nil 0 file "reset" "-q" "--")
861 (vc-git-command nil nil file "checkout" "-q" "--")))
863 (defvar vc-git-error-regexp-alist
864 '(("^ \\(.+\\)\\> *|" 1 nil nil 0))
865 "Value of `compilation-error-regexp-alist' in *vc-git* buffers.")
867 ;; To be called via vc-pull from vc.el, which requires vc-dispatcher.
868 (declare-function vc-compilation-mode "vc-dispatcher" (backend))
870 (defun vc-git--pushpull (command prompt extra-args)
871 "Run COMMAND (a string; either push or pull) on the current Git branch.
872 If PROMPT is non-nil, prompt for the Git command to run."
873 (let* ((root (vc-git-root default-directory))
874 (buffer (format "*vc-git : %s*" (expand-file-name root)))
875 (git-program vc-git-program)
876 args)
877 ;; If necessary, prompt for the exact command.
878 ;; TODO if pushing, prompt if no default push location - cf bzr.
879 (when prompt
880 (setq args (split-string
881 (read-shell-command
882 (format "Git %s command: " command)
883 (format "%s %s" git-program command)
884 'vc-git-history)
885 " " t))
886 (setq git-program (car args)
887 command (cadr args)
888 args (cddr args)))
889 (setq args (nconc args extra-args))
890 (require 'vc-dispatcher)
891 (apply 'vc-do-async-command buffer root git-program command args)
892 (with-current-buffer buffer
893 (vc-run-delayed
894 (vc-compilation-mode 'git)
895 (setq-local compile-command
896 (concat git-program " " command " "
897 (mapconcat 'identity args " ")))
898 (setq-local compilation-directory root)
899 ;; Either set `compilation-buffer-name-function' locally to nil
900 ;; or use `compilation-arguments' to set `name-function'.
901 ;; See `compilation-buffer-name'.
902 (setq-local compilation-arguments
903 (list compile-command nil
904 (lambda (_name-of-mode) buffer)
905 nil))))
906 (vc-set-async-update buffer)))
908 (defun vc-git-pull (prompt)
909 "Pull changes into the current Git branch.
910 Normally, this runs \"git pull\". If PROMPT is non-nil, prompt
911 for the Git command to run."
912 (vc-git--pushpull "pull" prompt '("--stat")))
914 (defun vc-git-push (prompt)
915 "Push changes from the current Git branch.
916 Normally, this runs \"git push\". If PROMPT is non-nil, prompt
917 for the Git command to run."
918 (vc-git--pushpull "push" prompt nil))
920 (defun vc-git-merge-branch ()
921 "Merge changes into the current Git branch.
922 This prompts for a branch to merge from."
923 (let* ((root (vc-git-root default-directory))
924 (buffer (format "*vc-git : %s*" (expand-file-name root)))
925 (branches (cdr (vc-git-branches)))
926 (merge-source
927 (completing-read "Merge from branch: "
928 (if (or (member "FETCH_HEAD" branches)
929 (not (file-readable-p
930 (expand-file-name ".git/FETCH_HEAD"
931 root))))
932 branches
933 (cons "FETCH_HEAD" branches))
934 nil t)))
935 (apply 'vc-do-async-command buffer root vc-git-program "merge"
936 (list merge-source))
937 (with-current-buffer buffer (vc-run-delayed (vc-compilation-mode 'git)))
938 (vc-set-async-update buffer)))
940 (defun vc-git-conflicted-files (directory)
941 "Return the list of files with conflicts in DIRECTORY."
942 (let* ((status
943 (vc-git--run-command-string directory "status" "--porcelain" "--"))
944 (lines (when status (split-string status "\n" 'omit-nulls)))
945 files)
946 ;; TODO: Look into reimplementing `vc-git-state', as well as
947 ;; `vc-git-dir-status-files', based on this output, thus making the
948 ;; extra process call in `vc-git-find-file-hook' unnecessary.
949 (dolist (line lines files)
950 (when (string-match "\\([ MADRCU?!][ MADRCU?!]\\) \\(.+\\)\\(?: -> \\(.+\\)\\)?"
951 line)
952 (let ((state (match-string 1 line))
953 (file (match-string 2 line)))
954 ;; See git-status(1).
955 (when (member state '("AU" "UD" "UA" ;; "DD"
956 "DU" "AA" "UU"))
957 (push (expand-file-name file directory) files)))))))
959 ;; Everywhere but here, follows vc-git-command, which uses vc-do-command
960 ;; from vc-dispatcher.
961 (autoload 'vc-resynch-buffer "vc-dispatcher")
963 (defun vc-git-resolve-when-done ()
964 "Call \"git add\" if the conflict markers have been removed."
965 (save-excursion
966 (goto-char (point-min))
967 (unless (re-search-forward "^<<<<<<< " nil t)
968 (vc-git-command nil 0 buffer-file-name "add")
969 (unless (or
970 (not (eq vc-git-resolve-conflicts 'unstage-maybe))
971 ;; Doing a merge, so bug#20292 doesn't apply.
972 (file-exists-p (expand-file-name ".git/MERGE_HEAD"
973 (vc-git-root buffer-file-name)))
974 (vc-git-conflicted-files (vc-git-root buffer-file-name)))
975 (vc-git-command nil 0 nil "reset"))
976 (vc-resynch-buffer buffer-file-name t t)
977 ;; Remove the hook so that it is not called multiple times.
978 (remove-hook 'after-save-hook 'vc-git-resolve-when-done t))))
980 (defun vc-git-find-file-hook ()
981 "Activate `smerge-mode' if there is a conflict."
982 (when (and buffer-file-name
983 ;; FIXME
984 ;; 1) the net result is to call git twice per file.
985 ;; 2) v-g-c-f is documented to take a directory.
986 ;; https://lists.gnu.org/r/emacs-devel/2014-01/msg01126.html
987 (vc-git-conflicted-files buffer-file-name)
988 (save-excursion
989 (goto-char (point-min))
990 (re-search-forward "^<<<<<<< " nil 'noerror)))
991 (vc-file-setprop buffer-file-name 'vc-state 'conflict)
992 (smerge-start-session)
993 (when vc-git-resolve-conflicts
994 (add-hook 'after-save-hook 'vc-git-resolve-when-done nil 'local))
995 (vc-message-unresolved-conflicts buffer-file-name)))
997 ;;; HISTORY FUNCTIONS
999 (autoload 'vc-setup-buffer "vc-dispatcher")
1001 (defcustom vc-git-print-log-follow nil
1002 "If true, follow renames in Git logs for files."
1003 :type 'boolean
1004 :version "26.1")
1006 (defun vc-git-print-log (files buffer &optional shortlog start-revision limit)
1007 "Print commit log associated with FILES into specified BUFFER.
1008 If SHORTLOG is non-nil, use a short format based on `vc-git-root-log-format'.
1009 \(This requires at least Git version 1.5.6, for the --graph option.)
1010 If START-REVISION is non-nil, it is the newest revision to show.
1011 If LIMIT is non-nil, show no more than this many entries."
1012 (let ((coding-system-for-read
1013 (or coding-system-for-read vc-git-log-output-coding-system)))
1014 ;; `vc-do-command' creates the buffer, but we need it before running
1015 ;; the command.
1016 (vc-setup-buffer buffer)
1017 ;; If the buffer exists from a previous invocation it might be
1018 ;; read-only.
1019 (let ((inhibit-read-only t))
1020 (with-current-buffer
1021 buffer
1022 (apply 'vc-git-command buffer
1023 'async files
1024 (append
1025 '("log" "--no-color")
1026 (when (and vc-git-print-log-follow
1027 (not (cl-some #'file-directory-p files)))
1028 ;; "--follow" on directories is broken
1029 ;; https://debbugs.gnu.org/cgi/bugreport.cgi?bug=8756
1030 ;; https://debbugs.gnu.org/cgi/bugreport.cgi?bug=16422
1031 (list "--follow"))
1032 (when shortlog
1033 `("--graph" "--decorate" "--date=short"
1034 ,(format "--pretty=tformat:%s"
1035 (car vc-git-root-log-format))
1036 "--abbrev-commit"))
1037 (when limit (list "-n" (format "%s" limit)))
1038 (when start-revision (list start-revision))
1039 '("--")))))))
1041 (defun vc-git-log-outgoing (buffer remote-location)
1042 (interactive)
1043 (vc-setup-buffer buffer)
1044 (vc-git-command
1045 buffer 'async nil
1046 "log"
1047 "--no-color" "--graph" "--decorate" "--date=short"
1048 (format "--pretty=tformat:%s" (car vc-git-root-log-format))
1049 "--abbrev-commit"
1050 (concat (if (string= remote-location "")
1051 "@{upstream}"
1052 remote-location)
1053 "..HEAD")))
1055 (defun vc-git-log-incoming (buffer remote-location)
1056 (interactive)
1057 (vc-setup-buffer buffer)
1058 (vc-git-command nil 0 nil "fetch")
1059 (vc-git-command
1060 buffer 'async nil
1061 "log"
1062 "--no-color" "--graph" "--decorate" "--date=short"
1063 (format "--pretty=tformat:%s" (car vc-git-root-log-format))
1064 "--abbrev-commit"
1065 (concat "HEAD.." (if (string= remote-location "")
1066 "@{upstream}"
1067 remote-location))))
1069 (defvar log-view-message-re)
1070 (defvar log-view-file-re)
1071 (defvar log-view-font-lock-keywords)
1072 (defvar log-view-per-file-logs)
1073 (defvar log-view-expanded-log-entry-function)
1075 (define-derived-mode vc-git-log-view-mode log-view-mode "Git-Log-View"
1076 (require 'add-log) ;; We need the faces add-log.
1077 ;; Don't have file markers, so use impossible regexp.
1078 (set (make-local-variable 'log-view-file-re) "\\`a\\`")
1079 (set (make-local-variable 'log-view-per-file-logs) nil)
1080 (set (make-local-variable 'log-view-message-re)
1081 (if (not (eq vc-log-view-type 'long))
1082 (cadr vc-git-root-log-format)
1083 "^commit *\\([0-9a-z]+\\)"))
1084 ;; Allow expanding short log entries.
1085 (when (memq vc-log-view-type '(short log-outgoing log-incoming))
1086 (setq truncate-lines t)
1087 (set (make-local-variable 'log-view-expanded-log-entry-function)
1088 'vc-git-expanded-log-entry))
1089 (set (make-local-variable 'log-view-font-lock-keywords)
1090 (if (not (eq vc-log-view-type 'long))
1091 (list (cons (nth 1 vc-git-root-log-format)
1092 (nth 2 vc-git-root-log-format)))
1093 (append
1094 `((,log-view-message-re (1 'change-log-acknowledgment)))
1095 ;; Handle the case:
1096 ;; user: foo@bar
1097 '(("^Author:[ \t]+\\([A-Za-z0-9_.+-]+@[A-Za-z0-9_.-]+\\)"
1098 (1 'change-log-email))
1099 ;; Handle the case:
1100 ;; user: FirstName LastName <foo@bar>
1101 ("^Author:[ \t]+\\([^<(]+?\\)[ \t]*[(<]\\([A-Za-z0-9_.+-]+@[A-Za-z0-9_.-]+\\)[>)]"
1102 (1 'change-log-name)
1103 (2 'change-log-email))
1104 ("^ +\\(?:\\(?:[Aa]cked\\|[Ss]igned-[Oo]ff\\)-[Bb]y:\\)[ \t]+\\([A-Za-z0-9_.+-]+@[A-Za-z0-9_.-]+\\)"
1105 (1 'change-log-name))
1106 ("^ +\\(?:\\(?:[Aa]cked\\|[Ss]igned-[Oo]ff\\)-[Bb]y:\\)[ \t]+\\([^<(]+?\\)[ \t]*[(<]\\([A-Za-z0-9_.+-]+@[A-Za-z0-9_.-]+\\)[>)]"
1107 (1 'change-log-name)
1108 (2 'change-log-email))
1109 ("^Merge: \\([0-9a-z]+\\) \\([0-9a-z]+\\)"
1110 (1 'change-log-acknowledgment)
1111 (2 'change-log-acknowledgment))
1112 ("^Date: \\(.+\\)" (1 'change-log-date))
1113 ("^summary:[ \t]+\\(.+\\)" (1 'log-view-message)))))))
1116 (defun vc-git-show-log-entry (revision)
1117 "Move to the log entry for REVISION.
1118 REVISION may have the form BRANCH, BRANCH~N,
1119 or BRANCH^ (where \"^\" can be repeated)."
1120 (goto-char (point-min))
1121 (prog1
1122 (when revision
1123 (search-forward
1124 (format "\ncommit %s" revision) nil t
1125 (cond ((string-match "~\\([0-9]\\)\\'" revision)
1126 (1+ (string-to-number (match-string 1 revision))))
1127 ((string-match "\\^+\\'" revision)
1128 (1+ (length (match-string 0 revision))))
1129 (t nil))))
1130 (beginning-of-line)))
1132 (defun vc-git-expanded-log-entry (revision)
1133 (with-temp-buffer
1134 (apply 'vc-git-command t nil nil (list "log" revision "-1" "--"))
1135 (goto-char (point-min))
1136 (unless (eobp)
1137 ;; Indent the expanded log entry.
1138 (while (re-search-forward "^ " nil t)
1139 (replace-match "")
1140 (forward-line))
1141 (buffer-string))))
1143 (defun vc-git-region-history (file buffer lfrom lto)
1144 "Insert into BUFFER the history of FILE for lines LFROM to LTO.
1145 This requires git 1.8.4 or later, for the \"-L\" option of \"git log\"."
1146 ;; The "git log" command below interprets the line numbers as applying
1147 ;; to the HEAD version of the file, not to the current state of the file.
1148 ;; So we need to look at all the local changes and adjust lfrom/lto
1149 ;; accordingly.
1150 ;; FIXME: Maybe this should be done in vc.el (i.e. for all backends), but
1151 ;; since Git is the only backend to support this operation so far, it's hard
1152 ;; to tell.
1153 (with-temp-buffer
1154 (vc-call-backend 'git 'diff file "HEAD" nil (current-buffer))
1155 (goto-char (point-min))
1156 (let ((last-offset 0)
1157 (from-offset nil)
1158 (to-offset nil))
1159 (while (re-search-forward
1160 "^@@ -\\([0-9]+\\),\\([0-9]+\\) \\+\\([0-9]+\\),\\([0-9]+\\) @@" nil t)
1161 (let ((headno (string-to-number (match-string 1)))
1162 (headcnt (string-to-number (match-string 2)))
1163 (curno (string-to-number (match-string 3)))
1164 (curcnt (string-to-number (match-string 4))))
1165 (cl-assert (equal (- curno headno) last-offset))
1166 (and (null from-offset) (> curno lfrom)
1167 (setq from-offset last-offset))
1168 (and (null to-offset) (> curno lto)
1169 (setq to-offset last-offset))
1170 (setq last-offset
1171 (- (+ curno curcnt) (+ headno headcnt)))))
1172 (setq lto (- lto (or to-offset last-offset)))
1173 (setq lfrom (- lfrom (or to-offset last-offset)))))
1174 (vc-git-command buffer 'async nil "log" "-p" ;"--follow" ;FIXME: not supported?
1175 (format "-L%d,%d:%s" lfrom lto (file-relative-name file))))
1177 (require 'diff-mode)
1179 (defvar vc-git-region-history-mode-map
1180 (let ((map (make-composed-keymap
1181 nil (make-composed-keymap
1182 (list diff-mode-map vc-git-log-view-mode-map)))))
1183 map))
1185 (defvar vc-git--log-view-long-font-lock-keywords nil)
1186 (defvar font-lock-keywords)
1187 (defvar vc-git-region-history-font-lock-keywords
1188 `((vc-git-region-history-font-lock)))
1190 (defun vc-git-region-history-font-lock (limit)
1191 (let ((in-diff (save-excursion
1192 (beginning-of-line)
1193 (or (looking-at "^\\(?:diff\\|commit\\)\\>")
1194 (re-search-backward "^\\(?:diff\\|commit\\)\\>" nil t))
1195 (eq ?d (char-after (match-beginning 0))))))
1196 (while
1197 (let ((end (save-excursion
1198 (if (re-search-forward "\n\\(diff\\|commit\\)\\>"
1199 limit t)
1200 (match-beginning 1)
1201 limit))))
1202 (let ((font-lock-keywords (if in-diff diff-font-lock-keywords
1203 vc-git--log-view-long-font-lock-keywords)))
1204 (font-lock-fontify-keywords-region (point) end))
1205 (goto-char end)
1206 (prog1 (< (point) limit)
1207 (setq in-diff (eq ?d (char-after))))))
1208 nil))
1210 (define-derived-mode vc-git-region-history-mode
1211 vc-git-log-view-mode "Git-Region-History"
1212 "Major mode to browse Git's \"log -p\" output."
1213 (setq-local vc-git--log-view-long-font-lock-keywords
1214 log-view-font-lock-keywords)
1215 (setq-local font-lock-defaults
1216 (cons 'vc-git-region-history-font-lock-keywords
1217 (cdr font-lock-defaults))))
1219 (defun vc-git--asciify-coding-system ()
1220 ;; Try to reconcile the content encoding with the encoding of Git's
1221 ;; auxiliary output (which is ASCII or ASCII-compatible), bug#23595.
1222 (unless (let ((samp "Binary files differ"))
1223 (string-equal samp (decode-coding-string
1224 samp coding-system-for-read t)))
1225 (setq coding-system-for-read 'undecided)))
1227 (autoload 'vc-switches "vc")
1229 (defun vc-git-diff (files &optional rev1 rev2 buffer _async)
1230 "Get a difference report using Git between two revisions of FILES."
1231 (let (process-file-side-effects
1232 (command "diff-tree"))
1233 (vc-git--asciify-coding-system)
1234 (if rev2
1235 ;; Diffing against the empty tree.
1236 (unless rev1 (setq rev1 "4b825dc642cb6eb9a060e54bf8d69288fbee4904"))
1237 (setq command "diff-index")
1238 (unless rev1 (setq rev1 "HEAD")))
1239 (if vc-git-diff-switches
1240 (apply #'vc-git-command (or buffer "*vc-diff*")
1241 1 ; bug#21969
1242 files
1243 command
1244 "--exit-code"
1245 (append (vc-switches 'git 'diff)
1246 (list "-p" (or rev1 "HEAD") rev2 "--")))
1247 (vc-git-command (or buffer "*vc-diff*") 1 files
1248 "difftool" "--exit-code" "--no-prompt" "-x"
1249 (concat "diff "
1250 (mapconcat 'identity
1251 (vc-switches nil 'diff) " "))
1252 rev1 rev2 "--"))))
1254 (defun vc-git-revision-table (_files)
1255 ;; What about `files'?!? --Stef
1256 (let (process-file-side-effects
1257 (table (list "HEAD")))
1258 (with-temp-buffer
1259 (vc-git-command t nil nil "for-each-ref" "--format=%(refname)")
1260 (goto-char (point-min))
1261 (while (re-search-forward "^refs/\\(heads\\|tags\\|remotes\\)/\\(.*\\)$"
1262 nil t)
1263 (push (match-string 2) table)))
1264 table))
1266 (defun vc-git-revision-completion-table (files)
1267 (letrec ((table (lazy-completion-table
1268 table (lambda () (vc-git-revision-table files)))))
1269 table))
1271 (defun vc-git-annotate-command (file buf &optional rev)
1272 (vc-git--asciify-coding-system)
1273 (let ((name (file-relative-name file)))
1274 (apply #'vc-git-command buf 'async nil "blame" "--date=short"
1275 (append (vc-switches 'git 'annotate)
1276 (list rev "--" name)))))
1278 (declare-function vc-annotate-convert-time "vc-annotate" (&optional time))
1280 (defun vc-git-annotate-time ()
1281 (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)
1282 (vc-annotate-convert-time
1283 (apply #'encode-time (mapcar (lambda (match)
1284 (if (match-beginning match)
1285 (string-to-number (match-string match))
1287 '(6 5 4 3 2 1 7))))))
1289 (defun vc-git-annotate-extract-revision-at-line ()
1290 (save-excursion
1291 (beginning-of-line)
1292 (when (looking-at "\\^?\\([0-9a-f]+\\) \\(\\([^(]+\\) \\)?")
1293 (let ((revision (match-string-no-properties 1)))
1294 (if (match-beginning 2)
1295 (let ((fname (match-string-no-properties 3)))
1296 ;; Remove trailing whitespace from the file name.
1297 (when (string-match " +\\'" fname)
1298 (setq fname (substring fname 0 (match-beginning 0))))
1299 (cons revision
1300 (expand-file-name fname (vc-git-root default-directory))))
1301 revision)))))
1303 ;;; TAG SYSTEM
1305 (defun vc-git-create-tag (dir name branchp)
1306 (let ((default-directory dir))
1307 (and (vc-git-command nil 0 nil "update-index" "--refresh")
1308 (if branchp
1309 (vc-git-command nil 0 nil "checkout" "-b" name)
1310 (vc-git-command nil 0 nil "tag" name)))))
1312 (defun vc-git-retrieve-tag (dir name _update)
1313 (let ((default-directory dir))
1314 (vc-git-command nil 0 nil "checkout" name)))
1317 ;;; MISCELLANEOUS
1319 (defun vc-git-previous-revision (file rev)
1320 "Git-specific version of `vc-previous-revision'."
1321 (if file
1322 (let* ((fname (file-relative-name file))
1323 (prev-rev (with-temp-buffer
1324 (and
1325 (vc-git--out-ok "rev-list" "-2" rev "--" fname)
1326 (goto-char (point-max))
1327 (bolp)
1328 (zerop (forward-line -1))
1329 (not (bobp))
1330 (buffer-substring-no-properties
1331 (point)
1332 (1- (point-max)))))))
1333 (or (vc-git-symbolic-commit prev-rev) prev-rev))
1334 ;; We used to use "^" here, but that fails on MS-Windows if git is
1335 ;; invoked via a batch file, in which case cmd.exe strips the "^"
1336 ;; because it is a special character for cmd which process-file
1337 ;; does not (and cannot) quote.
1338 (vc-git--rev-parse (concat rev "~1"))))
1340 (defun vc-git--rev-parse (rev)
1341 (with-temp-buffer
1342 (and
1343 (vc-git--out-ok "rev-parse" rev)
1344 (buffer-substring-no-properties (point-min) (+ (point-min) 40)))))
1346 (defun vc-git-next-revision (file rev)
1347 "Git-specific version of `vc-next-revision'."
1348 (let* ((default-directory (vc-git-root file))
1349 (file (file-relative-name file))
1350 (current-rev
1351 (with-temp-buffer
1352 (and
1353 (vc-git--out-ok "rev-list" "-1" rev "--" file)
1354 (goto-char (point-max))
1355 (bolp)
1356 (zerop (forward-line -1))
1357 (bobp)
1358 (buffer-substring-no-properties
1359 (point)
1360 (1- (point-max))))))
1361 (next-rev
1362 (and current-rev
1363 (with-temp-buffer
1364 (and
1365 (vc-git--out-ok "rev-list" "HEAD" "--" file)
1366 (goto-char (point-min))
1367 (search-forward current-rev nil t)
1368 (zerop (forward-line -1))
1369 (buffer-substring-no-properties
1370 (point)
1371 (progn (forward-line 1) (1- (point)))))))))
1372 (or (vc-git-symbolic-commit next-rev) next-rev)))
1374 (defun vc-git-delete-file (file)
1375 (vc-git-command nil 0 file "rm" "-f" "--"))
1377 (defun vc-git-rename-file (old new)
1378 (vc-git-command nil 0 (list old new) "mv" "-f" "--"))
1380 (defvar vc-git-extra-menu-map
1381 (let ((map (make-sparse-keymap)))
1382 (define-key map [git-grep]
1383 '(menu-item "Git grep..." vc-git-grep
1384 :help "Run the `git grep' command"))
1385 (define-key map [git-sn]
1386 '(menu-item "Stash a Snapshot" vc-git-stash-snapshot
1387 :help "Stash the current state of the tree and keep the current state"))
1388 (define-key map [git-st]
1389 '(menu-item "Create Stash..." vc-git-stash
1390 :help "Stash away changes"))
1391 (define-key map [git-ss]
1392 '(menu-item "Show Stash..." vc-git-stash-show
1393 :help "Show stash contents"))
1394 map))
1396 (defun vc-git-extra-menu () vc-git-extra-menu-map)
1398 (defun vc-git-extra-status-menu () vc-git-extra-menu-map)
1400 (defun vc-git-root (file)
1401 (or (vc-file-getprop file 'git-root)
1402 (vc-file-setprop file 'git-root (vc-find-root file ".git"))))
1404 ;; grep-compute-defaults autoloads grep.
1405 (declare-function grep-read-regexp "grep" ())
1406 (declare-function grep-read-files "grep" (regexp))
1407 (declare-function grep-expand-template "grep"
1408 (template &optional regexp files dir excl))
1410 ;; Derived from `lgrep'.
1411 (defun vc-git-grep (regexp &optional files dir)
1412 "Run git grep, searching for REGEXP in FILES in directory DIR.
1413 The search is limited to file names matching shell pattern FILES.
1414 FILES may use abbreviations defined in `grep-files-aliases', e.g.
1415 entering `ch' is equivalent to `*.[ch]'. As whitespace triggers
1416 completion when entering a pattern, including it requires
1417 quoting, e.g. `\\[quoted-insert]<space>'.
1419 With \\[universal-argument] prefix, you can edit the constructed shell command line
1420 before it is executed.
1421 With two \\[universal-argument] prefixes, directly edit and run `grep-command'.
1423 Collect output in a buffer. While git grep runs asynchronously, you
1424 can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
1425 in the grep output buffer,
1426 to go to the lines where grep found matches.
1428 This command shares argument histories with \\[rgrep] and \\[grep]."
1429 (interactive
1430 (progn
1431 (grep-compute-defaults)
1432 (cond
1433 ((equal current-prefix-arg '(16))
1434 (list (read-from-minibuffer "Run: " "git grep"
1435 nil nil 'grep-history)
1436 nil))
1437 (t (let* ((regexp (grep-read-regexp))
1438 (files
1439 (mapconcat #'shell-quote-argument
1440 (split-string (grep-read-files regexp)) " "))
1441 (dir (read-directory-name "In directory: "
1442 nil default-directory t)))
1443 (list regexp files dir))))))
1444 (require 'grep)
1445 (when (and (stringp regexp) (> (length regexp) 0))
1446 (let ((command regexp))
1447 (if (null files)
1448 (if (string= command "git grep")
1449 (setq command nil))
1450 (setq dir (file-name-as-directory (expand-file-name dir)))
1451 (setq command
1452 (grep-expand-template "git --no-pager grep -n -e <R> -- <F>"
1453 regexp files))
1454 (when command
1455 (if (equal current-prefix-arg '(4))
1456 (setq command
1457 (read-from-minibuffer "Confirm: "
1458 command nil nil 'grep-history))
1459 (add-to-history 'grep-history command))))
1460 (when command
1461 (let ((default-directory dir)
1462 (compilation-environment (cons "PAGER=" compilation-environment)))
1463 ;; Setting process-setup-function makes exit-message-function work
1464 ;; even when async processes aren't supported.
1465 (compilation-start command 'grep-mode))
1466 (if (eq next-error-last-buffer (current-buffer))
1467 (setq default-directory dir))))))
1469 (defun vc-git-stash (name)
1470 "Create a stash."
1471 (interactive "sStash name: ")
1472 (let ((root (vc-git-root default-directory)))
1473 (when root
1474 (vc-git--call nil "stash" "save" name)
1475 (vc-resynch-buffer root t t))))
1477 (defun vc-git-stash-show (name)
1478 "Show the contents of stash NAME."
1479 (interactive "sStash name: ")
1480 (vc-setup-buffer "*vc-git-stash*")
1481 (vc-git-command "*vc-git-stash*" 'async nil "stash" "show" "-p" name)
1482 (set-buffer "*vc-git-stash*")
1483 (diff-mode)
1484 (setq buffer-read-only t)
1485 (pop-to-buffer (current-buffer)))
1487 (defun vc-git-stash-apply (name)
1488 "Apply stash NAME."
1489 (interactive "sApply stash: ")
1490 (vc-git-command "*vc-git-stash*" 0 nil "stash" "apply" "-q" name)
1491 (vc-resynch-buffer (vc-git-root default-directory) t t))
1493 (defun vc-git-stash-pop (name)
1494 "Pop stash NAME."
1495 (interactive "sPop stash: ")
1496 (vc-git-command "*vc-git-stash*" 0 nil "stash" "pop" "-q" name)
1497 (vc-resynch-buffer (vc-git-root default-directory) t t))
1499 (defun vc-git-stash-snapshot ()
1500 "Create a stash with the current tree state."
1501 (interactive)
1502 (vc-git--call nil "stash" "save"
1503 (let ((ct (current-time)))
1504 (concat
1505 (format-time-string "Snapshot on %Y-%m-%d" ct)
1506 (format-time-string " at %H:%M" ct))))
1507 (vc-git-command "*vc-git-stash*" 0 nil "stash" "apply" "-q" "stash@{0}")
1508 (vc-resynch-buffer (vc-git-root default-directory) t t))
1510 (defun vc-git-stash-list ()
1511 (delete
1513 (split-string
1514 (replace-regexp-in-string
1515 "^stash@" " " (vc-git--run-command-string nil "stash" "list"))
1516 "\n")))
1518 (defun vc-git-stash-get-at-point (point)
1519 (save-excursion
1520 (goto-char point)
1521 (beginning-of-line)
1522 (if (looking-at "^ +\\({[0-9]+}\\):")
1523 (match-string 1)
1524 (error "Cannot find stash at point"))))
1526 ;; vc-git-stash-delete-at-point must be called from a vc-dir buffer.
1527 (declare-function vc-dir-refresh "vc-dir" ())
1529 (defun vc-git-stash-delete-at-point ()
1530 (interactive)
1531 (let ((stash (vc-git-stash-get-at-point (point))))
1532 (when (y-or-n-p (format "Remove stash %s ? " stash))
1533 (vc-git--run-command-string nil "stash" "drop" (format "stash@%s" stash))
1534 (vc-dir-refresh))))
1536 (defun vc-git-stash-show-at-point ()
1537 (interactive)
1538 (vc-git-stash-show (format "stash@%s" (vc-git-stash-get-at-point (point)))))
1540 (defun vc-git-stash-apply-at-point ()
1541 (interactive)
1542 (let (vc-dir-buffers) ; Small optimization.
1543 (vc-git-stash-apply (format "stash@%s" (vc-git-stash-get-at-point (point)))))
1544 (vc-dir-refresh))
1546 (defun vc-git-stash-pop-at-point ()
1547 (interactive)
1548 (let (vc-dir-buffers) ; Likewise.
1549 (vc-git-stash-pop (format "stash@%s" (vc-git-stash-get-at-point (point)))))
1550 (vc-dir-refresh))
1552 (defun vc-git-stash-menu (e)
1553 (interactive "e")
1554 (vc-dir-at-event e (popup-menu vc-git-stash-menu-map e)))
1557 ;;; Internal commands
1559 (defun vc-git-command (buffer okstatus file-or-list &rest flags)
1560 "A wrapper around `vc-do-command' for use in vc-git.el.
1561 The difference to vc-do-command is that this function always invokes
1562 `vc-git-program'."
1563 (let ((coding-system-for-read
1564 (or coding-system-for-read vc-git-log-output-coding-system))
1565 (coding-system-for-write
1566 (or coding-system-for-write vc-git-commits-coding-system))
1567 (process-environment (cons "GIT_DIR" process-environment)))
1568 (apply 'vc-do-command (or buffer "*vc*") okstatus vc-git-program
1569 ;; https://debbugs.gnu.org/16897
1570 (unless (and (not (cdr-safe file-or-list))
1571 (let ((file (or (car-safe file-or-list)
1572 file-or-list)))
1573 (and file
1574 (eq ?/ (aref file (1- (length file))))
1575 (equal file (vc-git-root file)))))
1576 file-or-list)
1577 (cons "--no-pager" flags))))
1579 (defun vc-git--empty-db-p ()
1580 "Check if the git db is empty (no commit done yet)."
1581 (let (process-file-side-effects)
1582 (not (eq 0 (vc-git--call nil "rev-parse" "--verify" "HEAD")))))
1584 (defun vc-git--call (buffer command &rest args)
1585 ;; We don't need to care the arguments. If there is a file name, it
1586 ;; is always a relative one. This works also for remote
1587 ;; directories. We enable `inhibit-null-byte-detection', otherwise
1588 ;; Tramp's eol conversion might be confused.
1589 (let ((inhibit-null-byte-detection t)
1590 (coding-system-for-read
1591 (or coding-system-for-read vc-git-log-output-coding-system))
1592 (coding-system-for-write
1593 (or coding-system-for-write vc-git-commits-coding-system))
1594 (process-environment (cons "PAGER=" process-environment)))
1595 (push "GIT_DIR" process-environment)
1596 (apply 'process-file vc-git-program nil buffer nil command args)))
1598 (defun vc-git--out-ok (command &rest args)
1599 (zerop (apply 'vc-git--call '(t nil) command args)))
1601 (defun vc-git--run-command-string (file &rest args)
1602 "Run a git command on FILE and return its output as string.
1603 FILE can be nil."
1604 (let* ((ok t)
1605 (str (with-output-to-string
1606 (with-current-buffer standard-output
1607 (unless (apply 'vc-git--out-ok
1608 (if file
1609 (append args (list (file-relative-name
1610 file)))
1611 args))
1612 (setq ok nil))))))
1613 (and ok str)))
1615 (defun vc-git-symbolic-commit (commit)
1616 "Translate COMMIT string into symbolic form.
1617 Returns nil if not possible."
1618 (and commit
1619 (let ((name (with-temp-buffer
1620 (and
1621 (vc-git--out-ok "name-rev" "--name-only" commit)
1622 (goto-char (point-min))
1623 (= (forward-line 2) 1)
1624 (bolp)
1625 (buffer-substring-no-properties (point-min)
1626 (1- (point-max)))))))
1627 (and name (not (string= name "undefined")) name))))
1629 (provide 'vc-git)
1631 ;;; vc-git.el ends here