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