Search code examples
gitshallow-clone

git shallow clone *several* specific refs (commits), *which are not branches*


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?


Solution

  • 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