LoginSignup
145
111

More than 5 years have passed since last update.

git rev-parseを使いこなす

Last updated at Posted at 2015-12-04

こんにちは!

Gitを使っているとプログラムからGitのメタ情報を取りたい!ってこと、よくありますよね?
でも、 git status をgrepしたりしていませんか??
git rev-parse から取れる情報もたくさんあるんですよ!
というわけで git rev-parse のちょっと凝った使い方を説明します。

そもそも git rev-parse ってなによ?

Pick out and massage parameters

とのことです。
ちなみに、Google翻訳によると「選ぶとマッサージパラメータ」って出てきました。
つまり、(与えられたモノが)何なのかを明らかにすることと、(gitの)パラメータを出力することができるやつってことです。(雑)

git rev-parse

objectのhashが取得できます。

git rev-parse master # => f62f59973b8d9aeff1731e6f6260ca7fb9694ead

git rev-parse --short

objectのhashの短縮表記が取得できます。

git rev-parse --short master # => f62f599
git rev-parse --short f62f59973b8d9aeff1731e6f6260ca7fb9694ead # => f62f599

git rev-parse --symbolic

objectがシンボルであればそれをそのまま取得します。

git rev-parse --symbolic master # => master
git rev-parse --symbolic f62f599 # => f62f599

git rev-parse -show-cdup

カレントディレクトリからgitのルートディレクトリへの相対パスを得ることができます。
gitのルートディレクトリではなにも得られません。

git rev-parse --show-cdup
cd eg
git rev-parse --show-cdup # => ../

git rev-parse --show-prefix

現在のディレクトリへの、gitのルートディレクトリからの相対パスを得ることができます。

git rev-parse --show-prefix

カレントディレクトリからの相対パスを渡すことでgitのルートディレクトリからの相対パスも作ることができます。

cd eg
git rev-parse --show-prefix lib/MyProj/DB.pm | tr -d '\n' # => eg/lib/MyProj/DB.pm

git rev-parse --is-inside-work-tree

ワークツリーの中にいるかどうかを true または false という文字列で得ることができます。

git rev-parse --is-inside-work-tree # => true

git rev-parse --git-dir

.gitディレクトリのフルパスを得ることができます。

git rev-parse --git-dir # => /Users/karupanerura/project/Aniki/.git

git rev-parse --resolve-git-dir

指定したパスが.gitディレクトリか判定することができます。
パスとして正しければディレクトリすら不在でも通ります。

git rev-parse --resolve-git-dir lib  # => fatal: not a gitdir 'lib'
git rev-parse --resolve-git-dir .git # => .git

git rev-parse --show-toplevel

gitのルートディレクトリを得ることができます。

git rev-parse --show-toplevel # => /Users/karupanerura/project/Aniki

具体例

こういうことができます。捗る!

https://github.com/karupanerura/dotfiles/blob/master/git/config#L62
https://github.com/karupanerura/dotfiles/blob/master/git/config#L69
https://github.com/karupanerura/dotfiles/blob/master/bin/git-save#L5-L8

まとめ

いかがでしたでしょうか? git rev-parse べんり!って感じが伝わればいいなーと思います。
他にもいろんなことができます。「これ判定できないのかな?」って困ったときは git rev-parsegit diffgit log のドキュメントを見ればだいたい解決するきがします。(しないかも)
gitに管理下でメタい操作を行いたいときには必ず使いたくなるコマンドだと思います。
ワンライナーに!やっつけスクリプトに!今晩のおかずに!なんにでもいけますね!

明日は @oh-sky さんの GitGitにしてあげましょうかね(CV:大坪由佳) です。意味深ですね。(意味深ですね。)
お楽しみに!

145
111
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
145
111