Amethyst Studio
403 words
2 minutes
Git稀疏检出
2024-03-23

当我们使用git clone命令的时候,我们是默认完整克隆整个仓库的。但是,如果我们要工作的仓库过于庞大,而我们本身又只需要修改其中的一部分文件的话,克隆整个仓库就会显得非常不必要,此时我们可以使用git的稀疏检出功能,来只克隆和修改部分文件。

做法#

假设我们的仓库名称为project,地址在https://github.com/<YourName>/project.git,我们可以这样做:

  1. 创建一个空目录来存放项目:

    $ mkdir project
    $ cd project
  2. 初始化git仓库,添加远端仓库地址

    $ git init
    $ git remote add origin https://github.com/<YourName>/project.git
  3. 配置本地仓库为稀疏检出模式:

    $ git config core.sparsecheckout true
  4. .git/info下,创建一个sparse-checkout文件,然后写入需要的文件和目录名,假设我们只需要修改README.md,目录dir1下的所有文件,以及目录dir2下的main.cc,那么在sparse-checkout文件下,可以这样写:

    README.md
    dir1/*
    dir2/main.cc
  5. 接着,拉取远端代码即可

    $ git pull origin master

更新稀疏检出路径#

如果后续需要修改.git/info/sparse-checkout来检出额外的文件或目录,可以直接编辑该文件并添加新行:

$ echo "dir3/*" >> .git/info/sparse-checkout

完成编辑后,运行以下命令刷新稀疏检出的内容:

$ git read-tree -mu HEAD

注意一下gitignore#

因此,不要将.gitignore文件内容用于稀疏检出,也就是不要把.gitignore写入到sparse-checkout文件里面。因为gitignore和sparse-checkout的作用正好相反。如果你讲.gitignore写到sparse-checkout里面,你会发现sparse-checkout将不会起作用。

Git稀疏检出
https://ziyue.cafe/posts/git-sparse-checkout/
Author
Kaida Amethyst
Published at
2024-03-23