The following two scripts, write dead branch is master, if the main branch is not master, you need to make corresponding changes.
Nikita240 - Stack Overflow
📚️Reference:
I modified and improved it. The new subtree will now point to the same commit as the old submodule. Previously, the script simply downloaded the latest commit from the target repository, which could cause compatibility issues.
#!/bin/bash -x # This script will convert all your git submodules into git subtrees. # This script ensures that your new subtrees point to the same commits as the # old submodules did, unlike most other scripts that do this. # THIS SCRIPT MUST BE PLACED OUTSIDE OF YOUR REPOSITORY!!!!!!!!!! # Otherwise, the script will interfere with the git commits. # Save the script in your home directory as `~/subtrees.sh` # `cd` into your repository # Run `~/subtrees.sh` # Enjoy!
# extract the list of submodules from .gitmodule cat .gitmodules |whileread i do if [[ $i == \[submodule* ]]; then echo converting $i read i # extract the module's prefix mpath=$(echo$i | grep -E "(\S+)$" -o) echo path: $mpath read i # extract the url of the submodule murl=$(echo$i|cut -d\= -f2|xargs) echo url: $murl # extract the module name mname=$(basename$mpath) echo name: $mname # extract the referenced commit mcommit=$(git submodule status $mpath | grep -E "\S+" -o | head -1) echo commit: $mcommit # deinit the module git submodule deinit $mpath # remove the module from git git rm -r --cached $mpath # remove the module from the filesystem rm -rf $mpath # commit the change git commit -m "Removed $mpath submodule at commit $mcommit" # add the remote git remote add -f $mname$murl # add the subtree git subtree add --prefix $mpath$mcommit --squash # commit any left over uncommited changes git commit -a -m "$mname cleaned up" # fetch the files git fetch $murl master echo fi done git rm .gitmodules git commit -a -m "Removed .gitmodules"
GaspardP - Stack Overflow
📚️Reference:
I modified it slightly, calledsubtree addInstead ofread-tree。 It will start with.gitmoduleto get a list of submodules, and extract the prefix, name, and URL of the module. It then removes each submodule and adds them as subtrees in the same location. It also adds each submodule’s remote as remote, so you can update the subtree by providing its name instead of its URL (iegit subtree pull -P Foo Foo master --squashInstead ofgit subtree pull -P Foo https://example.com/foo.git master --squash)。
If you want to import the entire history of the subtree into your repository, you can remove it --squash Parameter. use --squash, only the HEAD of the subtree will be imported into your repository. This is probably what most people want.