Git 自动化
Git Hooks
Git Hooks 是在特定 Git 事件(如提交、推送)前后自动执行的脚本。
常用钩子:
- pre-commit:提交前执行(如代码检查、格式化)。
- commit-msg:提交信息验证(如规范检查)。
- pre-push:推送前执行(如测试)。
- post-merge:合并后执行(如依赖安装)。
配置示例:
bash
# 创建 pre-commit 钩子
touch .git/hooks/pre-commit
chmod +x .git/hooks/pre-commit
# 添加脚本内容(例如运行 ESLint)
echo "#!/bin/sh\nnpm run lint" > .git/hooks/pre-commit使用 Husky 简化管理:
bash
# 安装 Husky
npm install husky --save-dev
# 启用 Git Hooks
npx husky install
# 添加 pre-commit 钩子
npx husky add .git/hooks/pre-commit "npm run lint"自动化工具
提交信息规范(Commitizen + Commitlint)
bash
# 安装工具
npm install commitizen @commitlint/config-conventional @commitlint/cli --save-dev
# 配置 Commitizen
npx commitizen init cz-conventional-changelog --save-dev --save-exact
# 配置 Commitlint
echo "module.exports = {extends: ['@commitlint/config-conventional']}" > commitlint.config.jsCI/CD 集成
结合 GitHub Actions、GitLab CI 等工具,实现自动化构建、测试和部署:
GitHub Actions 示例:
yaml
# .github/workflows/main.yml
name: CI
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Use Node.js
uses: actions/setup-node@v2
with:
node-version: '16'
- name: Install dependencies
run: npm ci
- name: Lint
run: npm run lint
- name: Test
run: npm test
- name: Build
run: npm run buildGit Aliases
简化常用命令:
bash
# 添加到 ~/.gitconfig
[alias]
st = status
ci = commit
br = branch
co = checkout
lg = log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit
amend = commit --amend --no-edit
unstage = reset HEAD --
last = log -1 HEAD