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