Git 子模組

Git 進階

Amanda Crawford-Adamo

Software and Data Engineer

什麼是 Git 子模組?

Git Submodule

git submodule
  • 巢狀於另一個儲存庫中的儲存庫
  • 獨立的版本控管與歷史
  • 子模組變更不影響主儲存庫
  • 主儲存庫可引用子模組的特定版本

一個儲存庫內含多個子儲存庫的示意圖。

Git 進階

新增子模組

使用連結或在路徑資料夾下的目錄新增子模組。

git submodule add <repository link|dir> <path>

$$

範例

將資料驗證函式庫加入 ETL 專案,在 ETL 儲存庫的 libs/validator 資料夾下。

git submodule add https://github.com/example/data-validator.git libs/validator
Git 進階

列出子模組

列出專案中的所有子模組

git submodule status

範例

$ git submodule status
e1f2...7w8x9 data_cleaning_lib
a1b2...q7r8 api_connector
d9e8...t3u2 visualization_toolkit
Git 進階

更新子模組

以最新變更更新子模組

有幾種方式:

  1. 更新來源程式碼在你電腦上的所有子模組。
    git submodule update --init 
    
  2. 更新來源程式碼在遠端儲存庫的所有子模組。
    git submodule update --init --remote 
    
  3. 更新特定子模組。
    git submodule update --init <path_to_submodule>
    
Git 進階

移除子模組

移除子模組流程

  1. 取消初始化子模組。
    git submodule deinit <submodule_name>
    
  2. 從 Git 儲存庫索引中移除子模組。
    git rm <path>
    
Git 進階

從大型儲存庫擷取成子模組

  1. 將要放入新子模組儲存庫的所有檔案,複製到儲存庫外的另一個資料夾。

  2. 在新資料夾內,為子模組建立新的儲存庫:

    git init <new-submodule>
    
  3. 使用 git filter-repo 從主專案中擷取相關檔案與歷史:

    git filter-repo --path <extract_path> --invert-paths
    
  4. 將擷取出的儲存庫作為子模組加入主專案:

    git submodule add <new-submodule_path> <path_to_store_submodule>
    
Git 進階

何時使用子模組與最佳實務

適用情境:

  1. 管理外部函式庫
  2. 跨專案共用程式碼
  3. 維持特定相依版本

最佳實務:

  1. 維持子模組為最新
  2. 使用相對路徑
  3. 與團隊同步變更
Git 進階

一起來練習吧!

Git 進階

Preparing Video For Download...