0Pricing
Git Advanced: Monorepo, Submodules & Workflows · Урок

Отладка с помощью Git Bisect

Используйте `git bisect`, чтобы эффективно определить точный коммит, в котором появилась ошибка, и сэкономить ценное время на отладку

«Отладка с помощью Git Bisect» — бесплатный урок Git Advanced: Monorepo, Submodules & Workflows на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Git Advanced: Monorepo, Submodules & Workflows, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Git Advanced: Monorepo, Submodules & Workflows содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

What is Git Bisect?

Imagine a bug appears in your project, but you're not sure which recent change caused it. Manually checking each commit can be a huge time sink!

git bisect is a powerful Git command that uses a binary search algorithm to quickly find the exact commit that introduced a bug.

The Binary Search Advantage

How does git bisect work so fast? It's like a game of 'hot or cold' with your commit history.

  • You tell Git a commit you know is bad (has the bug).
  • You tell Git a commit you know is good (before the bug existed).
  • Git picks a commit roughly in the middle and asks you to test it.
  • Based on your feedback, it halves the search space, repeating until the culprit is found.

Starting Your Bisect Hunt

To begin, first you need to tell Git you're starting a bisect session. Then, you mark the known 'bad' (buggy) commit and a known 'good' (working) commit.

You can use commit hashes, branch names, or tags.

git bisect start
git bisect bad HEAD
git bisect good <known_good_commit_hash>

The Iterative Process: Test & Mark

After you define your good and bad commits, Git will automatically check out a commit in the middle of that range. Your job is to test the code at this commit.

  • If the bug is present, mark it as bad.
  • If the bug is NOT present, mark it as good.

Git will then move to the next commit, halving the remaining search space.

Marking a Commit

Once you've tested the currently checked-out commit, use these commands to tell Git whether it's good or bad:

  • To mark the current commit as bad: git bisect bad
  • To mark the current commit as good: git bisect good

Git will then automatically check out the next commit to test.

git bisect bad
# OR
git bisect good

Narrowing Down the Problem

You'll repeat the 'test and mark' process. With each step, git bisect gets closer to the single commit that introduced the bug. It's much faster than checking commits one by one!

For a range of 100 commits, it takes at most 7 tests (log2(100) ≈ 6.64).

Found the Culprit!

Eventually, git bisect will narrow the range down to a single commit. It will then report the first 'bad' commit found, which is your bug introducer!

After finding the bug, it's crucial to exit the bisect session to return your repository to its original state (usually the branch you were on when you started).

git bisect reset

Handling Untestable Commits

Sometimes, git bisect might land on a commit that can't be tested (e.g., it doesn't compile, or dependencies are broken). In such cases, you can tell Git to skip it:

git bisect skip

Git will then pick another commit to test, making sure to exclude the skipped one from the potential range of the bug.

git bisect skip

Automating with Git Bisect Run

For even faster debugging, you can automate the testing process using git bisect run. This command takes a script that performs the test and exits with specific codes:

  • 0: The commit is good.
  • 1-127 (except 125): The commit is bad.
  • 125: The commit should be skipped (e.g., cannot build).

Git will then run the script automatically for each commit until the bug is found.

#!/bin/bash

# Example test script for git bisect run
# Replace 'make test' with your actual test command

if make test;
then
  exit 0 # Tests passed, commit is good
else
  exit 1 # Tests failed, commit is bad
fi

Bisect Workflow Check

Which of the following commands are essential when performing a manual git bisect to find a bug?

Debugging Power-Up!

You've mastered git bisect! This powerful tool transforms bug hunting from a tedious chore into an efficient, systematic process using binary search.

  • Start with git bisect start, defining good and bad commits.
  • Test and mark commits as good or bad.
  • Use git bisect skip for untestable commits.
  • Automate with git bisect run for fast, hands-free debugging.
  • Always finish with git bisect reset.

Happy bug hunting!

Часто задаваемые вопросы

Урок «Отладка с помощью Git Bisect» бесплатный?

Да — полный текст урока «Отладка с помощью Git Bisect» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Git Advanced: Monorepo, Submodules & Workflows, подпишись на CoddyKit PRO. Курс Git Advanced: Monorepo, Submodules & Workflows содержит 4 уроков всего.

Чему я научусь в уроке «Отладка с помощью Git Bisect»?

Используйте `git bisect`, чтобы эффективно определить точный коммит, в котором появилась ошибка, и сэкономить ценное время на отладку Ты практикуешь Git Advanced: Monorepo, Submodules & Workflows с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Git Advanced: Monorepo, Submodules & Workflows?

Предыдущий опыт не требуется. Git Advanced: Monorepo, Submodules & Workflows на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.

Сколько времени занимает урок «Отладка с помощью Git Bisect»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Git Advanced: Monorepo, Submodules & Workflows?

Да. Каждый урок Git Advanced: Monorepo, Submodules & Workflows включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Восстановление потерянных коммитов и веток
  2. Отладка с помощью Git Bisect
  3. Оптимизация производительности репозитория Git
  4. Спасение работы с помощью Reflog и Stash
← Назад к Git Advanced: Monorepo, Submodules & Workflows