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