How do I move an existing Git submodule within a Git repository?

后端 未结 10 665
面向向阳花
面向向阳花 2020-11-29 14:39

I would like to change the directory name of a Git submodule in my Git superproject.

Lets suppose I have the following entry in my .gitmodules file:

10条回答
  •  野性不改
    2020-11-29 15:04

    You can just add a new submodule and remove the old submodule using standard commands. (should prevent any accidental errors inside of .git)

    Example setup:

    mkdir foo; cd foo; git init; 
    echo "readme" > README.md; git add README.md; git commit -m "First"
    ## add submodule
    git submodule add git://github.com/jquery/jquery.git
    git commit -m "Added jquery"
    ## 
    

    Examle move 'jquery' to 'vendor/jquery/jquery' :

    oldPath="jquery"
    newPath="vendor/jquery/jquery"
    orginUrl=`git config --local --get submodule.${oldPath}.url`
    
    ## add new submodule
    mkdir -p `dirname "${newPath}"`
    git submodule add -- "${orginUrl}" "${newPath}"
    
    ## remove old submodule
    git config -f .git/config --remove-section "submodule.${oldPath}"
    git config -f .gitmodules --remove-section "submodule.${oldPath}"
    git rm --cached "${oldPath}"
    rm -rf "${oldPath}"              ## remove old src
    rm -rf ".git/modules/${oldPath}" ## cleanup gitdir (housekeeping)
    
    ## commit
    git add .gitmodules
    git commit -m "Renamed ${oldPath} to ${newPath}"
    

    Bonus method for large submodules:

    If the submodule is large and you prefer not to wait for the clone, you can create the new submodule using the old as origin, and then switch the origin.

    Example (use same example setup)

    oldPath="jquery"
    newPath="vendor/jquery/jquery"
    baseDir=`pwd`
    orginUrl=`git config --local --get submodule.${oldPath}.url`
    
    # add new submodule using old submodule as origin
    mkdir -p `dirname "${newPath}"`
    git submodule add -- "file://${baseDir}/${oldPath}" "${newPath}"
    
    ## change origin back to original
    git config -f .gitmodules submodule."${newPath}".url "${orginUrl}"
    git submodule sync -- "${newPath}"
    
    ## remove old submodule
    ...
    

提交回复
热议问题