如何在提交之前查看文件的更改?

56

我已经尝试过 git commit -v

ubuntu@ip:~/agile$ git commit -v
# On branch master
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#   modified:   .htaccess
#
no changes added to commit (use "git add" and/or "git commit -a")
ubuntu@ip:~/agile$ 

但它只是告诉我.htaccess已更改,但未告诉我更改了什么。我该怎么做才能实现这一点?

更新: 在 Aptana Studio 中,可以在提交任何内容之前查看更改。因此,回到我的问题,必须有一种方法可以查看与原始状态的差异,然后再实际提交。也许有一个不同的命令。


非常有用:在提交之前对文件进行代码检查 - Rituraj ratan
2个回答

68

查看所有已追踪但未暂存的文件的差异:

git diff
或者
git diff path/to/a/given/file

要仅查看文件的差异。您还可以查看项目中特定子目录中的差异:

git diff path/to/a/dir/
如果您已经使用 git add 暂存了更改,您可以通过以下命令查看您已暂存的补丁:
git diff --staged

您还可以使用--staged指定路径。


1
针对特定文件进行Git差异比较:git diff path/to/a/dir/test.php - Muhammad

35

确保您已经暂存了一些更改。否则,git commit -v将向您显示与您发布的类似的块,但不会执行任何操作。您可以使用git add手动暂存更改,或者如果文件已经有版本记录,则可以使用git commit -a -v暂存并提交更改。

例如:

$ echo "more foo" >> foo.txt
$ git commit -v
# On branch master
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#   modified:   foo.txt
#
no changes added to commit (use "git add" and/or "git commit -a")

通过使用 git commit -v 命令,可以将变更进行分阶段并展示差异:

:: git add foo.txt
:: GIT_EDITOR=cat git commit -v

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   modified:   foo.txt
#
diff --git a/foo.txt b/foo.txt
index 257cc56..a521556 100644
--- a/foo.txt
+++ b/foo.txt
@@ -1 +1,2 @@
 foo
+more foo
Aborting commit due to empty commit message.

如果你只想看到未被提交的更改,使用git diff命令,如果想看到已准备提交的更改,使用git diff --cached命令,或者使用git diff HEAD命令来查看工作树中已暂存和未暂存的更改。

更新:鉴于您的编辑,您确实需要上述git diff衍生命令。我不确定Aptana Studio是如何工作的。它可能不遵循典型的命令行git流程。在命令行上,您需要暂存修改,然后再提交。上述git diff命令可以用来检查这些修改。我通常通过将以下内容添加到我的~/.gitconfig文件来为它们设置别名:git unstagedgit stagedgit both

[alias]
    # show difference between working tree and the index
    unstaged = diff

    # show difference between the HEAD and the index
    staged = diff --cached

    # show staged and unstaged changes (what would be committed with "git commit -a")
    both = diff HEAD

1
+1 是的。git diff .htaccess 达到了我想要的效果。谢谢 :) - Houman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接