Skip to content

Instantly share code, notes, and snippets.

@robandpdx
Last active March 8, 2024 14:23
Show Gist options
  • Save robandpdx/85e8ca04ac5f28b2f67472524acd3569 to your computer and use it in GitHub Desktop.
Save robandpdx/85e8ca04ac5f28b2f67472524acd3569 to your computer and use it in GitHub Desktop.
Making a monorepo from multiple git repos using git subtree

Making a monorepo from multiple git repos using git subtree

You may have several git repos that you want to combine into a single git repo. Here is how you can accomplish this using git subtree...

  1. Create a new git empty repo.
  2. Add a remote for each repo you want to include in the final repo git remote add k8s-azure-terraform https://github.com/robandpdx/k8s-azure-terraform.git.
  3. Fetch the remote branches git fetch k8s-azure-terraform
  4. Use git subtree add to pull in the repo git subtree add --prefix k8s-azure-terraform k8s-azure-terraform main
  5. Push all tags git push --tags

Repeat the above steps for all repos you intend to combine in the monorepo.

Getting the branches

Create a new branch in the monorepo for each brach in the repo you are adding to the monorepo. Then use git subtree pull to merge the branch of the same name into the newly created branch. You may need to resolve conflicts. I usually resolve the conflicts using --theirs. It is important to note that this rebases the brances from main, which is probably OK, but definitely worth noting.

  git subtree pull --prefix=k8s-azure-terraform  k8s-azure-terraform webhook-autoscaler
  grep -lr '<<<<<<<' . | xargs git checkout --theirs
  git add -A
  git commit -m "resolved conflict using --theirs"

Then push all branches to origin...

for REF in $(git for-each-ref --format='%(refname)' refs/heads); do
      BRANCH_NAME=${REF#refs/heads/}
      git push -u origin ${BRANCH_NAME}
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment