gitツリーのルートにcdするBash / zsh関数

Nov 26 2020

gitツリールートにcdする関数、またはリポジトリの外部にいる場合は何もしない関数のレビューを取得したいと思います。

レビュー済みバージョン:

# 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%パスします。これは、問題が発生する可能性のあるすべてのものを引用することでうまくやっていることを意味します。
  • スコープ変数
  • [[条件付きを使用してif
  • それが何をしているのか、そしてその理由の良い説明

もっとよくなるはず

  • 上部のsh-bang行は、通常はログインスクリプト中にのみ取得される場合でも、スクリプトには適しています。
  • 内部関数は、外部関数とは異なる構文で定義されています。
  • 変数のスコープと定義を1行で行うことができます。例:local super_root="$(git rev-parse --show-superproject-working-tree)"。これにより、ローカル変数の定義に失敗したり、新しい変数のスコープに失敗したりすることがなくなります。そして、それぞれの場合にコード行を切り取ります。
  • git_root変数名と関数名を再利用すると混乱します。最初は、関数を定義した後、なぜ関数のスコープを設定しようとしているのか疑問に思いました。
  • [[最後の行の条件付きには条件付きを使用します。