LoginSignup
32
28

More than 5 years have passed since last update.

zsh で Git リポジトリのトップレベル ディレクトリに cd するプラグイン

Posted at

Git リポジトリの中にいるときに、トップレベルのディレクトリに移動したくなることがある。それを1回のコマンドで簡単にできるようなプラグインを作ったので紹介する。

このプラグインでできること

cd-gitroot というプラグインを作った。これをインストールすれば cd-gitroot というコマンドが使えるようになる。

使っている様子はこんな感じ。

# こんな感じで Git リポジトリの中にディレクトリがあったとする
# doc/
# src/
#   |-scripts/
#   `-web/

% cd /home/mollifier/git_repo
% cd src/web
% pwd
/home/mollifier/git_repo/src/web
# リポジトリの奥の方にいる時でも、すぐにトップに移動できる
% cd-gitroot
% pwd
/home/mollifier/git_repo

# 引数を指定するとリポジトリトップからの相対的なパスに移動できる
% cd-gitroot src/scripts
% pwd
/home/mollifier/git_repo/src/scripts

# タブで相対的なパスが補完できる
% cd-gitroot [TAB]
doc/  src/
% cd-gitroot src/[TAB]
scripts/  web/

インストール

まず https://github.com/mollifier/cd-gitroot から cd-gitroot, _cd-gitroot と2つファイルを取ってきて $fpath の通ったところに配置する。その後に .zshrcautoload すれば OK。

例えば $HOME/zsh/functions/cd-gitroot の下に配置したい場合はこんな感じ。

% cd $HOME/zsh/functions
% git clone https://github.com/mollifier/cd-gitroot.git cd-gitroot

# または $HOME/zsh/functions/cd-gitroot ディレクトリを作成して、
# その下に cd-gitroot, _cd-gitroot を置く

~/.zshrc にこんな感じで書く。

.zshrc
fpath=($HOME/zsh/functions/cd-gitroot(N-/) $fpath)

autoload -Uz cd-gitroot
alias cdu='cd-gitroot'

最後の alias は必須じゃないけど設定しておくと便利(元の名前が長いので)。好きな名前で alias を貼っておこう。

注意としては、fpath を設定するところは autoload -Uz compinit とやってるとこより前に書くこと。そうじゃないとこのプラグインの補完がうまく動かなくなる。

使い方

Git リポジトリの中に入って cd-gitroot と打てばリポジトリのトップに移動できる。
引数を指定したらリポジトリトップからの相対的なパスに移動する。
引数のディレクトリはタブで補完できるので、リポジトリの奥の方にいる時でも簡単に他の場所に移動できる。

謝辞

このプラグインの元ネタは id:hitode909 さんのブログ記事です。

Gitのリポジトリのトップレベルにcdするコマンド

タブで補完できたらもっと便利になると思ったので改めてプラグインとして書きました。hitode909 さん、ありがとうございました!

32
28
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
32
28