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