简体   繁体   中英

git shortcut to rebase from another branch onto the current branch

I want to rebase and checkout a branch onto the current branch without checking it out first. This saves time checkout out an old repository state and recompiling the files it touches.

For example, I have this:

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

I want the following. Basically checking out old and rebasing on top of main .

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

I would normally run:

git checkout old
git rebase main

The problem is I was working on the old branch months ago. Checking it out will touch many files. The repository is huge and I'll need to spend hours recompiling if I do that. What I really want to do is the following:

# 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

Is there a shorter way of doing this?

This just combines the commands in the question into a macro:

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

Bash completion (add to ~/.bashrc): __git_complete checkoutrebase _git_checkout

Usage:

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

It will break if another_branch is not actually a branch but another kind of reference.

Testing:

# 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM