やりたいこと
- 業務上gitでcommitするときにユーザ名のprefixが特定のprefixから始まっていないといけない
- そうでないユーザ名でcommitできないようにする
- リポジトリごとに設定するのは大変なので、すべてのリポジトリに対してチェックできるようにする
方法
gitのhook scriptを使うことで実現できます。
以下の要領でチェックできていることが分かります。
C:\Program Files\Git\etc\hooks\pre-commit
#!/bin/sh
user_name=$(git config user.name)
# echo "${user_name}"
if [ -z "${user_name}" ]; then
echo "fatal: user.name is not set."
exit 1
fi
if [[ ! ${user_name} =~ ^(hoge|foo)-.* ]]; then
echo "fatal: The username to commit GitHub repository is wrong."
echo "fatal: Check [git config user.name] ."
exit 1
fi
git config --global core.hooksPath "C:\Program Files\Git\etc\hooks"
D:\git\test>git init
Initialized empty Git repository in D:/git/test/.git/
D:\git\test>git config user.name
x-tutuz
D:\git\test>git config core.hooksPath
C:\Program Files\Git\etc\hooks
D:\git\test>vi hoge
D:\git\test>git add hoge
warning: LF will be replaced by CRLF in hoge.
The file will have its original line endings in your working directory
D:\git\test>git commit -a -m "add"
fatal: The username to commit GitHub repository is wrong.
fatal: Check [git config user.name] .
D:\git\test>git log
fatal: your current branch 'master' does not have any commits yet
D:\git\test>git config --global user.name hoge-tutuz
D:\git\test>git config user.name
hoge-tutuz
D:\git\test>git commit -a -m "add"
[master (root-commit) 4c61dda] add
1 file changed, 1 insertion(+)
create mode 100644 hoge
D:\git\test>git log
commit 4c61ddabcb64498090be408c6149c37125a5e445 (HEAD -> master)
Author: hoge-tutuz <hoge@gmail.com>
Date: Mon Apr 8 22:22:16 2019 +0900
add
D:\git\test>
余談
EclipseのEGitからのcommitにも使いたかったのですが、EGitではhook scriptが効きませんでした。