不创建提交记录的情况下设置git子模块

4

我有一个父项目,其中包含以下的.gitmodules文件。

[submodule "src/redux"]
    path = src/redux
    url = git@github.com:username/sub-package.git
    branch = master

以下是我用来克隆父项目以确保子模块设置正确的步骤。

git clone git@github.com:username/parent-project.git
git submodule init
git submodule update

之后,我将子模块的内容放在了父项目中。然而,子模块的HEAD处于分离状态。这是我没有做对的第一个迹象。由于父项目的.gitmodules文件指向主分支,我期望它应该在主分支上。

enter image description here

我随后检查了主分支,并设置子模块的主分支以跟踪远程主分支。
git checkout master
git branch -u origin/master master

当我回到父项目并运行git status时,子模块中有一个未提交的更改。

enter image description here

我觉得在初始设置时不应该进行这种更改。如果这样做,所有克隆项目的开发人员在设置本地环境时也会有自己独特的初始提交。我做错了什么?


可能是 git 子模块修改文件状态 的重复问题。 - smarber
@smarber,这确实回答了一些问题,但我仍然不明白.gitsubmodules中的branch = master有什么好处。 - David
1个回答

1
子模块有些棘手;如果你使用它们,你需要确保团队中的每个开发人员都理解Git模型以及它如何处理子模块。
当你将子模块添加到仓库中时,子模块的内容永远不会被添加到仓库本身;关于子模块,父仓库记录的唯一信息是它对应的提交哈希。如果你运行git diff -- src/redux,你可以看到这一点。
这意味着当你运行git submodule init时,你正在更新子模块的工作树以反映存储在索引中的哈希值;来自git-submodule(1)
   init
       Initialize the submodules recorded in the index (which were added
       and committed elsewhere) by copying submodule names and urls from
       .gitmodules to .git/config. Optional <path> arguments limit which
       submodules will be initialized. It will also copy the value of
       submodule.$name.update into .git/config. The key used in
       .git/config is submodule.$name.url. This command does not alter
       existing information in .git/config. You can then customize the
       submodule clone URLs in .git/config for your local setup and
       proceed to git submodule update; you can also just use git
       submodule update --init without the explicit init step if you do
       not intend to customize any submodule locations.

.gitmodules 存储有关子模块配置的其他信息,具体而言,当您更新子模块时,即将其指向更近期的提交时,使用 submodule.src/redux.branch;另外来自于git-submodule(1)

   --remote
       This option is only valid for the update command. Instead of using
       the superproject’s recorded SHA-1 to update the submodule, use the
       status of the submodule’s remote-tracking branch. The remote used
       is branch’s remote (branch.<name>.remote), defaulting to origin.
       The remote branch used defaults to master, but the branch name may
       be overridden by setting the submodule.<name>.branch option in
       either .gitmodules or .git/config (with .git/config taking
       precedence).

如果在子模块中创建并切换到一个特性分支,然后退出子模块并执行 git submodule update 命令,而 .gitmodules 文件指定了 branch = master,会发生什么?这样做是否会将主分支的提交拉入你的特性分支中? - David
再次引用 git-submodule(1) 中的内容:update: 通过克隆缺失的子模块并更新子模块的工作树,使注册的子模块与超级项目期望的匹配。根据命令行选项和 submodule.<name>.update 配置变量的值,可以以多种方式进行“更新”。 - Pockets

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接