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