1

For my specific use case, I only need a shallow git clone that contains just two specific commits, and nothing else (no remaining history, no other branches).

Here are some things I tried:

  • I want to fetch two refs, hence git clone --single-branch --branch BRANCHNAME is not good, because that fetches only one branch
  • I want to fetch refs which are not branch names (say, 4ebbd7cc6 and fc139d960), which is another reason why git clone --single-branch --branch BRANCHNAME is not good.
  • I want truly minimal history. Just those two commits and nothing else. There can be any arbitrarily long git history between those two commits, and there are hundreds of branches. Hence doing git clone --depth N --no-single-branch is not good, as it will fetch all the branches and tags that I don't need, and I can't know anyway what a good N could be, so that I would overfetch anyway even if there were no branches and tags.

What's the correct way to fetch exactly n commits and nothing else?

jakub.g
  • 38,512
  • 12
  • 92
  • 130

1 Answers1

1

Instead of cloning, the solution is to init an empty git repo, and fetch each ref one-by-one with --depth 1:

mkdir FOLDER_NAME
cd FOLDER_NAME
git init
git remote add origin GIT_URL
git fetch --depth 1 origin REF1
git fetch --depth 1 origin REF2
jakub.g
  • 38,512
  • 12
  • 92
  • 130
  • 1
    This is probably the way to go, because `git clone` runs `git fetch` for you in a way you can't control properly. Note however that `git clone -b ` does allow the given `` to be a tag name. Most servers do not allow raw hash IDs, but if you want a name that's not in a "normal" namespace (e.g., if you want `refs/for/master` for instance) I'm not sure `git clone` itself allows that. The explicit separate fetch definitely *does* allow it. – torek May 01 '20 at 10:54
  • I tried this but this fetches all of the objects twice. I can see the first fetch brought 85 MB, then I fetched a SHA that is the next commit after this (1 file changed only) and another 85 MB was downloaded. Is there a way to not re-fetch objects that I already have downloaded? – Premek Vysoky Nov 07 '22 at 12:54