Git Advanced

재성고·2025년 7월 17일
0

GIT

목록 보기
4/4

Git 고급 기능 완전 정리 🚀

Git의 기본 명령어들은 익숙하지만, 더 효율적이고 전문적인 개발을 위해서는 고급 기능들을 잘 활용해야 합니다. 실무에서 자주 사용되는 Git의 고급 기능들을 정리해보겠습니다.

1. 고급 브랜치 관리

Git Flow 전략

# Git Flow 초기화
git flow init

# 새로운 feature 브랜치 시작
git flow feature start new-feature

# feature 완료
git flow feature finish new-feature

# release 브랜치 시작
git flow release start 1.0.0

# release 완료
git flow release finish 1.0.0

브랜치 네이밍 전략

# 기능 개발
feature/user-authentication
feature/payment-integration

# 버그 수정
bugfix/login-error
hotfix/critical-security-patch

# 실험적 기능
experiment/new-ui-design

2. Rebase 마스터하기

Interactive Rebase로 커밋 히스토리 정리

# 최근 3개 커밋을 수정
git rebase -i HEAD~3

# 특정 커밋부터 rebase
git rebase -i <commit-hash>

Interactive Rebase 옵션들:

  • pick: 커밋을 그대로 사용
  • reword: 커밋 메시지 수정
  • edit: 커밋 수정
  • squash: 이전 커밋과 합치기
  • drop: 커밋 삭제

Rebase vs Merge 전략

# Merge (히스토리 보존)
git merge feature-branch

# Rebase (선형 히스토리)
git rebase main
git checkout main
git merge feature-branch  # Fast-forward merge

3. Cherry-pick으로 선택적 커밋 적용

# 특정 커밋만 현재 브랜치에 적용
git cherry-pick <commit-hash>

# 여러 커밋 cherry-pick
git cherry-pick <commit1> <commit2> <commit3>

# 범위로 cherry-pick
git cherry-pick <start-commit>..<end-commit>

# 충돌 해결 후 계속
git cherry-pick --continue

# cherry-pick 취소
git cherry-pick --abort

4. Stash 고급 활용

작업 중인 변경사항 임시 저장

# 현재 변경사항 stash
git stash push -m "작업 중인 기능 임시 저장"

# 특정 파일만 stash
git stash push -m "특정 파일만" -- file1.js file2.css

# Untracked 파일도 포함
git stash push -u -m "새 파일들도 포함"

# Stash 목록 확인
git stash list

# 특정 stash 적용
git stash apply stash@{2}

# Stash 적용하고 삭제
git stash pop

# Stash를 새 브랜치로 만들기
git stash branch new-feature-branch stash@{0}

5. 고급 로그 및 검색

강력한 로그 조회

# 그래프 형태로 로그 보기
git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit

# 특정 파일의 변경 히스토리
git log -p -- filename.js

# 특정 기간의 커밋
git log --since="2 weeks ago" --until="1 week ago"

# 특정 작성자의 커밋
git log --author="김개발"

# 커밋 메시지로 검색
git log --grep="버그수정"

# 코드 변경사항으로 검색
git log -S "function searchUser" --source --all

Git Blame과 Annotate

# 각 라인의 마지막 수정자 확인
git blame filename.js

# 특정 라인 범위만 확인
git blame -L 10,20 filename.js

# 공백 변경 무시
git blame -w filename.js

6. Bisect를 이용한 버그 추적

# Bisect 시작
git bisect start

# 현재 커밋이 나쁜 상태임을 표시
git bisect bad

# 정상 작동하는 커밋 표시
git bisect good <commit-hash>

# 테스트 후 결과 표시
git bisect good  # 또는 git bisect bad

# 자동화된 bisect
git bisect run ./test-script.sh

# Bisect 종료
git bisect reset

7. Worktree로 멀티 브랜치 작업

# 새로운 worktree 생성
git worktree add ../project-feature feature/new-ui

# 기존 브랜치로 worktree 생성
git worktree add ../project-hotfix hotfix/critical-bug

# Worktree 목록 확인
git worktree list

# Worktree 제거
git worktree remove ../project-feature

8. Submodules와 Subtrees

Submodules 관리

# Submodule 추가
git submodule add https://github.com/user/library.git lib/library

