我有一个git存储库,其中包含一些提交。我想重现完全状态的工作目录,因为它是在特定提交之后(这里我假设我已经提交了所有更改)。
我尝试使用git checkout
,但此命令不会删除工作目录中的现有文件(在所需的提交后添加)。
简单的例子来说明我的问题。我使用以下命令准备了存储库
u@u-desktop:/tmp/git$ git init
Initialized empty Git repository in /tmp/git/.git/
u@u-desktop:/tmp/git$ echo 'ffff' > first.file
u@u-desktop:/tmp/git$ git add first.file
u@u-desktop:/tmp/git$ git commit -m "Important file was added"
[master (root-commit) fb05f7e] Important file was added
1 files changed, 1 insertions(+), 0 deletions(-)
create mode 100644 first.file
u@u-desktop:/tmp/git$ echo 'Second line' >> first.file
u@u-desktop:/tmp/git$ git commit -m "Important data was added" -a
[master df93d04] Important data was added
1 files changed, 1 insertions(+), 0 deletions(-)
u@u-desktop:/tmp/git$ echo 'ssss' > second.file
u@u-desktop:/tmp/git$ git add second.file
u@u-desktop:/tmp/git$ git commit -m "Second important file was added"
[master b6c106a] Second important file was added
1 files changed, 1 insertions(+), 0 deletions(-)
create mode 100644 second.file
u@u-desktop:/tmp/git$ echo 'tttt' > third.file
u@u-desktop:/tmp/git$ git add third.file
u@u-desktop:/tmp/git$ git commit -m "Third important file was added"
[master 33fce06] Third important file was added
1 files changed, 1 insertions(+), 0 deletions(-)
create mode 100644 third.file
现在目录看起来像这样
u@u-desktop:/tmp/git$ ls
first.file second.file third.file
first.file
有以下内容
u@u-desktop:/tmp/git$ cat first.file
ffff
Second line
现在我想要在首次提交(fb05f7e
)
u@u-desktop:/tmp/git$ git checkout fb05f7e .
u@u-desktop:/tmp/git$ cat first.file
ffff
但second.file
和third.file
仍在目录
u@u-desktop:/tmp/git$ ls
first.file second.file third.file
答案 0 :(得分:3)
只是做:
git checkout fb05f7e
...即没有指定当前目录(.
)作为结帐路径。您会发现second.file
和third.file
已按预期删除。
原因是git checkout
有两种截然不同的操作模式,具体取决于您是否提供路径。如果你确实提供了一个路径,它根本不会改变HEAD
,只是
...从索引文件或命名的< tree-ish>更新工作树中的命名路径。 (通常是提交)
(那是来自git checkout
documentation)。这只会更新其他提交中实际存在的路径。
答案 1 :(得分:3)
删除.
中的git checkout
。手册页中的选择:
git checkout [<branch>], git checkout -b|-B <new_branch> [<start
point>], git checkout [--detach] [<commit>]
This form switches branches by updating the index, working tree,
and HEAD to reflect the specified branch or commit.
(...)
git checkout [-p|--patch] [<tree-ish>] [--] <pathspec>...
When <paths> or --patch are given, git checkout does not switch
branches. It updates the named paths in the working tree from the
index file or from a named <tree-ish> (most often a commit).
如果您想删除索引中未选中的文件,请使用git clean
(阅读手册页,您将拥有“反oops”选项传递命令行使其工作)。