Move a subdirectory into a new git repository

Print Friendly, PDF & Email

Context

In the real world, we may probably have a large Git repository where you want to move out some sub-directories into single Git repositories. Regarding the Git repository, we likely want to preserve old commits or commits relevant to those directories during the movement. Of course, we cannot move them using the standard way of moving files/directories as usual because the Git histories won’t be moved along with the files. Fortunately, Git supports us to do it by implementing subtree split command.

We will exercise with one of our GitHub repositories: https://github.com/ITersDesktop/devops although it is not a big repository. To ease your reading, we are supposed to move the K8s directory out of the repository.

Steps

Thanks for the answer, we demonstrate the step-by-step procedure to move the K8s directory from the GitHub repository above and create a new one.

Step 01: Create a new branch in the old/big repository

~/tmp > cd devops 
~/tmp/devops > git subtree split -P K8s -b k8s 
Created branch 'k8s' 
03d9101f8b5647da94c4b4387660746cfb45bca4

Note: <name-of-folder> must NOT contain leading or trailing characters. For instance, the folder named subproject MUST be passed as subproject, NOT ./subproject/

Note: <name-of-new-branch> is a branch you will be creating in the existing/old repo, NOT the new one [that comes later].

Note for Windows users: When your folder depth is > 1, <name-of-folder> you must have *nix style folder separator (/). For instance, the folder named path1\path2\subproject MUST be passed as path1/path2/subproject

Step 02: Create a new repository and pull all commits

~/tmp/devops > cd ../
 ~/tmp > mkdir k8s
 ~/tmp > cd k8s
 ~/tmp/k8s > git init
Initialized empty Git repository in /Users/tnguyen/tmp/k8s/.git/
 ~/tmp/k8s > git pull ~/tmp/devops k8s
remote: Enumerating objects: 12, done.
remote: Counting objects: 100% (12/12), done.
remote: Compressing objects: 100% (5/5), done.
remote: Total 12 (delta 3), reused 8 (delta 3), pack-reused 0
Unpacking objects: 100% (12/12), 3.60 KiB | 263.00 KiB/s, done.
From /Users/tnguyen/tmp/devops
 * branch            k8s        -> FETCH_HEAD

To clarify the result, we run git log or git log --oneline to see all the commit messages. Also, by running these commands on the old/big repository we can check all commits relevant to the K8s directory.

There have been four commits as of writing these lines. If we look into the long list of commit messages of the original repo as the screenshot below, we can find out where these commit messages come.

 

 

 

This just copies commits relevant to the specific subdirectory.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.