LoginSignup
0
2

More than 5 years have passed since last update.

gitのルートディレクトリに手軽に移動するラッパー関数

Posted at

作ったきっかけ

gitのルートディレクトリに移動したい❗
深い階層に潜っていると戻るのが面倒臭い😩
自分で書けばいいや😄

ラッパー関数

以下のようなディレクトリ構造で例えます。

git-root
┣━ foo
┃ ┗━ bar
┗━ baz
  • カレントディレクトリが git-root 以下のときに cd /git-root に移動
  • カレントディレクトリが git-root の場合は cd //に移動
  • カレントディレクトリが baz のときに cd /foo/bargit-root/foo/bar に移動
    • git-root 以下に対象のディレクトリが無ければ、/ 以下を探す

ラッパー関数を作る

gitcd() {
    # 引数が / で始まらない
    # または ホームディレクトリの path で始まる場合、普通に cd
    if [[ ! "${1}" =~ "^/.*" || "${1}" =~ "^${HOME}.*" ]]; then
        builtin cd "${@}"
        return
    fi

    # プロジェクトディレクトリの中じゃなければ普通にcd
    local insideProject=`git rev-parse --is-inside-work-tree 2>/dev/null`
    if [ ! "${insideProject}" = "true" ]; then
        builtin cd "${@}"
        return
    fi


    local currentDir=`pwd 2>/dev/null`
    local projectRoot=`git rev-parse --show-toplevel 2>/dev/null`

    # git-root に居れば / に移動
    if [ "${currentDir}" = "${projectRoot}" -a "${1}" = "/" ]; then
        builtin cd "/"
        return
    fi

    # /path/to が git-root 以下にあれば git-root/path/to に移動、
    # 無ければ /path/to に移動
    if [ -d "${projectRoot}${1}" ]; then
        builtin cd "${projectRoot}${1}"
    else
        builtin cd "${@}"
    fi
    return
}

alias cd=gitcd

これで完成です✨

今後の課題

git-root 以下で cd / とタイプしたときに git-root 以下のディレクトリを補完したい😣
ということでそのうち補完も効くようにしたいです、、、が補完周りはよくわからないのでしばらく先になりそうです😵

最後に

私のdotfilesです。よかったら参考にしてください。
シェルスクリプトは痒いところに手が届いて気持ちいいですね🙌

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2