Uzlopak
Uzlopak

Reputation: 342

Get Commit-Hash of specific file/folder from remote git-repo

Currently we do git log --pretty=tformat:"%H" -n 1 folder/file to retrieve the latest commit hash of the file in the current checked out branch. But this needs to have the git repo being cloned locally.

Is there a way to determine the commit hash of a specific file in a specific branch on the remote git repo?

I need a plain git command for this, not a command for a git interface like git or gitlab.

Upvotes: 1

Views: 1523

Answers (1)

torek
torek

Reputation: 487725

Is there a way to determine the commit hash of a specific file in a specific branch on the remote git repo?

Not exactly, no. You can only do this with commits that exist locally, and there's no guarantee that any commit that they have, you also have. So there are actually two problems here:

  • First, you need to determine the hash ID that they use for their branch name.

  • Then, having done the above, you need to make sure that you have that commit and its predecessors.

You can then use a local operation to find, locally, the local commit in which the file you care about was most recently changed, in the same way you're already doing it. But you need to hit both of those two bullet points first. The way to do that is to have the repository locally, add the other Git as a remote, and run git fetch to that remote, so that you get remote-tracking names that correspond to their branch names.

Let's say, for instance, that the URL for their Git repository is $url. You can then use:

git remote add them $url
git fetch them

followed by a tiny modification to:

git log --pretty=tformat:"%H" -n 1 folder/file

Just add them/branchname before the pathname (and, for general safety, add -- before the pathname as well):

git log --pretty=tformat:"%H" -n 1 them/branchname -- folder/file

Note that you need only use git remote add once, but you need to run the git fetch them just before any scan, to pick up any new commits they have and get the updated value of their branchname into your them/branchname.

(You can optionally use git fetch them branchname, which will sometimes save a little bit of time.)

Upvotes: 1

Related Questions