$shibayu36->blog;

クラスター株式会社のソフトウェアエンジニアです。エンジニアリングや読書などについて書いています。

git grepの結果に、その行を書いたAuthorを表示する

あまり知らないコードを触るときに、周りのコードを参考にしたいことが多い。しかし、そのコードの技術スタックに詳しくない場合、どのコードは筋が良いかというのが全く分からないことがある。そういう時に、その分野に知見がある人が書いたコードを参考にしながら学習したい。

そのように知見を素早く吸収するために、git grepの結果に、その行を書いたAuthorを表示するとどうかと思ったのでやってみた。

git-grep-with-author

#!/bin/bash

git grep -n "$@" | while IFS=: read i j k
do
  author=$(git blame -L $j,$j $i --line-porcelain | grep '^author ' | cut -d' ' -f2-)
  echo -e "$i:$j:$author:$k"
done

例えばRailsのrepositoryで使うと

$ git-grep-with-author ActiveModel
actionpack/lib/action_controller/metal/params_wrapper.rb:52:Prem Sichanugrist:  # If you're going to pass the parameters to an +ActiveModel+ object (such as
actionpack/lib/action_controller/metal/strong_parameters.rb:260:Francesco Rodriguez:    #   Person.new(params) # => ActiveModel::ForbiddenAttributesError
actionpack/lib/action_controller/metal/strong_parameters.rb:424:Francesco Rodriguez:    #   Person.new(params) # => ActiveModel::ForbiddenAttributesError
actionpack/lib/action_controller/metal/strong_parameters.rb:873:Prem Sichanugrist:    # This is required by ActiveModel attribute assignment, so that user can
actionpack/lib/action_controller/metal/strong_parameters.rb:1157:yuuji.yaginuma:  #     # ActiveModel::ForbiddenAttributesError exception because it'd
actionpack/test/controller/redirect_test.rb:6:Jon Moss:  extend ActiveModel::Naming
actionpack/test/controller/redirect_test.rb:7:Jon Moss:  include ActiveModel::Conversion

のようにファイル名と行の後に、Authorを出してくれるようになった。便利。