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?

【git】うっかりrebaseをしそうなときに止めてもらう(自分用.git-template)

Last updated at Posted at 2025-03-04

うっかり考えなしにrebaseをしてしまったので、.git-templateのhooksでrebaseの実行を警告する方法を模索していた。

目的

.git-templateのhooksを用いて、rebaseを行うときは警告(確認)を出すようにする。

ローカルの、自分の環境でのみ適用される。
チームには影響を与えない。

また、Windows環境である。

方法

  • git bashを開いて、以下のコマンドを実行する。
mkdir -p ~/.git-template/hooks

cat <<EOL > ~/.git-template/hooks/pre-rebase
#!/bin/sh
echo "⚠ リベースは禁止されています!" >&2
echo "リベースを中止しました。" >&2
exit 1
EOL

chmod +x ~/.git-template/hooks/pre-rebase
  • git にテンプレートを設定
git config --global init.templateDir ~/.git-template
  • rebaseできないようになっていることをテスト
# リポジトリに移動
git checkout -b test-branch  # テスト用ブランチ作成
echo "First commit" > file.txt
git add file.txt
git commit -m "First commit"

git checkout -b feature-branch  # もう一つ別のブランチ作成
echo "Feature commit" >> file.txt
git commit -am "Feature commit"

git checkout test-branch
git rebase feature-branch

補遺

積み残し課題

本当は「本当にrebaseしますか?(y/n)」というような風にしたかったのだが、うまく動作しなかったので断念した。

削除方法

「rebaseを実行するときに確認するのは絶対のことであり、そういったことのぼうしdhooksを使用するべきではない。pushするときは入念な注意を払って行うように」とお達しをいただいたので、この設定は削除することになった。
削除の仕方(git templateの解除方法)は、以下の通りである。

  • 現在の init.templateDir 設定を確認
git config --global --get init.templateDir
  • 出力例(それぞれのパスが出るよ)
/Users/username/.git-template
  • 保存されている箇所のパス
git config --global --unset init.templateDir
  • 設定が消えたか確認
git config --global --get init.templateDir

何も出力されなければOK。

rebaseについての覚書

rebaseはgitの履歴を改ざんする行為で、容易に使ってはいけないが(≒publicにある履歴を軽い気持ちで改ざんしてはいけないが)ローカルでやる分には有用な場合がある。

Merging vs. rebasing
https://www.atlassian.com/ja/git/tutorials/merging-vs-rebasing

あなたはmerge派?rebase派?綺麗なGitログで実感したメリット
https://style.biglobe.co.jp/entry/2022/03/22/090000

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?