操作步骤:
1. 查看当前的远程仓库配置
git remote -v
你会看到类似这样的输出(origin 指向原始仓库):
origin https://github.com/原作者/原仓库.git (fetch)
origin https://github.com/原作者/原仓库.git (push)
2. 重命名原始仓库为 upstream
git remote rename origin upstream
3. 添加你的个人仓库作为新的 origin
git remote add origin https://github.com/你的用户名/你的新仓库.git
4. 推送你的修改到你的仓库
# 推送主分支(通常是 main 或 master)
git push -u origin master
# 或者
git push -u origin main
5. 保持与原始仓库的同步
以后当你想要同步原始仓库的更新时:
# 从原始仓库拉取最新代码
git fetch upstream
# 合并更新到你的本地分支
git checkout main # 或 master
git merge upstream/master
# 推送更新到你的仓库
git push origin master
完整的配置结果:
# 查看最终的远程仓库配置
git remote -v
输出应该是:
origin https://github.com/你的用户名/你的新仓库.git (fetch)
origin https://github.com/你的用户名/你的新仓库.git (push)
upstream https://github.com/原作者/原仓库.git (fetch)
upstream https://github.com/原作者/原仓库.git (push)
常用工作流程:
-
开发新功能:在本地修改代码
-
提交修改 :
git add .&&git commit -m "你的修改说明" -
推送到你的仓库 :
git push origin master -
获取原始仓库更新 :
git fetch upstream -
合并更新 :
git merge upstream/master -
解决冲突(如果有)
-
推送合并后的代码 :
git push origin master
这样你既能将修改推送到自己的仓库,又能随时获取原始仓库的最新更新。