]> asedeno.scripts.mit.edu Git - git.git/blob - contrib/emacs/git.el
git.el: Avoid setting font lock keywords before entering log-edit mode.
[git.git] / contrib / emacs / git.el
1 ;;; git.el --- A user interface for git
2
3 ;; Copyright (C) 2005, 2006 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 ;;  - better handling of subprocess errors
39 ;;  - hook into file save (after-save-hook)
40 ;;  - diff against other branch
41 ;;  - renaming files from the status buffer
42 ;;  - creating tags
43 ;;  - fetch/pull
44 ;;  - switching branches
45 ;;  - revlist browser
46 ;;  - git-show-branch browser
47 ;;  - menus
48 ;;
49
50 (eval-when-compile (require 'cl))
51 (require 'ewoc)
52 (require 'log-edit)
53
54
55 ;;;; Customizations
56 ;;;; ------------------------------------------------------------
57
58 (defgroup git nil
59   "A user interface for the git versioning system."
60   :group 'tools)
61
62 (defcustom git-committer-name nil
63   "User name to use for commits.
64 The default is to fall back to the repository config,
65 then to `add-log-full-name' and then to `user-full-name'."
66   :group 'git
67   :type '(choice (const :tag "Default" nil)
68                  (string :tag "Name")))
69
70 (defcustom git-committer-email nil
71   "Email address to use for commits.
72 The default is to fall back to the git repository config,
73 then to `add-log-mailing-address' and then to `user-mail-address'."
74   :group 'git
75   :type '(choice (const :tag "Default" nil)
76                  (string :tag "Email")))
77
78 (defcustom git-commits-coding-system 'utf-8
79   "Default coding system for the log message of git commits."
80   :group 'git
81   :type '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
90 if 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
100 (defface git-status-face
101   '((((class color) (background light)) (:foreground "purple")))
102   "Git mode face used to highlight added and modified files."
103   :group 'git)
104
105 (defface git-unmerged-face
106   '((((class color) (background light)) (:foreground "red" :bold t)))
107   "Git mode face used to highlight unmerged files."
108   :group 'git)
109
110 (defface git-unknown-face
111   '((((class color) (background light)) (:foreground "goldenrod" :bold t)))
112   "Git mode face used to highlight unknown files."
113   :group 'git)
114
115 (defface git-uptodate-face
116   '((((class color) (background light)) (:foreground "grey60")))
117   "Git mode face used to highlight up-to-date files."
118   :group 'git)
119
120 (defface git-ignored-face
121   '((((class color) (background light)) (:foreground "grey60")))
122   "Git mode face used to highlight ignored files."
123   :group 'git)
124
125 (defface git-mark-face
126   '((((class color) (background light)) (:foreground "red" :bold t)))
127   "Git mode face used for the file marks."
128   :group 'git)
129
130 (defface git-header-face
131   '((((class color) (background light)) (:foreground "blue")))
132   "Git mode face used for commit headers."
133   :group 'git)
134
135 (defface git-separator-face
136   '((((class color) (background light)) (:foreground "brown")))
137   "Git mode face used for commit separator."
138   :group 'git)
139
140 (defface git-permission-face
141   '((((class color) (background light)) (:foreground "green" :bold t)))
142   "Git mode face used for permission changes."
143   :group 'git)
144
145
146 ;;;; Utilities
147 ;;;; ------------------------------------------------------------
148
149 (defconst git-log-msg-separator "--- log message follows this line ---")
150
151 (defvar git-log-edit-font-lock-keywords
152   `(("^\\(Author:\\|Date:\\|Parent:\\|Signed-off-by:\\)\\(.*\\)$"
153      (1 font-lock-keyword-face)
154      (2 font-lock-function-name-face))
155     (,(concat "^\\(" (regexp-quote git-log-msg-separator) "\\)$")
156      (1 font-lock-comment-face))))
157
158 (defun git-get-env-strings (env)
159   "Build a list of NAME=VALUE strings from a list of environment strings."
160   (mapcar (lambda (entry) (concat (car entry) "=" (cdr entry))) env))
161
162 (defun git-call-process-env (buffer env &rest args)
163   "Wrapper for call-process that sets environment strings."
164   (if env
165       (apply #'call-process "env" nil buffer nil
166              (append (git-get-env-strings env) (list "git") args))
167     (apply #'call-process "git" nil buffer nil args)))
168
169 (defun git-call-process-env-string (env &rest args)
170   "Wrapper for call-process that sets environment strings,
171 and returns the process output as a string."
172   (with-temp-buffer
173     (and (eq 0 (apply #' git-call-process-env t env args))
174          (buffer-string))))
175
176 (defun git-run-process-region (buffer start end program args)
177   "Run a git process with a buffer region as input."
178   (let ((output-buffer (current-buffer))
179         (dir default-directory))
180     (with-current-buffer buffer
181       (cd dir)
182       (apply #'call-process-region start end program
183              nil (list output-buffer nil) nil args))))
184
185 (defun git-run-command-buffer (buffer-name &rest args)
186   "Run a git command, sending the output to a buffer named BUFFER-NAME."
187   (let ((dir default-directory)
188         (buffer (get-buffer-create buffer-name)))
189     (message "Running git %s..." (car args))
190     (with-current-buffer buffer
191       (let ((default-directory dir)
192             (buffer-read-only nil))
193         (erase-buffer)
194         (apply #'git-call-process-env buffer nil args)))
195     (message "Running git %s...done" (car args))
196     buffer))
197
198 (defun git-run-command (buffer env &rest args)
199   (message "Running git %s..." (car args))
200   (apply #'git-call-process-env buffer env args)
201   (message "Running git %s...done" (car args)))
202
203 (defun git-run-command-region (buffer start end env &rest args)
204   "Run a git command with specified buffer region as input."
205   (message "Running git %s..." (car args))
206   (unless (eq 0 (if env
207                     (git-run-process-region
208                      buffer start end "env"
209                      (append (git-get-env-strings env) (list "git") args))
210                   (git-run-process-region
211                    buffer start end "git" args)))
212     (error "Failed to run \"git %s\":\n%s" (mapconcat (lambda (x) x) args " ") (buffer-string)))
213   (message "Running git %s...done" (car args)))
214
215 (defun git-get-string-sha1 (string)
216   "Read a SHA1 from the specified string."
217   (and string
218        (string-match "[0-9a-f]\\{40\\}" string)
219        (match-string 0 string)))
220
221 (defun git-get-committer-name ()
222   "Return the name to use as GIT_COMMITTER_NAME."
223   ; copied from log-edit
224   (or git-committer-name
225       (git-repo-config "user.name")
226       (and (boundp 'add-log-full-name) add-log-full-name)
227       (and (fboundp 'user-full-name) (user-full-name))
228       (and (boundp 'user-full-name) user-full-name)))
229
230 (defun git-get-committer-email ()
231   "Return the email address to use as GIT_COMMITTER_EMAIL."
232   ; copied from log-edit
233   (or git-committer-email
234       (git-repo-config "user.email")
235       (and (boundp 'add-log-mailing-address) add-log-mailing-address)
236       (and (fboundp 'user-mail-address) (user-mail-address))
237       (and (boundp 'user-mail-address) user-mail-address)))
238
239 (defun git-escape-file-name (name)
240   "Escape a file name if necessary."
241   (if (string-match "[\n\t\"\\]" name)
242       (concat "\""
243               (mapconcat (lambda (c)
244                    (case c
245                      (?\n "\\n")
246                      (?\t "\\t")
247                      (?\\ "\\\\")
248                      (?\" "\\\"")
249                      (t (char-to-string c))))
250                  name "")
251               "\"")
252     name))
253
254 (defun git-get-top-dir (dir)
255   "Retrieve the top-level directory of a git tree."
256   (let ((cdup (with-output-to-string
257                 (with-current-buffer standard-output
258                   (cd dir)
259                   (unless (eq 0 (call-process "git" nil t nil "rev-parse" "--show-cdup"))
260                     (error "cannot find top-level git tree for %s." dir))))))
261     (expand-file-name (concat (file-name-as-directory dir)
262                               (car (split-string cdup "\n"))))))
263
264 ;stolen from pcl-cvs
265 (defun git-append-to-ignore (file)
266   "Add a file name to the ignore file in its directory."
267   (let* ((fullname (expand-file-name file))
268          (dir (file-name-directory fullname))
269          (name (file-name-nondirectory fullname))
270          (ignore-name (expand-file-name git-per-dir-ignore-file dir))
271          (created (not (file-exists-p ignore-name))))
272   (save-window-excursion
273     (set-buffer (find-file-noselect ignore-name))
274     (goto-char (point-max))
275     (unless (zerop (current-column)) (insert "\n"))
276     (insert "/" name "\n")
277     (sort-lines nil (point-min) (point-max))
278     (save-buffer))
279   (when created
280     (git-run-command nil nil "update-index" "--info-only" "--add" "--" (file-relative-name ignore-name)))
281   (git-add-status-file (if created 'added 'modified) (file-relative-name ignore-name))))
282
283
284 ;;;; Wrappers for basic git commands
285 ;;;; ------------------------------------------------------------
286
287 (defun git-rev-parse (rev)
288   "Parse a revision name and return its SHA1."
289   (git-get-string-sha1
290    (git-call-process-env-string nil "rev-parse" rev)))
291
292 (defun git-repo-config (key)
293   "Retrieve the value associated to KEY in the git repository config file."
294   (let ((str (git-call-process-env-string nil "repo-config" key)))
295     (and str (car (split-string str "\n")))))
296
297 (defun git-symbolic-ref (ref)
298   "Wrapper for the git-symbolic-ref command."
299   (let ((str (git-call-process-env-string nil "symbolic-ref" ref)))
300     (and str (car (split-string str "\n")))))
301
302 (defun git-update-ref (ref val &optional oldval)
303   "Update a reference by calling git-update-ref."
304   (apply #'git-call-process-env nil nil "update-ref" ref val (if oldval (list oldval))))
305
306 (defun git-read-tree (tree &optional index-file)
307   "Read a tree into the index file."
308   (apply #'git-call-process-env nil
309          (if index-file `(("GIT_INDEX_FILE" . ,index-file)) nil)
310          "read-tree" (if tree (list tree))))
311
312 (defun git-write-tree (&optional index-file)
313   "Call git-write-tree and return the resulting tree SHA1 as a string."
314   (git-get-string-sha1
315    (git-call-process-env-string (and index-file `(("GIT_INDEX_FILE" . ,index-file))) "write-tree")))
316
317 (defun git-commit-tree (buffer tree head)
318   "Call git-commit-tree with buffer as input and return the resulting commit SHA1."
319   (let ((author-name (git-get-committer-name))
320         (author-email (git-get-committer-email))
321         author-date log-start log-end args)
322     (when head
323       (push "-p" args)
324       (push head args))
325     (with-current-buffer buffer
326       (goto-char (point-min))
327       (if
328           (setq log-start (re-search-forward (concat "^" (regexp-quote git-log-msg-separator) "\n") nil t))
329           (save-restriction
330             (narrow-to-region (point-min) log-start)
331             (goto-char (point-min))
332             (when (re-search-forward "^Author: +\\(.*?\\) *<\\(.*\\)> *$" nil t)
333               (setq author-name (match-string 1)
334                     author-email (match-string 2)))
335             (goto-char (point-min))
336             (when (re-search-forward "^Date: +\\(.*\\)$" nil t)
337               (setq author-date (match-string 1)))
338             (goto-char (point-min))
339             (while (re-search-forward "^Parent: +\\([0-9a-f]+\\)" nil t)
340               (unless (string-equal head (match-string 1))
341                 (push "-p" args)
342                 (push (match-string 1) args))))
343         (setq log-start (point-min)))
344       (setq log-end (point-max)))
345     (git-get-string-sha1
346      (with-output-to-string
347        (with-current-buffer standard-output
348          (let ((coding-system-for-write git-commits-coding-system)
349                (env `(("GIT_AUTHOR_NAME" . ,author-name)
350                       ("GIT_AUTHOR_EMAIL" . ,author-email)
351                       ("GIT_COMMITTER_NAME" . ,(git-get-committer-name))
352                       ("GIT_COMMITTER_EMAIL" . ,(git-get-committer-email)))))
353            (when author-date (push `("GIT_AUTHOR_DATE" . ,author-date) env))
354            (apply #'git-run-command-region
355                   buffer log-start log-end env
356                   "commit-tree" tree (nreverse args))))))))
357
358 (defun git-empty-db-p ()
359   "Check if the git db is empty (no commit done yet)."
360   (not (eq 0 (call-process "git" nil nil nil "rev-parse" "--verify" "HEAD"))))
361
362 (defun git-get-merge-heads ()
363   "Retrieve the merge heads from the MERGE_HEAD file if present."
364   (let (heads)
365     (when (file-readable-p ".git/MERGE_HEAD")
366       (with-temp-buffer
367         (insert-file-contents ".git/MERGE_HEAD" nil nil nil t)
368         (goto-char (point-min))
369         (while (re-search-forward "[0-9a-f]\\{40\\}" nil t)
370           (push (match-string 0) heads))))
371     (nreverse heads)))
372
373 ;;;; File info structure
374 ;;;; ------------------------------------------------------------
375
376 ; fileinfo structure stolen from pcl-cvs
377 (defstruct (git-fileinfo
378             (:copier nil)
379             (:constructor git-create-fileinfo (state name &optional old-perm new-perm rename-state orig-name marked))
380             (:conc-name git-fileinfo->))
381   marked              ;; t/nil
382   state               ;; current state
383   name                ;; file name
384   old-perm new-perm   ;; permission flags
385   rename-state        ;; rename or copy state
386   orig-name           ;; original name for renames or copies
387   needs-refresh)      ;; whether file needs to be refreshed
388
389 (defvar git-status nil)
390
391 (defun git-clear-status (status)
392   "Remove everything from the status list."
393   (ewoc-filter status (lambda (info) nil)))
394
395 (defun git-set-files-state (files state)
396   "Set the state of a list of files."
397   (dolist (info files)
398     (unless (eq (git-fileinfo->state info) state)
399       (setf (git-fileinfo->state info) state)
400       (setf (git-fileinfo->rename-state info) nil)
401       (setf (git-fileinfo->orig-name info) nil)
402       (setf (git-fileinfo->needs-refresh info) t))))
403
404 (defun git-state-code (code)
405   "Convert from a string to a added/deleted/modified state."
406   (case (string-to-char code)
407     (?M 'modified)
408     (?? 'unknown)
409     (?A 'added)
410     (?D 'deleted)
411     (?U 'unmerged)
412     (t nil)))
413
414 (defun git-status-code-as-string (code)
415   "Format a git status code as string."
416   (case code
417     ('modified (propertize "Modified" 'face 'git-status-face))
418     ('unknown  (propertize "Unknown " 'face 'git-unknown-face))
419     ('added    (propertize "Added   " 'face 'git-status-face))
420     ('deleted  (propertize "Deleted " 'face 'git-status-face))
421     ('unmerged (propertize "Unmerged" 'face 'git-unmerged-face))
422     ('uptodate (propertize "Uptodate" 'face 'git-uptodate-face))
423     ('ignored  (propertize "Ignored " 'face 'git-ignored-face))
424     (t "?       ")))
425
426 (defun git-rename-as-string (info)
427   "Return a string describing the copy or rename associated with INFO, or an empty string if none."
428   (let ((state (git-fileinfo->rename-state info)))
429     (if state
430         (propertize
431          (concat "   ("
432                  (if (eq state 'copy) "copied from "
433                    (if (eq (git-fileinfo->state info) 'added) "renamed from "
434                      "renamed to "))
435                  (git-escape-file-name (git-fileinfo->orig-name info))
436                  ")") 'face 'git-status-face)
437       "")))
438
439 (defun git-permissions-as-string (old-perm new-perm)
440   "Format a permission change as string."
441   (propertize
442    (if (or (not old-perm)
443            (not new-perm)
444            (eq 0 (logand ?\111 (logxor old-perm new-perm))))
445        "  "
446      (if (eq 0 (logand ?\111 old-perm)) "+x" "-x"))
447   'face 'git-permission-face))
448
449 (defun git-fileinfo-prettyprint (info)
450   "Pretty-printer for the git-fileinfo structure."
451   (insert (format "   %s %s %s  %s%s"
452                   (if (git-fileinfo->marked info) (propertize "*" 'face 'git-mark-face) " ")
453                   (git-status-code-as-string (git-fileinfo->state info))
454                   (git-permissions-as-string (git-fileinfo->old-perm info) (git-fileinfo->new-perm info))
455                   (git-escape-file-name (git-fileinfo->name info))
456                   (git-rename-as-string info))))
457
458 (defun git-parse-status (status)
459   "Parse the output of git-diff-index in the current buffer."
460   (goto-char (point-min))
461   (while (re-search-forward
462           ":\\([0-7]\\{6\\}\\) \\([0-7]\\{6\\}\\) [0-9a-f]\\{40\\} [0-9a-f]\\{40\\} \\(\\([ADMU]\\)\0\\([^\0]+\\)\\|\\([CR]\\)[0-9]*\0\\([^\0]+\\)\0\\([^\0]+\\)\\)\0"
463           nil t 1)
464     (let ((old-perm (string-to-number (match-string 1) 8))
465           (new-perm (string-to-number (match-string 2) 8))
466           (state (or (match-string 4) (match-string 6)))
467           (name (or (match-string 5) (match-string 7)))
468           (new-name (match-string 8)))
469       (if new-name  ; copy or rename
470           (if (eq ?C (string-to-char state))
471               (ewoc-enter-last status (git-create-fileinfo 'added new-name old-perm new-perm 'copy name))
472             (ewoc-enter-last status (git-create-fileinfo 'deleted name 0 0 'rename new-name))
473             (ewoc-enter-last status (git-create-fileinfo 'added new-name old-perm new-perm 'rename name)))
474         (ewoc-enter-last status (git-create-fileinfo (git-state-code state) name old-perm new-perm))))))
475
476 (defun git-find-status-file (status file)
477   "Find a given file in the status ewoc and return its node."
478   (let ((node (ewoc-nth status 0)))
479     (while (and node (not (string= file (git-fileinfo->name (ewoc-data node)))))
480       (setq node (ewoc-next status node)))
481     node))
482
483 (defun git-parse-ls-files (status default-state &optional skip-existing)
484   "Parse the output of git-ls-files in the current buffer."
485   (goto-char (point-min))
486   (let (infolist)
487     (while (re-search-forward "\\([HMRCK?]\\) \\([^\0]*\\)\0" nil t 1)
488       (let ((state (match-string 1))
489             (name (match-string 2)))
490         (unless (and skip-existing (git-find-status-file status name))
491           (push (git-create-fileinfo (or (git-state-code state) default-state) name) infolist))))
492     (dolist (info (nreverse infolist))
493       (ewoc-enter-last status info))))
494
495 (defun git-parse-ls-unmerged (status)
496   "Parse the output of git-ls-files -u in the current buffer."
497   (goto-char (point-min))
498   (let (files)
499     (while (re-search-forward "[0-7]\\{6\\} [0-9a-f]\\{40\\} [123]\t\\([^\0]+\\)\0" nil t)
500       (let ((node (git-find-status-file status (match-string 1))))
501         (when node (push (ewoc-data node) files))))
502     (git-set-files-state files 'unmerged)))
503
504 (defun git-add-status-file (state name)
505   "Add a new file to the status list (if not existing already) and return its node."
506   (unless git-status (error "Not in git-status buffer."))
507   (or (git-find-status-file git-status name)
508       (ewoc-enter-last git-status (git-create-fileinfo state name))))
509
510 (defun git-marked-files ()
511   "Return a list of all marked files, or if none a list containing just the file at cursor position."
512   (unless git-status (error "Not in git-status buffer."))
513   (or (ewoc-collect git-status (lambda (info) (git-fileinfo->marked info)))
514       (list (ewoc-data (ewoc-locate git-status)))))
515
516 (defun git-marked-files-state (&rest states)
517   "Return marked files that are in the specified states."
518   (let ((files (git-marked-files))
519         result)
520     (dolist (info files)
521       (when (memq (git-fileinfo->state info) states)
522         (push info result)))
523     result))
524
525 (defun git-refresh-files ()
526   "Refresh all files that need it and clear the needs-refresh flag."
527   (unless git-status (error "Not in git-status buffer."))
528   (ewoc-map
529    (lambda (info)
530      (let ((refresh (git-fileinfo->needs-refresh info)))
531        (setf (git-fileinfo->needs-refresh info) nil)
532        refresh))
533    git-status)
534   ; move back to goal column
535   (when goal-column (move-to-column goal-column)))
536
537 (defun git-refresh-ewoc-hf (status)
538   "Refresh the ewoc header and footer."
539   (let ((branch (git-symbolic-ref "HEAD"))
540         (head (if (git-empty-db-p) "Nothing committed yet"
541                 (substring (git-rev-parse "HEAD") 0 10)))
542         (merge-heads (git-get-merge-heads)))
543     (ewoc-set-hf status
544                  (format "Directory:  %s\nBranch:     %s\nHead:       %s%s\n"
545                          default-directory
546                          (if (string-match "^refs/heads/" branch)
547                              (substring branch (match-end 0))
548                            branch)
549                          head
550                          (if merge-heads
551                              (concat "\nMerging:    "
552                                      (mapconcat (lambda (str) (substring str 0 10)) merge-heads " "))
553                            ""))
554                  (if (ewoc-nth status 0) "" "    No changes."))))
555
556 (defun git-get-filenames (files)
557   (mapcar (lambda (info) (git-fileinfo->name info)) files))
558
559 (defun git-update-index (index-file files)
560   "Run git-update-index on a list of files."
561   (let ((env (and index-file `(("GIT_INDEX_FILE" . ,index-file))))
562         added deleted modified)
563     (dolist (info files)
564       (case (git-fileinfo->state info)
565         ('added (push info added))
566         ('deleted (push info deleted))
567         ('modified (push info modified))))
568     (when added
569       (apply #'git-run-command nil env "update-index" "--add" "--" (git-get-filenames added)))
570     (when deleted
571       (apply #'git-run-command nil env "update-index" "--remove" "--" (git-get-filenames deleted)))
572     (when modified
573       (apply #'git-run-command nil env "update-index" "--" (git-get-filenames modified)))))
574
575 (defun git-do-commit ()
576   "Perform the actual commit using the current buffer as log message."
577   (interactive)
578   (let ((buffer (current-buffer))
579         (index-file (make-temp-file "gitidx")))
580     (with-current-buffer log-edit-parent-buffer
581       (if (git-marked-files-state 'unmerged)
582           (message "You cannot commit unmerged files, resolve them first.")
583         (unwind-protect
584             (let ((files (git-marked-files-state 'added 'deleted 'modified))
585                   head head-tree)
586               (unless (git-empty-db-p)
587                 (setq head (git-rev-parse "HEAD")
588                       head-tree (git-rev-parse "HEAD^{tree}")))
589               (if files
590                   (progn
591                     (git-read-tree head-tree index-file)
592                     (git-update-index nil files)         ;update both the default index
593                     (git-update-index index-file files)  ;and the temporary one
594                     (let ((tree (git-write-tree index-file)))
595                       (if (or (not (string-equal tree head-tree))
596                               (yes-or-no-p "The tree was not modified, do you really want to perform an empty commit? "))
597                           (let ((commit (git-commit-tree buffer tree head)))
598                             (git-update-ref "HEAD" commit head)
599                             (condition-case nil (delete-file ".git/MERGE_HEAD") (error nil))
600                             (condition-case nil (delete-file ".git/MERGE_MSG") (error nil))
601                             (with-current-buffer buffer (erase-buffer))
602                             (git-set-files-state files 'uptodate)
603                             (when (file-directory-p ".git/rr-cache")
604                               (git-run-command nil nil "rerere"))
605                             (git-refresh-files)
606                             (git-refresh-ewoc-hf git-status)
607                             (message "Committed %s." commit))
608                         (message "Commit aborted."))))
609                 (message "No files to commit.")))
610           (delete-file index-file))))))
611
612
613 ;;;; Interactive functions
614 ;;;; ------------------------------------------------------------
615
616 (defun git-mark-file ()
617   "Mark the file that the cursor is on and move to the next one."
618   (interactive)
619   (unless git-status (error "Not in git-status buffer."))
620   (let* ((pos (ewoc-locate git-status))
621          (info (ewoc-data pos)))
622     (setf (git-fileinfo->marked info) t)
623     (ewoc-invalidate git-status pos)
624     (ewoc-goto-next git-status 1)))
625
626 (defun git-unmark-file ()
627   "Unmark the file that the cursor is on and move to the next one."
628   (interactive)
629   (unless git-status (error "Not in git-status buffer."))
630   (let* ((pos (ewoc-locate git-status))
631          (info (ewoc-data pos)))
632     (setf (git-fileinfo->marked info) nil)
633     (ewoc-invalidate git-status pos)
634     (ewoc-goto-next git-status 1)))
635
636 (defun git-unmark-file-up ()
637   "Unmark the file that the cursor is on and move to the previous one."
638   (interactive)
639   (unless git-status (error "Not in git-status buffer."))
640   (let* ((pos (ewoc-locate git-status))
641          (info (ewoc-data pos)))
642     (setf (git-fileinfo->marked info) nil)
643     (ewoc-invalidate git-status pos)
644     (ewoc-goto-prev git-status 1)))
645
646 (defun git-mark-all ()
647   "Mark all files."
648   (interactive)
649   (unless git-status (error "Not in git-status buffer."))
650   (ewoc-map (lambda (info) (setf (git-fileinfo->marked info) t) t) git-status)
651   ; move back to goal column after invalidate
652   (when goal-column (move-to-column goal-column)))
653
654 (defun git-unmark-all ()
655   "Unmark all files."
656   (interactive)
657   (unless git-status (error "Not in git-status buffer."))
658   (ewoc-map (lambda (info) (setf (git-fileinfo->marked info) nil) t) git-status)
659   ; move back to goal column after invalidate
660   (when goal-column (move-to-column goal-column)))
661
662 (defun git-toggle-all-marks ()
663   "Toggle all file marks."
664   (interactive)
665   (unless git-status (error "Not in git-status buffer."))
666   (ewoc-map (lambda (info) (setf (git-fileinfo->marked info) (not (git-fileinfo->marked info))) t) git-status)
667   ; move back to goal column after invalidate
668   (when goal-column (move-to-column goal-column)))
669
670 (defun git-next-file (&optional n)
671   "Move the selection down N files."
672   (interactive "p")
673   (unless git-status (error "Not in git-status buffer."))
674   (ewoc-goto-next git-status n))
675
676 (defun git-prev-file (&optional n)
677   "Move the selection up N files."
678   (interactive "p")
679   (unless git-status (error "Not in git-status buffer."))
680   (ewoc-goto-prev git-status n))
681
682 (defun git-next-unmerged-file (&optional n)
683   "Move the selection down N unmerged files."
684   (interactive "p")
685   (unless git-status (error "Not in git-status buffer."))
686   (let* ((last (ewoc-locate git-status))
687          (node (ewoc-next git-status last)))
688     (while (and node (> n 0))
689       (when (eq 'unmerged (git-fileinfo->state (ewoc-data node)))
690         (setq n (1- n))
691         (setq last node))
692       (setq node (ewoc-next git-status node)))
693     (ewoc-goto-node git-status last)))
694
695 (defun git-prev-unmerged-file (&optional n)
696   "Move the selection up N unmerged files."
697   (interactive "p")
698   (unless git-status (error "Not in git-status buffer."))
699   (let* ((last (ewoc-locate git-status))
700          (node (ewoc-prev git-status last)))
701     (while (and node (> n 0))
702       (when (eq 'unmerged (git-fileinfo->state (ewoc-data node)))
703         (setq n (1- n))
704         (setq last node))
705       (setq node (ewoc-prev git-status node)))
706     (ewoc-goto-node git-status last)))
707
708 (defun git-add-file ()
709   "Add marked file(s) to the index cache."
710   (interactive)
711   (let ((files (git-marked-files-state 'unknown)))
712     (unless files
713       (push (ewoc-data
714              (git-add-status-file 'added (file-relative-name
715                                           (read-file-name "File to add: " nil nil t))))
716             files))
717     (apply #'git-run-command nil nil "update-index" "--info-only" "--add" "--" (git-get-filenames files))
718     (git-set-files-state files 'added)
719     (git-refresh-files)))
720
721 (defun git-ignore-file ()
722   "Add marked file(s) to the ignore list."
723   (interactive)
724   (let ((files (git-marked-files-state 'unknown)))
725     (unless files
726       (push (ewoc-data
727              (git-add-status-file 'unknown (file-relative-name
728                                             (read-file-name "File to ignore: " nil nil t))))
729             files))
730     (dolist (info files) (git-append-to-ignore (git-fileinfo->name info)))
731     (git-set-files-state files 'ignored)
732     (git-refresh-files)))
733
734 (defun git-remove-file ()
735   "Remove the marked file(s)."
736   (interactive)
737   (let ((files (git-marked-files-state 'added 'modified 'unknown 'uptodate)))
738     (unless files
739       (push (ewoc-data
740              (git-add-status-file 'unknown (file-relative-name
741                                             (read-file-name "File to remove: " nil nil t))))
742             files))
743     (if (yes-or-no-p
744          (format "Remove %d file%s? " (length files) (if (> (length files) 1) "s" "")))
745         (progn
746           (dolist (info files)
747             (let ((name (git-fileinfo->name info)))
748               (when (file-exists-p name) (delete-file name))))
749           (apply #'git-run-command nil nil "update-index" "--info-only" "--remove" "--" (git-get-filenames files))
750           ; remove unknown files from the list, set the others to deleted
751           (ewoc-filter git-status
752                        (lambda (info files)
753                          (not (and (memq info files) (eq (git-fileinfo->state info) 'unknown))))
754                        files)
755           (git-set-files-state files 'deleted)
756           (git-refresh-files)
757           (unless (ewoc-nth git-status 0)  ; refresh header if list is empty
758             (git-refresh-ewoc-hf git-status)))
759       (message "Aborting"))))
760
761 (defun git-revert-file ()
762   "Revert changes to the marked file(s)."
763   (interactive)
764   (let ((files (git-marked-files))
765         added modified)
766     (when (and files
767                (yes-or-no-p
768                 (format "Revert %d file%s? " (length files) (if (> (length files) 1) "s" ""))))
769       (dolist (info files)
770         (case (git-fileinfo->state info)
771           ('added (push info added))
772           ('deleted (push info modified))
773           ('unmerged (push info modified))
774           ('modified (push info modified))))
775       (when added
776           (apply #'git-run-command nil nil "update-index" "--force-remove" "--" (git-get-filenames added))
777           (git-set-files-state added 'unknown))
778       (when modified
779           (apply #'git-run-command nil nil "checkout" "HEAD" (git-get-filenames modified))
780           (git-set-files-state modified 'uptodate))
781       (git-refresh-files))))
782
783 (defun git-resolve-file ()
784   "Resolve conflicts in marked file(s)."
785   (interactive)
786   (let ((files (git-marked-files-state 'unmerged)))
787     (when files
788       (apply #'git-run-command nil nil "update-index" "--" (git-get-filenames files))
789       (git-set-files-state files 'modified)
790       (git-refresh-files))))
791
792 (defun git-remove-handled ()
793   "Remove handled files from the status list."
794   (interactive)
795   (ewoc-filter git-status
796                (lambda (info)
797                  (not (or (eq (git-fileinfo->state info) 'ignored)
798                           (eq (git-fileinfo->state info) 'uptodate)))))
799   (unless (ewoc-nth git-status 0)  ; refresh header if list is empty
800     (git-refresh-ewoc-hf git-status)))
801
802 (defun git-setup-diff-buffer (buffer)
803   "Setup a buffer for displaying a diff."
804   (with-current-buffer buffer
805     (diff-mode)
806     (goto-char (point-min))
807     (setq buffer-read-only t))
808   (display-buffer buffer)
809   (shrink-window-if-larger-than-buffer))
810
811 (defun git-diff-file ()
812   "Diff the marked file(s) against HEAD."
813   (interactive)
814   (let ((files (git-marked-files)))
815     (git-setup-diff-buffer
816      (apply #'git-run-command-buffer "*git-diff*" "diff-index" "-p" "-M" "HEAD" "--" (git-get-filenames files)))))
817
818 (defun git-diff-file-merge-head (arg)
819   "Diff the marked file(s) against the first merge head (or the nth one with a numeric prefix)."
820   (interactive "p")
821   (let ((files (git-marked-files))
822         (merge-heads (git-get-merge-heads)))
823     (unless merge-heads (error "No merge in progress"))
824     (git-setup-diff-buffer
825      (apply #'git-run-command-buffer "*git-diff*" "diff-index" "-p" "-M"
826             (or (nth (1- arg) merge-heads) "HEAD") "--" (git-get-filenames files)))))
827
828 (defun git-diff-unmerged-file (stage)
829   "Diff the marked unmerged file(s) against the specified stage."
830   (let ((files (git-marked-files)))
831     (git-setup-diff-buffer
832      (apply #'git-run-command-buffer "*git-diff*" "diff-files" "-p" stage "--" (git-get-filenames files)))))
833
834 (defun git-diff-file-base ()
835   "Diff the marked unmerged file(s) against the common base file."
836   (interactive)
837   (git-diff-unmerged-file "-1"))
838
839 (defun git-diff-file-mine ()
840   "Diff the marked unmerged file(s) against my pre-merge version."
841   (interactive)
842   (git-diff-unmerged-file "-2"))
843
844 (defun git-diff-file-other ()
845   "Diff the marked unmerged file(s) against the other's pre-merge version."
846   (interactive)
847   (git-diff-unmerged-file "-3"))
848
849 (defun git-diff-file-combined ()
850   "Do a combined diff of the marked unmerged file(s)."
851   (interactive)
852   (git-diff-unmerged-file "-c"))
853
854 (defun git-diff-file-idiff ()
855   "Perform an interactive diff on the current file."
856   (interactive)
857   (error "Interactive diffs not implemented yet."))
858
859 (defun git-log-file ()
860   "Display a log of changes to the marked file(s)."
861   (interactive)
862   (let* ((files (git-marked-files))
863          (coding-system-for-read git-commits-coding-system)
864          (buffer (apply #'git-run-command-buffer "*git-log*" "rev-list" "--pretty" "HEAD" "--" (git-get-filenames files))))
865     (with-current-buffer buffer
866       ; (git-log-mode)  FIXME: implement log mode
867       (goto-char (point-min))
868       (setq buffer-read-only t))
869     (display-buffer buffer)))
870
871 (defun git-log-edit-files ()
872   "Return a list of marked files for use in the log-edit buffer."
873   (with-current-buffer log-edit-parent-buffer
874     (git-get-filenames (git-marked-files-state 'added 'deleted 'modified))))
875
876 (defun git-commit-file ()
877   "Commit the marked file(s), asking for a commit message."
878   (interactive)
879   (unless git-status (error "Not in git-status buffer."))
880   (let ((buffer (get-buffer-create "*git-commit*"))
881         (merge-heads (git-get-merge-heads))
882         (dir default-directory)
883         (sign-off git-append-signed-off-by))
884     (with-current-buffer buffer
885       (when (eq 0 (buffer-size))
886         (cd dir)
887         (erase-buffer)
888         (insert
889          (propertize
890           (format "Author: %s <%s>\n%s"
891                   (git-get-committer-name) (git-get-committer-email)
892                   (if merge-heads
893                       (format "Parent: %s\n%s\n"
894                               (git-rev-parse "HEAD")
895                               (mapconcat (lambda (str) (concat "Parent: " str)) merge-heads "\n"))
896                     ""))
897           'face 'git-header-face)
898          (propertize git-log-msg-separator 'face 'git-separator-face)
899          "\n")
900         (cond ((file-readable-p ".git/MERGE_MSG")
901                (insert-file-contents ".git/MERGE_MSG"))
902               (sign-off
903                (insert (format "\n\nSigned-off-by: %s <%s>\n"
904                                (git-get-committer-name) (git-get-committer-email)))))))
905     (log-edit #'git-do-commit nil #'git-log-edit-files buffer)
906     (setq font-lock-keywords (font-lock-compile-keywords git-log-edit-font-lock-keywords))
907     (re-search-forward (regexp-quote (concat git-log-msg-separator "\n")) nil t)))
908
909 (defun git-find-file ()
910   "Visit the current file in its own buffer."
911   (interactive)
912   (unless git-status (error "Not in git-status buffer."))
913   (let ((info (ewoc-data (ewoc-locate git-status))))
914     (find-file (git-fileinfo->name info))
915     (when (eq 'unmerged (git-fileinfo->state info))
916       (smerge-mode))))
917
918 (defun git-find-file-other-window ()
919   "Visit the current file in its own buffer in another window."
920   (interactive)
921   (unless git-status (error "Not in git-status buffer."))
922   (let ((info (ewoc-data (ewoc-locate git-status))))
923     (find-file-other-window (git-fileinfo->name info))
924     (when (eq 'unmerged (git-fileinfo->state info))
925       (smerge-mode))))
926
927 (defun git-find-file-imerge ()
928   "Visit the current file in interactive merge mode."
929   (interactive)
930   (unless git-status (error "Not in git-status buffer."))
931   (let ((info (ewoc-data (ewoc-locate git-status))))
932     (find-file (git-fileinfo->name info))
933     (smerge-ediff)))
934
935 (defun git-view-file ()
936   "View the current file in its own buffer."
937   (interactive)
938   (unless git-status (error "Not in git-status buffer."))
939   (let ((info (ewoc-data (ewoc-locate git-status))))
940     (view-file (git-fileinfo->name info))))
941
942 (defun git-refresh-status ()
943   "Refresh the git status buffer."
944   (interactive)
945   (let* ((status git-status)
946          (pos (ewoc-locate status))
947          (cur-name (and pos (git-fileinfo->name (ewoc-data pos)))))
948     (unless status (error "Not in git-status buffer."))
949     (git-clear-status status)
950     (git-run-command nil nil "update-index" "--info-only" "--refresh")
951     (if (git-empty-db-p)
952         ; we need some special handling for an empty db
953         (with-temp-buffer
954           (git-run-command t nil "ls-files" "-z" "-t" "-c")
955           (git-parse-ls-files status 'added))
956       (with-temp-buffer
957         (git-run-command t nil "diff-index" "-z" "-M" "HEAD")
958         (git-parse-status status)))
959       (with-temp-buffer
960         (git-run-command t nil "ls-files" "-z" "-u")
961         (git-parse-ls-unmerged status))
962       (when (file-readable-p ".git/info/exclude")
963         (with-temp-buffer
964           (git-run-command t nil "ls-files" "-z" "-t" "-o"
965                            "--exclude-from=.git/info/exclude"
966                            (concat "--exclude-per-directory=" git-per-dir-ignore-file))
967           (git-parse-ls-files status 'unknown)))
968     (git-refresh-files)
969     (git-refresh-ewoc-hf status)
970     ; move point to the current file name if any
971     (let ((node (and cur-name (git-find-status-file status cur-name))))
972       (when node (ewoc-goto-node status node)))))
973
974 (defun git-status-quit ()
975   "Quit git-status mode."
976   (interactive)
977   (bury-buffer))
978
979 ;;;; Major Mode
980 ;;;; ------------------------------------------------------------
981
982 (defvar git-status-mode-hook nil
983   "Run after `git-status-mode' is setup.")
984
985 (defvar git-status-mode-map nil
986   "Keymap for git major mode.")
987
988 (defvar git-status nil
989   "List of all files managed by the git-status mode.")
990
991 (unless git-status-mode-map
992   (let ((map (make-keymap))
993         (diff-map (make-sparse-keymap)))
994     (suppress-keymap map)
995     (define-key map "?"   'git-help)
996     (define-key map "h"   'git-help)
997     (define-key map " "   'git-next-file)
998     (define-key map "a"   'git-add-file)
999     (define-key map "c"   'git-commit-file)
1000     (define-key map "d"    diff-map)
1001     (define-key map "="   'git-diff-file)
1002     (define-key map "f"   'git-find-file)
1003     (define-key map "\r"  'git-find-file)
1004     (define-key map "g"   'git-refresh-status)
1005     (define-key map "i"   'git-ignore-file)
1006     (define-key map "l"   'git-log-file)
1007     (define-key map "m"   'git-mark-file)
1008     (define-key map "M"   'git-mark-all)
1009     (define-key map "n"   'git-next-file)
1010     (define-key map "N"   'git-next-unmerged-file)
1011     (define-key map "o"   'git-find-file-other-window)
1012     (define-key map "p"   'git-prev-file)
1013     (define-key map "P"   'git-prev-unmerged-file)
1014     (define-key map "q"   'git-status-quit)
1015     (define-key map "r"   'git-remove-file)
1016     (define-key map "R"   'git-resolve-file)
1017     (define-key map "T"   'git-toggle-all-marks)
1018     (define-key map "u"   'git-unmark-file)
1019     (define-key map "U"   'git-revert-file)
1020     (define-key map "v"   'git-view-file)
1021     (define-key map "x"   'git-remove-handled)
1022     (define-key map "\C-?" 'git-unmark-file-up)
1023     (define-key map "\M-\C-?" 'git-unmark-all)
1024     ; the diff submap
1025     (define-key diff-map "b" 'git-diff-file-base)
1026     (define-key diff-map "c" 'git-diff-file-combined)
1027     (define-key diff-map "=" 'git-diff-file)
1028     (define-key diff-map "e" 'git-diff-file-idiff)
1029     (define-key diff-map "E" 'git-find-file-imerge)
1030     (define-key diff-map "h" 'git-diff-file-merge-head)
1031     (define-key diff-map "m" 'git-diff-file-mine)
1032     (define-key diff-map "o" 'git-diff-file-other)
1033     (setq git-status-mode-map map)))
1034
1035 ;; git mode should only run in the *git status* buffer
1036 (put 'git-status-mode 'mode-class 'special)
1037
1038 (defun git-status-mode ()
1039   "Major mode for interacting with Git.
1040 Commands:
1041 \\{git-status-mode-map}"
1042   (kill-all-local-variables)
1043   (buffer-disable-undo)
1044   (setq mode-name "git status"
1045         major-mode 'git-status-mode
1046         goal-column 17
1047         buffer-read-only t)
1048   (use-local-map git-status-mode-map)
1049   (let ((buffer-read-only nil))
1050     (erase-buffer)
1051   (let ((status (ewoc-create 'git-fileinfo-prettyprint "" "")))
1052     (set (make-local-variable 'git-status) status))
1053   (set (make-local-variable 'list-buffers-directory) default-directory)
1054   (run-hooks 'git-status-mode-hook)))
1055
1056 (defun git-find-status-buffer (dir)
1057   "Find the git status buffer handling a specified directory."
1058   (let ((list (buffer-list))
1059         (fulldir (expand-file-name dir))
1060         found)
1061     (while (and list (not found))
1062       (let ((buffer (car list)))
1063         (with-current-buffer buffer
1064           (when (and list-buffers-directory
1065                      (string-equal fulldir (expand-file-name list-buffers-directory))
1066                      (string-match "\\*git-status\\*$" (buffer-name buffer)))
1067             (setq found buffer))))
1068       (setq list (cdr list)))
1069     found))
1070
1071 (defun git-status (dir)
1072   "Entry point into git-status mode."
1073   (interactive "DSelect directory: ")
1074   (setq dir (git-get-top-dir dir))
1075   (if (file-directory-p (concat (file-name-as-directory dir) ".git"))
1076       (let ((buffer (or (and git-reuse-status-buffer (git-find-status-buffer dir))
1077                         (create-file-buffer (expand-file-name "*git-status*" dir)))))
1078         (switch-to-buffer buffer)
1079         (cd dir)
1080         (git-status-mode)
1081         (git-refresh-status)
1082         (goto-char (point-min)))
1083     (message "%s is not a git working tree." dir)))
1084
1085 (defun git-help ()
1086   "Display help for Git mode."
1087   (interactive)
1088   (describe-function 'git-status-mode))
1089
1090 (provide 'git)
1091 ;;; git.el ends here