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