1

I want to fetch the second last commit from a repository without cloning. Currently I am using git ls-remote <repo> <branch> | cut -c1-7. This helps me to get the latest commit's sha1 without cloning the repository. Can I use this in some way or any other command to fetch the second-last commit?

Saurabh Shah
  • 576
  • 1
  • 5
  • 19
  • That doesn't seem to be possible without some kind of cloning/fetching: http://stackoverflow.com/questions/13941976/commit-history-on-remote-repository – VonC May 30 '16 at 07:43

1 Answers1

0

It's not possible in general.

It may be possible in specific cases.

Let's define a few terms so that the rest of this discussion makes sense:

  • B is the branch name you're interested in, i.e., you are running git ls-remote remote B.
  • IB is the identity (SHA-1 hash) obtained from B, i.e., is the tip commit on the branch.
  • The "second-last" commit is the parent of IB. If IB is a merge, it's the first parent (you did not specify this but it seems like a reasonable assumption; if it's wrong, make whatever changes you like to the procedure below). We'll call this ID W, for "want".

Your task is to identify W.

You cannot do this without assistance or a (possibly shallow) clone. If you have a clone, it's trivial to find W: git rev-parse B^ produces W. (If the clone is shallow, a depth of 2 or more suffices to have, and hence find, W.) If you do not have a clone, you will have to somehow get the remote to give you W.

If your remote offers a web interface, that may allow you to read the tip commit and hence find its parent IDs. It may even have an actual API (REST interface or whatever) by which you can traverse the commit graph, giving it IB and getting the list of parent IDs. But there is no standard interface other than cloning.

Note that if you make a single-branch shallow clone of depth 2 of branch B, that will get commit IB and all its parents, including W. So that's the obvious way to do the least amount of work and yet be guaranteed to be able to find W. But that involves making a clone, which you have ruled out.

Edit: I just realized this has a github tag as well, so you may be asking specifically about github. In github's case there is an API, and you can simply obtain information about IB directly.

torek
  • 448,244
  • 59
  • 642
  • 775