方案 1:使用 pre-push 钩子
-
实现方式
在本地配置 pre-push 钩子,在推送前运行检查。例如:
-
Rust 项目(手动配置):
bash
CollapseWrapCopy
# .git/hooks/pre-push #!/bin/sh cargo test # 运行所有测试 if [ $? -ne 0 ]; then echo "测试失败,推送中止" exit 1 fi
赋予执行权限:chmod +x .git/hooks/pre-push。
-
-
效果
每次运行 git push 时,钩子会触发检查,确保代码通过测试后再推送。
方案 2:通过 CI/CD 流水线检查
推送前在本地运行检查是可选的,但更常见的做法是将检查交给远程仓库的 CI/CD 流水线。这样可以避免本地环境的差异,确保检查结果一致。
-
GitHub Actions
-
在 .github/workflows/ci.yml 中定义工作流:
yaml
CollapseWrapCopy
name: CI on: [push] jobs: lint-and-test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Install Rust uses: actions-rs/toolchain@v1 with: toolchain: stable - name: Lint run: cargo clippy -- -D warnings - name: Test run: cargo test
-
推送代码到 GitHub 时,Actions 会自动运行 linting 和测试。
-
-
GitLab CI/CD
-
在 .gitlab-ci.yml 中定义流水线:
yaml
CollapseWrapCopy
stages: - check lint: stage: check script: - cargo clippy -- -D warnings test: stage: check script: - cargo test
-
推送代码到 GitLab 时,流水线会执行检查。
-
方案 3:远程仓库保护规则
在 GitHub 或 GitLab 上,还可以设置分支保护规则,确保只有通过检查的代码才能合并到主分支:
- GitHub:在分支设置中启用 "Protected Branches",要求通过指定的 CI 检查。
- GitLab:在合并请求(Merge Request)设置中要求 CI 流水线成功。
from Pomelo_刘金 ,转载请注明出处,感谢!