git / handbook

Git, the useful parts

Most of Git is rarely needed. This page keeps the commands that save real time every week — and the ones that rescue you when something went wrong.

Clean history before review rebase

Commit freely while working, then shape the branch into steps a reviewer can follow.

git commit --fixup=abc123        # "belongs to that commit"
git rebase -i --autosquash main     # fixups are folded in automatically
git push --force-with-lease         # refuses if someone pushed meanwhile

Never rewrite history that others already built on; --force-with-lease is the safe default when you must.

Nothing is really lost reflog

Every position of HEAD is recorded for about 90 days, including commits a bad reset or rebase seemed to delete.

git reflog                 # find the state before the mistake
git reset --hard HEAD@{4}
git branch rescue a1b2c3d   # or keep it on a new branch

Find the commit that broke it bisect

Binary search over history: 1000 commits need about ten checks. With a test script Git does the whole search for you.

git bisect start
git bisect bad                # current version is broken
git bisect good v2.4.0        # this one worked
git bisect run ./test.sh      # exit 0 = good, 1 = bad
git bisect reset

Two branches at once worktree

Check out a second branch in another directory instead of stashing half-finished work to fix a bug.

git worktree add ../hotfix release/2.4
git worktree list
git worktree remove ../hotfix

Clearer everyday commands switch

checkout did too many things. Newer commands split them:

git switch -c feature/login     # new branch
git restore src/app.py          # drop local changes in a file
git restore --staged src/app.py # unstage, keep changes

Resolve a conflict once rerere

"Reuse recorded resolution" remembers how you fixed a conflict and replays it on the next rebase of the same branch.

git config --global rerere.enabled true

Team conventions that pay off habits

Short-lived branches merged within days. Commit messages that say why, with a subject under about 50 characters. A .gitattributes with * text=auto to stop line-ending noise between Windows and Linux. Signed commits (gpg.format ssh works with your SSH key) for anything that deploys.

Big repositories scale

Partial clone downloads file contents only when needed; sparse checkout limits the working tree to the directories you touch.

git clone --filter=blob:none URL
git sparse-checkout set services/api docs

Written against Git 2.40 and newer. Older versions lack switch/restore and SSH signing.

Git: самое полезное

Большая часть Git нужна редко. Здесь собраны команды, которые экономят время каждую неделю, и те, что спасают, когда что-то пошло не так.

Чистая история перед ревью rebase

Коммитьте как удобно во время работы, а потом соберите ветку в шаги, которые легко проверить.

git commit --fixup=abc123        # «относится к тому коммиту»
git rebase -i --autosquash main     # fixup-коммиты вливаются сами
git push --force-with-lease         # откажет, если кто-то успел запушить

Не переписывайте историю, на которой уже строят другие; если всё же нужно — --force-with-lease как безопасный вариант.

Ничего не пропадает reflog

Каждое положение HEAD хранится около 90 дней — включая коммиты, которые будто бы удалил неудачный reset или rebase.

git reflog                 # найти состояние до ошибки
git reset --hard HEAD@{4}
git branch rescue a1b2c3d   # или сохранить в новой ветке

Найти коммит, который всё сломал bisect

Двоичный поиск по истории: на 1000 коммитов нужно около десяти проверок. Со скриптом-тестом Git пройдёт весь поиск сам.

git bisect start
git bisect bad                # текущая версия сломана
git bisect good v2.4.0        # а эта работала
git bisect run ./test.sh      # код 0 — хорошо, 1 — плохо
git bisect reset

Две ветки одновременно worktree

Вместо stash незаконченной работы ради срочного фикса — вторая ветка в соседней папке.

git worktree add ../hotfix release/2.4
git worktree list
git worktree remove ../hotfix

Понятные повседневные команды switch

checkout делал слишком много всего. Новые команды разделили это:

git switch -c feature/login     # новая ветка
git restore src/app.py          # отменить локальные правки в файле
git restore --staged src/app.py # убрать из индекса, правки оставить

Решить конфликт один раз rerere

«Reuse recorded resolution» запоминает, как вы разрешили конфликт, и повторяет это при следующем rebase той же ветки.

git config --global rerere.enabled true

Договорённости в команде привычки

Короткоживущие ветки, которые сливаются за несколько дней. Сообщения коммитов объясняют зачем, заголовок — примерно до 50 символов. .gitattributes с * text=auto, чтобы не было шума из-за переводов строк между Windows и Linux. Подписанные коммиты (gpg.format ssh работает с вашим SSH-ключом) для всего, что уходит в деплой.

Большие репозитории масштаб

Частичный клон скачивает содержимое файлов только по необходимости, sparse checkout оставляет в рабочей копии только нужные каталоги.

git clone --filter=blob:none URL
git sparse-checkout set services/api docs

Проверено на Git 2.40 и новее. В старых версиях нет switch/restore и подписи через SSH.