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