Тема: version-control
-
Tags and releases: lightweight versus annotated tags and how they travel
A lightweight tag is only a name for a commit; an annotated tag is an object with tagger, date, message and optional signature, which is why git describe ignores lightweight tags by default and why releases should use annotated or signed tags; tags are not pushed with branches unless --follow-tags or --tags is used, and a published tag should never be moved.
-
Cherry-picking: when it fits and what it costs the history
git cherry-pick replays the change of a commit as a new commit with a different ID; it is the right tool for backporting a fix to a maintenance branch or salvaging one commit from an abandoned branch, but each pick creates a duplicate that merges cannot recognise, so record the origin with -x and merge instead of picking when the whole branch is wanted.
-
Recovering lost commits and branches with the reflog
The reflog records every movement of HEAD and of each branch in the local repository, so a bad reset, rebase, amend or branch deletion can be undone by finding the earlier position and putting a new branch on it; entries expire after 90 days (30 for unreachable ones) by default, and uncommitted changes were never in it.
-
Gute Commit-Nachrichten: das Warum festhalten
Eine Betreffzeile von rund 50 Zeichen im Imperativ, eine Leerzeile, dann ein Text, der Motivation, Alternativen und Folgen erklärt, statt den Diff nachzuerzählen.
-
Rebase or merge: integrating a branch
Merging preserves history as it happened and adds a merge commit; rebasing rewrites a branch onto a new base for a linear history. Never rebase commits that others have based work on.
-
Воспроизводимый импорт ресурсов: идентичность, настройки и версии инструментов
Как восстановить обработку ресурсов из чистой копии проекта, сохранив исходники, идентичность ссылок, конфигурацию импорта и нужные версии инструментов.
-
Signing commits and tags with an SSH key or GPG
Git signs commits and tags with OpenPGP, X.509 or, since gpg.format=ssh, a plain SSH key; the signer sets gpg.format and user.signingKey, verifiers need an allowed-signers file (SSH) or a trusted key ring (GPG), and forges are checked with git verify-commit or the host's signature badge.
-
Как исключить коммиты переформатирования из git blame: -w и файлы ignore-revs
git blame -w игнорирует пробельные различия при отслеживании строк; --ignore-rev и включённый в репозиторий файл .git-blame-ignore-revs пропускают заданные коммиты, например массовое переформатирование, относя строки к предыдущему содержательному изменению; -M/-C отслеживают перемещённые и скопированные строки. GitHub автоматически читает тот же файл.
-
Stashing safely: messages, untracked files and stash branches
A stash is a commit stored under refs/stash whose older entries live only in that ref's reflog; give each stash a message, include untracked files deliberately, prefer apply over pop until the result is verified, and use git stash branch when the base has moved on.
-
Conventional Commits: машиночитаемые типы коммитов
Спецификация Conventional Commits добавляет к сообщениям коммитов префикс типа (feat, fix и другие) и отметки несовместимых изменений, чтобы автоматически формировать журналы изменений и определять повышение версии.
-
git exit codes an agent can rely on: diff --exit-code, ls-remote --exit-code, and bisect run's 125
Most git porcelain commands only document 'non-zero on failure' without a fixed numeric table, but three commands publish an exact, citable contract: git diff/--quiet uses 1 for differences, git ls-remote --exit-code uses 2 for no matching refs, and git bisect run reserves 125 to mean 'skip this commit,' not 'bad.' A conflicted merge is signalled by state (MERGE_HEAD), not a documented number.
-
Работа в большом репозитории с разреженным извлечением и частичным клонированием
Разреженное извлечение ограничивает каталоги в рабочем дереве (режим cone задаёт их списком), частичное клонирование с --filter=blob:none откладывает загрузку содержимого файлов до момента, когда оно понадобится, а поверхностное клонирование обрезает историю; эти три механизма решают разные задачи и сочетаются, но частичному клону нужен доступ по сети к обещающему удалённому репозиторию.
-
Выбор процесса работы с ветками Git
Как долговременные и тематические ветки складываются в рабочий процесс и какие вопросы помогают выбрать модель на основе основной линии разработки, веток функциональности или релизных веток.
-
Сообщения коммитов, объясняющие причину
Короткий проверяемый формат сообщения коммита: строка краткого описания длиной до примерно 50 символов, пустая строка и основной текст, объясняющий мотивы и последствия, а не пересказывающий diff.
-
Removing large binaries from Git history with git filter-repo
A repository stays large after a big file is deleted because every clone carries its history; shrinking means finding the offending blobs, rewriting all commits that contain them with git filter-repo in a fresh clone, force-pushing every branch and tag, and having everyone re-clone, because rewritten commits have new IDs.
-
Разработка в основной ветке и короткоживущие ветки
Интеграция работы всех участников в одну общую линию не реже раза в день, короткоживущие ветки и скрытие незавершённой работы за флагами уменьшают конфликты слияния и делают непрерывную интеграцию реальной.
-
.gitattributes: окончания строк, драйверы diff и merge, атрибут export-ignore
Файл .gitattributes, сохранённый в репозитории, задаёт поведение для отдельных путей всей команды: text=auto и eol нормализуют окончания строк, diff= назначает шаблоны заголовков блоков изменений или textconv для двоичных файлов, merge= выбирает драйвер, например union, binary помечает файлы, которые не следует преобразовывать, а export-ignore исключает пути из git archive.
-
Подмодули, поддеревья или вендоринг: три способа включить другой репозиторий
Подмодуль хранит указатель (gitlink) на коммит другого репозитория и требует дополнительных команд от каждого пользователя; git subtree копирует файлы другого проекта и при желании его историю в подкаталог с обычными файлами; простой вендоринг копирует файлы, а версию исходного проекта фиксируют вручную. Выбирайте по частоте изменений зависимости и по тому, кто должен иметь возможность клонировать репозиторий.
-
Приведение ветки в порядок перед ревью
Перед запросом ревью объедините исправляющие коммиты с исходными, разделите смешанные и перепишите сообщения так, чтобы каждый коммит представлял одно изменение, удобное для проверки; механическую часть выполнят git rebase -i и autosquash.
-
Git LFS: pointer files, smudge filters and when not to use it
Git LFS replaces tracked large files with small text pointers (version, sha256 oid, size) and stores the contents on a separate server through clean and smudge filters; it keeps clones small but adds a second storage system with its own quotas, so tracking rarely-changing small assets or build outputs with it usually costs more than it saves.
Машиночитаемо: JSON