情景描述
在将项目share到github后(已经push),发现push的文件中含有敏感的信息,所以想回滚状态到之前的版本。但使用log命令可以发现当前仅有一个commit状态:
Yitian-MacBook-Pro:springboot-learning yitian$ git log
commit f8e6d2455c8f494b860d0bb9a4b103624d75ef2a (HEAD -> master, origin/master)
Author: yitian <yitian.z@foxmail.com>
Date: Sat Feb 1 20:49:07 2020 +0800
init commit
使用reset命令无法回退到上次的提交状态(因为仅有一次提交,HEAD^状态并不存在),所以该方法不行。
解决方法
执行下面的命令,清除所有提交的版本并清空工作空间,这样就可以再进行第一次提交了:
git update-ref -d HEAD
执行之后,将文件中敏感信息去掉之后commit并push,应该会出现如下的问题:
Yitian-MacBook-Pro:springboot-learning yitian$ git push
To https://github.com/Yitian-Zhang/springboot-learning.git
! [rejected] master -> master (non-fast-forward)
error: failed to push some refs to 'https://github.com/Yitian-Zhang/springboot-learning.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
问题的原因,是因为当前的版本状态落后于remote中的版本,因此出现错误。提示中说明可以使用pull命令(合并远程代码到本地),但为了将远程代码完全替换掉,执行如下的强制push命令:
Yitian-MacBook-Pro:springboot-learning yitian$ git push -u origin master -f
Enumerating objects: 900, done.
Counting objects: 100% (900/900), done.
Delta compression using up to 8 threads
Compressing objects: 100% (876/876), done.
Writing objects: 100% (900/900), 715.17 KiB | 6.44 MiB/s, done.
Total 900 (delta 388), reused 0 (delta 0)
remote: Resolving deltas: 100% (388/388), done.
To https://github.com/Yitian-Zhang/springboot-learning.git
+ 9f30d39...f8e6d24 master -> master (forced update)
Branch 'master' set up to track remote branch 'master' from 'origin'.
Yitian-MacBook-Pro:springboot-learning yitian$ git status
On branch master
Your branch is up to date with 'origin/master'.
nothing to commit, working tree clean
需要注意:该命令需要谨慎使用,此时因为我只提交过初始的一次,因此替换掉之前的所有提交是没问题的,但如果之前有多次提交,这里需要谨慎使用。(但如果有多次提交,reset命令应该就可以使用了)
执行完成后,到github仓库中查看可以发现,目前项目的版本状态为初始的第一次提交状态,通过log命令仍能看出:
Yitian-MacBook-Pro:springboot-learning yitian$ git log
commit f8e6d2455c8f494b860d0bb9a4b103624d75ef2a (HEAD -> master, origin/master)
Author: yitian <yitian.z@foxmail.com>
Date: Sat Feb 1 20:49:07 2020 +0800
init commit
这样就完成了项目回滚第一次提交的过程。对于项目中存在的敏感信息在提交时,需要注意。
来源:CSDN
作者:一天_pika
链接:https://blog.csdn.net/yitian_z/article/details/104138469