首页 > 解决方案 > 如何在 Git 中回滚到以前的版本?

问题描述

我想看看我是否可以在文件中提交更改,但是这样做之后,repo 的所有文件都消失了。如何恢复以前的版本?

这是我所做的(注意这是我第一次连接到这个 Git 服务器)。首先我初始化我的存储库:

 $ rm -rf .git/
 $ git init
 $ git remote add origin https://remote.url/myProject.git
 $ git commit -m "My first commit"
 On branch master
 Initial commit
 Untracked files:
   (use "git add <file>..." to include in what will be committed)
        .foundry/
        .gitignore
        .teamcity/
        GitVersion.yml
        README.md
        config.ini
        block.py
        view.py
        entities.py
 nothing added to commit but untracked files present (use "git add" to track)

然后因为我只修改了entities.py,所以我将它添加到提交列表中:

$ git add entities.py
$ git status
On branch master
No commits yet
Changes to be committed:
  (use "git rm --cached <file>..." to unstage)
        new file:   entities.py
Untracked files:
  (use "git add <file>..." to include in what will be committed)
        .foundry/
        .gitignore
        .teamcity/
        GitVersion.yml
        README.md
        config.ini
        block.py
        view.py

Git 检测到entities.py的变化,所以我认为我很高兴:

$ git commit -m "entities.py first commit"
[master (root-commit) 1dc09d9] entities.py first commit
1 file changed, 535 insertions(+)
create mode 100644 entities.py
$ git push -f origin master
Enumerating objects: 3, done.
Counting objects: 100% (3/3), done.
Delta compression using up to 8 threads
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 6.64 KiB | 1.66 MiB/s, done.
Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
To https://remote.url/myProject.git
 + 4a0d8a5...1dc09d9 master -> master (forced update)

当我想在服务器上检查提交是否有效时,项目的所有文件都消失了!只有一个文件:entities.py。当我运行时git ls-tree只返回一个文件:

$ git ls-tree -r master --name-only
entities.py

正如你所看到的,我们已经失去了一切。我过去使用过 TFS,任何错误都可以在 1 分钟内轻松回滚,在这里我花了几个小时试图在 Git 书中寻找正确的命令,但找不到如何恢复以前的版本?至少可以在 Git 中回滚吗?

解决此问题的尝试失败

fatal: ambiguous argument 'HEAD~': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'
$ git push origin HEAD~1:master
error: src refspec HEAD~1 does not match any
error: failed to push some refs to 'https://remote.url/myProject.git'

标签: gitrollback

解决方案


幸好你知道遥控器上原主的简写。您的初始输出git push -f显示它位于4a0d8a5. 如果您对远程有 shell 访问权限,请到那里并在该提交处创建一个分支(或标签。您只需要使提交可访问):

git branch original-master 4a0d8a5    # Run on origin

现在,在本地仓库中:

git fetch origin
git reset --hard 4a0d8a5

推荐阅读