Git 트리의 루트로 이동하는 Bash / zsh 함수

Nov 26 2020

git 트리 루트로 이동하거나 저장소 외부에있는 경우 아무 작업도 수행하지 않는 함수에 대한 검토를 받고 싶습니다.

검토 버전 :

# cd to the root of the current git directory
# If $PWD is submodule, will cd to the root of the top ancestor
# It requires to stay in the current directory, if the root is . or unknown,
# and use cd only once, to have a way to do `cd -`
function cg {
  git_root() {
    local super_root
    local top
    top="$(git rev-parse --show-cdup)"
    top="${top:-./}"
    super_root="$(git rev-parse --show-superproject-working-tree)"
    if [[ "$super_root" ]]; then
      printf '%s' "$top../"
      ( cd "$top../" && git_root || return )
    fi
    printf '%s' "$top"
  }
  local git_root
  git_root="$(git_root)"
  [ "x${git_root}" != "x./" ] && cd "$(git_root)" && return || return 0
}

업데이트 된 버전 :

#!/bin/bash
# cd to the root of the current git directory
# If $PWD is submodule, will cd to the root of the top ancestor
# It requires to stay in the current directory, if the root is . or unknown,
# and use cd only once, to have a way to do `cd -`
function cg {
  function git_root {
    local top; top="$(git rev-parse --show-cdup)"
    top="${top:-./}"
    local super_root; super_root="$(git rev-parse --show-superproject-working-tree)"
    if [[ "$super_root" ]]; then
      printf '%s' "$top../"
      ( cd "$top../" && git_root || return )
    fi
    printf '%s' "$top"
  }
  local tree_root
  tree_root="$(git_root)"
  [[ "x${tree_root}" != "x./" ]] && cd "${tree_root}" && return || return 0
}

답변

4 chicks Nov 26 2020 at 10:12

  • 100 % shellcheck 를 통과 하므로 잠재적으로 문제가 될 수있는 모든 것을 인용하여 훌륭하게 수행하고 있습니다.
  • 범위 지정 변수
  • [[조건부 사용if
  • 그것이 무엇을하고 있고 왜 그랬는지에 대한 좋은 설명

더 나을 수 있습니다

  • 상단의 sh-bang 줄은 일반적으로 로그인 스크립트 중에 소스가 제공되는 경우에도 스크립트에 좋은 아이디어입니다.
  • 내부 함수는 외부 함수와 다른 구문으로 정의됩니다.
  • 한 줄로 변수의 범위를 지정하고 정의 할 수 있습니다. 예 : local super_root="$(git rev-parse --show-superproject-working-tree)". 이렇게하면 지역 변수를 정의하는 데 실패하거나 새 변수의 범위를 지정하는 데 실패하지 않습니다. 그리고 각각의 경우에 한 줄의 코드를 잘라냅니다.
  • git_root변수 이름과 함수 이름을 재사용 하는 것은 혼란 스럽습니다. 처음에는 함수를 정의한 후에 왜 범위를 지정하려고하는지 궁금했습니다.
  • 사용 [[마지막 줄에 조건에 대한 조건.