vc-git.el 56 KB

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