Gitignore и практические советы
Updated Jul 2026
.gitignore для тестовых артефактов
Автоматизация тестирования генерирует файлы, которые никогда не должны коммититься. Правильно настроенный .gitignore предотвращает случайные коммиты больших бинарных файлов, конфиденциальных учётных данных и временных результатов тестирования.
Необходимый .gitignore для QA-проектов
# Test results and reports
test-results/
playwright-report/
coverage/
allure-results/
allure-report/
junit-results/
*.xml.bak
# Screenshots and videos from test runs
screenshots/
videos/
*.png
!src/assets/*.png # Keep intentional assets (note the negation)
# Playwright traces
traces/
*.zip
# Environment and secrets
.env
.env.local
.env.*.local
*.pem
*.key
credentials.json
service-account.json
# IDE and OS files
.idea/
.vscode/settings.json # Keep shared settings, ignore personal ones
.DS_Store
Thumbs.db
# Dependencies
node_modules/
__pycache__/
*.pyc
.venv/
venv/
# Build artifacts
dist/
build/
*.tsbuildinfo
# Temporary files
tmp/
temp/
*.tmp
*.swp
Распространённые ошибки .gitignore
Забыли игнорировать результаты тестов
# Forgetting these means test results get committed
# Adding them later does not remove already-tracked files
test-results/
coverage/
Неправильная работа с паттернами отрицания
# This ignores ALL .png files, including intentional ones
*.png
# Fix: Use negation to keep specific files
*.png
!src/assets/*.png
!docs/images/*.png
Игнорирование слишком многого или слишком малого
# Too broad: ignores all JSON files (including test data you want to commit)
*.json
# Too narrow: misses test outputs in subdirectories
test-results/*.png # Does NOT match test-results/chromium/screenshot.png
# Fix: Use recursive patterns
test-results/**
Исправление случайно закоммиченных файлов
Если кто-то уже закоммитил файл, который должен быть проигнорирован, добавление его в .gitignore не удалит его из отслеживания. Нужно явно убрать его из отслеживания.
# Remove file from Git tracking without deleting it locally
git rm --cached test-results/report.html
# Remove an entire directory from tracking
git rm -r --cached test-results/
# After removing, add to .gitignore and commit
echo "test-results/" >> .gitignore
git add .gitignore
git commit -m "chore: stop tracking test results, add to .gitignore"
Для больших файлов, которые долго находились в истории и раздувают репозиторий, может потребоваться git filter-branch или BFG Repo-Cleaner для перезаписи истории. Это деструктивная операция — сначала согласуйте с командой.
Практические команды Git для QA-инженеров
Исследование изменений
# See what changed in the last 5 commits (useful for targeted testing)
git log --oneline -5 --stat
# Find all commits that touched a specific test file
git log --follow -- tests/checkout.spec.ts
# See who last modified each line of a test file (find the right person to ask)
git blame tests/checkout.spec.ts
# See the diff between your branch and main (what the PR will show)
git diff main...HEAD
# Show only the names of changed files (great for deciding what to test)
git diff main...HEAD --name-only
# Show changes in a specific file since a specific commit
git diff v2.3.0..HEAD -- tests/checkout.spec.ts
Управление незавершённой работой
# Stash your work-in-progress to switch branches for a hotfix
git stash push -m "WIP: refactoring payment tests"
# List all stashes
git stash list
# Apply the most recent stash (keeps it in the stash list)
git stash apply
# Pop the most recent stash (removes it from the stash list)
git stash pop
# Apply a specific stash
git stash apply stash@{2}
# Switch to a different branch, do work, and come back
git stash push -m "WIP: payment tests"
git checkout hotfix/urgent-fix
# ... do the work ...
git checkout feature/my-branch
git stash pop
Исправление ошибок
# Undo the last commit but keep the changes staged
git reset --soft HEAD~1
# Undo the last commit and unstage the changes
git reset HEAD~1
# Discard all uncommitted changes in a specific file
git checkout -- tests/broken-test.spec.ts
# Revert a specific commit (creates a new commit that undoes the changes)
git revert abc123f
# Recover a deleted branch (find the commit hash in reflog)
git reflog
# Find the commit hash of the branch tip
git checkout -b recovered-branch abc123f
Поиск по истории
# Find commits that contain a specific string in the diff
git log -S "data-testid=\"checkout-button\"" --oneline
# Find commits with a message matching a pattern
git log --grep="fix.*flaky" --oneline -i
# Find when a line was added or removed
git log -p -S "waitForTimeout" -- tests/
# Show the commit that last modified a specific line
git log -1 -L 42,42:tests/checkout.spec.ts
Антипаттерны Git-рабочего процесса для QA
| Антипаттерн | Проблема | Решение |
|---|---|---|
| Коммит результатов тестов | Репозиторий раздувается бинарными файлами | Добавьте test-results/ в .gitignore |
| Гигантские PR с 50 тестовыми файлами | Невозможно провести содержательное ревью | Разбейте на логичные, удобные для ревью части |
| Расплывчатые сообщения коммитов («fix tests») | Никто не знает, что изменилось и почему | Пишите описательные сообщения: «fix: stabilize checkout test by awaiting API response» |
| Долгоживущие фича-ветки | Расхождение с main, болезненные слияния | Делайте rebase регулярно, держите ветки короткоживущими |
| Force-push в общие ветки | Уничтожает локальную историю коллег | Делайте force-push только в свои ветки до ревью |
Коммит .env-файлов |
Учётные данные видны в истории репозитория | Добавьте .env в .gitignore, используйте управление секретами |
Неиспользование .gitignore с первого дня |
Артефакты накапливаются, сложно очистить позже | Начинайте каждый проект с исчерпывающего .gitignore |
Советы по настройке Git
# Set up useful aliases
git config --global alias.st "status"
git config --global alias.co "checkout"
git config --global alias.br "branch"
git config --global alias.lg "log --oneline --graph --decorate --all"
git config --global alias.last "log -1 HEAD --stat"
# Set default branch name
git config --global init.defaultBranch main
# Auto-prune deleted remote branches
git config --global fetch.prune true
# Use a better diff algorithm
git config --global diff.algorithm histogram
# Set up pull to rebase by default (keeps history cleaner)
git config --global pull.rebase true
Git-хуки для качества тестов
Git-хуки запускают скрипты автоматически в определённые моменты Git-рабочего процесса. Они могут обеспечивать стандарты качества локально.
# .git/hooks/pre-commit (or use husky for team-wide hooks)
#!/bin/sh
# Prevent committing .env files
if git diff --cached --name-only | grep -q '\.env'; then
echo "ERROR: Attempting to commit .env file. Aborting."
exit 1
fi
# Prevent committing test.only or describe.only
if git diff --cached | grep -q '\.only'; then
echo "ERROR: Found .only in test files. Remove before committing."
exit 1
fi
# Run lint on staged files
npx lint-staged
Использование husky для командных хуков:
// package.json
{
"husky": {
"hooks": {
"pre-commit": "lint-staged",
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
}
},
"lint-staged": {
"tests/**/*.ts": ["eslint --fix", "prettier --write"]
}
}
Практическое упражнение
- Проверьте
.gitignoreвашего проекта. Правильно ли игнорируются результаты тестов, скриншоты и.env-файлы? - Проверьте, не были ли случайно закоммичены тестовые артефакты:
git ls-files | grep -E "(test-results|coverage|screenshots)" - Настройте Git-алиасы, перечисленные выше, и используйте
git lgдля исследования истории проекта - Потренируйтесь в использовании
git stashдля переключения веток посреди работы и возврата без потери изменений - Используйте
git log -Sдля нахождения момента, когда конкретный тестовый селектор был добавлен или изменён - Настройте pre-commit хук, предотвращающий коммит
.onlyв тестовых файлах
Тема для интервью: «Я использую Git как инструмент QA, а не просто как хранилище кода. Я использую git bisect для бинарного поиска коммитов, вносящих регрессии, экономя часы ручного исследования. Я пишу описания PR, включающие доказательства тестирования и шаги верификации. Я достаточно хорошо понимаю стратегии ветвления, чтобы адаптировать свой план выполнения тестов — в trunk-based development я обеспечиваю готовность каждого коммита к развёртыванию, а в GitFlow планирую тестирование в нескольких точках интеграции. Я настраиваю .gitignore для исключения тестовых артефактов из репозитория и использую git-хуки для предотвращения распространённых ошибок вроде коммита .only или .env файлов. Я помечаю релизы тегами с метаданными результатов тестирования, чтобы у нас был чёткий аудиторский след того, что было проверено для каждого релиза.»