데이터 엔지니어 기술 블로그

[👾Git] Git 서브모듈(submodule) 사용법 본문

기술

[👾Git] Git 서브모듈(submodule) 사용법

jun_yeong_park 2021. 4. 17. 18:03
반응형

About

git submodule

프로젝트를 할 때 코드를 깃에 올려서 관리를 하는데, 나중에 다른 곳에서 중복 코드를 만들지 않고 사용하려면 깃을 분리해서 코드를 나누는 것이 좋다. 이럴 때를 위해서 git에서 제공해주는 것이 서브모듈(submodule)이다.

 

Submodule

서브모듈 추가하기

메인으로 사용하는 깃에서 서브모듈을 사용하고 싶다면 git submodule add 명령어를 사용하여 추가할 수 있다.

git submodule add <submodule-url>

이 명령어를 사용해서 추가하면 .gitmodules에 서브모듈이 아래처럼 추가된다.

[submodule "sample-submodule"]
	path = sample-submodule
	url = https://github.com/user-id/sample-submodule

git status 명령어를 사용하면 두가지가 추가된 것을 볼 수 있다. 특이한 점은 추가한 서브모듈이 new file로 추가된다는 것이다. 

# git status
On branch master

No commits yet

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)
        new file:   .gitmodules
        new file:   sample-submodule

만약 서브모듈을 수정한 뒤 메인 깃에서 git status를 하면 아래처럼 표시된다. 메인 깃에서 git add를 하려고 하면 수정된 파일이 잡히지 않는다.

git status
On branch master
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)
  (commit or discard the untracked or modified content in submodules)
        modified:   sample-submodule (modified content)

서브모듈 깃에서 수정사항을 commit 해준 뒤 다시 돌아와서 git add를 하게되면 잘 된다. 그러나 서브모듈을 수정한 뒤에 commit만 하고 push를 하지 않으면 외부에서 사용하려고 할 때 수정이 반영된 소스가 존재하지 않으므로 문제가 생기니 commit 후에는 push를 하는 것이 좋다.

 

 

서브모듈 Clone

서브모듈을 포함하는 메인 깃을 clone했을 때 서브모듈이 기본적으로 비어있다. 그래서 아래 두가지의 명령어를 더 실행시켜주어야 한다.

# 서브모듈 정보를 기반으로 로컬 환경설정 파일을 만들어준다.
git submodule init

# 서브모듈의 리모트 저장소에서 데이터를 가져오고 Checkout을 한다.
git submodule update

 

 

서브모듈 업데이트

서브모듈이 외부에서 업데이트가 되었을 때 현재 사용하려는 메인 깃에도 반영하려면 git submodule update 명령어를 사용하면 된다.

 

서브모듈 제거

git submodule deinit <your_submodule>
git rm <your_submodule>
git commit-m "Removed submodule"
rm -rf .git/modules/<your_submodule>

 

 

서브모듈 명령어 한 번에 실행하기

서브모듈들이 여러개가 있을 때 git submodule foreach를 사용하면 명령어를 여러 서브모듈에서 한 번에 실행할 수 있다.

git submodule foreach 'git pull'

 

반응형
Comments