【问题标题】:git shortcut to rebase from another branch onto the current branchgit 快捷方式从另一个分支变基到当前分支
【发布时间】:2022-01-11 01:02:37
【问题描述】:

我想在不先将其签出的情况下将分支重新设置为基础并将其签出到当前分支。这样可以节省签出旧存储库状态并重新编译它所涉及的文件的时间。

例如,我有这个:

A -> B -> C (HEAD -> main)
 \
  D -> E (old)

我想要以下。基本上检查old 并在main 之上重新定位。

A -> B -> C (main) -> D -> E (HEAD -> old)

我通常会跑:

git checkout old
git rebase main

问题是我几个月前在old 分支上工作。检查它会触及许多文件。存储库很大,如果这样做,我将需要花费数小时重新编译。我真正想做的是:

# Don't update 'main'
git checkout --detach

# Automatically cherry-picks commits after the common ancestor,
# just like a 'rebase' from that branch would do.
git cherry-pick main..old

# Update the branch ref
git branch -f old HEAD

# Check out the "rebased" branch
git checkout old

有没有更短的方法?

【问题讨论】:

  • 可以说,命令的git rebase main old 形式应该按照你想要的方式工作。事实上,它曾经按字面意思运行git checkout old; git rebase main,即您想要的方式。自从用 C 重写后,git rebase 的某些方面得到了改进,它可能按照您现在想要的方式工作,但我不会假设这一点。 (我也不喜欢git rebase U B 让你留在分支 B 上的事实,即使你在开始时在分支 C:它应该让你留在分支 C。所以无论如何我总是建议不要使用这种形式的变基。)
  • 请注意,以上不是答案:它是对 git rebase 过去有多糟糕的评论。 :-)(另外,我喜欢你的个人资料,但我注意到它是特定于 py2k 的。还有:你的用户名是 Red Dwarf 拼字游戏中使用的 Cat 这个词吗?)
  • @torek 我阅读了rebase docs。有些论点听起来像我想要的,但随后给出了不同的结果——可能是你所描述的。也许还有办法。 (你知道参考!很棒的表演:-))
  • 我有(我想我弄丢了)一个钥匙环,上面有一张太空虫的照片和一个标签:“我的另一艘宇宙飞船是红矮星”。 (我买了一本关于这个节目的杂志,主要是为了钥匙圈……)

标签: git shortcut rebase cherry-pick


【解决方案1】:

这只是将问题中的命令组合成一个宏:

git config --global alias.checkoutrebase '!git checkout --detach && git cherry-pick HEAD..$1 && git branch -f $1 HEAD && git checkout $1 && :'

Bash 补全(添加到 ~/.bashrc): __git_complete checkoutrebase _git_checkout

用法:

# Rebase another_branch onto the current HEAD and check it out
git checkoutrebase another_branch

如果another_branch 实际上不是一个分支而是另一种引用,它将中断。

测试:

# Setup
git init --initial-branch=main
touch one two
git add one two
git commit -am A
echo D > two ; git commit -am D
echo E > two ; git commit -am E
git branch old
git reset --hard HEAD~2
echo B > one ; git commit -am B
echo C > one ; git commit -am C
# State before
git log --all --graph --oneline
* 203b3f2 (HEAD -> main) C
* ee8761e B
| * aaf8ea8 (old) E
| * 0e592b1 D
|/  
* fede4c2 A

# Run the above alias
git checkoutrebase old
HEAD is now at 203b3f2 C
[detached HEAD 11bca25] D
 Date: Mon Jan 10 16:47:13 2022 -0800
 1 file changed, 1 insertion(+)
[detached HEAD 7e22429] E
 Date: Mon Jan 10 16:47:17 2022 -0800
 1 file changed, 1 insertion(+), 1 deletion(-)
Switched to branch 'old'

# State after
git log --all --graph --oneline
* 7e22429 (HEAD -> old) E
* 11bca25 D
* 203b3f2 (main) C
* ee8761e B
* fede4c2 A

【讨论】:

    猜你喜欢
    • 2012-12-11
    • 1970-01-01
    • 2013-11-04
    • 2013-08-14
    • 2020-08-11
    • 2023-03-05
    • 2013-03-10
    • 1970-01-01
    相关资源
    最近更新 更多