如何只克隆部分代碼?

如何只克隆部分代碼?

一、需求

根據整體規劃需求,多個模塊的源碼共存在一個倉庫中。在一些場景執行中,需要考慮執行效率,僅關注部分路徑的代碼。即僅需獲取部分路徑的文件。

二、解決方案

利用Sparse Checkout模式。官方信息描述如下:

Sparse checkout

"Sparse checkout" allows to sparsely populate working directory. It uses skip-worktree bit (see git-update-index(1)) to tell Git whether a file on working directory is worth looking at.

"git read-tree" and other merge-based commands ("git merge", "git checkout"…) can help maintaining skip-worktree bitmap and working directory update. $GIT_DIR/info/sparse-checkout is used to define the skip-worktree reference bitmap. When "git read-tree" needs to update working directory, it will reset skip-worktree bit in index based on this file, which uses the same syntax as .gitignore files. If an entry matches a pattern in this file, skip-worktree will be set on that entry. Otherwise, skip-worktree will be unset.

Then it compares the new skip-worktree value with the previous one. If skip-worktree turns from unset to set, it will add the corresponding file back. If it turns from set to unset, that file will be removed.

While $GIT_DIR/info/sparse-checkout is usually used to specify what files are in. You can also specify what files are not in, using negate patterns.

三、基本操作過程

1. 準備

$mkdir code_dir
$cd code_dir
$git init
$git remote add -f origin <url>

2. 啓用sparsecheckout模式

$git config core.sparsecheckout true

3. 設置排除的路徑

編輯 .git/info/sparse-checkout

$echo “want_dir/*” >> .git/info/sparse-checkout

4. 拉取代碼

$git pull origin master

四、如何設置sparsecheckout文件

子目錄的匹配

  • 如果目錄名稱前帶斜槓,如/docs/,將只匹配項目根目錄下的docs目錄
  • 如果目錄名稱前不帶斜槓,如docs/,其他目錄下如果也有這個名稱的目錄,如test/docs/也能被匹配。
  • 如果寫了多級目錄,如docs/05/,則不管前面是否帶有斜槓,都只匹配項目根目錄下的目錄,如test/docs/05/不能被匹配。

通配符 “*“ (星號)

支持通配符 “*“,如可以寫成以下格式:

*docs/
index.*
*.gif

排除項 “!” (感嘆號)

支持排除項 “!”,如只想排除排除項目下的 “docs” 目錄,可以按如下格式寫:

/*
!/docs/

五、如何關閉sparsecheckout模式

  1. 將core.sparsecheckout設爲false
  2. 修改 .git/info/sparse-checkout 文件,用一個”*“號替代其中的內容
  3. 執行 checkout 或 read-tree 命令

六、注意事項

  1. 如果排除是臨時性的,要及時清除相關設置,否則就是一個隱患,即導致環境不可重入。
  2. 僅限 Git 1.7以上版本

參考

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章