How to Move a Git Repository into a Sub-Folder of Another Repository

J.A. ShezanJ.A. Shezan
2 min read

Introduction

Git is essential for efficiently managing code. As projects grow, merging repositories becomes vital for smoother workflows. Git subtrees handle this by incorporating one repository into another as a subdirectory. This article explores the mechanics of Git subtrees and how to merge repositories effectively.

Understanding Git Subtrees

Git subtrees merge the history of one repository into another as a subdirectory, unlike submodules that maintain a separate repository within the parent. This consolidation streamlines project management by combining related codebases.

Merging Repositories with Git Subtrees

To merge a repository (Repo B) into another repository (Repo A) as a subfolder, Git provides the git subtree add command. This command requires three parameters:

  • <prefix>: The name of the subdirectory in Repo A where the contents of Repo B will be merged.

  • <repo>: The clone URL of Repo B, specifying which repository to include as a subtree.

  • <rev>: The revision of Repo B to merge into Repo A (usually HEAD for the latest commit).

Step-by-Step Guide:

  1. Identify Prefix: Determine the name of the subdirectory in Repo A where Repo B will reside.

  2. Clone Repository B: Obtain the clone URL of Repo B, ensuring access to its content.

  3. Execute Git Subtree Command: Run the following command inside Repo A, replacing placeholders with appropriate values:

     git subtree add -P <prefix> <repo> <rev>
    

    Example:

     git subtree add -P dir-name git-repo HEAD
    

Benefits of Using Git Subtrees:

  1. Simplified Management: Git subtrees simplify project organization by consolidating related repositories within a single structure.

  2. Preservation of History: The merge process keeps the commit history of Repo B intact, ensuring comprehensive version control.

  3. Ease of Collaboration: Collaborators can seamlessly work across multiple repositories without the complexity of managing separate submodules.

Conclusion

Git subtrees provide a flexible way to merge repositories, allowing developers to organize codebases efficiently and manage projects effectively. By combining repositories as subdirectories, teams can utilize Git's full history and features while maintaining a unified development environment. Integrating Git subtrees into version control workflows enables teams to scale their projects smoothly and collaborate confidently.

0
Subscribe to my newsletter

Read articles from J.A. Shezan directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

J.A. Shezan
J.A. Shezan

Shezan loves technology who is currently studying Computer Science and Engineering. He codes frontend & backend of a website. He also does penetration testing on web apps.