第 15 章 子模块 子模块
本作品已使用人工智能进行翻译。欢迎您提供反馈和意见:translation-feedback@oreilly.com
通常情况下,很多应用程序都依赖于 一个或一组实用程序库。在这种情况下,你会希望每个程序都在自己的 Git 仓库中开发、共享、分支和合并,因为这是逻辑上的分离单位,也可能是因为代码所有权的问题。
但这样划分应用程序会产生一个问题。每个应用程序都依赖于特定版本的共享库,你需要准确地跟踪哪个版本。如果有人不小心将共享库升级到了未经测试的版本,就可能会导致应用程序崩溃。此外,实用程序库并不完全是自己开发的;通常人们会对其进行调整,以添加自己应用程序所需的新功能。最终,他们希望与编写其他应用程序的所有人共享这些新功能;这就是实用程序库的作用。
为了解决这个问题,通常会使用几种策略,包括进行部分签出、将依赖代码直接导入到项目中,甚至将依赖项目作为子文件夹复制到项目中。但这些都不是优雅的解决方案;事实上,有些人认为它们是 "黑客"。
Git 通过子模块解决了这个问题。子模块就是一个项目,它是 Git 仓库的一部分,但也独立存在于自己的源代码控制仓库中。Git 的机制是通过 gitlink 来显示对另一个 Git 仓库的直接引用。在本章中,我们将首先介绍如何使用 git 链接,然后提供几种使用子模块的技巧。最后,我们将讨论作为子模块替代方案的subtree 命令。
Gitlinks
gitlink是树对象指向提交对象的链接。 回顾第二章,每个提交对象指向一个树对象,每个树对象指向一组 blobs 和树,它们分别对应文件和子目录。一个提交的树对象唯一标识了该提交的确切文件集、文件名和权限。还记得在"提交图 "中,提交本身在有向无环图(DAG)中相互连接。每个提交对象都指向零个或多个父提交,它们共同描述了项目的历史。
我们尚未讨论的是树对象如何通过 gitlinks 指向提交对象。我们现在就来讨论这个问题。
我们先创建一个superproject 仓库,将 Git 源代码导入其中:
$cd /tmp$mkdir myapp$cd myapp# Start the new superproject $git init -b mainInitialized empty Git repository in /tmp/myapp/.git/ $echo hello >hello.txt$git add hello.txt$git commit -m 'first commit'[main (root-commit) 2f8e120] first commit 1 file changed, 1 insertion(+) create mode 100644 hello.txt
接下来,我们将直接导入git 项目:
$lshello.txt # clone in a repository as a submodule $git submodule add https://github.com/git/git.git gitCloning into 'git'... remote: Enumerating objects: 329719, done. remote: Counting objects: 100% (338/338), done. remote: Compressing objects: 100% (156/156), done. remote: Total 329719 (delta ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access