Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the correct way to check if it's possible to perform a fast-forward merge with git merge-base?

Tags:

git

I've created a bash script that performs the following tasks:

  1. Fetch changes from upstream;
  2. Check if a fast-forward merge is possible;
  3. Merge origin/master into master if #2 is true;
  4. Rebase master on top of origin/master if #2 is false

The 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?

like image 525
Michael Benford Avatar asked Jul 01 '14 07:07

Michael Benford


2 Answers

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
like image 51
Scott Ding Avatar answered Nov 16 '22 18:11

Scott Ding


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.

like image 6
Tom Avatar answered Nov 16 '22 19:11

Tom