Git - How to merge two repositories into one using git subtree add
Git - How to merge two repositories into one using git subtree add
September 30, 2024
How to merge two repositories into one
例如你已經開發一個 web 一段時間,有一個 backend 的 repo 和一個 frontend 的 repo,現在想要將它們合併成一個 repo,又不想完全失去之前的歷史記錄,就可以用 git subtree add
加入指定 repo 的 commit tree。
git subtree add
git subtree add -P <prefix> add <repository> <remote-ref>
<prefix>
: 要放在哪個 subdirectory<repository>
: repository link<remote-ref>
: branch
Example
# Go to your new project folder and init git
echo "# my_project" >> README.md
git init
# You must have one commit to use git subtree add
git add README.md
git commit -m "first commit"
# For example, put the backend repo into the backend folder
git subtree add -P backend https://github.com/path_to_backend.git main
# And frontend folder
git subtree add -P frontend https://github.com/path_to_frontend.git main
Ref
- https://stackoverflow.com/a/32684526/19055115
- git subtree
- 除了 add 還有 merge 、split 等等各種進階的用法