기타 메모

VSCode에서 git worktree로 같은 리포지토리 다른 브랜치 작업 병행하기

Jonchann 2021. 5. 27. 12:14

자세한 설명은 Git Worktree 도큐멘트를 보는 것이 좋다.
git worktree란 제목에서도 알 수 있듯이 같은 리포지토리를 여러 개 clone하지 않고도 여러 브랜치에서 병행 작업할 수 있게 하는 기능이다.

주 커맨드는 아래와 같다.

$ git worktree add [-f] [--detach] [--checkout] [--lock] [-b <new-branch>] <path> [<commit-ish>]
$ git worktree list [--porcelain]
$ git worktree lock [--reason <string>] <worktree>
$ git worktree move <worktree> <new-path>
$ git worktree prune [-n] [-v] [--expire <expire>]
$ git worktree remove [-f] <worktree>
$ git worktree repair [<path>...]
$ git worktree unlock <worktree>

먼저 현재 워크트리 상태를 확인하려면 list를 사용하면 된다.

$ git worktree list
/Users/{user}/git_repositories/base_workplace   {head} [feature/base_workplace]

여기에 다른 브랜치를 추가하고 싶다면 add를 사용하면 된다.
여기에는 제일 간단한 사용례만 적어두지만 도큐멘트에 보면 옵션 사용례가 적혀있으니 참고하면 된다.

$ cd /Users/{user}/git_repositories/base_workplace
$ git worktree add ../sub_workplace feature/sub_workplace
$ git worktree list
/Users/{user}/git_repositories/base_workplace   {head} [feature/base_workplace]
/Users/{user}/git_repositories/sub_workplace  {head} [feature/sub_workplace]

경로지정할 때 왜 ../에 새로운 폴더를 생성하냐하면, feature/base_workplace브랜치가 이미 사용중이기 때문이다.
만약 경로를 지정하지 않으면 feature/라는 것을 디렉토리로 인식해서 git_repositories/base_workplace/feature라는 경로를 새로 만들어 딱히 브랜치를 지정하지 않은 worktree를 생성해버린다.

$ cd /Users/{user}/git_repositories/base_workplace
$ ls
src

$ git worktree add feature/sub_workplace
$ ls
src    feature

이럴 때는 remove를 사용하면 된다.

$ git worktree list
/Users/{user}/git_repositories/base_workplace   {head} [feature/base_workplace]
/Users/{user}/git_repositories/base_workplace/feature  {head} [sub_workplace]

$ git worktree remove sub_workplace

이렇게 worktree를 다른 경로에 추가한 상태에서 checkout을 시도하면 아래처럼 이미 브랜치가 사용 중이라는 메세지가 뜨면서 checkout에 실패한다.

$ git checkout feature/sub_workplace
fatal: 'feature/sub_workplace'은(는) 이미 '/Users/{user}/git_repositories/sub_workplace' 위치에 받아져 있습니다

이럴 때는 (우리 팀은 VSCode 사용 중이기 때문에 VSCode로 말하자면) File - New Window 로 새 창을 열어서 git_repositories/sub_workplace를 열어주면 된다. 게다가 이렇게 하면 창만 왔다 갔다 하면서 브랜치를 왔다 갔다 할 수 있어서 편하다.