1

If I query the bitbucket api for commits, I get the long version:

bitbucket_curl(){
    curl -H 'Authorization:Basic YW1JyKg==' "https://api.bitbucket.org$@"
}

commits="$(bitbucket_curl '/2.0/repositories/interos/datavana/commits/alex/dockerize?pagelen=3')"

latest_commit="$(echo "$commits" | jq -r '.values[0].hash')"

given a long commit: c56cefbd0c81142558cf814cba7d7cd75d7cb6a7

is there a way to reliably get the short commit hash? Isn't it like the last 10 chars or something? Or perhaps there is a way to request the short hash from the Bitbucket API? On that subject I am looking for a reliable way to get the most recent commit for a branch.

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
  • 1
    There is no *reliable* way. *By convention* it's **the first** 7 characters for small projects, 8 for big projects and 10 for huge projects. *Almost* certainly you'll be safe by always taking the first 10. – phd May 29 '19 at 23:58
  • 1
    A short hash that is valid today might not be tomorrow. Just stick with the long ones. – Andrew C May 30 '19 at 04:59

2 Answers2

2

I don't know the Bitbucket API well, and whether or not its endpoints require the full SHA-1 hash, but as far as I know there is no official short version of commit hash. The only general requirement is that the fragment of a hash used can correctly resolve to just a single commit.

Bitbucket web seems to display only the first 7 characters of the SHA-1 hash. There are roughly 78 billion different hashes of length 7, so it would be unlikely to have a collision on a single page.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • Sounds like it's best to stick to the long-hash since one day you may want hashes that are universally unique not just unique for one repo. – Alexander Mills May 30 '19 at 22:14
1

git has a command to get the short version of a commit hash, given the full commit hash as input.

git rev-parse --short $commit

If the $commit is c56cefbd0c81142558cf814cba7d7cd75d7cb6a7, this would output c56cefb

Found the solution in this SO answer by mark-longair

Snailedlt
  • 460
  • 6
  • 14
  • according to the other answers/commits, the long-hash is more reliable, and I think originally this is about the bitbucket api not necessarily git locally (although they aren't really different in terms of how git works) – Alexander Mills May 11 '22 at 19:22
  • @AlexanderMills The command is a git command, not a bitbucket command, so it shouldn't really matter if it's bitbucket, GitHub, GitLab, or just git locally. It should work either way. And yes, for very, very large projects it's possible that you could get the same short commit hash, in which case it would be better to use the full commit hash instead. That said, the short hash is nice to use if you want to reference something in something temporary, like a feature branch, and you don't want it to take up a lot of space. – Snailedlt May 11 '22 at 20:18