CI 和其他集成设置
您可以——也应该——设置 CI 流水线来运行 Oxfmt,并在格式化差异时使构建失败。
本页面还涵盖您可能想要包含的其他集成,如 git pre-commit hooks。
CI
GitHub Actions
首先,如果尚未添加 fmt:check 脚本到您的 package.json:
json
{
"scripts": {
"fmt:check": "oxfmt --check"
}
}然后将 job 添加到您的 GitHub Actions 工作流:
yaml
name: CI
on:
pull_request:
push:
branches: [main]
permissions: {}
jobs:
format:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: pnpm/action-setup@v4
- uses: actions/setup-node@v6
with:
node-version: lts/*
cache: pnpm
# 或 yarn、npm 等
- run: pnpm install --frozen-lockfile
- run: pnpm run fmt:check自动修复格式化问题
如果您经常忘记在提交 PR 前运行 Oxfmt,并且不能或无法使用 pre-commit hooks,可以使用 autofix.ci 在 CI 工作流中添加自动修复步骤。
详见 https://autofix.ci/setup,您还需要安装相关的 GitHub App。
以下是可用的 GitHub Actions 工作流示例:
yaml
name: autofix.ci # 需要使用此名称
on:
pull_request:
push:
branches: ["main"]
permissions:
contents: read
jobs:
autofix:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: pnpm/action-setup@v4
- uses: actions/setup-node@v6
with:
node-version: lts/*
cache: pnpm
# 或 yarn、npm 等
- run: pnpm install --frozen-lockfile
# 运行 oxfmt 写入更改,autofix.ci 将在有差异时提交它们。
# 如果尚未添加,请确保在 package.json 中添加 `fmt` 脚本。
- run: pnpm run fmt
# 注意:强烈建议使用此 action 的最新 SHA 哈希而不是版本号。(详见 https://autofix.ci/setup)
- uses: autofix-ci/action@1.3.2GitLab CI
如果您使用 GitLab CI,可以将 Oxfmt 设置为 CI 流水线的一部分来强制执行代码格式化。
首先,如果尚未添加 fmt:check 脚本到您的 package.json:
json
{
"scripts": {
"fmt:check": "oxfmt --check"
}
}然后在 .gitlab-ci.yml 中添加 job,以检查所有代码是否正确格式化:
yml
oxfmt:
image: node:lts
stage: test
before_script:
# 或 pnpm、yarn 等
- npm install
script:
- npm run fmt:check您可能还想为包管理器添加缓存以加速安装。
Pre-commit hook
要自动格式化暂存文件,使用 oxfmt --no-error-on-unmatched-pattern。这会格式化所有支持的文件,并在没有文件匹配时避免错误(例如,仅暂存了 Ruby 文件)。
使用 --check 验证格式化但不写入文件。
对于 lint-staged,添加到 package.json:
json
{
"lint-staged": {
"*": "oxfmt --no-error-on-unmatched-pattern"
}
}要在安装依赖时自动安装 git hook,考虑同时使用 husky。