我想覆盖主分支并保留文件的历史记录。
我有一个生成代码的API。每次为API生成代码时,我都想覆盖主分支,并从远程主分支中删除本地没有的任何文件。我在本地拥有的文件,我想在推送它们后跟踪它们的历史记录。
我使用了git push --set-upstream origin master -f
,这删除了所有文件的历史记录。
发布于 2020-01-02 22:51:40
以下是几个选项:
git reset
你可以标记你当前的HEAD
,一旦它被标记,你就可以恢复之前的任何提交,因为git将保留完整的历史记录
git checkout <backup branch>
将当前分支历史记录备份到新分支中
“撤消”给定的提交或提交范围。
reset命令将“撤消”在给定提交中所做的任何更改。
带有撤消补丁的新提交将被提交,而原始提交也将保留在历史中。
# add new commit with the undoing of the original one.
# the <sha-1> can be any commit(s) or commit range
git revert <sha-1>
完整的答案:选择一个适合你的选择-我还添加了一些额外的信息,这样你就可以有完整的图片
在回答之前,让我们添加一些背景知识,解释一下这是什么HEAD
。
First of all what is HEAD?
HEAD
只是对当前分支上的当前提交(最新)的引用。
在任何给定时间只能有一个HEAD
。(不包括git worktree
)
HEAD
的内容存储在.git/HEAD
中,它包含当前提交的40个字节的SHA-1。
detached HEAD
如果您没有执行最近一次提交-意味着HEAD
指向历史上的前一次提交,那么它被称为detached HEAD
.
在命令行上,它将类似于- SHA-1而不是分支名称,因为HEAD
没有指向当前分支的顶端
关于如何从分离的头部恢复的几个选项-或者在您的情况下如何在git中保留历史记录( in git)。
git checkout <commit_id>
git checkout -b <new branch> <commit_id>
git checkout HEAD~X // x is the number of commits t go back
这将签出指向所需提交的新分支。
此命令将签出到给定的提交。
此时,您可以创建一个分支并从此点开始工作。
# Checkout a given commit.
# Doing so will result in a `detached HEAD` which mean that the `HEAD`
# is not pointing to the latest so you will need to checkout branch
# in order to be able to update the code.
git checkout <commit-id>
# create a new branch forked to the given commit
git checkout -b <branch name>
您也可以随时使用reflog
。
git reflog
将显示更新了HEAD
的任何更改,并且检出所需的reflog条目会将HEAD
设置回此提交。
每次修改reflog
头时, HEAD中都会有一个新条目
git reflog
git checkout HEAD@{...}
这将使您返回到所需的提交
“移动”你的头回到你想要的提交。
# This will destroy any local modifications.
# Don't do it if you have uncommitted work you want to keep.
git reset --hard 0d1d7fc32
# Alternatively, if there's work to keep:
git stash
git reset --hard 0d1d7fc32
git stash pop
# This saves the modifications, then reapplies that patch after resetting.
# You could get merge conflicts if you've modified things which were
# changed since the commit you reset to.
您也可以使用git rebase --no-autostash
。
“撤消”给定的提交或提交范围。
reset命令将“撤消”在给定提交中所做的任何更改。
带有撤消补丁的新提交将被提交,而原始提交也将保留在历史中。
# add new commit with the undo of the original one.
# the <sha-1> can be any commit(s) or commit range
git revert <sha-1>
这个模式说明了哪个命令做了什么。
如您所见,reset && checkout
修改HEAD
。
https://stackoverflow.com/questions/59569188
复制