Git相当于hg update

9
以下是使用Mercurial的小例子,同样也适用于Git。 我不太明白如何在Git中执行hg update
我有一个小型的Mercurial设置,其中包含4个提交 - 我需要回退一个提交。
hg init
echo "1" > a.txt; hg commit -A -m "1. commit" a.txt
echo "2" >> a.txt; hg commit -m "2. commit" a.txt
echo "3" >> a.txt; hg commit -m "3. commit" a.txt
echo "4" >> a.txt; hg commit -m "4. commit" a.txt
hg update -r 3
thg # or hg view`

这个图片呈现了以下内容

thg

请注意,我看到了所有四个提交——即包括先前历史和之后的提交

让我尝试使用Git做同样的例子

git init
echo "1" > a.txt; git add a.txt; git commit  -m "1. commit" a.txt
echo "2" >> a.txt; git commit -m "2. commit" a.txt
echo "3" >> a.txt; git commit -m "3. commit" a.txt
echo "4" >> a.txt; git commit -m "4. commit" a.txt # gives for me [master 57bb375]

让我看看提交记录:

git log --graph --pretty=format:'%h -%d %s (%cr) <%an>' 

 * 57bb375 - (HEAD, master) 4. commit (14 minutes ago) <Peter Toft>
 * 724a493 - 3. commit (14 minutes ago) <Peter Toft>
 * bb38732 - 2. commit (14 minutes ago) <Peter Toft>
 * 879c593 - 1. commit (15 minutes ago) <Peter Toft>

非常好 - 四次提交如预期一样。让我回到上一个提交(类似于 hg update)。

git checkout 724a493

现在Git日志怎么样了?
git log --graph --pretty=format:'%h -%d %s (%cr) <%an>' 

 * 724a493 - (HEAD) 3. commit (19 minutes ago) <Peter Toft>
 * bb38732 - 2. commit (19 minutes ago) <Peter Toft>
 * 879c593 - 1. commit (19 minutes ago) <Peter Toft>

gitk也只会显示前3个提交吗?

因此,“git checkout”并不仅仅类似于“hg update”。下面的提交在哪里?

3个回答

8

hg update -r 3会自动创建一个分支头,你可以在这个分支上继续提交。而在git中,checkout命令只是让你切换到指定的提交版本,并不会创建新的分支头。如果你想要创建新的分支头,可以使用以下命令:

git checkout -b new_branch_name 724a493

当然,可以使用任何你喜欢的名称。如果你不使用-b,就会进入一个分离头状态...这正是hg update -r 3git checkout 724a493之间的区别。请注意,当你执行检出操作时,Git会打印出一条消息(来自于我运行你的示例):

Note: checking out '2ffb5e0'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b new_branch_name

HEAD is now at 2ffb5e0... 3. commit

提交 57bb375 仍然在“master”分支的顶端。要将其取回,您只需要执行“git checkout master”。如果您想将其放到新建的分支上,您可以在该新分支上执行“git merge master”或“git cherry-pick 57bb375”。 - Wolf

4
简单来说,当您运行git checkout 724a493时,57bb375提交并没有移动到任何地方。您看到的行为仅仅是git log只显示被检出提交的祖先提交。在Mercurial术语中,git log相当于:
$ hg log -r ::.

这意味着“显示是.祖先的提交,即工作副本父级修订版本”。要获得与hg log相当的Git命令,只需运行:

$ git log --all

这个小差别是Git的一个关键功能,它允许您从许多其他存储库中拉取提交,而默认情况下不会看到它们。只有在您检出分支(或在您的情况下检出��交)时,才会看到您下载到存储库中的提交。

不错 - 而且 "gitk --all" 显示未来的提交(就像你的 git log --all 一样) - Peter Toft

0
另一种解决方案变体: 添加

[alias]
    restore = "!f() { git checkout $(git rev-list -n 1 HEAD -- $1)~1 -- $(git diff --name-status $(git rev-list -n 1 HEAD -- $1)~1 | grep ^D | cut -f 2); }; f"

那么 "git restore" 将使我向后移动一个提交点,而无需创建一个人工分支。

如果我想返回到主分支

git checkout master

1
你可以使用 git checkout "HEAD^" 命令来切换到前一个提交。 - Martin Geisler

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