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