TIL: Extract subdirectory with git history to another repository

:til: :git:

Today I needed to extract git history of particular subdirectory and move it to a separate repository. Source repository here contains original code from which we want to extract the history. Meanwhile target repo is new repository to which we want to import the history.

Command below creates a branch named “kyria” on source repository with commits from specific path only:

$ git subtree split --prefix=keyboards/kyria/pawka --branch=kyria

Keep in mind that files in the new branch are displayed as those were created at the root of repository. Let’s say if we had a file on source repo keyboards/kyria/pawka/config.h. On the kyria branch it will be placed on the root as config.h only (no keyboards/kyria/pawka/ prefix). This is allows treat a subdirectory as completely new repo if needed. But I needed to create a new repo and place all files on specific path.

Let’s create a new repo:

$ cd ~/
$ mkdir target_repo
$ cd target_repo

Command below must be executed on the new repository to import history from the kyria branch to specific path. New repository must contain at least one commit

  • make sure there is one.
$ git subtree add --preffix=qmk/keyboards/kyria/ ../source_repo kyria

This will clone all files from the kyria branch on source_repo to the qmk/keyboards/kyria/ path on the target_repo.

In this way I’ve successfully imported history of couple paths from the original repository.