Git 递归地向子模块添加遥控器

Git add remotes to submodules recursively

我的机器上有一个 git 存储库 /path/to/repo,其中包含几个子模块,/path/to/repo/submoduleA/path/to/repo/foo/bar/submoduleB

由于我无法更改的工作流程,git 存储库被复制(如在 scp -r 中)到我处理代码的远程服务器。我想将更改拉回原始机器。来自远程服务器的 Cloning/pushing 不是一个选项。

去每个子模块做

很乏味

git remote add <name> <url>:/server/path/to/repo/<path to submodule>

有没有更快的方法?像

这样神奇的东西

git remote add --submodules <name> <url>:/server/path/to/repo

从顶级 repo 执行,它将递归到每个子模块并将适当的相对路径添加到每个子模块的远程? git remote --help 没有显示任何有用的信息,Git Pro Book section on submodules.

也没有显示任何有用的信息

我最好的猜测是

git submodule foreach 'git remote add <name> <url>:/server/path/to/repo/...'

可能会起作用,如果有一种方法可以将 ... 替换为该 foreach 中每个子模块的循环相关相对路径。我只是不知道 git submodule foreach

中内置了这样的机制

git submodule foreach 包含一个变量列表,应该有帮助:

The command has access to the variables:

  • $name.gitmodules
  • 中相关子模块段的名称
  • $sm_path: 直接超级项目中记录的子模块路径,
  • $displaypath:包含当前工作目录到子模块根目录的相对路径,
  • $sha1:直接超级项目中记录的提交,以及
  • $toplevel: 直接超级项目顶层的绝对路径。

所以在你的情况下:

git submodule foreach 'git remote add $name <url>:/server/path/to/repo/$sm_path'

$displaypath 会将 ... 替换为每个子模块的依赖于循环的相对路径。
但是,正如 OP waldol1 in 所指出的,$sm_path 是一个固定值,而不是相对路径。

带有 docker/docker.github.io 的示例,在 子文件夹 中执行 tests:

D:\git\docker.github.io\tests>git submodule foreach "echo $displaypath"
Entering 'src/github.com/gdevillele/frontparser'
src/github.com/gdevillele/frontparser

vs.

D:\git\docker.github.io\tests>git submodule foreach "echo $sm_path"
Entering 'src/github.com/gdevillele/frontparser'
tests/src/github.com/gdevillele/frontparser