Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate if commit exists

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
like image 600
takeshin Avatar asked Nov 08 '10 20:11

takeshin


People also ask

How do you check if a commit exists git?

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...

How do you check if commit is present in branch?

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.

What is grep in git?

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.


2 Answers

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).

like image 129
Janne Avatar answered Nov 01 '22 21:11

Janne


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.

like image 45
Cascabel Avatar answered Nov 01 '22 23:11

Cascabel