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