【问题标题】:将现有 Git 推送到新分支
【发布时间】:2022-01-23 06:00:54
【问题描述】:

我在尝试将我的分支推送到 Git 时遇到了一些问题,并且无法找到我可以遵循的直截了当的答案。

我下载了一个克隆的存储库并做了一些更改。然后,我在 Github 上创建了一个名为“features/library”的新分支。

然后我完成了:

  • git switch features/library
  • git status
  • git add *
  • git commit -am 'My message'
  • git branch --set-upstream-to origin feature/library
  • git push origin features/library

我收到以下错误:

 ! [rejected]        feature/library -> feature/library (non-fast-forward)
error: failed to push some refs to 'https://github.com/my/repo.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

查看错误,我们的主分支后面似乎没有代码,尽管它正在抛出错误。我们对这个新提交进行了许多更改,这可能是引发错误的原因。

我希望能够将我的本地分支推送到 Github 上的新分支,而不会覆盖我现有的本地文件/更改并影响主分支。

感谢您的帮助! 干杯!

【问题讨论】:

  • Git 推送提交,而不是文件。这意味着您需要准确了解什么是提交、Git 如何找到提交以及 Git 如何处理提交。请参阅Timothy Truckle's answer 以获得非常简短的概述:其中的小写字母代表提交。

标签: git github command-line-interface version github-for-windows


【解决方案1】:

问题是,您在 GitHub 上创建分支的提交不是您启动本地分支的提交的直接前身:

a -- b -- c -- d <- origin/features/library
            \- e -- f <- features/library

您有 2 个选项:

  1. rebase远程分支之上的本地分支

     git fetch
     git rebase -i origin/features/library
     git push
    

    这会导致

    a -- b -- c -- d -- e' -- f' [origin/]features/library
    
  2. 更危险的版本是强制推送你的本地历史状态到远程仓库

      git fetch
      git push --force-with-lease
    

    然后你得到

    a -- b -- c -- e -- f [origin/]features/library
    

    请注意,提交 d 已经消失!
    (事实上​​,在 last common anchester 之后的所有提交,直到并包括当前远程分支 HEAD 都将丢失)。

    选择此方法时,我强烈建议不要使用较短的开关 -f,因为它不需要先获取,从而增加了意外丢失提交的风险。
    在使用任一强制选项推动时务必格外小心!

写完这个更好的选择是通过直接推送到远程而不事先在 GitHub 上创建它来隐式创建远程分支。

【讨论】:

  • 难道我还不必担心在运行 fetch 时我的本地更改被覆盖,以及我的 MAIN/origin 分支被覆盖吗?
  • @Mark-exe fetch 不会覆盖任何内容。它只是使用其他人所做的更改来更新您的本地存储库副本。您的本地更改总是与此远程更改不同。 但是当强制将你的更改推送到遥控器时,你可以“覆盖”其他人的更改。
猜你喜欢
  • 2019-02-26
  • 2010-11-07
  • 2018-01-27
  • 1970-01-01
  • 1970-01-01
  • 2020-12-06
  • 1970-01-01
  • 2020-11-15
  • 2014-02-04
相关资源
最近更新 更多