LoginSignup
9
6

More than 1 year has passed since last update.

Git submoduleを、リモートリポジトリのmainブランチの最新版に反映させる

Last updated at Posted at 2022-07-28

初めに

とあるプロジェクトのリポジトリAで、
外部リポジトリBをsubmoduleとして登録している場合に、
外部リポジトリB側のリモートリポジトリのmain(master)ブランチに新しいコミットが追加されたとします。

リポジトリA側にも、外部リポジトリBの上記の変更を反映させたい場合、
反映させる方法は概ね2パターンあります。

前提条件

今回ご紹介する例では、

  • リポジトリAのディレクトリ名を、main_project_A
  • 外部リポジトリBのディレクトリ名を、sub_project_B

とします。

パターン①:リポジトリA側だけでコマンド実行

こちらの方法が楽だと思います。
リポジトリA側のプロジェクトのルートディレクトリに移動して
git submodule update --remoteコマンドを実行します。
この時、--remoteオプションをつけないと反映されません。

# main_project_A ディレクトリに移動
$ cd main_project_A

# リポジトリA側から参照するsubmoduleを、外部リポジトリBのリモートリポジトリの最新のmainブランチに反映させる
$ git submodule update --remote
Submodule path 'sub_project_B': checked out 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' # ←コミットID

次に、git statusコマンドを実行すると
差分が検知されるので、
git addコマンド -> git commitコマンドで反映完了です。

ちなみに、
git submodule update --remoteコマンドの実行結果を
やっぱりなかったことにしたい場合は、--remoteオプションを外して
再度git submodule updateコマンドを実行すれば元に戻ります。

パターン②:両方のリポジトリ側でコマンド実行

まず外部リポジトリB側のプロジェクトのルートディレクトリに移動します。
次にmainブランチを指定してから
git pull origin mainコマンドを実行して、
外部リポジトリB(ローカル)を、リモートリポジトリの最新のmainブランチと同期させます。

# sub_project_B ディレクトリに移動
$ cd sub_project_B

# mainブランチを指定
$ git checkout main
$ git branch
* main

# git pullで、リモートリポジトリの最新のmainブランチと同期
$ git pull origin main

次に、リポジトリA側のプロジェクトのルートディレクトリに移動します。
git statusコマンドを実行すると、
submoduleが最新のリモートリポジトリのmainブランチと同期された変更により、
差分が検知されるようになります。

なので、ここからはパターン①と同様に、
git addコマンド -> git commitコマンドで反映完了です。

# main_project_A ディレクトリに移動
$ cd main_project_A

# git statusを実行すると、差分が検知されるようになる
$ git status
On branch main
Your branch is ahead of 'origin/main' by 1 commit.
  (use "git push" to publish your local commits)

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        modified:   sub_project_B (new commits)

no changes added to commit (use "git add" and/or "git commit -a")

# git add & git commitで反映させる
$ git add .
$ git commmit

9
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
6