programming

[Git / Github] git submodule pull 받아오는 방법 및 용도

Turtle-hwan 2024. 3. 25. 12:41

git submodule 사용 계기

이번 ithome 프로젝트를 Next.js + TS 로 마이그레이션 하면서 git submodule 기능을 사용했다.

기존에는 하나의 repository에 프론트, 백이 폴더로 구분되어 같이 들어 있었다.

프론트만 환경을 Next.js로 바꾸면서 프론트 repo를 따로 만들었다.

localhost에서 테스트할 때 편의성을 위해 백 repo를 포함시킬 필요가 있어서 submodule로 포함시켰다.

## 기존 구조
ithome
---/frontend (React)
---/backend  (Nest.js)
---docker-compose.yaml

## 새로운 구조
ithome-front (Next.js 메인)
---/backend @ 8d972c3 (submodule)
---/public
---/src
---/src/@core
---/src/@shared
---/src/@store
---/src/@type
---/src/app (app router)

submodule로 포함하면 독립된 git 저장소를 가져올 수 있으며 commit부터 저장소 자체를 별개로 관리할 수 있는 이점이 있다. 일종의 바로가기와 비슷하다고 보면 될 것이다.

Git 공식 문서 - 서브모듈

 

Git - 서브모듈

gitmodules 파일에 있는 URL은 조건에 맞는 사람이면 누구든지 Clone 하고 Fetch 할 수 있도록 접근할 수 있어야 한다. 예를 들어 다른 사람이 Pull을 하는 URL과 라이브러리의 작업을 Push 하는 URL이 서로

git-scm.com

 

submodule이 포함된 저장소 clone 시 submodule 받아오는 방법

submodule이 포함된 git 저장소를 쓸 때, clone 이후 받는 방식과 clone 시 한 번에 받는 방식이 있다.

git clone 이후 따로 받는 법

## submodule이 있는 폴더로 이동한다.

git submodule init 
### 해당 명령어로 git submodule을 초기화 해줘야 그 안에서 pull을 할 수 있다.  
### 이걸 해줘야 submodule 별도의 git remote가 연결되는 것 같다.

git submodule update # submodule pull 가져오는 명령어
git submodule update --remote

git clone과 동시에 받는 법

git clone --recurse-submodules <https://github.com/~>

새로 clone 받는 개념이라 .env 파일 다시 받아줘야 하며, npm i도 따로 해줘야 한다

git clone 이후 init, update 한 번에 하기

git submodule update --init #이 명령으로 init과 update 한 번에 가능하다.
git submodule update --init <submodule 경로>

 

submodule 만드는 법

git submodule add <private repository 주소>

해당 명령어를 입력하면, 루트 디렉토리에 .gitmodule 파일이 생기고, 그 안에는 폴더명과 remote url이 담겨있다

# .gitmodule 파일 예시
[submodule "backend"]
    path = backend
    url = <https://github.com/Sublet-K/Sublet.git>

 

submodule의 여러 사용법

submodule로 백엔드, 프론트 등 별개의 repository를 연결하는 것 외에도 .env 환경변수, 000.pem 등 노출되면 안 되는 파일 관리에도 사용할 수 있다.

프로젝트가 커질수록 팀원별로 동일하게 관리하기가 아주 힘들어지는 .env 파일들을 모은 private repo를 하나 만들고, 이걸 submodule로 연결시켜주는 방식이다.

참고 자료

Java11 + Spring boot 환경에서 application.yml 파일 git submodule로 관리하기 : https://percyfrank.github.io/infra/Infra01/#5-github-actions-cicd-스크립트