LoginSignup
8
5

More than 5 years have passed since last update.

Gitのcommit-msg hookでプロンプト表示して確認

Posted at

概要

git hookを使ってフォーマットをチェックして、正しくなければ確認を促すスクリプトを作ってみました。
フォーマット確認とか、チケット番号の自動補完は見かけたのですが入力を受け付けるサンプルが少なかったので。

この投稿が役に立つ人

 チケット駆動で開発している。
 チケット番号とブランチ名が連動している。(ex. #1234, iss-1234)
 一つのブランチに複数のチケットを結びつけることを許している。

 →チケット番号を間違えてコミットして、メンバーに怒られる!(俺)

実例

前提

チケット番号1234に結びついたiss-1234ブランチにいるとする。

$ git branch
  develop
* iss-1234

チケット番号をうっかり間違えた場合

コミットメッセージにブランチ名内のチケット番号が含まれない場合は、確認する
"y"以外を入力した場合は、コミット中止

$ touch testfile
$ git add .
$ git commit -m "refs #5678 add testfile"
[NOTICE] refs #5678 is not match iss-1234. Is that right? [y/N]

aborted

チケット番号を意図的に変えた場合

"y"を明示的に入力した場合はコミット

$ git commit -m "refs #5678 add testfile" 
[NOTICE] refs #5678 is not match iss-1234. Is that right? [y/N]
y
[iss-1234 6d4be6c] refs #5678 add testfile
 0 files changed
 create mode 100644 testfile

commit-msg コード

rubyで記述してあります。ブランチ名のprefixはお好みで。
.git/hooks/commit-msg

.git/hooks/commit-msg
#!/usr/bin/env ruby

require "readline"

message_file = ARGV[0]
message = File.read(message_file)

$regex = /refs #(\d+)/

if !$regex.match(message)
  puts "[POLICY] Your message is not formatted correctly"
  puts 'ex. git commit -m "refs #XXXX test"'
  exit 1
end
$message_ticket_no = $1

$current_branch_name = `git rev-parse --abbrev-ref HEAD`.chomp
/iss-(\d+)/ =~ $current_branch_name
$branch_ticket_no = $1

if $message_ticket_no != $branch_ticket_no
  puts "[NOTICE] refs ##{$message_ticket_no} is not match #{$current_branch_name}. Is that right? [y/N]"
  STDIN.reopen('/dev/tty')
  input = Readline.readline
  if input != "y"
    puts "aborted"
    exit 1
  end
end

参考にしたページ

Git の commit-msg hook でコミットメッセージにチケット番号が含まれるかチェックする

How do I prompt the user from within a commit-msg hook?

8
5
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
8
5