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