【问题标题】:Reset other branch to current without a checkout无需结帐即可将其他分支重置为当前分支
【发布时间】:2010-12-08 03:30:54
【问题描述】:

我正在为我的 Git 工作流程编写一些脚本。

我需要将其他(现有)分支重置为当前分支,无需结帐。

之前:

 CurrentBranch: commit A
 OtherBranch: commit B

之后:

 CurrentBranch: commit A
 OtherBranch: commit A

等价于

 $ git checkout otherbranch 
 $ git reset --soft currentbranch
 $ git checkout currentbranch

(注意--soft:我不想影响工作树。)

这可能吗?

【问题讨论】:

  • 有谁知道这在 Egit 中是否也可以实现?

标签: git


【解决方案1】:

通过运行将otherbranch 设置为指向与currentbranch 相同的提交

git branch -f otherbranch currentbranch

-f(强制)选项告诉git branch是的,我真的是想用新的otherbranch 覆盖任何现有的引用

来自documentation

-f
--强制

如果已经存在则重置为。没有 -f git branch 拒绝更改现有分支。

【讨论】:

  • 这是最简单的答案。谢谢!
  • 我在尝试执行此操作时收到 fatal: Cannot force update the current branch.
  • @FuadSaud 那是因为您已经签出了otherbranch。这个 SO 问题专门关于将 another 分支重置为不同的提交(即不重置签出分支)。您要做的是使用git reset targetbranch 重置当前分支以强制当前分支指向targetbranch。添加--hard 也将工作树强制为该内容。或--soft 不理会索引,只更改分支本身。
  • 对,所以,我知道重置。我正在寻找的是一种在例程中始终将本地主机指向上游/主机的方法,而与检查的内容无关。我认为branch -f 可以做到这一点。
  • Imo,这应该是公认的答案。这大大改善了我的工作流程!
【解决方案2】:

您描述的工作流程并不相同:当您执行 reset --hard 时,您会丢失工作树中的所有更改(您可能希望将其设为 reset --soft)。

你需要的是

git update-ref refs/heads/OtherBranch refs/heads/CurrentBranch

【讨论】:

  • 伙计,我希望没有多余的refs/heads/ ...
  • 一个更好的方法是git push . current:other。这在没有refs/heads (/cc @elliottcable) 的情况下有效,并且它还会阻止您更新签出的分支。请注意,如果更新不是快进,您可能需要传递 -f(或使用 +current:other)。
  • 您也可以使用-m 'some text'参数记录git reflog OtherBranch命令显示ref更新的原因,例如“同步到CurrentBranch”。记住你后来为什么这样做可能会很有用。
  • 当您可以使用更清洁的 (IMO) git branch -f OtherBranch CurrentBranch 时,为什么还要使用 git update-ref refs/heads/OtherBranch refs/heads/CurrentBranchgit push . CurrentBranch OtherBranch? (见下文my answer on git branch -f
  • @ColinDBennett 为未来的读者节省一些时间:如果 OtherBranch 当前已签出,git branch -f 将不起作用,而 git update-ref 将。
【解决方案3】:

您可以随时使用此命令同步您的分支

$ git push . CurrentBranch:OtherBranch -f

同样没有 -f 它替换这组命令

$ git checkout OtherBranch
$ git merge CurrentBranch
$ git checkout CurrentBranch

当您不需要在 CurrentBranch 中提交所有文件并且无法切换到其他分支时,它会很有用。

【讨论】:

  • 可能导致“远程:错误:拒绝非快进”
  • 除非绝对不可避免,否则我不会包含 -f 选项。在我的情况下,没有它它也能很好地工作。
【解决方案4】:

其他答案都不错,但有点吓人。我只是提供了另一种选择,通过我每天使用的命令的变化来实现所要求的内容。

简而言之,这些选项都不会与您所在的当前分支或当前负责人混淆。

git branch -C other_branch(从当前 HEAD 强制创建 other_branch)

要将 other_branch 重置为您不在的分支...

git branch -C old_branch other_branch(从 old_branch 强制创建 other_branch)

在遥控器上将 other_branch 重置为 some_branch,有点不同...

git pull -f origin old_branch:other_branch(强制拉(忽略已经是最新的东西)origin/old_branch 到本地的 other_branch)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-09
    • 2011-02-15
    • 2011-01-18
    • 2021-02-03
    • 2021-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多