【GIT】初学者向け、git bisect によるバグ特定

【GIT】初学者向け、git bisect によるバグ特定

二分探索アルゴリズムを使用してバグが導入されたコミットを特定する方法をまとめておきます。

GIT #Github#初学者

【GIT】初学者向け、git bisect によるバグ特定

サムネイル

二分探索アルゴリズムを使用してバグが導入されたコミットを特定する方法をまとめておきます。

更新日: 8/5/2025

bisectの動作原理

git bisectは、正常なcommitと問題のあるcommitの間で二分探索を実行します。各段階でcommitをtestし、結果に基づいて検索範囲を絞り込みます。

# 1. bisectセッション開始
git bisect start

# 2. 現在の状態をバグありとしてマーク
git bisect bad

# 3. 正常だった過去のcommitをマーク
git bisect good v1.0.0

# 4-6. testと判定を繰り返し
# (Gitが自動的に中間commitをチェックアウト)

# 7. セッション終了
git bisect reset

buildエラーの原因調査

# compileエラーの原因調査
git bisect start

# 現在はbuildエラーが発生
git bisect bad

# 1週間前のリリース版は正常
git bisect good release/v1.2.0

# 中間commitがチェックアウトされる
# buildの確認
npm run build

# 結果に基づいて判定
git bisect good  # build成功
# または
git bisect bad   # build失敗

# 原因commitが特定されるまで繰り返し

APIエンドポイントエラーの調査

git bisect start
git bisect bad

# 以前のバージョンではAPIが正常動作
git bisect good HEAD~20

# 各commitでサーバー起動とtest
npm start &
SERVER_PID=$!
sleep 5

# APIテスト実行
curl -f http://localhost:3000/api/users
RESULT=$?
kill $SERVER_PID

# 結果に基づいて判定
if [ $RESULT -eq 0 ]; then
    git bisect good
else
    git bisect bad
fi

testスクリプトによる自動調査

# buildテスト用スクリプト
cat > check_build.sh << 'EOF'
#!/bin/bash
npm install --silent
npm run build
exit $?
EOF

chmod +x check_build.sh

# 自動bisect実行
git bisect start
git bisect bad
git bisect good v1.0.0
git bisect run ./check_build.sh

unitテストでの自動調査

# 特定のtestが失敗する原因調査
cat > test_feature.sh << 'EOF'
#!/bin/bash
npm install --silent
npm test -- --grep "認証機能"
exit $?
EOF

chmod +x test_feature.sh

git bisect start
git bisect bad
git bisect good HEAD~30
git bisect run ./test_feature.sh

パフォーマンス回帰の調査

cat > perf_check.sh << 'EOF'
#!/bin/bash
npm install --silent
npm run build

# 処理時間測定
start_time=$(date +%s%N)
node dist/heavy-task.js
end_time=$(date +%s%N)
execution_time=$(( (end_time - start_time) / 1000000 ))

# 5秒以内なら正常、それ以上なら回帰
if [ $execution_time -lt 5000 ]; then
    echo "Performance OK: ${execution_time}ms"
    exit 0
else
    echo "Performance regression: ${execution_time}ms"  
    exit 1
fi
EOF

chmod +x perf_check.sh

git bisect start
git bisect bad
git bisect good release/v1.1.0
git bisect run ./perf_check.sh

特定ファイルに関連するcommitのみ調査

# 認証関連ファイルの変更のみを対象
git bisect start -- src/auth/
git bisect bad
git bisect good HEAD~15

commitのスキップ

# buildできないcommitをスキップ
git bisect skip

# 複数のcommitを一度にスキップ
git bisect skip abc1234 def5678 ghi9012

bisectセッションの保存と復元

# セッション状況をファイル保存
git bisect log > investigation.log

# セッション終了
git bisect reset

# 後で同じセッションを復元
git bisect replay investigation.log

調査のコツ

bisectは履歴を変更しないため、共有ブランチでも安全に使用できます。ただし、test環境の準備に時間がかかる場合は、自動化スクリプトの作成をお勧めします。

# 範囲を狭めることで調査時間短縮
git bisect good HEAD~10  # 10commit前から調査

# package-lock.jsonを使用した確実なインストール
npm ci  

# 不安定なtestを除外
npm run test:unit  

# 調査過程をログファイルに記録
git bisect log > bug_investigation_$(date +%Y%m%d).log

git bisectを活用するのもいいが、他ツールで十分かもと思いました。
GITコマンド大好きな方が使うんだろうなと…。

検索

検索条件に一致する記事が見つかりませんでした