           (message "You cannot commit unmerged files, resolve them first.")
         (unwind-protect
             (let ((files (git-marked-files-state 'added 'deleted 'modified))
-                  head head-tree)
+                  head tree head-tree)
               (unless (git-empty-db-p)
                 (setq head (git-rev-parse "HEAD")
                       head-tree (git-rev-parse "HEAD^{tree}")))
               (if files
                   (progn
                     (message "Running git commit...")
-                    (git-read-tree head-tree index-file)
-                    (git-update-index nil files)         ;update both the default index
-                    (git-update-index index-file files)  ;and the temporary one
-                    (let ((tree (git-write-tree index-file)))
+                    (when
+                        (and
+                         (git-read-tree head-tree index-file)
+                         (git-update-index nil files)         ;update both the default index
+                         (git-update-index index-file files)  ;and the temporary one
+                         (setq tree (git-write-tree index-file)))
                       (if (or (not (string-equal tree head-tree))
                               (yes-or-no-p "The tree was not modified, do you really want to perform an empty commit? "))
                           (let ((commit (git-commit-tree buffer tree head)))

    (and (eq 0 (apply #' git-call-process-env t env args))
         (buffer-string))))

(defun git-run-process-region (buffer start end program args)
  "Run a git process with a buffer region as input."
  (let ((output-buffer (current-buffer))


(defun git-read-tree (tree &optional index-file)
  "Read a tree into the index file."
  (let ((process-environment
         (append (and index-file (list (concat "GIT_INDEX_FILE=" index-file))) process-environment)))
    (apply 'git-call-process-display-error "read-tree" (if tree (list tree)))))

(defun git-write-tree (&optional index-file)
  "Call git-write-tree and return the resulting tree SHA1 as a string."
  (let ((process-environment
         (append (and index-file (list (concat "GIT_INDEX_FILE=" index-file))) process-environment)))
    (git-get-string-sha1
     (git-call-process-string-display-error "write-tree"))))

(defun git-commit-tree (buffer tree head)
  "Call git-commit-tree with buffer as input and return the resulting commit SHA1."