# Submodule 초기화 및 업데이트
git submodule init
git submodule update

# 또는 한 번에
git submodule update --init --recursive

# Submodule 업데이트
git submodule update --remote

# Submodule 제거
git submodule deinit lib/library
git rm lib/library

Subtrees 사용

# Subtree 추가
git subtree add --prefix=lib/library https://github.com/user/library.git main --squash

# Subtree 업데이트
git subtree pull --prefix=lib/library https://github.com/user/library.git main --squash

# 변경사항을 원본 저장소로 push
git subtree push --prefix=lib/library https://github.com/user/library.git main

9. Git Hooks 활용

Pre-commit Hook 예제

#!/bin/sh
# .git/hooks/pre-commit

# ESLint 검사
npm run lint
if [ $? -ne 0 ]; then
  echo "ESLint 오류가 있습니다. 커밋을 중단합니다."
  exit 1
fi

# 테스트 실행
npm test
if [ $? -ne 0 ]; then
  echo "테스트가 실패했습니다. 커밋을 중단합니다."
  exit 1
fi

Commit Message Hook

#!/bin/sh
# .git/hooks/commit-msg

# 커밋 메시지 형식 검사
commit_regex='^(feat|fix|docs|style|refactor|test|chore)(\(.+\))?: .{1,50}'

if ! grep -qE "$commit_regex" "$1"; then
    echo "커밋 메시지 형식이 올바르지 않습니다."
    echo "형식: type(scope): description"
    echo "예: feat(auth): add login functionality"
    exit 1
fi

10. 고급 설정과 최적화

유용한 Git 설정

# 글로벌 설정
git config --global user.name "김개발"
git config --global user.email "kim@example.com"

# 에디터 설정
git config --global core.editor "code --wait"

# 자동 색상
git config --global color.ui auto

# 기본 브랜치명
git config --global init.defaultBranch main

# 자동 CRLF 변환 (Windows)
git config --global core.autocrlf true

# Push 기본 동작
git config --global push.default simple

# Rebase 시 자동 스태시
git config --global rebase.autoStash true

별칭(Alias) 설정

# 유용한 별칭들
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
git config --global alias.unstage 'reset HEAD --'
git config --global alias.last 'log -1 HEAD'
git config --global alias.visual '!gitk'
git config --global alias.lg "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"

11. 성능 최적화

대용량 저장소 최적화

# 가비지 컬렉션
git gc --aggressive --prune=now

# 저장소 크기 확인
git count-objects -vH

# 큰 파일 찾기
git rev-list --objects --all | git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' | sed -n 's/^blob //p' | sort --numeric-sort --key=2 | tail -10

# 불필요한 파일 제거
git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch large-file.zip' --prune-empty --tag-name-filter cat -- --all

Shallow Clone과 Partial Clone

# 얕은 복사 (최신 커밋만)
git clone --depth 1 https://github.com/user/repo.git

# 특정 브랜치만 복사
git clone --single-branch --branch main https://github.com/user/repo.git

# Partial clone (blob 없이)
git clone --filter=blob:none https://github.com/user/repo.git

12. 고급 병합 전략

복잡한 병합 상황 해결

# Three-way merge
git merge -X ours feature-branch    # 충돌 시 현재 브랜치 우선
git merge -X theirs feature-branch  # 충돌 시 병합 브랜치 우선

# Octopus merge (여러 브랜치 동시 병합)
git merge branch1 branch2 branch3

# 병합 커밋 없이 병합
git merge --squash feature-branch
git commit -m "Squash merge of feature-branch"

실무 팁

  1. 커밋은 작고 논리적으로 - 하나의 기능이나 수정사항당 하나의 커밋
  2. 의미있는 커밋 메시지 - 나중에 히스토리를 이해할 수 있도록
  3. 정기적인 rebase - 브랜치를 최신 상태로 유지
  4. 테스트 후 커밋 - 항상 동작하는 코드만 커밋
  5. 브랜치 전략 일관성 - 팀에서 정한 규칙을 따르기

이러한 고급 Git 기능들을 잘 활용하면 더욱 효율적이고 전문적인 개발 워크플로우를 구축할 수 있습니다. 각 기능들을 프로젝트 상황에 맞게 적절히 조합해서 사용해보세요!

0개의 댓글