0
0

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 1 year has passed since last update.

Gitのpre-pushフックでmainブランチへの誤pushを防ぐ方法

Last updated at Posted at 2023-08-05

はじめに

ブランチの切り替えを忘れてしまい、誤ってmainブランチに直接pushしてしまった経験はありませんか? GitHubなどではリポジトリの設定を変更することで、mainブランチへのpushを制限できますが、その設定がなされていない場合でも、ローカル環境で特定のブランチ(例えばmain)へのpushを防ぐ対策があります。Gitでは、特定のアクションが起こる前後に実行されるスクリプト、つまり「フック(hook)」という機能を利用することで、このような問題を未然に防ぐことが可能です。今回は、pre-pushフックを用いて、mainブランチへのpushを防止する方法を紹介します。

目次

  1. 方法
  2. 結果
  3. おまけ

方法

リポジトリのルートディレクトリに移動します。

bash
cd /path/to/your/repository

.git/hooksディレクトリにpre-pushという名前の新しいファイルを作成します。

bash
touch .git/hooks/pre-push

ファイルに実行権限を付与します。

bash
chmod +x .git/hooks/pre-push

pre-pushファイルを開き、以下の内容を追加します。

bash
nano .git/hooks/pre-push

ファイルが開いたら、以下のスクリプトを追加します。

bash
#!/bin/bash

protected_branch='main'

while read local_ref local_sha remote_ref remote_sha
do
    if [ $protected_branch = ${remote_ref:11} ]; then
        echo "Cannot push to $protected_branch"
        exit 1
    fi
done

最後に、pre-push ファイルに実行許可を与えるために以下のコマンドを実行します。

bash
chmod +x .git/hooks/pre-push

結果

application.scssをmainブランチへpushしようとすると
image.png

このようなエラーが表示されpushができない
image.png

おまけ

プロテクトするブランチを追加することもできます

bash
#!/bin/bash

protected_branches=("main" "develop")

while read local_ref local_sha remote_ref remote_sha
do
    for branch in "${protected_branches[@]}"; do
        if [ $branch = ${remote_ref:11} ]; then
            echo "Cannot push to $branch"
            exit 1
        fi
    done
done
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?