设置 CI 及其他集成
你应当(并且应该)设置你的 CI 流水线,以运行 Oxfmt 并在格式不一致时使构建失败。
本页还涵盖你可能希望包含的其他集成,例如 git pre-commit 钩子。
CI
GitHub Actions
首先,如果你还没有 fmt:check 脚本,请在 package.json 中添加一个:
json
{
"scripts": {
"fmt:check": "oxfmt --check"
}
}然后,在你的 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 钩子,可以使用 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
# 注意:强烈建议为此操作使用最新的 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 中添加一个作业,以检查所有代码是否格式正确:
yml
oxfmt:
image: node:lts
stage: test
before_script:
# 或 pnpm、yarn 等
- npm install
script:
- npm run fmt:check你还可以为包管理器添加缓存,以加快安装速度。
Pre-commit 钩子
要自动格式化已暂存的文件,请使用 oxfmt --no-error-on-unmatched-pattern。这会格式化所有受支持的文件,并在没有匹配文件时避免报错(例如,仅暂存了 Ruby 文件时)。
使用 --check 可以在不写入文件的情况下验证格式。
对于 lint-staged,请将其添加到 package.json:
json
{
"lint-staged": {
"*": "oxfmt --no-error-on-unmatched-pattern"
}
}为了在安装依赖时自动安装 git 钩子,还可考虑使用 husky。
