PageRenderTime 73ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/vendor/git.el

http://github.com/gregnewman/20seven-emacs
Emacs Lisp | 1588 lines | 1361 code | 151 blank | 76 comment | 36 complexity | bcedf92e7e2436d6c478b133fb1daf82 MD5 | raw file
Possible License(s): GPL-2.0
  1. ;;; git.el --- A user interface for git
  2. ;; Copyright (C) 2005, 2006, 2007 Alexandre Julliard <julliard@winehq.org>
  3. ;; Version: 1.0
  4. ;; This program is free software; you can redistribute it and/or
  5. ;; modify it under the terms of the GNU General Public License as
  6. ;; published by the Free Software Foundation; either version 2 of
  7. ;; the License, or (at your option) any later version.
  8. ;;
  9. ;; This program is distributed in the hope that it will be
  10. ;; useful, but WITHOUT ANY WARRANTY; without even the implied
  11. ;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  12. ;; PURPOSE. See the GNU General Public License for more details.
  13. ;;
  14. ;; You should have received a copy of the GNU General Public
  15. ;; License along with this program; if not, write to the Free
  16. ;; Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
  17. ;; MA 02111-1307 USA
  18. ;;; Commentary:
  19. ;; This file contains an interface for the git version control
  20. ;; system. It provides easy access to the most frequently used git
  21. ;; commands. The user interface is as far as possible identical to
  22. ;; that of the PCL-CVS mode.
  23. ;;
  24. ;; To install: put this file on the load-path and place the following
  25. ;; in your .emacs file:
  26. ;;
  27. ;; (require 'git)
  28. ;;
  29. ;; To start: `M-x git-status'
  30. ;;
  31. ;; TODO
  32. ;; - portability to XEmacs
  33. ;; - diff against other branch
  34. ;; - renaming files from the status buffer
  35. ;; - creating tags
  36. ;; - fetch/pull
  37. ;; - switching branches
  38. ;; - revlist browser
  39. ;; - git-show-branch browser
  40. ;; - menus
  41. ;;
  42. (eval-when-compile (require 'cl))
  43. (require 'ewoc)
  44. (require 'log-edit)
  45. (require 'easymenu)
  46. ;;;; Customizations
  47. ;;;; ------------------------------------------------------------
  48. (defgroup git nil
  49. "A user interface for the git versioning system."
  50. :group 'tools)
  51. (defcustom git-committer-name nil
  52. "User name to use for commits.
  53. The default is to fall back to the repository config,
  54. then to `add-log-full-name' and then to `user-full-name'."
  55. :group 'git
  56. :type '(choice (const :tag "Default" nil)
  57. (string :tag "Name")))
  58. (defcustom git-committer-email nil
  59. "Email address to use for commits.
  60. The default is to fall back to the git repository config,
  61. then to `add-log-mailing-address' and then to `user-mail-address'."
  62. :group 'git
  63. :type '(choice (const :tag "Default" nil)
  64. (string :tag "Email")))
  65. (defcustom git-commits-coding-system nil
  66. "Default coding system for the log message of git commits."
  67. :group 'git
  68. :type '(choice (const :tag "From repository config" nil)
  69. (coding-system)))
  70. (defcustom git-append-signed-off-by nil
  71. "Whether to append a Signed-off-by line to the commit message before editing."
  72. :group 'git
  73. :type 'boolean)
  74. (defcustom git-reuse-status-buffer t
  75. "Whether `git-status' should try to reuse an existing buffer
  76. if there is already one that displays the same directory."
  77. :group 'git
  78. :type 'boolean)
  79. (defcustom git-per-dir-ignore-file ".gitignore"
  80. "Name of the per-directory ignore file."
  81. :group 'git
  82. :type 'string)
  83. (defcustom git-show-uptodate nil
  84. "Whether to display up-to-date files."
  85. :group 'git
  86. :type 'boolean)
  87. (defcustom git-show-ignored nil
  88. "Whether to display ignored files."
  89. :group 'git
  90. :type 'boolean)
  91. (defcustom git-show-unknown t
  92. "Whether to display unknown files."
  93. :group 'git
  94. :type 'boolean)
  95. (defface git-status-face
  96. '((((class color) (background light)) (:foreground "purple"))
  97. (((class color) (background dark)) (:foreground "salmon")))
  98. "Git mode face used to highlight added and modified files."
  99. :group 'git)
  100. (defface git-unmerged-face
  101. '((((class color) (background light)) (:foreground "red" :bold t))
  102. (((class color) (background dark)) (:foreground "red" :bold t)))
  103. "Git mode face used to highlight unmerged files."
  104. :group 'git)
  105. (defface git-unknown-face
  106. '((((class color) (background light)) (:foreground "goldenrod" :bold t))
  107. (((class color) (background dark)) (:foreground "goldenrod" :bold t)))
  108. "Git mode face used to highlight unknown files."
  109. :group 'git)
  110. (defface git-uptodate-face
  111. '((((class color) (background light)) (:foreground "grey60"))
  112. (((class color) (background dark)) (:foreground "grey40")))
  113. "Git mode face used to highlight up-to-date files."
  114. :group 'git)
  115. (defface git-ignored-face
  116. '((((class color) (background light)) (:foreground "grey60"))
  117. (((class color) (background dark)) (:foreground "grey40")))
  118. "Git mode face used to highlight ignored files."
  119. :group 'git)
  120. (defface git-mark-face
  121. '((((class color) (background light)) (:foreground "red" :bold t))
  122. (((class color) (background dark)) (:foreground "tomato" :bold t)))
  123. "Git mode face used for the file marks."
  124. :group 'git)
  125. (defface git-header-face
  126. '((((class color) (background light)) (:foreground "blue"))
  127. (((class color) (background dark)) (:foreground "blue")))
  128. "Git mode face used for commit headers."
  129. :group 'git)
  130. (defface git-separator-face
  131. '((((class color) (background light)) (:foreground "brown"))
  132. (((class color) (background dark)) (:foreground "brown")))
  133. "Git mode face used for commit separator."
  134. :group 'git)
  135. (defface git-permission-face
  136. '((((class color) (background light)) (:foreground "green" :bold t))
  137. (((class color) (background dark)) (:foreground "green" :bold t)))
  138. "Git mode face used for permission changes."
  139. :group 'git)
  140. ;;;; Utilities
  141. ;;;; ------------------------------------------------------------
  142. (defconst git-log-msg-separator "--- log message follows this line ---")
  143. (defvar git-log-edit-font-lock-keywords
  144. `(("^\\(Author:\\|Date:\\|Parent:\\|Signed-off-by:\\)\\(.*\\)$"
  145. (1 font-lock-keyword-face)
  146. (2 font-lock-function-name-face))
  147. (,(concat "^\\(" (regexp-quote git-log-msg-separator) "\\)$")
  148. (1 font-lock-comment-face))))
  149. (defun git-get-env-strings (env)
  150. "Build a list of NAME=VALUE strings from a list of environment strings."
  151. (mapcar (lambda (entry) (concat (car entry) "=" (cdr entry))) env))
  152. (defun git-call-process-env (buffer env &rest args)
  153. "Wrapper for call-process that sets environment strings."
  154. (let ((process-environment (append (git-get-env-strings env)
  155. process-environment)))
  156. (apply #'call-process "git" nil buffer nil args)))
  157. (defun git-call-process-display-error (&rest args)
  158. "Wrapper for call-process that displays error messages."
  159. (let* ((dir default-directory)
  160. (buffer (get-buffer-create "*Git Command Output*"))
  161. (ok (with-current-buffer buffer
  162. (let ((default-directory dir)
  163. (buffer-read-only nil))
  164. (erase-buffer)
  165. (eq 0 (apply 'call-process "git" nil (list buffer t) nil args))))))
  166. (unless ok (display-message-or-buffer buffer))
  167. ok))
  168. (defun git-call-process-env-string (env &rest args)
  169. "Wrapper for call-process that sets environment strings,
  170. and returns the process output as a string, or nil if the git failed."
  171. (with-temp-buffer
  172. (and (eq 0 (apply #' git-call-process-env t env args))
  173. (buffer-string))))
  174. (defun git-run-process-region (buffer start end program args)
  175. "Run a git process with a buffer region as input."
  176. (let ((output-buffer (current-buffer))
  177. (dir default-directory))
  178. (with-current-buffer buffer
  179. (cd dir)
  180. (apply #'call-process-region start end program
  181. nil (list output-buffer nil) nil args))))
  182. (defun git-run-command-buffer (buffer-name &rest args)
  183. "Run a git command, sending the output to a buffer named BUFFER-NAME."
  184. (let ((dir default-directory)
  185. (buffer (get-buffer-create buffer-name)))
  186. (message "Running git %s..." (car args))
  187. (with-current-buffer buffer
  188. (let ((default-directory dir)
  189. (buffer-read-only nil))
  190. (erase-buffer)
  191. (apply #'git-call-process-env buffer nil args)))
  192. (message "Running git %s...done" (car args))
  193. buffer))
  194. (defun git-run-command-region (buffer start end env &rest args)
  195. "Run a git command with specified buffer region as input."
  196. (unless (eq 0 (if env
  197. (git-run-process-region
  198. buffer start end "env"
  199. (append (git-get-env-strings env) (list "git") args))
  200. (git-run-process-region
  201. buffer start end "git" args)))
  202. (error "Failed to run \"git %s\":\n%s" (mapconcat (lambda (x) x) args " ") (buffer-string))))
  203. (defun git-run-hook (hook env &rest args)
  204. "Run a git hook and display its output if any."
  205. (let ((dir default-directory)
  206. (hook-name (expand-file-name (concat ".git/hooks/" hook))))
  207. (or (not (file-executable-p hook-name))
  208. (let (status (buffer (get-buffer-create "*Git Hook Output*")))
  209. (with-current-buffer buffer
  210. (erase-buffer)
  211. (cd dir)
  212. (setq status
  213. (if env
  214. (apply #'call-process "env" nil (list buffer t) nil
  215. (append (git-get-env-strings env) (list hook-name) args))
  216. (apply #'call-process hook-name nil (list buffer t) nil args))))
  217. (display-message-or-buffer buffer)
  218. (eq 0 status)))))
  219. (defun git-get-string-sha1 (string)
  220. "Read a SHA1 from the specified string."
  221. (and string
  222. (string-match "[0-9a-f]\\{40\\}" string)
  223. (match-string 0 string)))
  224. (defun git-get-committer-name ()
  225. "Return the name to use as GIT_COMMITTER_NAME."
  226. ; copied from log-edit
  227. (or git-committer-name
  228. (git-config "user.name")
  229. (and (boundp 'add-log-full-name) add-log-full-name)
  230. (and (fboundp 'user-full-name) (user-full-name))
  231. (and (boundp 'user-full-name) user-full-name)))
  232. (defun git-get-committer-email ()
  233. "Return the email address to use as GIT_COMMITTER_EMAIL."
  234. ; copied from log-edit
  235. (or git-committer-email
  236. (git-config "user.email")
  237. (and (boundp 'add-log-mailing-address) add-log-mailing-address)
  238. (and (fboundp 'user-mail-address) (user-mail-address))
  239. (and (boundp 'user-mail-address) user-mail-address)))
  240. (defun git-get-commits-coding-system ()
  241. "Return the coding system to use for commits."
  242. (let ((repo-config (git-config "i18n.commitencoding")))
  243. (or git-commits-coding-system
  244. (and repo-config
  245. (fboundp 'locale-charset-to-coding-system)
  246. (locale-charset-to-coding-system repo-config))
  247. 'utf-8)))
  248. (defun git-get-logoutput-coding-system ()
  249. "Return the coding system used for git-log output."
  250. (let ((repo-config (or (git-config "i18n.logoutputencoding")
  251. (git-config "i18n.commitencoding"))))
  252. (or git-commits-coding-system
  253. (and repo-config
  254. (fboundp 'locale-charset-to-coding-system)
  255. (locale-charset-to-coding-system repo-config))
  256. 'utf-8)))
  257. (defun git-escape-file-name (name)
  258. "Escape a file name if necessary."
  259. (if (string-match "[\n\t\"\\]" name)
  260. (concat "\""
  261. (mapconcat (lambda (c)
  262. (case c
  263. (?\n "\\n")
  264. (?\t "\\t")
  265. (?\\ "\\\\")
  266. (?\" "\\\"")
  267. (t (char-to-string c))))
  268. name "")
  269. "\"")
  270. name))
  271. (defun git-success-message (text files)
  272. "Print a success message after having handled FILES."
  273. (let ((n (length files)))
  274. (if (equal n 1)
  275. (message "%s %s" text (car files))
  276. (message "%s %d files" text n))))
  277. (defun git-get-top-dir (dir)
  278. "Retrieve the top-level directory of a git tree."
  279. (let ((cdup (with-output-to-string
  280. (with-current-buffer standard-output
  281. (cd dir)
  282. (unless (eq 0 (call-process "git" nil t nil "rev-parse" "--show-cdup"))
  283. (error "cannot find top-level git tree for %s." dir))))))
  284. (expand-file-name (concat (file-name-as-directory dir)
  285. (car (split-string cdup "\n"))))))
  286. ;stolen from pcl-cvs
  287. (defun git-append-to-ignore (file)
  288. "Add a file name to the ignore file in its directory."
  289. (let* ((fullname (expand-file-name file))
  290. (dir (file-name-directory fullname))
  291. (name (file-name-nondirectory fullname))
  292. (ignore-name (expand-file-name git-per-dir-ignore-file dir))
  293. (created (not (file-exists-p ignore-name))))
  294. (save-window-excursion
  295. (set-buffer (find-file-noselect ignore-name))
  296. (goto-char (point-max))
  297. (unless (zerop (current-column)) (insert "\n"))
  298. (insert "/" name "\n")
  299. (sort-lines nil (point-min) (point-max))
  300. (save-buffer))
  301. (when created
  302. (git-call-process-env nil nil "update-index" "--add" "--" (file-relative-name ignore-name)))
  303. (git-update-status-files (list (file-relative-name ignore-name)) 'unknown)))
  304. ; propertize definition for XEmacs, stolen from erc-compat
  305. (eval-when-compile
  306. (unless (fboundp 'propertize)
  307. (defun propertize (string &rest props)
  308. (let ((string (copy-sequence string)))
  309. (while props
  310. (put-text-property 0 (length string) (nth 0 props) (nth 1 props) string)
  311. (setq props (cddr props)))
  312. string))))
  313. ;;;; Wrappers for basic git commands
  314. ;;;; ------------------------------------------------------------
  315. (defun git-rev-parse (rev)
  316. "Parse a revision name and return its SHA1."
  317. (git-get-string-sha1
  318. (git-call-process-env-string nil "rev-parse" rev)))
  319. (defun git-config (key)
  320. "Retrieve the value associated to KEY in the git repository config file."
  321. (let ((str (git-call-process-env-string nil "config" key)))
  322. (and str (car (split-string str "\n")))))
  323. (defun git-symbolic-ref (ref)
  324. "Wrapper for the git-symbolic-ref command."
  325. (let ((str (git-call-process-env-string nil "symbolic-ref" ref)))
  326. (and str (car (split-string str "\n")))))
  327. (defun git-update-ref (ref newval &optional oldval reason)
  328. "Update a reference by calling git-update-ref."
  329. (let ((args (and oldval (list oldval))))
  330. (push newval args)
  331. (push ref args)
  332. (when reason
  333. (push reason args)
  334. (push "-m" args))
  335. (apply 'git-call-process-display-error "update-ref" args)))
  336. (defun git-read-tree (tree &optional index-file)
  337. "Read a tree into the index file."
  338. (apply #'git-call-process-env nil
  339. (if index-file `(("GIT_INDEX_FILE" . ,index-file)) nil)
  340. "read-tree" (if tree (list tree))))
  341. (defun git-write-tree (&optional index-file)
  342. "Call git-write-tree and return the resulting tree SHA1 as a string."
  343. (git-get-string-sha1
  344. (git-call-process-env-string (and index-file `(("GIT_INDEX_FILE" . ,index-file))) "write-tree")))
  345. (defun git-commit-tree (buffer tree head)
  346. "Call git-commit-tree with buffer as input and return the resulting commit SHA1."
  347. (let ((author-name (git-get-committer-name))
  348. (author-email (git-get-committer-email))
  349. (subject "commit (initial): ")
  350. author-date log-start log-end args coding-system-for-write)
  351. (when head
  352. (setq subject "commit: ")
  353. (push "-p" args)
  354. (push head args))
  355. (with-current-buffer buffer
  356. (goto-char (point-min))
  357. (if
  358. (setq log-start (re-search-forward (concat "^" (regexp-quote git-log-msg-separator) "\n") nil t))
  359. (save-restriction
  360. (narrow-to-region (point-min) log-start)
  361. (goto-char (point-min))
  362. (when (re-search-forward "^Author: +\\(.*?\\) *<\\(.*\\)> *$" nil t)
  363. (setq author-name (match-string 1)
  364. author-email (match-string 2)))
  365. (goto-char (point-min))
  366. (when (re-search-forward "^Date: +\\(.*\\)$" nil t)
  367. (setq author-date (match-string 1)))
  368. (goto-char (point-min))
  369. (while (re-search-forward "^Parent: +\\([0-9a-f]+\\)" nil t)
  370. (unless (string-equal head (match-string 1))
  371. (setq subject "commit (merge): ")
  372. (push "-p" args)
  373. (push (match-string 1) args))))
  374. (setq log-start (point-min)))
  375. (setq log-end (point-max))
  376. (goto-char log-start)
  377. (when (re-search-forward ".*$" nil t)
  378. (setq subject (concat subject (match-string 0))))
  379. (setq coding-system-for-write buffer-file-coding-system))
  380. (let ((commit
  381. (git-get-string-sha1
  382. (with-output-to-string
  383. (with-current-buffer standard-output
  384. (let ((env `(("GIT_AUTHOR_NAME" . ,author-name)
  385. ("GIT_AUTHOR_EMAIL" . ,author-email)
  386. ("GIT_COMMITTER_NAME" . ,(git-get-committer-name))
  387. ("GIT_COMMITTER_EMAIL" . ,(git-get-committer-email)))))
  388. (when author-date (push `("GIT_AUTHOR_DATE" . ,author-date) env))
  389. (apply #'git-run-command-region
  390. buffer log-start log-end env
  391. "commit-tree" tree (nreverse args))))))))
  392. (and (git-update-ref "HEAD" commit head subject)
  393. commit))))
  394. (defun git-empty-db-p ()
  395. "Check if the git db is empty (no commit done yet)."
  396. (not (eq 0 (call-process "git" nil nil nil "rev-parse" "--verify" "HEAD"))))
  397. (defun git-get-merge-heads ()
  398. "Retrieve the merge heads from the MERGE_HEAD file if present."
  399. (let (heads)
  400. (when (file-readable-p ".git/MERGE_HEAD")
  401. (with-temp-buffer
  402. (insert-file-contents ".git/MERGE_HEAD" nil nil nil t)
  403. (goto-char (point-min))
  404. (while (re-search-forward "[0-9a-f]\\{40\\}" nil t)
  405. (push (match-string 0) heads))))
  406. (nreverse heads)))
  407. (defun git-get-commit-description (commit)
  408. "Get a one-line description of COMMIT."
  409. (let ((coding-system-for-read (git-get-logoutput-coding-system)))
  410. (let ((descr (git-call-process-env-string nil "log" "--max-count=1" "--pretty=oneline" commit)))
  411. (if (and descr (string-match "\\`\\([0-9a-f]\\{40\\}\\) *\\(.*\\)$" descr))
  412. (concat (substring (match-string 1 descr) 0 10) " - " (match-string 2 descr))
  413. descr))))
  414. ;;;; File info structure
  415. ;;;; ------------------------------------------------------------
  416. ; fileinfo structure stolen from pcl-cvs
  417. (defstruct (git-fileinfo
  418. (:copier nil)
  419. (:constructor git-create-fileinfo (state name &optional old-perm new-perm rename-state orig-name marked))
  420. (:conc-name git-fileinfo->))
  421. marked ;; t/nil
  422. state ;; current state
  423. name ;; file name
  424. old-perm new-perm ;; permission flags
  425. rename-state ;; rename or copy state
  426. orig-name ;; original name for renames or copies
  427. needs-refresh) ;; whether file needs to be refreshed
  428. (defvar git-status nil)
  429. (defun git-clear-status (status)
  430. "Remove everything from the status list."
  431. (ewoc-filter status (lambda (info) nil)))
  432. (defun git-set-fileinfo-state (info state)
  433. "Set the state of a file info."
  434. (unless (eq (git-fileinfo->state info) state)
  435. (setf (git-fileinfo->state info) state
  436. (git-fileinfo->new-perm info) (git-fileinfo->old-perm info)
  437. (git-fileinfo->rename-state info) nil
  438. (git-fileinfo->orig-name info) nil
  439. (git-fileinfo->needs-refresh info) t)))
  440. (defun git-status-filenames-map (status func files &rest args)
  441. "Apply FUNC to the status files names in the FILES list."
  442. (when files
  443. (setq files (sort files #'string-lessp))
  444. (let ((file (pop files))
  445. (node (ewoc-nth status 0)))
  446. (while (and file node)
  447. (let ((info (ewoc-data node)))
  448. (if (string-lessp (git-fileinfo->name info) file)
  449. (setq node (ewoc-next status node))
  450. (if (string-equal (git-fileinfo->name info) file)
  451. (apply func info args))
  452. (setq file (pop files))))))))
  453. (defun git-set-filenames-state (status files state)
  454. "Set the state of a list of named files."
  455. (when files
  456. (git-status-filenames-map status #'git-set-fileinfo-state files state)
  457. (unless state ;; delete files whose state has been set to nil
  458. (ewoc-filter status (lambda (info) (git-fileinfo->state info))))))
  459. (defun git-state-code (code)
  460. "Convert from a string to a added/deleted/modified state."
  461. (case (string-to-char code)
  462. (?M 'modified)
  463. (?? 'unknown)
  464. (?A 'added)
  465. (?D 'deleted)
  466. (?U 'unmerged)
  467. (?T 'modified)
  468. (t nil)))
  469. (defun git-status-code-as-string (code)
  470. "Format a git status code as string."
  471. (case code
  472. ('modified (propertize "Modified" 'face 'git-status-face))
  473. ('unknown (propertize "Unknown " 'face 'git-unknown-face))
  474. ('added (propertize "Added " 'face 'git-status-face))
  475. ('deleted (propertize "Deleted " 'face 'git-status-face))
  476. ('unmerged (propertize "Unmerged" 'face 'git-unmerged-face))
  477. ('uptodate (propertize "Uptodate" 'face 'git-uptodate-face))
  478. ('ignored (propertize "Ignored " 'face 'git-ignored-face))
  479. (t "? ")))
  480. (defun git-file-type-as-string (old-perm new-perm)
  481. "Return a string describing the file type based on its permissions."
  482. (let* ((old-type (lsh (or old-perm 0) -9))
  483. (new-type (lsh (or new-perm 0) -9))
  484. (str (case new-type
  485. (?\100 ;; file
  486. (case old-type
  487. (?\100 nil)
  488. (?\120 " (type change symlink -> file)")
  489. (?\160 " (type change subproject -> file)")))
  490. (?\120 ;; symlink
  491. (case old-type
  492. (?\100 " (type change file -> symlink)")
  493. (?\160 " (type change subproject -> symlink)")
  494. (t " (symlink)")))
  495. (?\160 ;; subproject
  496. (case old-type
  497. (?\100 " (type change file -> subproject)")
  498. (?\120 " (type change symlink -> subproject)")
  499. (t " (subproject)")))
  500. (?\110 nil) ;; directory (internal, not a real git state)
  501. (?\000 ;; deleted or unknown
  502. (case old-type
  503. (?\120 " (symlink)")
  504. (?\160 " (subproject)")))
  505. (t (format " (unknown type %o)" new-type)))))
  506. (cond (str (propertize str 'face 'git-status-face))
  507. ((eq new-type ?\110) "/")
  508. (t ""))))
  509. (defun git-rename-as-string (info)
  510. "Return a string describing the copy or rename associated with INFO, or an empty string if none."
  511. (let ((state (git-fileinfo->rename-state info)))
  512. (if state
  513. (propertize
  514. (concat " ("
  515. (if (eq state 'copy) "copied from "
  516. (if (eq (git-fileinfo->state info) 'added) "renamed from "
  517. "renamed to "))
  518. (git-escape-file-name (git-fileinfo->orig-name info))
  519. ")") 'face 'git-status-face)
  520. "")))
  521. (defun git-permissions-as-string (old-perm new-perm)
  522. "Format a permission change as string."
  523. (propertize
  524. (if (or (not old-perm)
  525. (not new-perm)
  526. (eq 0 (logand ?\111 (logxor old-perm new-perm))))
  527. " "
  528. (if (eq 0 (logand ?\111 old-perm)) "+x" "-x"))
  529. 'face 'git-permission-face))
  530. (defun git-fileinfo-prettyprint (info)
  531. "Pretty-printer for the git-fileinfo structure."
  532. (let ((old-perm (git-fileinfo->old-perm info))
  533. (new-perm (git-fileinfo->new-perm info)))
  534. (insert (concat " " (if (git-fileinfo->marked info) (propertize "*" 'face 'git-mark-face) " ")
  535. " " (git-status-code-as-string (git-fileinfo->state info))
  536. " " (git-permissions-as-string old-perm new-perm)
  537. " " (git-escape-file-name (git-fileinfo->name info))
  538. (git-file-type-as-string old-perm new-perm)
  539. (git-rename-as-string info)))))
  540. (defun git-insert-info-list (status infolist)
  541. "Insert a list of file infos in the status buffer, replacing existing ones if any."
  542. (setq infolist (sort infolist
  543. (lambda (info1 info2)
  544. (string-lessp (git-fileinfo->name info1)
  545. (git-fileinfo->name info2)))))
  546. (let ((info (pop infolist))
  547. (node (ewoc-nth status 0)))
  548. (while info
  549. (cond ((not node)
  550. (setq node (ewoc-enter-last status info))
  551. (setq info (pop infolist)))
  552. ((string-lessp (git-fileinfo->name (ewoc-data node))
  553. (git-fileinfo->name info))
  554. (setq node (ewoc-next status node)))
  555. ((string-equal (git-fileinfo->name (ewoc-data node))
  556. (git-fileinfo->name info))
  557. ;; preserve the marked flag
  558. (setf (git-fileinfo->marked info) (git-fileinfo->marked (ewoc-data node)))
  559. (setf (git-fileinfo->needs-refresh info) t)
  560. (setf (ewoc-data node) info)
  561. (setq info (pop infolist)))
  562. (t
  563. (setq node (ewoc-enter-before status node info))
  564. (setq info (pop infolist)))))))
  565. (defun git-run-diff-index (status files)
  566. "Run git-diff-index on FILES and parse the results into STATUS.
  567. Return the list of files that haven't been handled."
  568. (let ((remaining (copy-sequence files))
  569. infolist)
  570. (with-temp-buffer
  571. (apply #'git-call-process-env t nil "diff-index" "-z" "-M" "HEAD" "--" files)
  572. (goto-char (point-min))
  573. (while (re-search-forward
  574. ":\\([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"
  575. nil t 1)
  576. (let ((old-perm (string-to-number (match-string 1) 8))
  577. (new-perm (string-to-number (match-string 2) 8))
  578. (state (or (match-string 4) (match-string 6)))
  579. (name (or (match-string 5) (match-string 7)))
  580. (new-name (match-string 8)))
  581. (if new-name ; copy or rename
  582. (if (eq ?C (string-to-char state))
  583. (push (git-create-fileinfo 'added new-name old-perm new-perm 'copy name) infolist)
  584. (push (git-create-fileinfo 'deleted name 0 0 'rename new-name) infolist)
  585. (push (git-create-fileinfo 'added new-name old-perm new-perm 'rename name) infolist))
  586. (push (git-create-fileinfo (git-state-code state) name old-perm new-perm) infolist))
  587. (setq remaining (delete name remaining))
  588. (when new-name (setq remaining (delete new-name remaining))))))
  589. (git-insert-info-list status infolist)
  590. remaining))
  591. (defun git-find-status-file (status file)
  592. "Find a given file in the status ewoc and return its node."
  593. (let ((node (ewoc-nth status 0)))
  594. (while (and node (not (string= file (git-fileinfo->name (ewoc-data node)))))
  595. (setq node (ewoc-next status node)))
  596. node))
  597. (defun git-run-ls-files (status files default-state &rest options)
  598. "Run git-ls-files on FILES and parse the results into STATUS.
  599. Return the list of files that haven't been handled."
  600. (let (infolist)
  601. (with-temp-buffer
  602. (apply #'git-call-process-env t nil "ls-files" "-z" (append options (list "--") files))
  603. (goto-char (point-min))
  604. (while (re-search-forward "\\([^\0]*?\\)\\(/?\\)\0" nil t 1)
  605. (let ((name (match-string 1)))
  606. (push (git-create-fileinfo default-state name 0
  607. (if (string-equal "/" (match-string 2)) (lsh ?\110 9) 0))
  608. infolist)
  609. (setq files (delete name files)))))
  610. (git-insert-info-list status infolist)
  611. files))
  612. (defun git-run-ls-files-cached (status files default-state)
  613. "Run git-ls-files -c on FILES and parse the results into STATUS.
  614. Return the list of files that haven't been handled."
  615. (let ((remaining (copy-sequence files))
  616. infolist)
  617. (with-temp-buffer
  618. (apply #'git-call-process-env t nil "ls-files" "-z" "-s" "-c" "--" files)
  619. (goto-char (point-min))
  620. (while (re-search-forward "\\([0-7]\\{6\\}\\) [0-9a-f]\\{40\\} 0\t\\([^\0]+\\)\0" nil t)
  621. (let* ((new-perm (string-to-number (match-string 1) 8))
  622. (old-perm (if (eq default-state 'added) 0 new-perm))
  623. (name (match-string 2)))
  624. (push (git-create-fileinfo default-state name old-perm new-perm) infolist)
  625. (setq remaining (delete name remaining)))))
  626. (git-insert-info-list status infolist)
  627. remaining))
  628. (defun git-run-ls-unmerged (status files)
  629. "Run git-ls-files -u on FILES and parse the results into STATUS."
  630. (with-temp-buffer
  631. (apply #'git-call-process-env t nil "ls-files" "-z" "-u" "--" files)
  632. (goto-char (point-min))
  633. (let (unmerged-files)
  634. (while (re-search-forward "[0-7]\\{6\\} [0-9a-f]\\{40\\} [123]\t\\([^\0]+\\)\0" nil t)
  635. (push (match-string 1) unmerged-files))
  636. (git-set-filenames-state status unmerged-files 'unmerged))))
  637. (defun git-get-exclude-files ()
  638. "Get the list of exclude files to pass to git-ls-files."
  639. (let (files
  640. (config (git-config "core.excludesfile")))
  641. (when (file-readable-p ".git/info/exclude")
  642. (push ".git/info/exclude" files))
  643. (when (and config (file-readable-p config))
  644. (push config files))
  645. files))
  646. (defun git-run-ls-files-with-excludes (status files default-state &rest options)
  647. "Run git-ls-files on FILES with appropriate --exclude-from options."
  648. (let ((exclude-files (git-get-exclude-files)))
  649. (apply #'git-run-ls-files status files default-state "--directory" "--no-empty-directory"
  650. (concat "--exclude-per-directory=" git-per-dir-ignore-file)
  651. (append options (mapcar (lambda (f) (concat "--exclude-from=" f)) exclude-files)))))
  652. (defun git-update-status-files (files &optional default-state)
  653. "Update the status of FILES from the index."
  654. (unless git-status (error "Not in git-status buffer."))
  655. (when (or git-show-uptodate files)
  656. (git-run-ls-files-cached git-status files 'uptodate))
  657. (let* ((remaining-files
  658. (if (git-empty-db-p) ; we need some special handling for an empty db
  659. (git-run-ls-files-cached git-status files 'added)
  660. (git-run-diff-index git-status files))))
  661. (git-run-ls-unmerged git-status files)
  662. (when (or remaining-files (and git-show-unknown (not files)))
  663. (setq remaining-files (git-run-ls-files-with-excludes git-status remaining-files 'unknown "-o")))
  664. (when (or remaining-files (and git-show-ignored (not files)))
  665. (setq remaining-files (git-run-ls-files-with-excludes git-status remaining-files 'ignored "-o" "-i")))
  666. (git-set-filenames-state git-status remaining-files default-state)
  667. (git-refresh-files)
  668. (git-refresh-ewoc-hf git-status)))
  669. (defun git-mark-files (status files)
  670. "Mark all the specified FILES, and unmark the others."
  671. (setq files (sort files #'string-lessp))
  672. (let ((file (and files (pop files)))
  673. (node (ewoc-nth status 0)))
  674. (while node
  675. (let ((info (ewoc-data node)))
  676. (if (and file (string-equal (git-fileinfo->name info) file))
  677. (progn
  678. (unless (git-fileinfo->marked info)
  679. (setf (git-fileinfo->marked info) t)
  680. (setf (git-fileinfo->needs-refresh info) t))
  681. (setq file (pop files))
  682. (setq node (ewoc-next status node)))
  683. (when (git-fileinfo->marked info)
  684. (setf (git-fileinfo->marked info) nil)
  685. (setf (git-fileinfo->needs-refresh info) t))
  686. (if (and file (string-lessp file (git-fileinfo->name info)))
  687. (setq file (pop files))
  688. (setq node (ewoc-next status node))))))))
  689. (defun git-marked-files ()
  690. "Return a list of all marked files, or if none a list containing just the file at cursor position."
  691. (unless git-status (error "Not in git-status buffer."))
  692. (or (ewoc-collect git-status (lambda (info) (git-fileinfo->marked info)))
  693. (list (ewoc-data (ewoc-locate git-status)))))
  694. (defun git-marked-files-state (&rest states)
  695. "Return marked files that are in the specified states."
  696. (let ((files (git-marked-files))
  697. result)
  698. (dolist (info files)
  699. (when (memq (git-fileinfo->state info) states)
  700. (push info result)))
  701. result))
  702. (defun git-refresh-files ()
  703. "Refresh all files that need it and clear the needs-refresh flag."
  704. (unless git-status (error "Not in git-status buffer."))
  705. (ewoc-map
  706. (lambda (info)
  707. (let ((refresh (git-fileinfo->needs-refresh info)))
  708. (setf (git-fileinfo->needs-refresh info) nil)
  709. refresh))
  710. git-status)
  711. ; move back to goal column
  712. (when goal-column (move-to-column goal-column)))
  713. (defun git-refresh-ewoc-hf (status)
  714. "Refresh the ewoc header and footer."
  715. (let ((branch (git-symbolic-ref "HEAD"))
  716. (head (if (git-empty-db-p) "Nothing committed yet"
  717. (git-get-commit-description "HEAD")))
  718. (merge-heads (git-get-merge-heads)))
  719. (ewoc-set-hf status
  720. (format "Directory: %s\nBranch: %s\nHead: %s%s\n"
  721. default-directory
  722. (if branch
  723. (if (string-match "^refs/heads/" branch)
  724. (substring branch (match-end 0))
  725. branch)
  726. "none (detached HEAD)")
  727. head
  728. (if merge-heads
  729. (concat "\nMerging: "
  730. (mapconcat (lambda (str) (git-get-commit-description str)) merge-heads "\n "))
  731. ""))
  732. (if (ewoc-nth status 0) "" " No changes."))))
  733. (defun git-get-filenames (files)
  734. (mapcar (lambda (info) (git-fileinfo->name info)) files))
  735. (defun git-update-index (index-file files)
  736. "Run git-update-index on a list of files."
  737. (let ((env (and index-file `(("GIT_INDEX_FILE" . ,index-file))))
  738. added deleted modified)
  739. (dolist (info files)
  740. (case (git-fileinfo->state info)
  741. ('added (push info added))
  742. ('deleted (push info deleted))
  743. ('modified (push info modified))))
  744. (when added
  745. (apply #'git-call-process-env nil env "update-index" "--add" "--" (git-get-filenames added)))
  746. (when deleted
  747. (apply #'git-call-process-env nil env "update-index" "--remove" "--" (git-get-filenames deleted)))
  748. (when modified
  749. (apply #'git-call-process-env nil env "update-index" "--" (git-get-filenames modified)))))
  750. (defun git-run-pre-commit-hook ()
  751. "Run the pre-commit hook if any."
  752. (unless git-status (error "Not in git-status buffer."))
  753. (let ((files (git-marked-files-state 'added 'deleted 'modified)))
  754. (or (not files)
  755. (not (file-executable-p ".git/hooks/pre-commit"))
  756. (let ((index-file (make-temp-file "gitidx")))
  757. (unwind-protect
  758. (let ((head-tree (unless (git-empty-db-p) (git-rev-parse "HEAD^{tree}"))))
  759. (git-read-tree head-tree index-file)
  760. (git-update-index index-file files)
  761. (git-run-hook "pre-commit" `(("GIT_INDEX_FILE" . ,index-file))))
  762. (delete-file index-file))))))
  763. (defun git-do-commit ()
  764. "Perform the actual commit using the current buffer as log message."
  765. (interactive)
  766. (let ((buffer (current-buffer))
  767. (index-file (make-temp-file "gitidx")))
  768. (with-current-buffer log-edit-parent-buffer
  769. (if (git-marked-files-state 'unmerged)
  770. (message "You cannot commit unmerged files, resolve them first.")
  771. (unwind-protect
  772. (let ((files (git-marked-files-state 'added 'deleted 'modified))
  773. head head-tree)
  774. (unless (git-empty-db-p)
  775. (setq head (git-rev-parse "HEAD")
  776. head-tree (git-rev-parse "HEAD^{tree}")))
  777. (if files
  778. (progn
  779. (message "Running git commit...")
  780. (git-read-tree head-tree index-file)
  781. (git-update-index nil files) ;update both the default index
  782. (git-update-index index-file files) ;and the temporary one
  783. (let ((tree (git-write-tree index-file)))
  784. (if (or (not (string-equal tree head-tree))
  785. (yes-or-no-p "The tree was not modified, do you really want to perform an empty commit? "))
  786. (let ((commit (git-commit-tree buffer tree head)))
  787. (when commit
  788. (condition-case nil (delete-file ".git/MERGE_HEAD") (error nil))
  789. (condition-case nil (delete-file ".git/MERGE_MSG") (error nil))
  790. (with-current-buffer buffer (erase-buffer))
  791. (git-update-status-files (git-get-filenames files) 'uptodate)
  792. (git-call-process-env nil nil "rerere")
  793. (git-call-process-env nil nil "gc" "--auto")
  794. (git-refresh-files)
  795. (git-refresh-ewoc-hf git-status)
  796. (message "Committed %s." commit)
  797. (git-run-hook "post-commit" nil)))
  798. (message "Commit aborted."))))
  799. (message "No files to commit.")))
  800. (delete-file index-file))))))
  801. ;;;; Interactive functions
  802. ;;;; ------------------------------------------------------------
  803. (defun git-mark-file ()
  804. "Mark the file that the cursor is on and move to the next one."
  805. (interactive)
  806. (unless git-status (error "Not in git-status buffer."))
  807. (let* ((pos (ewoc-locate git-status))
  808. (info (ewoc-data pos)))
  809. (setf (git-fileinfo->marked info) t)
  810. (ewoc-invalidate git-status pos)
  811. (ewoc-goto-next git-status 1)))
  812. (defun git-unmark-file ()
  813. "Unmark the file that the cursor is on and move to the next one."
  814. (interactive)
  815. (unless git-status (error "Not in git-status buffer."))
  816. (let* ((pos (ewoc-locate git-status))
  817. (info (ewoc-data pos)))
  818. (setf (git-fileinfo->marked info) nil)
  819. (ewoc-invalidate git-status pos)
  820. (ewoc-goto-next git-status 1)))
  821. (defun git-unmark-file-up ()
  822. "Unmark the file that the cursor is on and move to the previous one."
  823. (interactive)
  824. (unless git-status (error "Not in git-status buffer."))
  825. (let* ((pos (ewoc-locate git-status))
  826. (info (ewoc-data pos)))
  827. (setf (git-fileinfo->marked info) nil)
  828. (ewoc-invalidate git-status pos)
  829. (ewoc-goto-prev git-status 1)))
  830. (defun git-mark-all ()
  831. "Mark all files."
  832. (interactive)
  833. (unless git-status (error "Not in git-status buffer."))
  834. (ewoc-map (lambda (info) (unless (git-fileinfo->marked info)
  835. (setf (git-fileinfo->marked info) t))) git-status)
  836. ; move back to goal column after invalidate
  837. (when goal-column (move-to-column goal-column)))
  838. (defun git-unmark-all ()
  839. "Unmark all files."
  840. (interactive)
  841. (unless git-status (error "Not in git-status buffer."))
  842. (ewoc-map (lambda (info) (when (git-fileinfo->marked info)
  843. (setf (git-fileinfo->marked info) nil)
  844. t)) git-status)
  845. ; move back to goal column after invalidate
  846. (when goal-column (move-to-column goal-column)))
  847. (defun git-toggle-all-marks ()
  848. "Toggle all file marks."
  849. (interactive)
  850. (unless git-status (error "Not in git-status buffer."))
  851. (ewoc-map (lambda (info) (setf (git-fileinfo->marked info) (not (git-fileinfo->marked info))) t) git-status)
  852. ; move back to goal column after invalidate
  853. (when goal-column (move-to-column goal-column)))
  854. (defun git-next-file (&optional n)
  855. "Move the selection down N files."
  856. (interactive "p")
  857. (unless git-status (error "Not in git-status buffer."))
  858. (ewoc-goto-next git-status n))
  859. (defun git-prev-file (&optional n)
  860. "Move the selection up N files."
  861. (interactive "p")
  862. (unless git-status (error "Not in git-status buffer."))
  863. (ewoc-goto-prev git-status n))
  864. (defun git-next-unmerged-file (&optional n)
  865. "Move the selection down N unmerged files."
  866. (interactive "p")
  867. (unless git-status (error "Not in git-status buffer."))
  868. (let* ((last (ewoc-locate git-status))
  869. (node (ewoc-next git-status last)))
  870. (while (and node (> n 0))
  871. (when (eq 'unmerged (git-fileinfo->state (ewoc-data node)))
  872. (setq n (1- n))
  873. (setq last node))
  874. (setq node (ewoc-next git-status node)))
  875. (ewoc-goto-node git-status last)))
  876. (defun git-prev-unmerged-file (&optional n)
  877. "Move the selection up N unmerged files."
  878. (interactive "p")
  879. (unless git-status (error "Not in git-status buffer."))
  880. (let* ((last (ewoc-locate git-status))
  881. (node (ewoc-prev git-status last)))
  882. (while (and node (> n 0))
  883. (when (eq 'unmerged (git-fileinfo->state (ewoc-data node)))
  884. (setq n (1- n))
  885. (setq last node))
  886. (setq node (ewoc-prev git-status node)))
  887. (ewoc-goto-node git-status last)))
  888. (defun git-add-file ()
  889. "Add marked file(s) to the index cache."
  890. (interactive)
  891. (let ((files (git-get-filenames (git-marked-files-state 'unknown 'ignored))))
  892. ;; FIXME: add support for directories
  893. (unless files
  894. (push (file-relative-name (read-file-name "File to add: " nil nil t)) files))
  895. (when (apply 'git-call-process-display-error "update-index" "--add" "--" files)
  896. (git-update-status-files files 'uptodate)
  897. (git-success-message "Added" files))))
  898. (defun git-ignore-file ()
  899. "Add marked file(s) to the ignore list."
  900. (interactive)
  901. (let ((files (git-get-filenames (git-marked-files-state 'unknown))))
  902. (unless files
  903. (push (file-relative-name (read-file-name "File to ignore: " nil nil t)) files))
  904. (dolist (f files) (git-append-to-ignore f))
  905. (git-update-status-files files 'ignored)
  906. (git-success-message "Ignored" files)))
  907. (defun git-remove-file ()
  908. "Remove the marked file(s)."
  909. (interactive)
  910. (let ((files (git-get-filenames (git-marked-files-state 'added 'modified 'unknown 'uptodate 'ignored))))
  911. (unless files
  912. (push (file-relative-name (read-file-name "File to remove: " nil nil t)) files))
  913. (if (yes-or-no-p
  914. (format "Remove %d file%s? " (length files) (if (> (length files) 1) "s" "")))
  915. (progn
  916. (dolist (name files)
  917. (ignore-errors
  918. (if (file-directory-p name)
  919. (delete-directory name)
  920. (delete-file name))))
  921. (when (apply 'git-call-process-display-error "update-index" "--remove" "--" files)
  922. (git-update-status-files files nil)
  923. (git-success-message "Removed" files)))
  924. (message "Aborting"))))
  925. (defun git-revert-file ()
  926. "Revert changes to the marked file(s)."
  927. (interactive)
  928. (let ((files (git-marked-files-state 'added 'deleted 'modified 'unmerged))
  929. added modified)
  930. (when (and files
  931. (yes-or-no-p
  932. (format "Revert %d file%s? " (length files) (if (> (length files) 1) "s" ""))))
  933. (dolist (info files)
  934. (case (git-fileinfo->state info)
  935. ('added (push (git-fileinfo->name info) added))
  936. ('deleted (push (git-fileinfo->name info) modified))
  937. ('unmerged (push (git-fileinfo->name info) modified))
  938. ('modified (push (git-fileinfo->name info) modified))))
  939. ;; check if a buffer contains one of the files and isn't saved
  940. (dolist (file modified)
  941. (let ((buffer (get-file-buffer file)))
  942. (when (and buffer (buffer-modified-p buffer))
  943. (error "Buffer %s is modified. Please kill or save modified buffers before reverting." (buffer-name buffer)))))
  944. (let ((ok (and
  945. (or (not added)
  946. (apply 'git-call-process-display-error "update-index" "--force-remove" "--" added))
  947. (or (not modified)
  948. (apply 'git-call-process-display-error "checkout" "HEAD" modified)))))
  949. (git-update-status-files (append added modified) 'uptodate)
  950. (when ok
  951. (dolist (file modified)
  952. (let ((buffer (get-file-buffer file)))
  953. (when buffer (with-current-buffer buffer (revert-buffer t t t)))))
  954. (git-success-message "Reverted" (git-get-filenames files)))))))
  955. (defun git-resolve-file ()
  956. "Resolve conflicts in marked file(s)."
  957. (interactive)
  958. (let ((files (git-get-filenames (git-marked-files-state 'unmerged))))
  959. (when files
  960. (when (apply 'git-call-process-display-error "update-index" "--" files)
  961. (git-update-status-files files 'uptodate)
  962. (git-success-message "Resolved" files)))))
  963. (defun git-remove-handled ()
  964. "Remove handled files from the status list."
  965. (interactive)
  966. (ewoc-filter git-status
  967. (lambda (info)
  968. (case (git-fileinfo->state info)
  969. ('ignored git-show-ignored)
  970. ('uptodate git-show-uptodate)
  971. ('unknown git-show-unknown)
  972. (t t))))
  973. (unless (ewoc-nth git-status 0) ; refresh header if list is empty
  974. (git-refresh-ewoc-hf git-status)))
  975. (defun git-toggle-show-uptodate ()
  976. "Toogle the option for showing up-to-date files."
  977. (interactive)
  978. (if (setq git-show-uptodate (not git-show-uptodate))
  979. (git-refresh-status)
  980. (git-remove-handled)))
  981. (defun git-toggle-show-ignored ()
  982. "Toogle the option for showing ignored files."
  983. (interactive)
  984. (if (setq git-show-ignored (not git-show-ignored))
  985. (progn
  986. (message "Inserting ignored files...")
  987. (git-run-ls-files-with-excludes git-status nil 'ignored "-o" "-i")
  988. (git-refresh-files)
  989. (git-refresh-ewoc-hf git-status)
  990. (message "Inserting ignored files...done"))
  991. (git-remove-handled)))
  992. (defun git-toggle-show-unknown ()
  993. "Toogle the option for showing unknown files."
  994. (interactive)
  995. (if (setq git-show-unknown (not git-show-unknown))
  996. (progn
  997. (message "Inserting unknown files...")
  998. (git-run-ls-files-with-excludes git-status nil 'unknown "-o")
  999. (git-refresh-files)
  1000. (git-refresh-ewoc-hf git-status)
  1001. (message "Inserting unknown files...done"))
  1002. (git-remove-handled)))
  1003. (defun git-expand-directory (info)
  1004. "Expand the directory represented by INFO to list its files."
  1005. (when (eq (lsh (git-fileinfo->new-perm info) -9) ?\110)
  1006. (let ((dir (git-fileinfo->name info)))
  1007. (git-set-filenames-state git-status (list dir) nil)
  1008. (git-run-ls-files-with-excludes git-status (list (concat dir "/")) 'unknown "-o")
  1009. (git-refresh-files)
  1010. (git-refresh-ewoc-hf git-status)
  1011. t)))
  1012. (defun git-setup-diff-buffer (buffer)
  1013. "Setup a buffer for displaying a diff."
  1014. (let ((dir default-directory))
  1015. (with-current-buffer buffer
  1016. (diff-mode)
  1017. (goto-char (point-min))
  1018. (setq default-directory dir)
  1019. (setq buffer-read-only t)))
  1020. (display-buffer buffer)
  1021. ; shrink window only if it displays the status buffer
  1022. (when (eq (window-buffer) (current-buffer))
  1023. (shrink-window-if-larger-than-buffer)))
  1024. (defun git-diff-file ()
  1025. "Diff the marked file(s) against HEAD."
  1026. (interactive)
  1027. (let ((files (git-marked-files)))
  1028. (git-setup-diff-buffer
  1029. (apply #'git-run-command-buffer "*git-diff*" "diff-index" "-p" "-M" "HEAD" "--" (git-get-filenames files)))))
  1030. (defun git-diff-file-merge-head (arg)
  1031. "Diff the marked file(s) against the first merge head (or the nth one with a numeric prefix)."
  1032. (interactive "p")
  1033. (let ((files (git-marked-files))
  1034. (merge-heads (git-get-merge-heads)))
  1035. (unless merge-heads (error "No merge in progress"))
  1036. (git-setup-diff-buffer
  1037. (apply #'git-run-command-buffer "*git-diff*" "diff-index" "-p" "-M"
  1038. (or (nth (1- arg) merge-heads) "HEAD") "--" (git-get-filenames files)))))
  1039. (defun git-diff-unmerged-file (stage)
  1040. "Diff the marked unmerged file(s) against the specified stage."
  1041. (let ((files (git-marked-files)))
  1042. (git-setup-diff-buffer
  1043. (apply #'git-run-command-buffer "*git-diff*" "diff-files" "-p" stage "--" (git-get-filenames files)))))
  1044. (defun git-diff-file-base ()
  1045. "Diff the marked unmerged file(s) against the common base file."
  1046. (interactive)
  1047. (git-diff-unmerged-file "-1"))
  1048. (defun git-diff-file-mine ()
  1049. "Diff the marked unmerged file(s) against my pre-merge version."
  1050. (interactive)
  1051. (git-diff-unmerged-file "-2"))
  1052. (defun git-diff-file-other ()
  1053. "Diff the marked unmerged file(s) against the other's pre-merge version."
  1054. (interactive)
  1055. (git-diff-unmerged-file "-3"))
  1056. (defun git-diff-file-combined ()
  1057. "Do a combined diff of the marked unmerged file(s)."
  1058. (interactive)
  1059. (git-diff-unmerged-file "-c"))
  1060. (defun git-diff-file-idiff ()
  1061. "Perform an interactive diff on the current file."
  1062. (interactive)
  1063. (let ((files (git-marked-files-state 'added 'deleted 'modified)))
  1064. (unless (eq 1 (length files))
  1065. (error "Cannot perform an interactive diff on multiple files."))
  1066. (let* ((filename (car (git-get-filenames files)))
  1067. (buff1 (find-file-noselect filename))
  1068. (buff2 (git-run-command-buffer (concat filename ".~HEAD~") "cat-file" "blob" (concat "HEAD:" filename))))
  1069. (ediff-buffers buff1 buff2))))
  1070. (defun git-log-file ()
  1071. "Display a log of changes to the marked file(s)."
  1072. (interactive)
  1073. (let* ((files (git-marked-files))
  1074. (coding-system-for-read git-commits-coding-system)
  1075. (buffer (apply #'git-run-command-buffer "*git-log*" "rev-list" "--pretty" "HEAD" "--" (git-get-filenames files))))
  1076. (with-current-buffer buffer
  1077. ; (git-log-mode) FIXME: implement log mode
  1078. (goto-char (point-min))
  1079. (setq buffer-read-only t))
  1080. (display-buffer buffer)))
  1081. (defun git-log-edit-files ()
  1082. "Return a list of marked files for use in the log-edit buffer."
  1083. (with-current-buffer log-edit-parent-buffer
  1084. (git-get-filenames (git-marked-files-state 'added 'deleted 'modified))))
  1085. (defun git-log-edit-diff ()
  1086. "Run a diff of the current files being committed from a log-edit buffer."
  1087. (with-current-buffer log-edit-parent-buffer
  1088. (git-diff-file)))
  1089. (defun git-append-sign-off (name email)
  1090. "Append a Signed-off-by entry to the current buffer, avoiding duplicates."
  1091. (let ((sign-off (format "Signed-off-by: %s <%s>" name email))
  1092. (case-fold-search t))
  1093. (goto-char (point-min))
  1094. (unless (re-search-forward (concat "^" (regexp-quote sign-off)) nil t)
  1095. (goto-char (point-min))
  1096. (unless (re-search-forward "^Signed-off-by: " nil t)
  1097. (setq sign-off (concat "\n" sign-off)))
  1098. (goto-char (point-max))
  1099. (insert sign-off "\n"))))
  1100. (defun git-setup-log-buffer (buffer &optional author-name author-email subject date msg)
  1101. "Setup the log buffer for a commit."
  1102. (unless git-status (error "Not in git-status buffer."))
  1103. (let ((merge-heads (git-get-merge-heads))
  1104. (dir default-directory)
  1105. (committer-name (git-get-committer-name))
  1106. (committer-email (git-get-committer-email))
  1107. (sign-off git-append-signed-off-by))
  1108. (with-current-buffer buffer
  1109. (cd dir)
  1110. (erase-buffer)
  1111. (insert
  1112. (propertize
  1113. (format "Author: %s <%s>\n%s%s"
  1114. (or author-name committer-name)
  1115. (or author-email committer-email)
  1116. (if date (format "Date: %s\n" date) "")
  1117. (if merge-heads
  1118. (format "Parent: %s\n%s\n"
  1119. (git-rev-parse "HEAD")
  1120. (mapconcat (lambda (str) (concat "Parent: " str)) merge-heads "\n"))
  1121. ""))
  1122. 'face 'git-header-face)
  1123. (propertize git-log-msg-separator 'face 'git-separator-face)
  1124. "\n")
  1125. (when subject (insert subject "\n\n"))
  1126. (cond (msg (insert msg "\n"))
  1127. ((file-readable-p ".git/rebase-apply/msg")
  1128. (insert-file-contents ".git/rebase-apply/msg"))
  1129. ((file-readable-p ".git/MERGE_MSG")
  1130. (insert-file-contents ".git/MERGE_MSG")))
  1131. ; delete empty lines at end
  1132. (goto-char (point-min))
  1133. (when (re-search-forward "\n+\\'" nil t)
  1134. (replace-match "\n" t t))
  1135. (when sign-off (git-append-sign-off committer-name committer-email)))
  1136. buffer))
  1137. (defun git-commit-file ()
  1138. "Commit the marked file(s), asking for a commit message."
  1139. (interactive)
  1140. (unless git-status (error "Not in git-status buffer."))
  1141. (when (git-run-pre-commit-hook)
  1142. (let ((buffer (get-buffer-create "*git-commit*"))
  1143. (coding-system (git-get-commits-coding-system))
  1144. author-name author-email subject date)
  1145. (when (eq 0 (buffer-size buffer))
  1146. (when (file-readable-p ".git/rebase-apply/info")
  1147. (with-temp-buffer
  1148. (insert-file-contents ".git/rebase-apply/info")
  1149. (goto-char (point-min))
  1150. (when (re-search-forward "^Author: \\(.*\\)\nEmail: \\(.*\\)$" nil t)
  1151. (setq author-name (match-string 1))
  1152. (setq author-email (match-string 2)))
  1153. (goto-char (point-min))
  1154. (when (re-search-forward "^Subject: \\(.*\\)$" nil t)
  1155. (setq subject (match-string 1)))
  1156. (goto-char (point-min))
  1157. (when (re-search-forward "^Date: \\(.*\\)$" nil t)
  1158. (setq date (match-string 1)))))
  1159. (git-setup-log-buffer buffer author-name author-email subject date))
  1160. (if (boundp 'log-edit-diff-function)
  1161. (log-edit 'git-do-commit nil '((log-edit-listfun . git-log-edit-files)
  1162. (log-edit-diff-function . git-log-edit-diff)) buffer)
  1163. (log-edit 'git-do-commit nil 'git-log-edit-files buffer))
  1164. (setq font-lock-keywords (font-lock-compile-keywords git-log-edit-font-lock-keywords))
  1165. (setq buffer-file-coding-system coding-system)
  1166. (re-search-forward (regexp-quote (concat git-log-msg-separator "\n")) nil t))))
  1167. (defun git-setup-commit-buffer (commit)
  1168. "Setup the commit buffer with the contents of COMMIT."
  1169. (let (author-name author-email subject date msg)
  1170. (with-temp-buffer
  1171. (let ((coding-system (git-get-logoutput-coding-system)))
  1172. (git-call-process-env t nil "log" "-1" "--pretty=medium" commit)
  1173. (goto-char (point-min))
  1174. (when (re-search-forward "^Author: *\\(.*\\) <\\(.*\\)>$" nil t)
  1175. (setq author-name (match-string 1))
  1176. (setq author-email (match-string 2)))
  1177. (when (re-search-forward "^Date: *\\(.*\\)$" nil t)
  1178. (setq date (match-string 1)))
  1179. (while (re-search-forward "^ \\(.*\\)$" nil t)
  1180. (push (match-string 1) msg))
  1181. (setq msg (nreverse msg))
  1182. (setq subject (pop msg))
  1183. (while (and msg (zerop (length (car msg))) (pop msg)))))
  1184. (git-setup-log-buffer (get-buffer-create "*git-commit*")
  1185. author-name author-email subject date
  1186. (mapconcat #'identity msg "\n"))))
  1187. (defun git-get-commit-files (commit)
  1188. "Retrieve the list of files modified by COMMIT."
  1189. (let (files)
  1190. (with-temp-buffer
  1191. (git-call-process-env t nil "diff-tree" "-r" "-z" "--name-only" "--no-commit-id" commit)
  1192. (goto-char (point-min))
  1193. (while (re-search-forward "\\([^\0]*\\)\0" nil t 1)
  1194. (push (match-string 1) files)))
  1195. files))
  1196. (defun git-amend-commit ()
  1197. "Undo the last commit on HEAD, and set things up to commit an
  1198. amended version of it."
  1199. (interactive)
  1200. (unless git-status (error "Not in git-status buffer."))
  1201. (when (git-empty-db-p) (error "No commit to amend."))
  1202. (let* ((commit (git-rev-parse "HEAD"))
  1203. (files (git-get-commit-files commit)))
  1204. (when (git-call-process-display-error "reset" "--soft" "HEAD^")
  1205. (git-update-status-files (copy-sequence files) 'uptodate)
  1206. (git-mark-files git-status files)
  1207. (git-refresh-files)
  1208. (git-setup-commit-buffer commit)
  1209. (git-commit-file))))
  1210. (defun git-find-file ()
  1211. "Visit the current file in its own buffer."
  1212. (interactive)
  1213. (unless git-status (error "Not in git-status buffer."))
  1214. (let ((info (ewoc-data (ewoc-locate git-status))))
  1215. (unless (git-expand-directory info)
  1216. (find-file (git-fileinfo->name info))
  1217. (when (eq 'unmerged (git-fileinfo->state info))
  1218. (smerge-mode 1)))))
  1219. (defun git-find-file-other-window ()
  1220. "Visit the current file in its own buffer in another window."
  1221. (interactive)
  1222. (unless git-status (error "Not in git-status buffer."))
  1223. (let ((info (ewoc-data (ewoc-locate git-status))))
  1224. (find-file-other-window (git-fileinfo->name info))
  1225. (when (eq 'unmerged (git-fileinfo->state info))
  1226. (smerge-mode))))
  1227. (defun git-find-file-imerge ()
  1228. "Visit the current file in interactive merge mode."
  1229. (interactive)
  1230. (unless git-status (error "Not in git-status buffer."))
  1231. (let ((info (ewoc-data (ewoc-locate git-status))))
  1232. (find-file (git-fileinfo->name info))
  1233. (smerge-ediff)))
  1234. (defun git-view-file ()
  1235. "View the current file in its own buffer."
  1236. (interactive)
  1237. (unless git-status (error "Not in git-status buffer."))
  1238. (let ((info (ewoc-data (ewoc-locate git-status))))
  1239. (view-file (git-fileinfo->name info))))
  1240. (defun git-refresh-status ()
  1241. "Refresh the git status buffer."
  1242. (interactive)
  1243. (let* ((status git-status)
  1244. (pos (ewoc-locate status))
  1245. (marked-files (git-get-filenames (ewoc-collect status (lambda (info) (git-fileinfo->marked info)))))
  1246. (cur-name (and pos (git-fileinfo->name (ewoc-data pos)))))
  1247. (unless status (error "Not in git-status buffer."))
  1248. (message "Refreshing git status...")
  1249. (git-call-process-env nil nil "update-index" "--refresh")
  1250. (git-clear-status status)
  1251. (git-update-status-files nil)
  1252. ; restore file marks
  1253. (when marked-files
  1254. (git-status-filenames-map status
  1255. (lambda (info)
  1256. (setf (git-fileinfo->marked info) t)
  1257. (setf (git-fileinfo->needs-refresh info) t))
  1258. marked-files)
  1259. (git-refresh-files))
  1260. ; move point to the current file name if any
  1261. (message "Refreshing git status...done")
  1262. (let ((node (and cur-name (git-find-status-file status cur-name))))
  1263. (when node (ewoc-goto-node status node)))))
  1264. (defun git-status-quit ()
  1265. "Quit git-status mode."
  1266. (interactive)
  1267. (bury-buffer))
  1268. ;;;; Major Mode
  1269. ;;;; ------------------------------------------------------------
  1270. (defvar git-status-mode-hook nil
  1271. "Run after `git-status-mode' is setup.")
  1272. (defvar git-status-mode-map nil
  1273. "Keymap for git major mode.")
  1274. (defvar git-status nil
  1275. "List of all files managed by the git-status mode.")
  1276. (unless git-status-mode-map
  1277. (let ((map (make-keymap))
  1278. (commit-map (make-sparse-keymap))
  1279. (diff-map (make-sparse-keymap))
  1280. (toggle-map (make-sparse-keymap)))
  1281. (suppress-keymap map)
  1282. (define-key map "?" 'git-help)
  1283. (define-key map "h" 'git-help)
  1284. (define-key map " " 'git-next-file)
  1285. (define-key map "a" 'git-add-file)
  1286. (define-key map "c" 'git-commit-file)
  1287. (define-key map "\C-c" commit-map)
  1288. (define-key map "d" diff-map)
  1289. (define-key map "=" 'git-diff-file)
  1290. (define-key map "f" 'git-find-file)
  1291. (define-key map "\r" 'git-find-file)
  1292. (define-key map "g" 'git-refresh-status)
  1293. (define-key map "i" 'git-ignore-file)
  1294. (define-key map "l" 'git-log-file)
  1295. (define-key map "m" 'git-mark-file)
  1296. (define-key map "M" 'git-mark-all)
  1297. (define-key map "n" 'git-next-file)
  1298. (define-key map "N" 'git-next-unmerged-file)
  1299. (define-key map "o" 'git-find-file-other-window)
  1300. (define-key map "p" 'git-prev-file)
  1301. (define-key map "P" 'git-prev-unmerged-file)
  1302. (define-key map "q" 'git-status-quit)
  1303. (define-key map "r" 'git-remove-file)
  1304. (define-key map "R" 'git-resolve-file)
  1305. (define-key map "t" toggle-map)
  1306. (define-key map "T" 'git-toggle-all-marks)
  1307. (define-key map "u" 'git-unmark-file)
  1308. (define-key map "U" 'git-revert-file)
  1309. (define-key map "v" 'git-view-file)
  1310. (define-key map "x" 'git-remove-handled)
  1311. (define-key map "\C-?" 'git-unmark-file-up)
  1312. (define-key map "\M-\C-?" 'git-unmark-all)
  1313. ; the commit submap
  1314. (define-key commit-map "\C-a" 'git-amend-commit)
  1315. ; the diff submap
  1316. (define-key diff-map "b" 'git-diff-file-base)
  1317. (define-key diff-map "c" 'git-diff-file-combined)
  1318. (define-key diff-map "=" 'git-diff-file)
  1319. (define-key diff-map "e" 'git-diff-file-idiff)
  1320. (define-key diff-map "E" 'git-find-file-imerge)
  1321. (define-key diff-map "h" 'git-diff-file-merge-head)
  1322. (define-key diff-map "m" 'git-diff-file-mine)
  1323. (define-key diff-map "o" 'git-diff-file-other)
  1324. ; the toggle submap
  1325. (define-key toggle-map "u" 'git-toggle-show-uptodate)
  1326. (define-key toggle-map "i" 'git-toggle-show-ignored)
  1327. (define-key toggle-map "k" 'git-toggle-show-unknown)
  1328. (define-key toggle-map "m" 'git-toggle-all-marks)
  1329. (setq git-status-mode-map map))
  1330. (easy-menu-define git-menu git-status-mode-map
  1331. "Git Menu"
  1332. `("Git"
  1333. ["Refresh" git-refresh-status t]
  1334. ["Commit" git-commit-file t]
  1335. ("Merge"
  1336. ["Next Unmerged File" git-next-unmerged-file t]
  1337. ["Prev Unmerged File" git-prev-unmerged-file t]
  1338. ["Mark as Resolved" git-resolve-file t]
  1339. ["Interactive Merge File" git-find-file-imerge t]
  1340. ["Diff Against Common Base File" git-diff-file-base t]
  1341. ["Diff Combined" git-diff-file-combined t]
  1342. ["Diff Against Merge Head" git-diff-file-merge-head t]
  1343. ["Diff Against Mine" git-diff-file-mine t]
  1344. ["Diff Against Other" git-diff-file-other t])
  1345. "--------"
  1346. ["Add File" git-add-file t]
  1347. ["Revert File" git-revert-file t]
  1348. ["Ignore File" git-ignore-file t]
  1349. ["Remove File" git-remove-file t]
  1350. "--------"
  1351. ["Find File" git-find-file t]
  1352. ["View File" git-view-file t]
  1353. ["Diff File" git-diff-file t]
  1354. ["Interactive Diff File" git-diff-file-idiff t]
  1355. ["Log" git-log-file t]
  1356. "--------"
  1357. ["Mark" git-mark-file t]
  1358. ["Mark All" git-mark-all t]
  1359. ["Unmark" git-unmark-file t]
  1360. ["Unmark All" git-unmark-all t]
  1361. ["Toggle All Marks" git-toggle-all-marks t]
  1362. ["Hide Handled Files" git-remove-handled t]
  1363. "--------"
  1364. ["Show Uptodate Files" git-toggle-show-uptodate :style toggle :selected git-show-uptodate]
  1365. ["Show Ignored Files" git-toggle-show-ignored :style toggle :selected git-show-ignored]
  1366. ["Show Unknown Files" git-toggle-show-unknown :style toggle :selected git-show-unknown]
  1367. "--------"
  1368. ["Quit" git-status-quit t])))
  1369. ;; git mode should only run in the *git status* buffer
  1370. (put 'git-status-mode 'mode-class 'special)
  1371. (defun git-status-mode ()
  1372. "Major mode for interacting with Git.
  1373. Commands:
  1374. \\{git-status-mode-map}"
  1375. (kill-all-local-variables)
  1376. (buffer-disable-undo)
  1377. (setq mode-name "git status"
  1378. major-mode 'git-status-mode
  1379. goal-column 17
  1380. buffer-read-only t)
  1381. (use-local-map git-status-mode-map)
  1382. (let ((buffer-read-only nil))
  1383. (erase-buffer)
  1384. (let ((status (ewoc-create 'git-fileinfo-prettyprint "" "")))
  1385. (set (make-local-variable 'git-status) status))
  1386. (set (make-local-variable 'list-buffers-directory) default-directory)
  1387. (make-local-variable 'git-show-uptodate)
  1388. (make-local-variable 'git-show-ignored)
  1389. (make-local-variable 'git-show-unknown)
  1390. (run-hooks 'git-status-mode-hook)))
  1391. (defun git-find-status-buffer (dir)
  1392. "Find the git status buffer handling a specified directory."
  1393. (let ((list (buffer-list))
  1394. (fulldir (expand-file-name dir))
  1395. found)
  1396. (while (and list (not found))
  1397. (let ((buffer (car list)))
  1398. (with-current-buffer buffer
  1399. (when (and list-buffers-directory
  1400. (string-equal fulldir (expand-file-name list-buffers-directory))
  1401. (eq major-mode 'git-status-mode))
  1402. (setq found buffer))))
  1403. (setq list (cdr list)))
  1404. found))
  1405. (defun git-status (dir)
  1406. "Entry point into git-status mode."
  1407. (interactive "DSelect directory: ")
  1408. (setq dir (git-get-top-dir dir))
  1409. (if (file-directory-p (concat (file-name-as-directory dir) ".git"))
  1410. (let ((buffer (or (and git-reuse-status-buffer (git-find-status-buffer dir))
  1411. (create-file-buffer (expand-file-name "*git-status*" dir)))))
  1412. (switch-to-buffer buffer)
  1413. (cd dir)
  1414. (git-status-mode)
  1415. (git-refresh-status)
  1416. (goto-char (point-min))
  1417. (add-hook 'after-save-hook 'git-update-saved-file))
  1418. (message "%s is not a git working tree." dir)))
  1419. (defun git-update-saved-file ()
  1420. "Update the corresponding git-status buffer when a file is saved.
  1421. Meant to be used in `after-save-hook'."
  1422. (let* ((file (expand-file-name buffer-file-name))
  1423. (dir (condition-case nil (git-get-top-dir (file-name-directory file)) (error nil)))
  1424. (buffer (and dir (git-find-status-buffer dir))))
  1425. (when buffer
  1426. (with-current-buffer buffer
  1427. (let ((filename (file-relative-name file dir)))
  1428. ; skip files located inside the .git directory
  1429. (unless (string-match "^\\.git/" filename)
  1430. (git-call-process-env nil nil "add" "--refresh" "--" filename)
  1431. (git-update-status-files (list filename) 'uptodate)))))))
  1432. (defun git-help ()
  1433. "Display help for Git mode."
  1434. (interactive)
  1435. (describe-function 'git-status-mode))
  1436. (provide 'git)
  1437. ;;; git.el ends here