LoginSignup
11
11

More than 5 years have passed since last update.

gitで秘密の情報がコミットされないようにpre-commitでチェック

Last updated at Posted at 2015-01-30

github.comのリポジトリに、秘密の情報をpushしてしまわないようにするため、git pre-commitを使ってコミットメッセージに特定キーワードが含まれる場合はコミットさせないようにした。

なお、以下は社内がGH:Eの環境で一方でgithub.comのpublicなリポジトリも普段使いする人向けに書いているので、GH:E使っておらずgithub.comでprivateなリポジトリを運用している人のケースではそのまま適用できないこと予めご了承ください。

pre-commit

以下のファイルを${my_repos}/.git/hooks/pre-commitに置いて実行権限をつければよい。

pre-commit
#!/bin/sh

# This prevents pushing prohibited words e.g in-house information to
# github.com by mistake.
#
# Usage:
#
# Add words you do not want to publish to the internet as follow,
#   $ echo "secretword" >> ~/.git_prohibited_words
#
git remote -v | grep -E '^.+\s+(git@github.com:|https?://github.com/).+\(push\)$' >/dev/null
if [ $? -eq 0 ]; then
  if [ -e ~/.git_prohibited_words ]; then
    while read word; do
      # Skip comment or blank lines
      echo $word | grep ^# > /dev/null && continue
      echo $word | grep '^\s*$' > /dev/null && continue

      git diff --cached -U0 | grep -i "$word" > /dev/null
      if [ $? -eq 0 ]; then
        echo "Can't commit because of including the prohibited word '$word'" >&2
        exit 1
      fi
    done < ~/.git_prohibited_words
  fi
fi

秘密のキーワードは以下のように追加する。

$ echo 'secretword' >> ~/.git_prohibited_words

既存リポジトリ、新規リポジトリ

既存リポジトリ全部に配る必要があるのと、今後git initやgit cloneする場合にも適用したいので、gitのhooksを管理する(自分用テンプレートを使う)の方法を参考にする。

この方法のイケてない所

僕の場合、~/.git_prohibited_wordsにとりあえず社内のFQDNを入れてみたが、入れてはいけないワードを全部予め入れることが難しい。今後増えるかもしれないし、それを都度入れるのか?と言われると怪しいところである。。。またパスワード情報がコミットされないようにしたい!といった用途には向かいない。

完璧な対策とならないものの、多少なりともミス軽減にはなるので、ひとまずこれで運用してみる。

もっと良いやり方があれば教えていただきたい。

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