LoginSignup
9
9

More than 5 years have passed since last update.

git commit時に自動的に行末の空白を修正する

Last updated at Posted at 2013-12-07

コーディング規約で、行末の空白(trailing whitespace)が禁止されていることがあります。
githubでコードレビューをする場合、diffで行末にスペースがあってもハイライトされたりしないため、これを防ぐのは難しいです。

pre-commit hook

そこで、以下のスクリプトをpre-commitフックにすると、コミットする際に変更した行から行末のスペースが自動的に取り除かれるため、行末の空白のある行が新たに追加されるのを防ぐことができます。

そのコミットで変更した行のみに適用されるため、余計な行を修正してdiffが煩雑になることはありません。

#!/bin/sh

if git-rev-parse --verify HEAD >/dev/null 2>&1
then
  against=HEAD
else
  # Initial commit: diff against an empty tree object
  against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi

for diff in `git diff-index --check --cached $against -- |
  grep 'trailing whitespace' | sed 's/: trailing whitespace.//'`
do
  file=`echo "$diff" | sed 's/:[^:]*$//'`
  line=`echo "$diff" | sed 's/^[^:]*://'`

  sed -i '' -e "$line"'s/ *$//' "$file"
  git add "$file"
done

exit 0

インストール方法

.gitのあるディレクトリで以下のコマンドを実行してください

curl -o .git/hooks/pre-commit https://gist.github.com/k0kubun/7835814/raw
chmod +x .git/hooks/pre-commit
9
9
2

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
9
9