Search code examples
gitgit-clone

How can I clone up to a specific tag in a git repository and not include history or commits following that tag?


I've read dozens and dozens of similarly worded questions and none of them seemed to fit my needs. I have a repository with many tags and commits. I would like to go back to a commit/tag from several years ago and clone that tag and the history leading up to that tag and no further.

Here is a simplified representation:

A - B - C - D - H - I - ... ZZZ
  \            /     \     /
   E - F - G          J - K

I want to clone the repo, but only up to commit H, resulting in a repo that appears as follows:

A - B - C - D - H
  \            / 
   E - F - G

I am aware of the destructive nature of the action I am planning. I will backup the existing repo before messing with it. It is definitely my intent to not include I onward in the resulting clone.


Solution

  • You're going to have to clone more history than you want. But once you have it, you can truncate the history to the tag of your choice. Start by cloning the repository:

    git clone --no-tags someurl myrepo
    

    Now, reset the head of the repository to your chosen reference:

    cd myrepo
    git reset --hard ref-of-interest
    

    And you should have what you want.

    Note that here I've explicitly cloned with --no-tags, so tags won't be available locally. If you do want to truncate the history to a particular tag, you can (a) clone without the --no-tags option, or (b) git reset --hard to an explicit commit id, rather than the tag name.