Search code examples
gitdirectorybranchshared

How to set a folder to be used in different branches in git?


Suppose we have two branches as A and B, and these branches have files and folders.

But I want to set a folder named X to be used in both branches simultaneously.

For example: Branch A will contain a1.js, a2.js and the X folder. Branch B will contain b1.js, b2.js and the same X folder as in A.

In short, the X folder will be shared in A and B branches so that all the changes in X will automatically be applied for both.

How can I do that?


Solution

  • Short answer

    You cannot do that with branches

    Longer answer

    In git folders and files does not belong to branches, they are contained in commits.

    So when you commit something "on a branch", there is no way that the folder is updated in another branch and this does not even makes sense: the only option is to create a new commit on the other branch with the same modifications to the shared folder.

    This is not the place to discuss all git details but there is a lot more to know to understand this answer...

    Branches is not what you are looking for

    There are many options to solve your problem. I'm listing three of them from worst to best but I encourage you to keep researching the best solution to your specific case

    1. [worst] Make a script to cherry pick the commits about the shared folder from one branch to the other

    2. [better] Put the shared folder in a separate repository and set up a submodule

    3. [probably best of three] Review your architecture and take the shared resource in a separate module (application module, not git stuff) and treat it separately from your code