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