Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fork part of a monorepo and still be able to merge upstream commits?

Sometimes I find monorepo on GitHub that consists of multiple npm packages, which I would like to make some modification and use it in my projects. But it's much harder for npm to install package from a git subdirectory than to install from a git repository[1][2]. Since I would make my own modification, I wonder how can I set up my own git repository so that it is easy for npm to install, and for me to merge upstream changes.

Currently, I used this guide from GitHub to split the package from the rest of the monorepo, i.e.

git filter-branch --prune-empty --subdirectory-filter FOLDER-NAME  BRANCH-NAME 

Npm can install the repo easily, but I find it difficult to merge any upstream change.

Has anyone done this before? Any idea?

like image 451
user5532169 Avatar asked Oct 24 '25 22:10

user5532169


1 Answers

Actually, I think I missed something - merging upstream changes is not as hard as I thought, because git subtree split is deterministic i.e. it produces the same SHA1 for the same subtree split, no matter how many times the process is repeated.


So here's my solution:

  1. Clone the monorepo
  2. Rename the default branch (master) to something else e.g. upstream

    git checkout master
    git branch -m upstream
    
  3. Split the subdirectory from the monorepo

    git checkout upstream
    git subtree split -P <subdirectory path> -b master
    

    Now we have a master branch sitting there with only commits related to the subdirectory path.

  4. (optional) Set the remote for master branch and push it to GitHub.

Now if the upstream monorepo added some changes:

  1. Checkout the upstream branch and pull the changes

    git checkout upstream
    git pull
    
  2. Split again

    git subtree split -P <subdirectory path> -b upstream-patch
    

    Check the revision graph, you will see that the new branch (upstream-patch) is related to master.

    gitk master upstream-patch
    
  3. Now simply merge the new branch to master

    git checkout master
    git merge upstream-patch
    

    Manually resolve any merge conflicts.

  4. (optional) git push
like image 83
user5532169 Avatar answered Oct 27 '25 18:10

user5532169