Git and GitHub have become the de facto standard for version control in modern web development. Using these tools correctly is critical to effective work by both individual developers and teams. In this article, we’ll cover all aspects of working with Git and GitHub, from basic commands to advanced techniques.
The importance of version control
A version control system (VCS) is a fundamental tool in modern development. Git provides:
- Tracking changes to code
- The ability to revert to previous versions
- Parallel development within a team
- Code backups
- An audit trail of changes and responsibility
Git basics
Initializing a repository
# Создание нового репозитория
git init
# Клонирование существующего репозитория
git clone https://github.com/username/repository.git
# Клонирование с указанием папки
git clone https://github.com/username/repository.git my-projectBasic commands
# Проверка статуса
git status
# Добавление файлов в staging area
git add filename.js
git add . # Добавить все файлы
# Создание коммита
git commit -m "Add user authentication feature"
# Просмотр истории коммитов
git log
git log --oneline
git log --graph --oneline --allConfiguring Git
# Настройка пользователя
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
# Настройка редактора
git config --global core.editor "code --wait"
# Настройка ветки по умолчанию
git config --global init.defaultBranch main
# Просмотр конфигурации
git config --listWorking with branches
Creating and switching branches
# Создание новой ветки
git branch feature/user-auth
# Переключение на ветку
git checkout feature/user-auth
# Создание и переключение одной командой
git checkout -b feature/user-auth
# Просмотр всех веток
git branch -a
# Удаление ветки
git branch -d feature/user-auth
git branch -D feature/user-auth # Принудительное удалениеModern Git (Git 2.23+)
# Новые команды для работы с ветками
git switch feature/user-auth
git switch -c feature/user-auth
# Восстановление файлов
git restore filename.js
git restore --staged filename.jsMerging branches
# Слияние ветки в текущую
git merge feature/user-auth
# Слияние с отменой fast-forward
git merge --no-ff feature/user-auth
# Слияние с squash (объединение коммитов)
git merge --squash feature/user-auth
git commit -m "Merge feature/user-auth"Working with remote repositories
Configuring a remote
# Добавление удаленного репозитория
git remote add origin https://github.com/username/repository.git
# Просмотр удаленных репозиториев
git remote -v
# Изменение URL удаленного репозитория
git remote set-url origin https://github.com/username/new-repository.git
# Удаление remote
git remote remove originSyncing with a remote repository
# Получение изменений
git fetch origin
git fetch origin main
# Получение и слияние изменений
git pull origin main
git pull --rebase origin main
# Отправка изменений
git push origin main
git push -u origin main # Установка upstream
# Принудительная отправка (осторожно!)
git push --force-with-lease origin mainEffective commits
Commit structure
# Conventional Commits
git commit -m "feat: add user authentication"
git commit -m "fix: resolve login validation issue"
git commit -m "docs: update README with installation steps"
git commit -m "style: format code according to style guide"
git commit -m "refactor: simplify authentication logic"
git commit -m "test: add unit tests for user service"
git commit -m "chore: update dependencies"Commit types
- feat: new functionality
- fix: bug fixes
- docs: documentation changes
- style: code formatting
- refactor: code refactoring
- test: adding tests
- chore: updating dependencies or configuration
Interactive rebase
# Редактирование последних коммитов
git rebase -i HEAD~3
# Команды в интерактивном режиме:
# pick - использовать коммит как есть
# reword - изменить сообщение коммита
# edit - остановиться для редактирования
# squash - объединить с предыдущим коммитом
# fixup - объединить, но удалить сообщение
# drop - удалить коммитGitHub workflow
Creating a pull request
# 1. Создание feature ветки
git checkout -b feature/new-feature
# 2. Внесение изменений
# ... редактирование файлов ...
# 3. Коммит изменений
git add .
git commit -m "feat: implement new feature"
# 4. Отправка ветки
git push origin feature/new-feature
# 5. Создание Pull Request на GitHubPull request template
## Описание
Краткое описание изменений
## Тип изменений
- [ ] Bug fix
- [ ] New feature
- [ ] Breaking change
- [ ] Documentation update
## Тестирование
- [ ] Unit tests добавлены/обновлены
- [ ] Manual testing выполнен
- [ ] All tests pass
## Чек-лист
- [ ] Код соответствует style guide
- [ ] Документация обновлена
- [ ] Коммиты следуют conventional commits
- [ ] Self-review выполнен
## Скриншоты (если применимо)Code review
# Просмотр изменений в PR
git fetch origin pull/123/head:pr-123
git checkout pr-123
# Добавление комментариев к конкретным строкам
# В GitHub интерфейсе: клик на номер строки
# Запрос изменений
# В GitHub: Request changes
# Одобрение изменений
# В GitHub: ApproveAdvanced techniques
Stash
# Сохранение изменений во временное хранилище
git stash
git stash push -m "WIP: working on feature"
# Просмотр stash
git stash list
# Применение stash
git stash pop
git stash apply stash@{0}
# Удаление stash
git stash drop stash@{0}
git stash clearCherry-pick
# Применение конкретного коммита
git cherry-pick abc1234
# Применение диапазона коммитов
git cherry-pick abc1234..def5678
# Cherry-pick с продолжением
git cherry-pick --continue
git cherry-pick --abortRebase
# Rebase текущей ветки на main
git rebase main
# Интерактивный rebase
git rebase -i HEAD~5
# Rebase с продолжением
git rebase --continue
git rebase --abort
git rebase --skipBisect
# Поиск коммита, который ввел баг
git bisect start
git bisect bad HEAD
git bisect good abc1234
# После тестирования
git bisect good # или git bisect bad
# Завершение bisect
git bisect resetGit hooks
Pre-commit hook
#!/bin/sh
# .git/hooks/pre-commit
# Запуск линтера
npm run lint
# Запуск тестов
npm test
# Проверка типов (TypeScript)
npm run type-checkCommit-msg hook
#!/bin/sh
# .git/hooks/commit-msg
# Проверка conventional commits
commit_regex='^(feat|fix|docs|style|refactor|test|chore)(\(.+\))?: .{1,50}'
if ! grep -qE "$commit_regex" "$1"; then
echo "Error: Commit message does not follow conventional commits format"
exit 1
fiAutomating with Husky
// package.json
{
"husky": {
"hooks": {
"pre-commit": "lint-staged",
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
}
},
"lint-staged": {
"*.{js,jsx,ts,tsx}": [
"eslint --fix",
"prettier --write"
]
}
}GitHub Actions
CI/CD pipeline
# .github/workflows/ci.yml
name: CI/CD Pipeline
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main ]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run linter
run: npm run lint
- name: Run tests
run: npm test
- name: Build project
run: npm run buildDeploying to GitHub Pages
# .github/workflows/deploy.yml
name: Deploy to GitHub Pages
on:
push:
branches: [ main ]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install dependencies
run: npm ci
- name: Build project
run: npm run build
- name: Deploy to GitHub Pages
uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./distBest practices
1. Commit structure
- Use conventional commits
- Write clear commit messages
- Make atomic commits
- Avoid "WIP" commits
2. Working with branches
- Use feature branches
- Give branches clear names
- Delete stale branches
- Use protected branches
3. Pull requests
- Create small PRs
- Add descriptions
- Use templates
- Require code review
4. Security
- Don’t commit secrets
- Use .gitignore
- Check dependencies
- Update regularly
5. Teamwork
- Agree on a workflow
- Use consistent standards
- Conduct code reviews
- Document processes
Troubleshooting
Undoing the last commit
# Отмена коммита, сохранение изменений
git reset --soft HEAD~1
# Отмена коммита, удаление изменений
git reset --hard HEAD~1
# Создание нового коммита для отмены
git revert HEADRecovering deleted files
# Восстановление файла из последнего коммита
git checkout HEAD -- filename.js
# Восстановление из конкретного коммита
git checkout abc1234 -- filename.js
# Восстановление удаленной ветки
git reflog
git checkout -b recovered-branch abc1234Resolving conflicts
# Просмотр конфликтующих файлов
git status
# Редактирование файлов с конфликтами
# ... разрешение конфликтов вручную ...
# Добавление разрешенных файлов
git add filename.js
# Продолжение операции
git commit # для merge
git rebase --continue # для rebaseConclusion
Git and GitHub are powerful tools for managing code versions. Using these tools correctly can significantly improve code quality, speed up development, and simplify teamwork.
Key points to remember:
- Learn the basics of Git - commands, branches, commits
- Use conventional commits for a clear history
- Work with branches effectively
- Conduct code reviews to ensure code quality
- Automate processes with hooks and CI/CD
- Follow best practices for teamwork
By following these recommendations, you can create an effective development workflow that scales as the project and team grow.