반응형
Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

테크매니아

Git : 브랜치 명 Bash에 표시하기 본문

카테고리 없음

Git : 브랜치 명 Bash에 표시하기

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

브랜치 명을 Bash에 표시하자

PS1에 깃허브 브랜치 명이 표시된다. *과 =은 커밋추적되지 않은 파일이 있음, 커밋이 뒤떨어져 있는지 등을 나탄낸다. 자세한건 글에 설명을 썼다!## /etc/bash_completion.d/ 밑에 git-prompt 파일에는 깃 명령어 자동 완성에 관한 내용이 적혀있다.

### 파일에 명시된 /usr/lib/git-core/git-sh-prompt 파일을 찾아보자

아래 파일 내용을 읽어보면 GIT_PS1_SHOWDIRTYSTATE라는 환경 변수를 어떤 값이던 정의만 해놓으면
git-sh-prompt에 있는 __git_ps1 함수를 이용해 현재 깃이 가지고 있는 브랜치 정보를 알 수 있다고 한다.

이 소스파일에 등장하는 여러가지 옵션들에 대해서 설명과 정리를 잘해놓은 글을 참고하면 좋을 것 같다.

# In addition, if you set GIT_PS1_SHOWDIRTYSTATE to a nonempty value,
# unstaged (*) and staged (+) changes will be shown next to the branch
# name.  You can configure this per-repository with the
# bash.showDirtyState variable, which defaults to true once
# GIT_PS1_SHOWDIRTYSTATE is enabled.
#
# You can also see if currently something is stashed, by setting
# GIT_PS1_SHOWSTASHSTATE to a nonempty value. If something is stashed,
# then a '$' will be shown next to the branch name.
#
# If you would like to see if there're untracked files, then you can set
# GIT_PS1_SHOWUNTRACKEDFILES to a nonempty value. If there're untracked
# files, then a '%' will be shown next to the branch name.  You can
# configure this per-repository with the bash.showUntrackedFiles
# variable, which defaults to true once GIT_PS1_SHOWUNTRACKEDFILES is
# enabled.
#
# If you would like to see the difference between HEAD and its upstream,
# set GIT_PS1_SHOWUPSTREAM=auto.  A < indicates you are behind, >
# indicates you are ahead, <> indicates you have diverged and =
# indicates that there is no difference. You can further control
# behaviour by setting GIT_PS1_SHOWUPSTREAM to a space-separated list
# of values:
#
#     verbose       show number of commits ahead/behind (+/-) upstream
#     name          if verbose, then also show the upstream abbrev name
#     legacy        don't use the '--count' option available in recent
#                   versions of git-rev-list
#     git           always compare HEAD to @{upstream}
#     svn           always compare HEAD to your SVN upstream
#
# You can change the separator between the branch name and the above
# state symbols by setting GIT_PS1_STATESEPARATOR. The default separator
# is SP.
#
# By default, __git_ps1 will compare HEAD to your SVN upstream if it can
# find one, or @{upstream} otherwise.  Once you have set
# GIT_PS1_SHOWUPSTREAM, you can override it on a per-repository basis by
# setting the bash.showUpstream config variable.
#
# If you would like to see more information about the identity of
# commits checked out as a detached HEAD, set GIT_PS1_DESCRIBE_STYLE
# to one of these values:
#
#     contains      relative to newer annotated tag (v1.6.3.2~35)
#     branch        relative to newer tag or branch (master~4)
#     describe      relative to older annotated tag (v1.6.3.1-13-gdd42c2f)
#     tag           relative to any older tag (v1.6.3.1-13-gdd42c2f)
#     default       exactly matching tag
#
# If you would like a colored hint about the current dirty state, set
# GIT_PS1_SHOWCOLORHINTS to a nonempty value. The colors are based on
# the colored output of git status -sb and are available only when
# using __git_ps1 for PROMPT_COMMAND or precmd.
#
# If you would like __git_ps1 to do nothing in the case when the current
# directory is set up to be ignored by git, then set
# GIT_PS1_HIDE_IF_PWD_IGNORED to a nonempty value. Override this on the
# repository level by setting bash.hideIfPwdIgnored to false.

__git_ps1 함수를 이용하면 Branch를 표시

.git폴더가 있는 프로젝트 디렉토리 안에서 쉘에 __git_ps1 함수를 eval로 호출하면 현재 브랜치 정보를 불러온다.

echo `__git_ps1`
# 출력
(develop u= origin/develop)

SHOWDIRTYSTATE말고도 여러 옵션들이 있는데 환경변수로 지정해주거나

export GIT_PS1_SHOWSTASHSTATE=true
export GIT_PS1_SHOWDIRTYSTATE=true
export GIT_PS1_SHOWUNTRACKEDFILES=true
export GIT_PS1_SHOWUPSTREAM=verbose name # 구분자로 스페이스를 사용한다.

.git/config 파일에 직접 적어주거나 (특정 리포만 적용하고 싶을 때)

[bash]
    showDirtyState = true
    showUntrackedFiles = true
    showUpstream = true

git config 명령어를 이용하면 된다.

git config bash.showDirtyState true
git config bash.showUntracked true
git config bash.showUpstream true

쌍이 맞아서 SHOWSTASHSTATE 옵션도 있을까 싶지만 git-prompt.sh 파일에서 보면 설정을 확인하는

473 ~ 505라인에 SHOWSTASHSTATE만 환경변수명으로 체크를 한다. config를 따로 확인하지 않고.

bash.showStashstate가 따로 검색되지 않기에 지레짐작으로 대응되는 config 키값이 없지 않을까 하고 있다.

if [ true = $inside_gitdir ]; then
        if [ true = $bare_repo ]; then
            c=BARE:
        else
            b=GIT_DIR!
        fi
    elif [ true = $inside_worktree ]; then
        if [ -n ${GIT_PS1_SHOWDIRTYSTATE-} ] &&
           [ $(git config --bool bash.showDirtyState) != false ]
        then
            git diff --no-ext-diff --quiet || w=*
            git diff --no-ext-diff --cached --quiet || i=+
            if [ -z $short_sha ] && [ -z $i ]; then
                i=#
            fi
        fi
        if [ -n ${GIT_PS1_SHOWSTASHSTATE-} ] &&
           git rev-parse --verify --quiet refs/stash >/dev/null
        then
            s=$
        fi

        if [ -n ${GIT_PS1_SHOWUNTRACKEDFILES-} ] &&
           [ $(git config --bool bash.showUntrackedFiles) != false ] &&
           git ls-files --others --exclude-standard --directory --no-empty-directory --error-unmatch -- ':/*' >/dev/null 2>/dev/null
        then
            u=%${ZSH_VERSION+%}
        fi

        if [ -n ${GIT_PS1_SHOWUPSTREAM-} ]; then
            __git_ps1_show_upstream
        fi
    fi

부록에 적는 딴짓

git 명령어 매핑 구조 살펴보기

Ubuntu 20.04를 기준으로 /usr/lib/git-core 에는 다양한 핵심 명령어들이 있다.
아래 이미지에서 보이듯 git [options] [args] 하고 치는 명령어들은 git에 걸려있는 심볼릭 링크 들이다.

## Git hook 예제 템플릿이 들어있는 /usr/share/git-core

git init 명령어를 통해 .git 폴더를 생성할 때 이곳에 있는 템플릿이 복사된다.

참고문헌

Options For Git Status in Shell Prompt

반응형