LoginSignup
2
4

More than 5 years have passed since last update.

Gitシリーズ - ①コミット時にGitユーザをAuthorに設定してみた

Last updated at Posted at 2017-07-24

はじめに

  • 2週間の長い夏休みをいただきました。リハビリ開始します。
  • さて、Gitが約1年半くらい前に弊社で導入されるまでは、Subversionを使ってました。
  • Subversionは導入当時は画期的な管理ツールで、その中でも便利だったのはソースコードに記載する際のauthorをコミットユーザに置換してくれる機能です。
  • 今回は、これとGitに導入してみたいとおもいます。

ユーザの設定

ユーザ設定の追加

$ cd path/to/clone or path/to/git_init
$ vi .git/config

※SourceTreeの場合
Sourcetreeアプリケーション右上に表示されている 設定 -> 設定ファイルを編集 を押します。

※TortoiseGitの場合
gitの設定ファイル.gitconfigに下記設定を追加します。

[core]
    repositoryformatversion = 0
    filemode = false
    bare = false
    logallrefupdates = true
    symlinks = false
    ignorecase = true
    hideDotFiles = dotGitOnly
    autoCRLF = false
[user]
    name = {ユーザ名}
    email = {メールアドレス}
[http]
    sslVerify = false

hook scriptの設定

  • git では commit や push などリポジトリの操作を行う前後でscriptを実行できます。

参考

コミット時に@authorを自動更新する

pre-commitを編集する

$ vi .git/hooks/pre-commit
pre-commit
#!/bin/sh
# git commit前処理
# 置換でコメントを追加する

# 更新チェックの比較対象を取得
git rev-parse --verify HEAD >/dev/null 2>&1

if [ $? -eq 0 ]; then
    against='HEAD'
else
    # 最初はHEADがないので初期値を使用
    against='4b825dc642cb6eb9a060e54bf8d69288fbee4904'
fi

# git 設定から名前、メールアドレスを取得
user_name=`git config user.name`
user_email=`git config user.email`

# 各更新ファイルのキーワード置換
for file in `git diff --name-only $against`; do
    # ファイル形式がtextの場合のみ置換
    if [ 0 -lt `file "$file" | grep -c 'PHP script text'` ]; then
        # @authorを置換
        sed -i -e "s/@author \(.*\) <\(.*\)>/@author ${user_name} <${user_email}>/g" "$file" 

        git add -f "$file" 
    fi
done

post-commitを編集する

$ vi .git/hooks/post-commit 
post-commit
#!/bin/sh
# git commit後処理

# コマンドの説明
# git log -p -1 --pretty=oneline --name-only
#  直前のコミット情報をファイル名のみ取得する
# grep -v "^[0-9a-fA-F]\{40\} \(.*\)$" 
#  gitハッシュ値の行を非表示にする

# コミットしたファイルの最新ものを取得する
#   個別にファイル指定してコミットした時にファイルの差分が出てしまうため、>最新のものを取得する
for file in `git log -p -1 --pretty=oneline --name-only | grep -v "^[0-9a-fA-F]\{40\} \(.*\)$"`; do
    git checkout HEAD "$file" 
done

結果イメージ

コメット前

/**
 * コメント
 *
 * @package Sample
 * @author before <before@example.co.jp>
 */

コミット後

/**
 * コメント
 *
 * @package Sample
 * @author after <after@example.co.jp>
 */

まとめ

  • hook scriptを使えば、他にもコミットコメントなどの情報を取得してファイルに差し込んだり、勝手にファイルを作成/削除などhack的なことができると思います。
  • 次回も引き続きhook script使ってみたいとおもいます。

シリーズページリンク

2
4
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
2
4