카테고리 없음

Git : .gitignore와 .gitattributes

SciomageLAB 2024. 10. 3. 16:46
반응형

.gitignore

추적에서 제외할 파일들을 명시할 수 있다. 정규표현식을 지원한다.

예시

# ignore all .a files
*.a

# but do track lib.a, even though you're ignoring .a files above
!lib.a

# only ignore the TODO file in the current directory, not subdir/TODO
/TODO

# ignore all files in any directory named build
build/

# ignore doc/notes.txt, but not doc/server/arch.txt
doc/*.txt

# ignore all .pdf files in the doc/ directory and any of its subdirectories
doc/**/*.pdf

.gitattributes

디렉토리와 파일 별로로 Merge 방법, diff방법, checkout시 필터링 여부를 정해줄 수 있다.

예시

비주얼 스튜디오의 csproj 파일 같은 경우는 협업 작업할 때 같이 커밋을 안 할 수도 없는데 매번 충돌이 나는 파일 중에 하나이다. 아래처럼 설정을 해주면 merge할 때는 binary모드로, end-of-line 문자열 끝을 의미하는 문자는 윈도우 방식이 crlf로 하도록 별도 지정이 가능하다.

또 diff를 파일확장자에 따라 달리 지정도 가능하다. png 같은 이미지 파일은 exif(이미지 정보 추출 프로그램)을 이용하여 diff하고 코드는 vimdiff, 일반 텍스트는 linuxdiff로 지정해줄 수 있다.

export-ignore는 archive 명령어로 스냅샷을 파일로 뜰 때 특정 파일을 포함하지 않도록 해주는 옵션이다.

# VisualStudio.gitattributes
*.csproj    text eol=crlf
*.csproj    merge=binary
*.png       diff=exif
.gitattributes export-ignore
.gitignore     export-ignore
.gitkeep       export-ignore

파일별로 필터 걸기

아래 코드처럼 필터를 설정하면 해당 확장자를 가지 필터는 myfilter라는 명령어를 거치고 난 다음에 commit되거나 checkout되거나 하게 할 수 있다. 예를 들어 모든 소스코드 파일 위에 저자 표기나, 업데이트 된 날짜 등을 적고 싶다면 코드 안에 AUTHOR_AND_DATE를 치환하도록 만들거나 추가하도록 만들 수 있다.

# main.c
CODE_INFO = AUTHOR_AND_DATE

# .gitattributes
*.c filter=myfilter

# After filter
CODE_INFO = jisu choi / 2021-02-28

필터의 동작 시점에 따라서 두 가지가 있는데 clean과 smudge 필터가 있다. clean은 커밋할 때, smudge는 체크 아웃할 때 사용한다. 필터 종류 설정은 config 명령어를 통해 할 수 있다.

git config filter.myfilter.smudge <arg or command>
git config filter.myfilter.clean <arg or command>

# Ex : myfilter 커맨드에 매개변수를 넘기거나
git config filter.myfilter.smudge authoronly
git config filter.myfilter.clean full

# Ex : 체크아웃 할 때는 myfilter를 쓰고 커밋할 때는 다른 필터를 쓰게 할 수 있다.
git config filter.myfilter.smudge myfilter
git config filter.myfilter.clean otherfilter

파일별로 Merge 전략 다르게 해서 환경설정 파일에 적용하기

Android Studio, Visual Studio, Eclipse 등의 IDE에서 생성하는 홈 폴더 기준으로 생성되는 환경 설정 파일이나 배포할 DB서버의 URL, DB이름이 적혀있는 xml파일들은 배포할 때는 배포용을 푸시해야되서 추적은 해야 한다. 그런데 로컬에서 개개인이 테스트나 개발 목적으로 가지고 있는 설정 파일은 다를 수 있다. 예를 들어 리눅스에서 안드로이드 개발하는 사람은 NDK_PATH같은 것이 $HOME/ 이고 윈도우는 C\:ProgramFiles\ 일 수 있다.

이때는 저장소에 올라가야 하는 환경설정 파일을 pull 받을 때 merge 전략을 ours로 지정해서 특정 파일만 내 것을 쓰도록 하면 된다.

# .gitattributes
database.xml merge=ours

git config --global merge.ours.driver true

.gitattributes에 database.xml파일은 merge 시 ours 전략을 사용하도록 설정한다. merge에 사용하는 도구가 따로 있다면 그것을 적도록 한다. ours 전략으로 동작하는 드라이버에 true 값을 매개변수로 넘겨주면 병합 충돌이 일어날 때 마다 database.xml 파일은 자기 것을 사용하게 된다.

참고 문헌

.gitignore 예시

반응형