開発の最中、main
ブランチへ移動した際についうっかりブランチの最新情報の取得(git pull
)をし忘れてしまうことはありませんか?
「Git フック」という機能を使うことで特定のブランチへ checkout
した時に git pull
を自動的に実行するよう設定できます。
当記事ではその設定方法を共有します。
設定手順
① まずは任意のリポジトリの .git/hooks
ディレクトリに移動します。
② 続いて .git/hooks
ディレクトリ内に post-checkout
という名前のファイルを作成します。
③ この post-checkout
に以下のコードを記述します。
.git/hooks/post-checkout
#!/bin/sh
# 現在のブランチ名を取得
branch=$(git rev-parse --abbrev-ref HEAD)
# `main` ブランチへと移動した際に git pull を実行する
if [ "$branch" = "main" ]; then
git pull origin $branch
fi
④ post-checkout
の編集が終わったらターミナルで任意のリポジトリのルートに移動します。
⑤ ターミナルで以下のコマンドを実行し、post-checkout
ファイルにスクリプトの実行権限を与えます。
chmod +x .git/hooks/post-checkout
以上で設定はすべて完了です。
上記 post-checkout
ファイルの内容ですと、何らかのブランチから main
ブランチへ git checkout
(もしくは git switch
)した際に自動で git pull
が行われるようになります。
複数のブランチに対して「ブランチ移動時のローカル自動最新化」を設定したい場合
post-checkout
ファイルを以下のように編集してください。
.git/hooks/post-checkout
#!/bin/sh
# 現在のブランチ名を取得
branch=$(git rev-parse --abbrev-ref HEAD)
# `main` ブランチ もしくは `develop` ブランチへと移動した際に git pull を実行する
if [ "$branch" = "main" ] || [ "$branch" = "develop" ]; then
git pull origin $branch
fi