git - 如何在 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 中回滚吗?
解决此问题的尝试失败
- 我试过这个答案How do I undo the most recent local commits in Git? 并运行
git reset HEAD~
,但我有以下错误
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 - rollback to previous commit返回另一条错误消息:
$ 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'
- 这个答案并不精确如何恢复丢失的文件:How do I undo 'git add' before commit?
解决方案
幸好你知道遥控器上原主的简写。您的初始输出git push -f
显示它位于4a0d8a5
. 如果您对远程有 shell 访问权限,请到那里并在该提交处创建一个分支(或标签。您只需要使提交可访问):
git branch original-master 4a0d8a5 # Run on origin
现在,在本地仓库中:
git fetch origin
git reset --hard 4a0d8a5
推荐阅读
- c - 我不明白如何初始化游戏的链表(Snake)
- css - 用 express 和 node js 添加 css
- php - 在静态类中使用数据库助手 [Code Igniter]
- android - android 10(Android q)batterystat中的负uid
- c# - 如何使用 C# 从服务器读取客户端上的 NFC 阅读器?
- c# - 在 Blazor 应用程序中使用意外名称进行标记?
- c# - BPAC SDK 已安装但显示 CLSID 未注册
- python - 使用自定义函数合并两个 Python 数据帧以进行近似匹配和阈值分数
- c++ - 使用 clang++ 和 g++ 在 C++ 中进行变量初始化
- python - pytmx 是否为您提供了一种方法来判断图像是否已旋转、水平翻转/诊断是否与 Tiled 一起使用?