如何将仓库子目录迁移至另一仓库根目录(保留提交历史)
Got it, let's solve this properly—you need to move folder1, folder2, folder3 from repo1/folder0 to repo2's root while preserving all their commit history. Copying files manually loses history, so we'll use Git's official recommended tool for history rewriting: git filter-repo (it replaces the old, deprecated filter-branch).
Here's the step-by-step process:
Clone a temporary copy of repo1's folder0
We'll work on a temp repo to avoid messing with your original repository:git clone git@git...net:/folder0.git repo1-temp cd repo1-tempRewrite history to isolate and relocate the target folders
This command will strip out all content exceptfolder1,folder2,folder3(which are underfolder0), and move them directly to the repo root:git filter-repo --path folder0/folder1 --path folder0/folder2 --path folder0/folder3 --path-rename folder0/:''--pathtells Git to only keep commits related to those three folders--path-rename folder0/:''removes thefolder0/prefix, moving the folders to the root
Prepare repo2 to receive the migrated content
Clone repo2 (if you don't already have a local copy) and navigate into it:git clone git@git...net: repo2 cd repo2Pull the filtered content into repo2
Add your temp repo as a remote, then pull its history into repo2 (we use--allow-unrelated-historiesbecause the two repos have no shared history initially):git remote add repo1-temp ../repo1-temp git pull repo1-temp main --allow-unrelated-historiesNote: Replace
mainwithmasterif your repo uses the old default branch name.Verify the migration
Check thatfolder1,folder2,folder3are in repo2's root, and confirm their commit history is intact:# List files in root ls -la # Check commit history for folder1 git log --oneline -- folder1Push the changes to repo2's remote
Once everything looks good, push the updated repo2 to GitLab:git push origin mainClean up the temporary repo
Delete the temp repo since we don't need it anymore:cd .. rm -rf repo1-temp
Important Notes
- Install git-filter-repo first: If you don't have it, install via your package manager (e.g.,
sudo apt install git-filter-repoon Ubuntu,brew install git-filter-repoon Mac) or download the official script from Git's docs. - Team coordination: If other developers have cloned repo2, they'll need to either re-clone the repo or run
git pull --rebaseto avoid merge conflicts with the rewritten history. - Backup first: Always make backups of your original repos before running history-rewriting commands, just in case something goes wrong.
内容的提问来源于stack exchange,提问作者Barath Ravichander

