LoginSignup
0
1

コミットメッセージの先頭に文字列を自動で追加

Posted at

概要

現プロジェクトでBacklogを使っており、コミットメッセージ先頭に課題キーを付与するルールとしています。
コミットの度に手動入力するのが面倒なので自動追加する運用にしています。

.git/hook/commit-msgを使った方法について説明します。

前提

ブランチ名の命名規則は以下。

feature/${課題キー}      # 基本
feature/${課題キー}/xxx  # 同課題でブランチを分けたい時①
feature/${課題キー}-xxx  # 同課題でブランチを分けたい時②
feature/${課題キー}_xxx  # 同課題でブランチを分けたい時③

コミットメッセージ形式は以下。

${課題キー} ${任意のコメント}

課題キー形式は以下。

ABCD-${数字}

方法

以下のcommit-msgファイルを${リポジトリ}/.git/hooksに格納する。

#!/bin/bash

# 現在のブランチ名取得
branch_name=$(git rev-parse --abbrev-ref HEAD)

# ブランチ名からチケットキー取得
ticket_key=$(echo "$branch_name" | sed -E 's/^[^/]+\/(ABCD-[0-9]+).*/\1/')

# ブランチ名にチケットキーが存在する時
if [ -n "$ticket_key" ]; then
  # コミットメッセージファイルパス取得
  commit_msg_file=$1

  # コミットメッセージ取得
  commit_msg=$(cat "$commit_msg_file")

  # コミットメッセージにチケットキーが含まれていない時
  if ! echo "$commit_msg" | grep -q "^ABCD-"; then
    # コミットメッセージ先頭にチケットキーを付与
    echo "$ticket_key $commit_msg" > "$commit_msg_file"
  fi
fi

commit-msgファイルに実行権限を付与する。

$ chmod a+x .git/hooks/commit-msg

以上です。

git commitgit commit -m "hoge"はもちろんのこと、SourceTree等GUIツールからのコミットでも動作します。
rebaseamend時にキーを多重付与しないよう、「# コミットメッセージにチケットキーが含まれていない時」の判定を入れています。

0
1
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
0
1