改写历史记录后更新远程分支

GitGitBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

Git 是一个强大的版本控制系统,它允许开发者跟踪对其代码库所做的更改。Git 的关键特性之一是能够改写历史记录,当你需要对之前的提交进行更改时,这会很有用。然而,在尝试将更改推送到远程仓库时,改写历史记录可能会导致问题。在本实验中,你将学习如何在本地改写历史记录后更新远程分支。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL git(("`Git`")) -.-> git/CollaborationandSharingGroup(["`Collaboration and Sharing`"]) git/CollaborationandSharingGroup -.-> git/remote("`Manage Remotes`") subgraph Lab Skills git/remote -.-> lab-12734{{"`改写历史记录后更新远程分支`"}} end

改写历史记录后更新远程分支

当你在本地改写历史记录时,会创建一个具有不同 SHA-1 哈希值的新提交。这意味着你本地分支上的提交历史与远程分支上的提交历史不同。如果你尝试将更改推送到远程分支,Git 会拒绝推送,因为它会认为提交历史已经分叉。要解决这个问题,你需要强制更新远程分支。

要完成本实验,你将使用 GitHub 账户中的 git-playground Git 仓库,它是从 https://github.com/labex-labs/git-playground.git 派生而来的。

  1. git-playground 仓库克隆到你的本地机器:
git clone https://github.com/your-username/git-playground.git
  1. 将提交消息为 “Added file2.txt” 的提交更新为提交消息为 “Update file2.txt” 的提交:
git commit --amend
  1. 将本地分支的更改推送到远程仓库:
git push
  1. 如果你无法成功推送,请强制推送:
git push -f origin master

-f 标志会强制 Git 使用你的更改更新远程分支,即使提交历史已经分叉。

这是最终结果:

commit b8c530558ecd004156dd05ac7d22d8cf07b2c28e (HEAD -> master, origin/master, origin/HEAD)
Author: Hang <[email protected]>
Date:   Wed Apr 26 14:16:25 2023 +0800

    Update file2.txt

commit cf80005e40a3c661eb212fcea5fad06f8283f08f
Author: Hang <[email protected]>
Date:   Wed Apr 26 14:16:25 2023 +0800

    Added file1.txt

commit b00b9374a7c549d1af111aa777fdcc868d8a2a01
Author: Hang <[email protected]>
Date:   Wed Apr 26 14:16:00 2023 +0800

    Initial commit

总结

在本实验中,你学习了如何在本地改写历史记录后更新远程分支。通过使用 git push -f 命令,你可以强制 Git 使用你的更改更新远程分支,即使提交历史已经分叉。谨慎使用此命令很重要,因为它可能会覆盖其他开发者所做的更改。

您可能感兴趣的其他 Git 教程