How do I avoid Git's `--fork-point` becoming confused by a retroactively created branch?

42 Views Asked by At

When I find that I should've made a branch for my current changes, I usually do something along the lines of

$ git switch -t -c new-branch
$ git switch master # switch back
$ git reset --hard origin/master # assume I had no staged changes
$ git switch new-branch

But then if I pull some external changes into master and then try to git rebase my new-branch (which uses --fork-point by default), it will just erase everything and reset it to the new master.

Can I do the retroactive branch creation part differently in order to avoid this problem?

1

There are 1 best solutions below

0
Cem On

The obvious solution is not to use the --fork-point option, e.g. by adding --no-fork-point at the end of the rebase command.

If that's not an option, since the --fork-point uses the reflog of the master branch, this reflog has to be modified. The command below prunes entries in the reflog of the master branch that are not reachable from the tip of master. Note that this is a destructive operation, it is not limited to the commits in new-branch and you may lose other log data by doing this.

git reflog expire --expire=never --expire-unreachable=all master

The whole workflow then looks like this:

# we don't need to switch back-and-forth
git branch -t new-branch

# reset to upstream
git reset --hard @{u}

# prune reflog
git reflog expire --expire=never --expire-unreachable=all master