LoginSignup
6
5

More than 5 years have passed since last update.

gitのhookをrakeで管理してみる

Last updated at Posted at 2016-06-07

git の hook は .git/hooks 配下に配置されます。
.git はgitの履歴管理外です。

となると「複数人で利用する場合の git の hook をどう管理しよう?」
という問題がでてきます。
そこで %project%/githooks ディレクトリを作って、そこで hook のスクリプトを管理し、
rake タスクで %project%/.git/hooks/some_hook に symlink を作成したいと思います。

前提

  • ruby install 済み
  • rubocop install 済み

サンプル

構成

$ tree
.
├── Rakefile
├── githooks
│   └── pre-commit
└── src
    └── hoge.rb

プログラム

hoge.rb

ruby としては valid だけど rubocop 的には invalid なコード

  def hoge
  puts :hoge
end

hoge
hoge

Rakefile

namespace :githooks do
  desc "git pre-commit hookの設定"
  task :setup_pre_commit do 
    base_dir = File.expand_path(File.dirname(__FILE__))
    old_path = "#{base_dir}/.git/hooks/pre-commit"
    new_path = "#{base_dir}/githooks/pre-commit"
    if File.symlink?(old_path)
      puts "symlink #{old_path} already exist."
    else
      File.symlink(new_path, old_path)
      puts "success setup symlink to #{old_path}."
    end
  end
end

githooks/pre-commit

src以下を静的解析するrubocopを実行する git の pre-commit hook

#! /usr/bin/ruby

exit(system("rubocop src"))

デモ

$ rake githooks:setup_pre_commit
success setup symlink to %project%/.git/hooks/pre-commit.

# 作成済みの場合はその旨メッセージが表示される
$ rake githooks:setup_pre_commit
symlink %project%/.git/hooks/pre-commit already exist.

$ git add -A

# commit 時に rubocop が実行されていることがわかる。commitも未完了。
$ git commit -m "test"
Inspecting 1 file
W

Offenses:

src/hoge.rb:1:3: C: Indentation of first line in file detected.
  def hoge
  ^^^
src/hoge.rb:2:3: C: Use 2 (not 0) spaces for indentation.
  puts :hoge

src/hoge.rb:3:1: W: end at 3, 0 is not aligned with def at 1, 2.
end
^^^
src/hoge.rb:5:1: C: Inconsistent indentation detected.
hoge
^^^^
src/hoge.rb:6:1: C: Inconsistent indentation detected.
hoge
^^^^

1 file inspected, 5 offenses detected

外部資料

6
5
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
6
5