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
You can just run git cat-file -t $sha and check it returns "commit". You are right, you don't need to actually print the actual object for that...
Search the branch (say, feature ) with exact matching. You can also search in both local and remote branches (use -a ) or only in remote branches (use -r ). The grep here could also result in false positives if there are other branches containing the commit whose names also contain <branch-name> as a substring.
Git Grep. Git ships with a command called grep that allows you to easily search through any committed tree, the working directory, or even the index for a string or regular expression. For the examples that follow, we'll search through the source code for Git itself.
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).
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.
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