0%

git如何正确回滚代码

git 如何正确回滚代码

方法一,删除远程分支再提交

① 首先保证当前工作区是干净的,并且和远程分支代码一致

1
2
3
$ git co currentBranch
$ git pull origin currentBranch
$ git co ./

② 备份当前分支(如有必要)

1
$ git branch currentBranchBackUp

③ 恢复到指定的 commit hash

1
$ git reset --hard resetVersionHash //将当前branch的HEAD指针指向commit hash

image

④ 删除当前分支的远程分支

1
2
$ git push origin :currentBranch
$ //或者这么写git push origin --delete currentBranch

⑤ 把当前分支提交到远程

1
$ git push origin currentBranch

方法二,强制 push 远程分支

① 首先保证当前工作区是干净的,并且和远程分支代码一致

② 备份当前分支(如有必要)

③ 恢复到指定的 commit hash

1
$ git reset --hard resetVersionHash

④ 把当前分支强制提交到远程

1
$ git push -f origin currentBranch

方法三,从回滚位置生成新的 commit hash

① 首先保证当前工作区是干净的,并且和远程分支代码一致

② 备份当前分支(如有必要)

③ 使用 git revert 恢复到指定的 commit hash,当前分支恢复到 a>3 版本(见下图)

a)此方法会产生一条多余的 commit hash&log,其实 1c0ce98 和 01592eb 内容上是一致的

b)git revert 是以要回滚的 commit hash(1c0ce98)为基础,新生成一个 commit hash(01592eb)

1
$ git revert resetVersionHash

image

④ 提交远程分支

1
$ git push origin currentBranch

方法四,从回滚位置生成新的分支 merge

① 首先保证当前工作区是干净的,并且和远程分支代码一致

② 备份当前分支(如有必要)

③ 把当前工作区的 HEAD 指针指向回滚的 commit hash(注意不是 branch 的 HEAD 指针)

Notice:这个时候工作区 HEAD 没有指向分支,称为匿名分支 detached HEAD

这个时候提交 commit 后无法保存状态,git 中的任何提交必须是在当前工作区 HEAD 所在分支的 HEAD 上进行 push hash 入栈,所以 HEAD 必须是属于某个分支的 HEAD 位置,提交才生效。

1
$ git co resetVersionHash

④ 以该 commit hash 创建一个新的分支

1
$ git co -b newRevertedHash

⑤ 切换到当前分支,合并 newRevertedHash。

1
2
$ git co currentBranch
$ git merge newRevertedHash

⑥ 进行代码 diff,完成代码回滚,push 到远程 currentBranch

Notice: 也可以直接 hotfix,从要回滚的地方直接重新打包一个新 tag 包,发版本 hotFixVersion 即可。