I've created a bash script that performs the following tasks:
origin/master
into master
if #2 is true;master
on top of origin/master
if #2 is falseThe code is as follows:
#!/bin/sh
local_branch=$(git rev-parse --symbolic-full-name --abbrev-ref HEAD)
remote_branch=$(git rev-parse --abbrev-ref --symbolic-full-name @{u})
remote=$(git config branch.$local_branch.remote)
echo "Fetching from $remote..."
git fetch $remote
if git merge-base --is-ancestor $local_branch $remote_branch; then
echo 'Fast-forward is possible. Merging...'
git merge --ff-only $remote_branch
else
echo 'Fast-forward is not possible. Rebasing...'
git rebase --preserve-merges $remote_branch
fi
I tested it a few times and it seems to work, but I'm not very confident about the git merge-base
part. I know the theory behind a fast-forward merge, and it seems right to use master
and origin/master
as arguments to merge-base
, but I'm no Git expert.
So I ask: is that the correct way to check if a fast-forward merge is possible just after a fetch is performed?
git merge-base --is-ancestor <commit> <commit>
--is-ancestor
Checks if the first <commit>
is an ancestor of the second <commit>
, and exit with status 0 if true, or with status 1 if not. Errors are signaled by a non-zero status that is not 1.
e.g.
git merge-base --is-ancestor origin/master master
You want to use the --ff-only
option.
git merge origin/master --ff-only
If it is possible to fast-forward, it will happen automatically. If it is not possible the command will fail with fatal: Not possible to fast-forward, aborting.
and you can run a rebase command instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With