Allow 'browse-url-emacs' to fetch URL in the selected window
[emacs.git] / lisp / vc / vc-git.el
blob5456467815368a9c43048512a6e4aa68a59922d4
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))
107 (defgroup vc-git nil
108 "VC Git backend."
109 :version "24.1"
110 :group 'vc)
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))
119 :version "23.1")
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))
128 :version "25.1")
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
135 the staging area."
136 :type '(choice (const :tag "Don't resolve" nil)
137 (const :tag "Resolve" t)
138 (const :tag "Resolve and maybe unstage all files"
139 unstage-maybe))
140 :version "25.1")
142 (defcustom vc-git-program "git"
143 "Name of the Git executable (excluding any arguments)."
144 :version "24.1"
145 :type 'string)
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)
156 (3 'change-log-name)
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))
165 :version "24.1")
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")
173 :version "25.1")
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")
180 :version "25.1")
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)))
206 (when dir
207 (with-temp-buffer
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
211 ;; path specs.
212 ;; See also: http://marc.info/?l=git&m=125787684318129&w=2
213 (name (file-relative-name file dir))
214 (str (ignore-errors
215 (cd dir)
216 (vc-git--out-ok "ls-files" "-c" "-z" "--" name)
217 ;; If result is empty, use ls-tree to check for deleted
218 ;; file.
219 (when (eq (point-min) (point-max))
220 (vc-git--out-ok "ls-tree" "--name-only" "-z" "HEAD"
221 "--" name))
222 (buffer-string))))
223 (and str
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)
231 (?M 'edited)
232 (?A 'added)
233 (?D 'removed)
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.
247 (string-match
248 "git version \\([0-9.]+\\)\\(\.windows.[0-9]+\\)?$"
249 version-string))
250 (match-string 1 version-string)
251 "0")))))
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.
262 (pcase code-list
263 ('nil 'up-to-date)
264 (`(,code)
265 (pcase code
266 ("!!" 'ignored)
267 ("??" 'unregistered)
268 ;; I have only seen this with a file that is only present in the
269 ;; index. Let us call this `removed'.
270 ("AD" 'removed)
271 (_ (cond
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)
276 (t 'edited)))))
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'.
286 (_ '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).
296 (let* ((args
297 `("status" "--porcelain" "-z"
298 ;; Just to be explicit, it's the default anyway.
299 "--untracked-files"
300 ,@(when (version<= "1.7.6.3" (vc-git--program-version))
301 '("--ignored"))
302 "--"))
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.
307 (if (null status)
308 ;; If status is nil, there was an error calling git, likely because
309 ;; the file is not in a git repo.
310 'unregistered
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
315 (mapcar (lambda (s)
316 (substring s 0 2))
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
330 (if str
331 (if (string-match "^\\(refs/heads/\\)?\\(.+\\)$" str)
332 (match-string 2 str)
333 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)
344 'face face
345 'help-echo (concat help-echo "\nCurrent revision: " rev))))
347 (cl-defstruct (vc-git-extra-fileinfo
348 (:copier nil)
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)
359 (concat "\""
360 (mapconcat (lambda (c)
361 (pcase c
362 (?\n "\\n")
363 (?\t "\\t")
364 (?\\ "\\\\")
365 (?\" "\\\"")
366 (_ (char-to-string c))))
367 name "")
368 "\"")
369 name))
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))
375 (str (pcase new-type
376 (?\100 ;; File.
377 (pcase old-type
378 (?\100 nil)
379 (?\120 " (type change symlink -> file)")
380 (?\160 " (type change subproject -> file)")))
381 (?\120 ;; Symlink.
382 (pcase old-type
383 (?\100 " (type change file -> symlink)")
384 (?\160 " (type change subproject -> symlink)")
385 (_ " (symlink)")))
386 (?\160 ;; Subproject.
387 (pcase old-type
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.
393 (pcase old-type
394 (?\120 " (symlink)")
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) "/")
399 (t ""))))
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))))
406 (if rename-state
407 (propertize
408 (concat " ("
409 (if (eq rename-state 'copy) "copied from "
410 (if (eq state 'added) "renamed from "
411 "renamed to "))
412 (vc-git-escape-file-name
413 (vc-git-extra-fileinfo->orig-name extra))
414 ")")
415 'face 'font-lock-comment-face)
416 "")))
418 (defun vc-git-permissions-as-string (old-perm new-perm)
419 "Format a permission change as string."
420 (propertize
421 (if (or (not old-perm)
422 (not new-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))))
435 (insert
437 (propertize (format "%c" (if (vc-dir-fileinfo->marked info) ?* ? ))
438 'face 'font-lock-type-face)
440 (propertize
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)
451 'help-echo
452 (if isdir
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
461 (:copier nil)
462 (:conc-name vc-git-dir-status-state->))
463 ;; Current stage.
464 stage
465 ;; List of files still to be processed.
466 files
467 ;; Update function to be called at the end.
468 update-function
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."
480 (let (next-stage
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)
484 (`update-index
485 (setq next-stage (if (vc-git--empty-db-p) 'ls-files-added 'diff-index)))
486 (`ls-files-added
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")
502 'up-to-date
503 'conflict)
504 (vc-git-create-extra-fileinfo perm perm)))))
505 (`ls-files-conflict
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)))))
514 (`ls-files-unknown
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))))
519 (`ls-files-ignored
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))))
523 (`diff-index
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"
527 nil t 1)
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
538 'copy name))
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
545 'rename name)))
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)
554 (if next-stage
555 (vc-git-dir-status-goto-stage git-state)
556 (funcall (vc-git-dir-status-state->update-function git-state)
557 (let ((result nil))
558 (maphash (lambda (key value)
559 (push (cons key value) result))
560 (vc-git-dir-status-state->hash git-state))
561 result)
562 nil))))
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)))
572 (erase-buffer)
573 (pcase (vc-git-dir-status-state->stage git-state)
574 (`update-index
575 (if files
576 (vc-git-command (current-buffer) 'async files "add" "--refresh" "--")
577 (vc-git-command (current-buffer) 'async nil
578 "update-index" "--refresh")))
579 (`ls-files-added
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" "--"))
585 (`ls-files-conflict
586 (vc-git-command (current-buffer) 'async files
587 "ls-files" "-z" "-c" "-s" "--"))
588 (`ls-files-unknown
589 (vc-git-command (current-buffer) 'async files
590 "ls-files" "-z" "-o" "--directory"
591 "--no-empty-directory" "--exclude-standard" "--"))
592 (`ls-files-ignored
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.
597 (`diff-index
598 (vc-git-command (current-buffer) 'async files
599 "diff-index" "--relative" "-z" "-M" "HEAD" "--")))
600 (vc-run-delayed
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
610 :files files
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)
625 map))
627 (defvar vc-git-stash-menu-map
628 (let ((map (make-sparse-keymap "Git Stash")))
629 (define-key map [de]
630 '(menu-item "Delete Stash" vc-git-stash-delete-at-point
631 :help "Delete the current stash"))
632 (define-key map [ap]
633 '(menu-item "Apply Stash" vc-git-stash-apply-at-point
634 :help "Apply the current stash and keep it in the stash list"))
635 (define-key map [po]
636 '(menu-item "Apply and Remove Stash (Pop)" vc-git-stash-pop-at-point
637 :help "Apply the current stash and remove it"))
638 (define-key map [sh]
639 '(menu-item "Show Stash" vc-git-stash-show-at-point
640 :help "Show the contents of the current stash"))
641 map))
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)
651 (progn
652 (setq branch (match-string 2 str))
653 (setq remote
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)))
660 (when remote
661 (setq remote-url
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.
670 (concat
671 (propertize "Branch : " 'face 'font-lock-type-face)
672 (propertize branch
673 'face 'font-lock-variable-name-face)
674 (when remote
675 (concat
676 "\n"
677 (propertize "Remote : " 'face 'font-lock-type-face)
678 (propertize remote-url
679 'face 'font-lock-variable-name-face)))
680 "\n"
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))
686 (if stash
687 (concat
688 (propertize "Stash :\n" 'face 'font-lock-type-face
689 'help-echo stash-help-echo)
690 (mapconcat
691 (lambda (x)
692 (propertize x
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))
697 stash "\n"))
698 (concat
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."
708 (with-temp-buffer
709 (vc-git--call t "branch")
710 (goto-char (point-min))
711 (let (current-branch branches)
712 (while (not (eobp))
713 (when (looking-at "^\\([ *]\\) \\(.+\\)$")
714 (if (string-equal (match-string 1) "*")
715 (setq current-branch (match-string 2))
716 (push (match-string 2) branches)))
717 (forward-line 1))
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."
728 (let (flist dlist)
729 (dolist (crt files)
730 (if (file-directory-p crt)
731 (push crt dlist)
732 (push crt flist)))
733 (when flist
734 (vc-git-command nil 0 flist "update-index" "--add" "--"))
735 (when dlist
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
750 the commit message."
751 (interactive)
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."
757 (interactive)
758 (when (log-edit-toggle-header "Amend" "yes")
759 (goto-char (point-max))
760 (unless (bolp) (insert "\n"))
761 (insert (with-output-to-string
762 (vc-git-command
763 standard-output 1 nil
764 "log" "--max-count=1" "--pretty=format:%B" "HEAD")))
765 (save-excursion
766 (rfc822-goto-eoh)
767 (forward-line 1)
768 (let ((pt (point)))
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)
780 map))
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)
797 locale-coding-system
798 (or coding-system-for-write vc-git-commits-coding-system)))
799 (msg-file
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
809 (argument)
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"))
817 (let ((args
818 (log-edit-extract-headers
819 `(("Author" . "--author")
820 ("Date" . "--date")
821 ("Amend" . ,(boolean-arg-fn "--amend"))
822 ("Sign-Off" . ,(boolean-arg-fn "--signoff")))
823 comment)))
824 (when msg-file
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)))
829 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)
837 (fullname
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.
842 (if (string= fn "")
843 (file-relative-name file (vc-git-root default-directory))
844 (substring fn 0 -1)))))
845 (vc-git-command
846 buffer 0
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"
853 (vc-git-root file)))
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."
860 (if contents-done
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)
880 args)
881 ;; If necessary, prompt for the exact command.
882 ;; TODO if pushing, prompt if no default push location - cf bzr.
883 (when prompt
884 (setq args (split-string
885 (read-shell-command
886 (format "Git %s command: " command)
887 (format "%s %s" git-program command)
888 'vc-git-history)
889 " " t))
890 (setq git-program (car args)
891 command (cadr args)
892 args (cddr 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
897 (vc-run-delayed
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)
909 nil))))
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)))
930 (merge-source
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"
935 root))))
936 branches
937 (cons "FETCH_HEAD" branches))
938 nil t)))
939 (apply 'vc-do-async-command buffer root vc-git-program "merge"
940 (list merge-source))
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."
946 (let* ((status
947 (vc-git--run-command-string directory "status" "--porcelain" "--"))
948 (lines (when status (split-string status "\n" 'omit-nulls)))
949 files)
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?!]\\) \\(.+\\)\\(?: -> \\(.+\\)\\)?"
955 line)
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"
960 "DU" "AA" "UU"))
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."
969 (save-excursion
970 (goto-char (point-min))
971 (unless (re-search-forward "^<<<<<<< " nil t)
972 (vc-git-command nil 0 buffer-file-name "add")
973 (unless (or
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
987 ;; FIXME
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)
992 (save-excursion
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."
1007 :type 'boolean
1008 :version "26.1")
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
1019 ;; the command.
1020 (vc-setup-buffer buffer)
1021 ;; If the buffer exists from a previous invocation it might be
1022 ;; read-only.
1023 (let ((inhibit-read-only t))
1024 (with-current-buffer
1025 buffer
1026 (apply 'vc-git-command buffer
1027 'async files
1028 (append
1029 '("log" "--no-color")
1030 (when (and vc-git-print-log-follow
1031 (null (cdr files))
1032 (car files)
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
1037 (list "--follow"))
1038 (when shortlog
1039 `("--graph" "--decorate" "--date=short"
1040 ,(format "--pretty=tformat:%s"
1041 (car vc-git-root-log-format))
1042 "--abbrev-commit"))
1043 (when limit (list "-n" (format "%s" limit)))
1044 (when start-revision (list start-revision))
1045 '("--")))))))
1047 (defun vc-git-log-outgoing (buffer remote-location)
1048 (interactive)
1049 (vc-setup-buffer buffer)
1050 (vc-git-command
1051 buffer 'async nil
1052 "log"
1053 "--no-color" "--graph" "--decorate" "--date=short"
1054 (format "--pretty=tformat:%s" (car vc-git-root-log-format))
1055 "--abbrev-commit"
1056 (concat (if (string= remote-location "")
1057 "@{upstream}"
1058 remote-location)
1059 "..HEAD")))
1061 (defun vc-git-log-incoming (buffer remote-location)
1062 (interactive)
1063 (vc-setup-buffer buffer)
1064 (vc-git-command nil 0 nil "fetch")
1065 (vc-git-command
1066 buffer 'async nil
1067 "log"
1068 "--no-color" "--graph" "--decorate" "--date=short"
1069 (format "--pretty=tformat:%s" (car vc-git-root-log-format))
1070 "--abbrev-commit"
1071 (concat "HEAD.." (if (string= remote-location "")
1072 "@{upstream}"
1073 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)))
1099 (append
1100 `((,log-view-message-re (1 'change-log-acknowledgment)))
1101 ;; Handle the case:
1102 ;; user: foo@bar
1103 '(("^Author:[ \t]+\\([A-Za-z0-9_.+-]+@[A-Za-z0-9_.-]+\\)"
1104 (1 'change-log-email))
1105 ;; Handle the case:
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))
1127 (prog1
1128 (when revision
1129 (search-forward
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))))
1135 (t nil))))
1136 (beginning-of-line)))
1138 (defun vc-git-expanded-log-entry (revision)
1139 (with-temp-buffer
1140 (apply 'vc-git-command t nil nil (list "log" revision "-1" "--"))
1141 (goto-char (point-min))
1142 (unless (eobp)
1143 ;; Indent the expanded log entry.
1144 (while (re-search-forward "^ " nil t)
1145 (replace-match "")
1146 (forward-line))
1147 (buffer-string))))
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
1155 ;; accordingly.
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
1158 ;; to tell.
1159 (with-temp-buffer
1160 (vc-call-backend 'git 'diff file "HEAD" nil (current-buffer))
1161 (goto-char (point-min))
1162 (let ((last-offset 0)
1163 (from-offset nil)
1164 (to-offset nil))
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))
1176 (setq 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)))))
1189 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
1198 (beginning-of-line)
1199 (or (looking-at "^\\(?:diff\\|commit\\)\\>")
1200 (re-search-backward "^\\(?:diff\\|commit\\)\\>" nil t))
1201 (eq ?d (char-after (match-beginning 0))))))
1202 (while
1203 (let ((end (save-excursion
1204 (if (re-search-forward "\n\\(diff\\|commit\\)\\>"
1205 limit t)
1206 (match-beginning 1)
1207 limit))))
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))
1211 (goto-char end)
1212 (prog1 (< (point) limit)
1213 (setq in-diff (eq ?d (char-after))))))
1214 nil))
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)
1240 (if rev2
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*")
1247 1 ; bug#21969
1248 files
1249 command
1250 "--exit-code"
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"
1255 (concat "diff "
1256 (mapconcat 'identity
1257 (vc-switches nil 'diff) " "))
1258 rev1 rev2 "--"))))
1260 (defun vc-git-revision-table (_files)
1261 ;; What about `files'?!? --Stef
1262 (let (process-file-side-effects
1263 (table (list "HEAD")))
1264 (with-temp-buffer
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\\)/\\(.*\\)$"
1268 nil t)
1269 (push (match-string 2) table)))
1270 table))
1272 (defun vc-git-revision-completion-table (files)
1273 (letrec ((table (lazy-completion-table
1274 table (lambda () (vc-git-revision-table files)))))
1275 table))
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 ()
1296 (save-excursion
1297 (beginning-of-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))))
1305 (cons revision
1306 (expand-file-name fname (vc-git-root default-directory))))
1307 revision)))))
1309 ;;; TAG SYSTEM
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")
1314 (if branchp
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)))
1323 ;;; MISCELLANEOUS
1325 (defun vc-git-previous-revision (file rev)
1326 "Git-specific version of `vc-previous-revision'."
1327 (if file
1328 (let* ((fname (file-relative-name file))
1329 (prev-rev (with-temp-buffer
1330 (and
1331 (vc-git--out-ok "rev-list" "-2" rev "--" fname)
1332 (goto-char (point-max))
1333 (bolp)
1334 (zerop (forward-line -1))
1335 (not (bobp))
1336 (buffer-substring-no-properties
1337 (point)
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)
1347 (with-temp-buffer
1348 (and
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))
1356 (current-rev
1357 (with-temp-buffer
1358 (and
1359 (vc-git--out-ok "rev-list" "-1" rev "--" file)
1360 (goto-char (point-max))
1361 (bolp)
1362 (zerop (forward-line -1))
1363 (bobp)
1364 (buffer-substring-no-properties
1365 (point)
1366 (1- (point-max))))))
1367 (next-rev
1368 (and current-rev
1369 (with-temp-buffer
1370 (and
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
1376 (point)
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"))
1400 map))
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]."
1436 (interactive
1437 (progn
1438 (grep-compute-defaults)
1439 (cond
1440 ((equal current-prefix-arg '(16))
1441 (list (read-from-minibuffer "Run: " "git grep"
1442 nil nil 'grep-history)
1443 nil))
1444 (t (let* ((regexp (grep-read-regexp))
1445 (files
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))))))
1451 (require 'grep)
1452 (when (and (stringp regexp) (> (length regexp) 0))
1453 (let ((command regexp))
1454 (if (null files)
1455 (if (string= command "git grep")
1456 (setq command nil))
1457 (setq dir (file-name-as-directory (expand-file-name dir)))
1458 (setq command
1459 (grep-expand-template "git --no-pager grep -n -e <R> -- <F>"
1460 regexp files))
1461 (when command
1462 (if (equal current-prefix-arg '(4))
1463 (setq command
1464 (read-from-minibuffer "Confirm: "
1465 command nil nil 'grep-history))
1466 (add-to-history 'grep-history command))))
1467 (when 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)
1477 "Create a stash."
1478 (interactive "sStash name: ")
1479 (let ((root (vc-git-root default-directory)))
1480 (when root
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*")
1490 (diff-mode)
1491 (setq buffer-read-only t)
1492 (pop-to-buffer (current-buffer)))
1494 (defun vc-git-stash-apply (name)
1495 "Apply stash 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)
1501 "Pop stash 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."
1508 (interactive)
1509 (vc-git--call nil "stash" "save"
1510 (let ((ct (current-time)))
1511 (concat
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 ()
1518 (delete
1520 (split-string
1521 (replace-regexp-in-string
1522 "^stash@" " " (vc-git--run-command-string nil "stash" "list"))
1523 "\n")))
1525 (defun vc-git-stash-get-at-point (point)
1526 (save-excursion
1527 (goto-char point)
1528 (beginning-of-line)
1529 (if (looking-at "^ +\\({[0-9]+}\\):")
1530 (match-string 1)
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 ()
1537 (interactive)
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))
1541 (vc-dir-refresh))))
1543 (defun vc-git-stash-show-at-point ()
1544 (interactive)
1545 (vc-git-stash-show (format "stash@%s" (vc-git-stash-get-at-point (point)))))
1547 (defun vc-git-stash-apply-at-point ()
1548 (interactive)
1549 (let (vc-dir-buffers) ; Small optimization.
1550 (vc-git-stash-apply (format "stash@%s" (vc-git-stash-get-at-point (point)))))
1551 (vc-dir-refresh))
1553 (defun vc-git-stash-pop-at-point ()
1554 (interactive)
1555 (let (vc-dir-buffers) ; Likewise.
1556 (vc-git-stash-pop (format "stash@%s" (vc-git-stash-get-at-point (point)))))
1557 (vc-dir-refresh))
1559 (defun vc-git-stash-menu (e)
1560 (interactive "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
1569 `vc-git-program'."
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
1575 (append
1576 `("GIT_DIR"
1577 ;; Avoid repository locking during background operations
1578 ;; (bug#21559).
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)
1586 file-or-list)))
1587 (and file
1588 (eq ?/ (aref file (1- (length file))))
1589 (equal file (vc-git-root file)))))
1590 file-or-list)
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.
1617 FILE can be nil."
1618 (let* ((ok t)
1619 (str (with-output-to-string
1620 (with-current-buffer standard-output
1621 (unless (apply 'vc-git--out-ok
1622 (if file
1623 (append args (list (file-relative-name
1624 file)))
1625 args))
1626 (setq ok nil))))))
1627 (and ok str)))
1629 (defun vc-git-symbolic-commit (commit)
1630 "Translate COMMIT string into symbolic form.
1631 Returns nil if not possible."
1632 (and commit
1633 (let ((name (with-temp-buffer
1634 (and
1635 (vc-git--out-ok "name-rev" "--name-only" commit)
1636 (goto-char (point-min))
1637 (= (forward-line 2) 1)
1638 (bolp)
1639 (buffer-substring-no-properties (point-min)
1640 (1- (point-max)))))))
1641 (and name (not (string= name "undefined")) name))))
1643 (provide 'vc-git)
1645 ;;; vc-git.el ends here