LoginSignup
5
3

More than 5 years have passed since last update.

gitで最新のマージに特定の変更が含まれているか確認する

Posted at

最近CIサーバ上で、「特定のディレクトリが変更された場合にのみ、ある処理を行う」
というスクリプトを書く必要があったので、メモ。

TL;DR

以下の通り(HOGEは監視したいディレクトリへのpath)

  latest_commit=$(  git log --merges -n 2 --pretty=format:"%H" | head -n 1 | tail -n 1)
  previous_commit=$(git log --merges -n 2 --pretty=format:"%H" | head -n 2 | tail -n 1)

  diff=$(git diff $latest_commit..$previous_commit --name-only | grep 'HOGE/')

  if [[ -z $diff ]]; then
    echo "HOGEに変更はありません。"
  else
    echo "HOGEが変更されました。処理を開始します。"
fi

解説

commit hashの取得

  • git log --merges
    →マージされたコミットを表示
  • git log --merges -n 2
    →マージされたコミットのうち、直近2つを表示
  • git log --merges -n 2 --pretty=format:"%H"
    →マージされたコミットのうち、直近2つのcommit hashのみを表示
  • head -n 2
    →入力された内容の、先頭の2行を表示する
  • tail -n 1
    →入力された内容の、末尾の1行を表示する
  • head -n 2 | tail -n 1
    →入力された内容の、2行目を表示する(入力された内容の先頭の2行の末尾の1行 = 2行目のみ)
  • git log --merges -n 2 --pretty=format:"%H" | head -n 1 | tail -n 1
    →最新のマージコミットを取得
  • git log --merges -n 2 --pretty=format:"%H" | head -n 2 | tail -n 1
    →最新の1つ前のマージコミットを取得

差分の確認

  • git diff $latest_commit..$previous_commit
    $latest_commit$previous_commitの間の差分を表示
  • git diff $latest_commit..$previous_commit --name-only
    $latest_commit$previous_commitの間で差分があるファイルをpathで表示
  • git diff $latest_commit..$previous_commit --name-only | grep 'HOGE/'
    $latest_commit$previous_commitの間で差分があるファイルのうち、pathにHOGE/が含まれるものを表示

判定

  • if [[ -z $diff ]]; then
    $diffが空文字列でない場合、true
5
3
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
5
3