🔄

git submodule を利用して repository の内容を同期する

2023/11/05に公開

概要

  • Git で管理しているコードを、他の repository でも利用する方法のまとめ

きっかけ

ポリレポのスキーマファイル(*.proto)の更新の仕組み化をしたかった。(どちらかのファイルのコピペ・protoc gen)

前提

Github Repository B の内容を、Github Repository A に取り込みたいとする

  • Github Repository A: 開発中の repository: repoA
repoA
~/submodules-test-a main
❯ tree            
.
└── README.md
  • Github Repository B: 同期したいコードがあるrepository(push済): repoB
repoB
~/submodules-test-b main
❯ tree 
.
├── README.md
└── docs
    └── text.txt
docs/docs.txt
test commit

手順

初期

repoA
~/submodules-test-a main
❯ git submodules add https://github.com/Misha434/submodules-test-b.git targets

~/submodules-test-a main
❯ git submodule update --init --recursive

~/submodules-test-a main
❯ git commit -m "Add repoB as a submodule"                                    
git push

更新方法

repoB のファイルの記載内容を変更

docs/docs.txt(repoB)
test commit

update commit

repoB の内容を push

repoB
~/submodules-test-b main
❯ git add .           

~/submodules-test-b main*
❯ git commit -m 'add update file'
[main de62cc7] add update file
 1 file changed, 2 insertions(+)

~/submodules-test-b main ⇡
❯ git push origin HEAD           
Enumerating objects: 7, done.
Counting objects: 100% (7/7), done.
Delta compression using up to 8 threads
Compressing objects: 100% (2/2), done.
Writing objects: 100% (4/4), 347 bytes | 347.00 KiB/s, done.
Total 4 (delta 0), reused 0 (delta 0), pack-reused 0
To https://github.com/Misha434/submodules-test-b.git
   4159ec5..de62cc7  HEAD -> main

repo A 側更新

repoA
~/submodules-test-a main
❯ git submodule update --remote                                               
remote: Enumerating objects: 7, done.
remote: Counting objects: 100% (7/7), done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 4 (delta 0), reused 4 (delta 0), pack-reused 0
Unpacking objects: 100% (4/4), 327 bytes | 65.00 KiB/s, done.
From https://github.com/Misha434/submodules-test-b
   4159ec5..de62cc7  main       -> origin/main
Submodule path 'targets': checked out 'de62cc7c07800d29cb625f3d1cdb4d4f5416c0ad'
docs/docs.txt(repoA)
test commit

repoA の docs を git add, git commit

~/submodules-test-a main*
❯ git add .                    

~/submodules-test-a main*
❯ git commit -m "Update docs test.txt"    
[main dd6281a] Update docs test.txt
 1 file changed, 1 insertion(+), 1 deletion(-)

~/submodules-test-a main ⇡
❯ git push origin HEAD                
Enumerating objects: 3, done.
Counting objects: 100% (3/3), done.
Delta compression using up to 8 threads
Compressing objects: 100% (2/2), done.
Writing objects: 100% (2/2), 250 bytes | 250.00 KiB/s, done.
Total 2 (delta 1), reused 0 (delta 0), pack-reused 0
remote: Resolving deltas: 100% (1/1), completed with 1 local object.
To https://github.com/Misha434/submodules-test-a.git
   ca34747..dd6281a  HEAD -> main

リポジトリ

参考

Discussion