git - Git覆盖master并保留历史
问题描述
我想覆盖主分支并保留文件的历史记录。
我有一个生成代码的 API。每次我为 API 生成代码时,我都想覆盖 master 分支,并从远程 master 分支中删除我在本地没有的任何文件。我在本地拥有的文件,一旦我推送它们,我想跟踪它们的历史记录。
我用过git push --set-upstream origin master -f
,这删除了所有文件的历史记录。
解决方案
几个选项:
git reset
你可以标记你当前HEAD
的,一旦它被标记,你可以恢复任何先前的提交,因为 git 将保留完整的历史记录
git checkout <backup branch>
将当前分支历史备份到新分支
git revert <sha-1>
“撤消”给定的提交或提交范围。
重置命令将“撤消”在给定提交中所做的任何更改。
将提交带有撤消补丁的新提交,而原始提交也将保留在历史记录中。
# 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
它没有指向当前分支的尖端
关于如何从分离的 HEAD 中恢复的一些选项 - 或者在您的情况下如何将历史记录保存在 git
git checkout
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>
git reflog
您也可以随时使用reflog
。
git reflog
将显示更新的任何更改,HEAD
并检查所需的 reflog 条目将设置HEAD
回此提交。
每次修改 HEAD 都会在reflog
git reflog
git checkout HEAD@{...}
这将使您回到所需的提交
git reset --hard <commit_id>
将您的 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 2.7 开始)
你也可以使用git rebase --no-autostash
。
git revert <sha-1>
“撤消”给定的提交或提交范围。
重置命令将“撤消”在给定提交中所做的任何更改。
将提交带有撤消补丁的新提交,而原始提交也将保留在历史记录中。
# 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
.
推荐阅读
- python - 带有字节对象的 FastApi 发布请求得到 422 错误
- javascript - 从数组中删除关联的复选框值
- blockchain - 通过以太坊节点获取 TOKEN 的交易列表
- regex - 正则表达式替换字符
- php - 不能在路由中使用带保护的多身份验证中间件
- c# - C# grpc 服务器端唯一证书
- c - cs50 过滤器(模糊)分配(pset4)(已解决!)
- .htaccess - 如何将 /page/ 重定向到 page.html
- scala - PySpark 将 Dataframe 作为额外参数传递给映射
- java - Collection.reverse() 方法不适用于 Integer ArrayList