Git サブモジュールの追加と削除方法
プロジェクトでは外部モジュールが必要になる場合がある。そのようなときに使うサブモジュールの使い方を説明する。
概要
外部モジュールを参照したい場合は、git submodule コマンドを使って外部モジュールを追加、つまり clone できる。git submodule は git clone と異なり、同じ作業ディレクトリ内に複数のモジュールを追加できるという利点がある。
ここではコマンド例として、Hugo のテーマである book をサブモジュールとして追加し、その後削除してみる。
Git Submodule の追加方法
git submodule add コマンドで、外部モジュールを現在の作業ディレクトリへ追加、つまり clone できる。
git submodule add {Git Repository URL} {Submodule Project directory}
% git submodule add https://github.com/alex-shpak/hugo-book.git themes/book
Cloning into '/Users/user/develop/devkuma-hugo-blog/themes/book'...
remote: Enumerating objects: 4124, done.
remote: Counting objects: 100% (6/6), done.
remote: Compressing objects: 100% (5/5), done.
remote: Total 4124 (delta 2), reused 2 (delta 1), pack-reused 4118
Receiving objects: 100% (4124/4124), 6.63 MiB | 5.50 MiB/s, done.
Resolving deltas: 100% (2122/2122), done.
追加された内容は git status で確認できる。
% git status
On branch main
Your branch is up to date with 'origin/main'.
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
modified: .gitmodules
new file: themes/book
... 以下省略 ...
この変更内容を git commit でコミットすればよい。
git commit -m "{commit message}
追加された git submodule の確認
submodule が追加されていれば、git submodule status コマンドで追加されたモジュール一覧を確認できる。
% git submodule status
036e037a63ba06ca366adb1a0c3a005d1a0b15b8 themes/book (v9-54-g036e037)
Git Submodule の削除方法
まず git submodule deinit コマンドで対象の submodule を解除する。
git submodule deinit -f {Submodule Project directory}
% git submodule deinit -f themes/book
Cleared directory 'themes/book'
Submodule 'themes/book' (https://github.com/alex-shpak/hugo-book) unregistered for path 'themes/book'
次に rm コマンドで .git/modules 配下の該当ディレクトリを削除する。
rm -rf .git/modules/{Submodule Project directory}
% rm -rf .git/modules/themes/book
そして Git から対象ディレクトリを削除する。
git rm -f {Submodule Project directory}
% git rm -f themes/book
rm 'themes/book'
最後に git commit を実行し、外部モジュールを削除した内容をコミットする。
git commit -m "{commit message}
% git commit -m "rm themes/book"
[main f9aaff69] rm themes/book
2 files changed, 4 deletions(-)
delete mode 160000 themes/book