15
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

gitでmasterへのpushを防ぐhook

15
Last updated at Posted at 2015-01-31

やりたいこと

  • masterにpushしようとしたときに弾く
    • ただしurlがあるパターンにマッチした場合は弾かないようにする

よくあるhookの例としてmasterブランチにいるときに弾く設定はあるけど、masterブランチにいなくてもmasterにpushはできるし、masterにいてもmaster以外にpushしたいことがあるので、このようなhookを使った。

pre-hook

pre-hook
# !/usr/bin/env bash
# An example hook script to verify what is about to be pushed. Called by "git
# push" after it has checked the remote status, but before anything has been
# pushed. If this script exits with a non-zero status nothing will be pushed.
#
# This hook is called with the following parameters:
#
# $1 -- Name of the remote to which the push is being done
# $2 -- URL to which the push is being done
#
# If pushing without using a named remote those arguments will be equal.
#
# Information about the commits which are being pushed is supplied as lines to
# the standard input in the form:
#
# <local ref> <local sha1> <remote ref> <remote sha1>
#
# This sample shows how to prevent push for master branch.
remote="$1"
url="$2"
 
allow=$(git config --get-all prevent-push-master.allow)
for pattern in $allow
do
    if [[ $url =~ $pattern ]]; then
        exit 0
    fi
done
 
read local_ref local_sha remote_ref remote_sha
if [[ $remote_ref =~ 'master' ]]; then
    echo 'Prevented push for master branch!'
    exit 1
fi

pre-pushを設置する

上のスクリプトをGitリポジトリの.git/hooks以下に置いて、実行権限をつける。

$ cd <Gitリポジトリ>/.git/hooks
$ vim pre-push
# コードを貼り付けて保存して終了
$ chmod +x pre-push

毎回手でセットするのが面倒な場合はtemplatedirの設定をして、そこにスクリプトを置く。

$ git config --global init.templatedir '~/.git_template'
$ mkdir -p ~/.git_template/hooks
$ cd ~/.git_template/hooks
$ vim pre-push
# コードを貼り付けて保存して終了
$ chmod +x pre-push

こうしておくと、git initgit cloneした時に、.git/hooksにシンボリックリンクを貼ってくれる。
すでにあるGitリポジトリに対してもgit initしてやるとシンボリックリンクを貼る。

設定

mersterへのpushを許可したいユーザーやリポジトリがある場合は

$ git config --global prevent-push-master.allow 'tmsanrinsha'
$ git config --global --add prevent-push-master.allow 'repo2'

のように設定する。remoteのURLが上記の設定のどれかに部分一致すると、masterへのpushが許可される。

あとは通常通りgit pushしてみる。ただ、設定がうまくいってなくて、masterにpushされてしまうと大変なので、
問題のないリポジトリに対して、まずは試して下さい。

15
10
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
15
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?