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