Конфигурация Git
Настройки Git для эффективной работы в команде.
Глобальная конфигурация
Базовые настройки
# Имя и email
git config --global user.name "Ваше Имя"
git config --global user.email "your-email@example.com"
# Редактор по умолчанию
git config --global core.editor "code --wait"
# Автокоррекция команд
git config --global help.autocorrect 1
# Цветной вывод
git config --global color.ui auto
# Настройка push
git config --global push.default simple
git config --global push.autoSetupRemote true
# Настройка pull
git config --global pull.rebase true
# Автоматическое удаление пробелов
git config --global core.autocrlf false
git config --global core.whitespace trailing-space,space-before-tab
git config --global apply.whitespace fix
SSH ключи
# Генерация SSH ключа
ssh-keygen -t ed25519 -C "your-email@example.com"
# Добавление в ssh-agent
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519
# Копирование публичного ключа
cat ~/.ssh/id_ed25519.pub
Алиасы
# Короткие команды
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
git config --global alias.unstage 'reset HEAD --'
git config --global alias.last 'log -1 HEAD'
git config --global alias.visual '!gitk'
# Полезные алиасы
git config --global alias.lg "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"
git config --global alias.tree "log --graph --pretty=format:'%Cred%h%Creset %Cgreen(%cr)%Creset %C(bold blue)<%an>%Creset%C(yellow)%d%Creset %s' --abbrev-commit --all"
git config --global alias.amend "commit --amend --no-edit"
git config --global alias.fixup "commit --fixup"
git config --global alias.squash "commit --squash"
git config --global alias.wip "commit -am 'WIP'"
git config --global alias.undo "reset --soft HEAD~1"
git config --global alias.cleanup "!git branch --merged | grep -v '\\*\\|master\\|main\\|develop' | xargs -n 1 git branch -d"
.gitconfig файл
Создаем ~/.gitconfig
:
[user]
name = Ваше Имя
email = your-email@example.com
[core]
editor = code --wait
autocrlf = false
whitespace = trailing-space,space-before-tab
excludesfile = ~/.gitignore_global
[color]
ui = auto
[push]
default = simple
autoSetupRemote = true
[pull]
rebase = true
[merge]
tool = vscode
[mergetool "vscode"]
cmd = code --wait $MERGED
[diff]
tool = vscode
[difftool "vscode"]
cmd = code --wait --diff $LOCAL $REMOTE
[alias]
co = checkout
br = branch
ci = commit
st = status
unstage = reset HEAD --
last = log -1 HEAD
lg = log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit
tree = log --graph --pretty=format:'%Cred%h%Creset %Cgreen(%cr)%Creset %C(bold blue)<%an>%Creset%C(yellow)%d%Creset %s' --abbrev-commit --all
amend = commit --amend --no-edit
wip = commit -am 'WIP'
undo = reset --soft HEAD~1
cleanup = "!git branch --merged | grep -v '\\*\\|master\\|main\\|develop' | xargs -n 1 git branch -d"
[help]
autocorrect = 1
[init]
defaultBranch = main
[credential]
helper = store
Глобальный .gitignore
Создаем ~/.gitignore_global
:
# OS files
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
Desktop.ini
# IDE/Editor files
.vscode/
.idea/
*.swp
*.swo
*~
# Logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Dependencies
node_modules/
.npm
.pnp
.pnp.js
# Production builds
/dist
/build
*.tgz
*.tar.gz
# Environment files
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
# Cache
.cache/
.parcel-cache/
.next/
.nuxt/
# Coverage directory used by tools like istanbul
coverage/
*.lcov
# Temporary files
*.tmp
*.temp
.temp/
.tmp/
Git Hooks
Pre-commit hook
Создаем .git/hooks/pre-commit
:
#!/bin/sh
# Проверка кода на соответствие стандартам
echo "Running pre-commit checks..."
# Проверка ESLint (если используется)
if command -v eslint >/dev/null 2>&1; then
echo "Running ESLint..."
eslint --ext .js,.ts,.jsx,.tsx src/
if [ $? -ne 0 ]; then
echo "ESLint failed. Please fix errors before committing."
exit 1
fi
fi
# Проверка Prettier (если используется)
if command -v prettier >/dev/null 2>&1; then
echo "Running Prettier..."
prettier --check "src/**/*.{js,ts,jsx,tsx,json,css,md}"
if [ $? -ne 0 ]; then
echo "Prettier check failed. Run 'prettier --write' to fix formatting."
exit 1
fi
fi
# Проверка на коммиты в main/master
branch=$(git rev-parse --abbrev-ref HEAD)
if [ "$branch" = "main" ] || [ "$branch" = "master" ]; then
echo "Direct commits to main/master branch are not allowed!"
exit 1
fi
echo "Pre-commit checks passed!"
chmod +x .git/hooks/pre-commit
Commit-msg hook
Создаем .git/hooks/commit-msg
:
#!/bin/sh
# Проверка формата commit message
commit_regex='^(feat|fix|docs|style|refactor|test|chore)(\(.+\))?: .{1,50}'
if ! grep -qE "$commit_regex" "$1"; then
echo "Invalid commit message format!"
echo "Format: type(scope): description"
echo "Types: feat, fix, docs, style, refactor, test, chore"
echo "Example: feat(auth): add login functionality"
exit 1
fi
chmod +x .git/hooks/commit-msg
Git workflows
Feature branch workflow
# Создание feature ветки
git checkout main
git pull origin main
git checkout -b feature/new-feature
# Работа с feature
git add .
git commit -m "feat: implement new feature"
git push origin feature/new-feature
# Merge в main
git checkout main
git pull origin main
git merge feature/new-feature
git push origin main
git branch -d feature/new-feature
Git Flow workflow
# Инициализация git flow
git flow init
# Новая feature
git flow feature start new-feature
# Работа...
git flow feature finish new-feature
# Новый release
git flow release start 1.0.0
# Подготовка релиза...
git flow release finish 1.0.0
# Hotfix
git flow hotfix start urgent-fix
# Исправление...
git flow hotfix finish urgent-fix
Полезные команды
Поиск и история
# Поиск в коммитах
git log --grep="keyword"
# Поиск в коде
git log -S "function_name"
# История файла
git log --follow -p filename
# Кто изменил строку
git blame filename
# Изменения между ветками
git diff main..feature-branch
# Файлы изменённые между коммитами
git diff --name-only HEAD~2 HEAD
Исправление ошибок
# Отмена последнего коммита (сохранить изменения)
git reset --soft HEAD~1
# Отмена последнего коммита (удалить изменения)
git reset --hard HEAD~1
# Изменение последнего коммита
git commit --amend
# Откат файла к предыдущей версии
git checkout HEAD~1 -- filename
# Интерактивный rebase
git rebase -i HEAD~3
# Сохранение изменений без коммита
git stash
git stash pop
git stash list
git stash drop
Работа с удалёнными репозиториями
# Добавление upstream
git remote add upstream https://github.com/original/repo.git
# Синхронизация с upstream
git fetch upstream
git checkout main
git merge upstream/main
# Просмотр удалённых веток
git branch -r
# Удаление удалённой ветки
git push origin --delete feature-branch
# Принудительный push (осторожно!)
git push --force-with-lease
Скрипты автоматизации
Скрипт для обновления всех репозиториев
#!/bin/bash
# git-update-all.sh
find . -name ".git" -type d | while read dir; do
cd "$dir/.."
echo "Updating $(pwd)"
# Проверяем, есть ли uncommitted changes
if [[ `git status --porcelain` ]]; then
echo " Uncommitted changes found, skipping..."
else
git pull
fi
cd - > /dev/null
done
Скрипт для создания backup
#!/bin/bash
# git-backup.sh
REPO_DIR=$1
BACKUP_DIR="/backups/git"
DATE=$(date +%Y%m%d_%H%M%S)
if [ -z "$REPO_DIR" ]; then
echo "Usage: $0 /path/to/repo"
exit 1
fi
mkdir -p "$BACKUP_DIR"
# Создаем bare clone
git clone --bare "$REPO_DIR" "$BACKUP_DIR/$(basename $REPO_DIR)_$DATE.git"
echo "Backup created: $BACKUP_DIR/$(basename $REPO_DIR)_$DATE.git"