如何将 git 子模块作为普通目录添加到 git 仓库中?

how can I add git submodule into git repo as normal directory?

让我们看看它是什么

mkdir test sub
cd test && git init && touch README && git add README && git commit -m "initialize the git repo" && cd ..
cd sub && git init && touch README && git add README && git commit -m "initialize the sub git repo" && cd ..
mv sub test
cd test 
git add sub
git commit -m "add sub directory"

我想将它们作为一个git repo 并远程推送它们,但是现在无法包含sub 目录下的文件?

我怎样才能以简单的方式实现这一点,比如将子目录视为普通目录?

此用例

我尝试使用 Dockerfile 将我的 jenkins 数据文件夹 (JENKINS_HOME) 添加到 docker 图像中进行演示。 (ADD JEKINS_HOME /opt/jenkins)

JENKINS_HOME
Dockerfile

我的 jenkin 有 scriptler plugin,其中包含用于其用途的 git 回购协议。然后它存在于我的 docker 图片 git 仓库中,如下所示

$ find jenkins-docker
./.git
./.git/.. (skipped
./Dockerfile
./JENKINS_HOME
./JENKINS_HOME/scriptler
./JENKINS_HOME/scriptler/scripts
./JENKINS_HOME/scriptler/scripts/.git
./JENKINS_HOME/scriptler/scripts/.git/... (skipped)
./JENKINS_HOME/scriptler/scripts/Sample.groovy
./JENKINS_HOME/... (skipped)
./README

看来你不能那样做。名称 .git 在源代码中是硬编码的:https://github.com/git/git/blob/fe9122a35213827348c521a16ffd0cf2652c4ac5/dir.c#L1260

可能一种方法是制作一个脚本,将 .git 重命名为其他名称,然后在将其添加到 repo 之前和之后重新命名,例如

scripts

下的工作目录中
mv .git hidden-git

在 Dockerfile 中

RUN mv $JENKINS_HOME/scriptler/scripts/hidden-git     
$JENKINS_HOME/scriptler/scripts/.git

或者,可能可以将 GIT_DIR 环境变量传递给插件,这样它就可以使用另一个名称。

git add sub
git commit -m "add sub directory"

I want to treat them as one git repo and push them remotely, but now the files under sub directory can not be included ?

它们不包括在内,因为 test 看到回购 sub ,而不是它的 url 如果 sub 被添加为一个子模块。

您需要先将 sub 推送到远程 url,然后将其添加为 test 的子模块以查看 sub 文件。

 cd test
 git submodule add -- /url/to/sub

或者你需要to use a subtree

cd test
git subtree --prefix sub /url/to/sub master --squash