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