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