Reputation: 50638
How to validate whether the commit with given sha exists in current branch?
There are many ways to parse outputs, but I need optimal way which returns boolean (for usage in bash script).
e.g.
sha=$1
if [ -z `git magic --validate $sha` ]; then
echo "Invalid commit sha: $sha"
exit 1
fi
Upvotes: 22
Views: 13156
Reputation: 83205
git merge-base --is-ancestor $sha HEAD
This tests if $sha
is an ancestor commit for the current branch (HEAD
), and exits successfully if it is.
In your example,
sha=$1
if ! git merge-base --is-ancestor $sha HEAD; then
echo "Invalid commit sha: $sha"
exit 1
fi
Upvotes: 2
Reputation: 89
git cat-file prints information about the objects in the repository. "-e" checks if the object is valid and exits with a 0 status and when invalid exists with a 1.
git cat-file -e 3d68db1028afe27a0055c2234f98fc945b1958f5
echo $?
1
Upvotes: 4
Reputation: 259
git rev-parse --quiet --verify <commit>
Does not actually verify that commit (I guess SHA1 is what is meant) exists. It verifies that there is an object in the database corresponding to the SHA1 provided. That is, if there is a blob or tree object that matches the SHA1, it will report that it exists, even if it is not a commit.
git rev-parse --quiet --verify <sha1>^{commit}
This will verify that the object exists and that it is an object that can be used as a commit (commit or annotated tag).
Upvotes: 25
Reputation: 496722
The rev-list | grep
method works fine; there's the tiniest bit of overhead because git has to print out all the SHA1s for grep
to see, but it's not really a big deal.
You can also do it with git merge-base
if you like - if the merge base of the target commit and the branch is the target commit, the branch contains the target commit:
if [ "$(git merge-base $commit $branch)" = "$commit" ]; then
...
fi
Either way you do it, note that rev-list
and merge-base
are going to be printing out SHA1s, so if the commit you're testing for inclusion is named by a branch or tag, you'll want to use git rev-parse
to turn it into an SHA1 first.
Upvotes: 4
Reputation: 601351
You can look at the output of
git rev-list HEAD..$sha
If this command fails because the sha1 does not exist at all in the repository, the exit code will be non-zero. If the output is empty, the commit is in the current branch, and if it is non-empty, it is not. So your script would look like
if revlist=`git rev-list HEAD..$sha 2>/dev/null` && [ -z "$revlist" ]; then
:
fi
In case you already know that $sha
really names a commit (as a SHA1 hash or in any other way), this simplifies to
if [ -z "`git rev-list HEAD..$sha`" ]; then
:
fi
Upvotes: 4
Reputation: 58770
git rev-list branch-youre-interested-in | grep -q sha-youre-interested-in
You can use the exit code from grep in conditionals.
For the current branch,
git rev-list HEAD | grep -q sha-youre-interested-in
Upvotes: 1