codegen-and-toolchain

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Codegen and toolchain

Codegen 与工具链

One deterministic codegen pass is the source of truth for every generated file; run it first, scope it tightly, and decide once whether its output lives in git. Applies whenever a project uses
build_runner
or
gen-l10n
.
Read the reference for the task at hand:
  • references/codegen-scoping.md
    — the generator inventory,
    generate_for:
    scoping tables, error-to-fix recovery map.
  • references/commit-vs-gitignore.md
    — the two committed/gitignored strategies, their tradeoffs, and the exact CI gate each one requires.
  • references/toolchain-and-workspace.md
    — SDK pinning, analyzer/coverage excludes, and the multi-package workspace layering (fenced, opt-in).
Run
scripts/regen.sh
(codegen → format → analyze) before a PR, and
scripts/check-codegen-hygiene.sh
to verify excludes and commit-policy parity.
一次确定性的 codegen 流程是所有生成文件的唯一事实来源; 先运行它,将范围尽可能收窄,并一次性决定其输出是否进入 git。 适用于任何使用
build_runner
或
gen-l10n
的项目。
针对当前任务阅读参考资料:
  • references/codegen-scoping.md
    ——生成器清单、
    generate_for:
    限定范围对照表,以及错误到修复方案的对照表。
  • references/commit-vs-gitignore.md
    ——两种 committed/gitignored 策略、 各自的 tradeoffs,以及每种策略所需的准确 CI gate。
  • references/toolchain-and-workspace.md
    ——SDK 固定、analyzer/coverage excludes,以及多 package workspace 分层(隔离且可选启用)。
提交 PR 前运行
scripts/regen.sh
(codegen → format → analyze),并运行
scripts/check-codegen-hygiene.sh
,验证 excludes 与 commit-policy 的一致性。

Non-negotiable rules

不可妥协的规则

  1. Codegen runs FIRST, before
    flutter analyze
    .
    Generated files may be absent on a fresh clone or stale after editing an annotation. Analyzing that tree emits misleading "missing part file" and "undefined class
    _$Foo
    " errors. Regenerate, then analyze — never chase the symptom at the call site.
  2. Always pass
    --delete-conflicting-outputs
    .
    Without it
    build_runner
    refuses to overwrite an output from a renamed/deleted source and fails with a wall of "conflicting outputs" text. That is not a bug to investigate.
  3. Never hand-edit a generated file. The next build silently reverts it and takes your edit with it. Change the annotated source and rerun codegen.
  4. Scope every builder with
    generate_for:
    in a per-package
    build.yaml
    .
    A change in one directory must not regenerate the whole tree. Point each glob at the narrowest directory that owns the annotation.
  5. Decide commit-vs-gitignore ONCE, back it with the matching CI gate. Gitignored → CI regenerates first, before analyze. Committed → CI regenerates then runs
    git diff --exit-code
    as a freshness gate. Either is valid; a policy without its gate is not (see
    references/commit-vs-gitignore.md
    ).
  6. Mirror generated-file globs into the analyzer AND coverage excludes. A glob that lints machine output wastes review; a glob missing from lcov inflates coverage. Exclude the emitted suffix — verify it, do not guess.
  7. Pin the SDK; local must equal CI. The CI Flutter/Dart version must match the pinned local version (
    .fvmrc
    under FVM, or the tool the repo standardizes on). A drift here reproduces "works on my machine" format/codegen churn.
  8. watch
    is a local edit-loop tool only.
    CI and the pre-analyze step always use the one-shot
    build
    command.
  1. Codegen 必须最先运行,在
    flutter analyze
    之前。
    全新克隆的仓库中, 生成文件可能不存在;编辑 annotation 后,生成文件也可能已过期。分析这样的 工作树会产生误导性的 "missing part file" 和 "undefined class
    _$Foo
    " 错误。重新生成后再分析——绝不要在调用点追逐这些症状。
  2. 始终传入
    --delete-conflicting-outputs
    。
    如果不传入,
    build_runner
    会拒绝覆盖重命名或删除源文件后遗留的输出,并以大量 "conflicting outputs" 文本失败。这并不是需要调查的 bug。
  3. 绝不手动编辑生成文件。 下次构建会悄无声息地将其还原,你的修改也会 随之消失。应修改带 annotation 的源文件,然后重新运行 codegen。
  4. 使用每个 package 自己的
    build.yaml
    ,通过
    generate_for:
    限定每一个 builder。
    一个目录中的变更不得触发整个工作树重新生成。让每个 glob 指向拥有相应 annotation 的最窄目录。
  5. 只做一次 commit-vs-gitignore 决策,并用匹配的 CI gate 落实。 Gitignored → CI 先重新生成,再 analyze。Committed → CI 重新生成后运行
    git diff --exit-code
    ,作为 freshness gate。两种方式都有效;但没有 gate 支撑的策略不算策略(参见
    references/commit-vs-gitignore.md
    )。
  6. 将生成文件 globs 同步到 analyzer 和 coverage excludes。 应排除实际输出的后缀——先验证,不要猜。
  7. 固定 SDK;本地版本必须与 CI 一致。 CI 的 Flutter/Dart 版本必须与 固定的本地版本一致(FVM 下的
    .fvmrc
    ,或仓库统一采用的其他工具)。 版本漂移会再现“works on my machine”式的格式/codegen 变动。
  8. watch
    只能用于本地编辑循环。
    CI 和 analyze 前步骤始终使用一次性的
    build
    命令。

The canonical command

标准命令

Run from the repository root:
bash
dart run build_runner build --delete-conflicting-outputs
This regenerates every builder —
drift_dev
,
freezed
,
json_serializable
,
riverpod_generator
,
mockito
— in one pass.
gen-l10n
runs through the Flutter tool but is treated identically (regenerated first, same commit policy):
bash
flutter gen-l10n   # if not auto-triggered by `flutter pub get` via l10n.yaml
Fresh clone / after pull / after editing any annotation, the fixed order is:
build_runner build --delete-conflicting-outputs   →   format   →   analyze   →   test
Never reorder codegen after analyze. During an active edit session only, a watcher rebuilds affected outputs on save:
bash
dart run build_runner watch --delete-conflicting-outputs
从仓库根目录运行:
bash
dart run build_runner build --delete-conflicting-outputs
一次流程会重新生成所有 builder——
drift_dev
、
freezed
、
json_serializable
、
riverpod_generator
、
mockito
。
gen-l10n
通过 Flutter 工具运行,但处理方式完全相同(先重新生成,采用相同的 commit policy):
bash
flutter gen-l10n   # if not auto-triggered by `flutter pub get` via l10n.yaml
全新克隆 / pull 后 / 编辑任何 annotation 后,固定顺序为:
build_runner build --delete-conflicting-outputs   →   format   →   analyze   →   test
绝不把 codegen 调整到 analyze 之后。仅在活跃编辑会话期间,watcher 会在保存时 重新构建受影响的输出:
bash
dart run build_runner watch --delete-conflicting-outputs

Scoping builders with build.yaml

使用 build.yaml 限定 builder 范围

Give every codegen-carrying package (or the single app package) its own
build.yaml
, and fence each builder's
generate_for:
at the narrowest directory that owns its annotation. An unscoped root config fans out to every annotation in the tree, so editing one
Task
model regenerates unrelated
Order
and
Account
outputs. Copy
examples/build.yaml
;
references/codegen-scoping.md
has the full generator-to-suffix table and per-builder globs.
为每个包含 codegen 的 package(或单一 app package)提供自己的
build.yaml
, 并在每个 builder 的
generate_for:
处设置边界,将其限定到拥有相应 annotation 的最窄目录。未限定范围的根配置会扩散到工作树中的每个 annotation,因此编辑一个
Task
模型会重新生成无关的
Order
和
Account
输出。复制
examples/build.yaml
;
references/codegen-scoping.md
中包含完整的生成器到输出 后缀对照表,以及各 builder 的 globs。

Commit vs gitignore: pick one, wire its gate

Commit 与 gitignore:选择一种,并配置对应的 gate

Both strategies are legitimate; they trade different risks (see rule 5). Gitignore keeps the tree clean but needs a working toolchain to build. Committing survives a broken future toolchain and makes schema diffs reviewable, but needs a
.gitattributes
diff-collapse (
examples/gitattributes.example
) AND a mandatory freshness gate — regenerate, then
git diff --exit-code -- '*.g.dart' '*.freezed.dart' '*.drift.dart'
. A policy without its gate is not a policy. Both strategies, their tradeoffs, and the exact gate each requires:
references/commit-vs-gitignore.md
.
两种策略都合理,但承担的风险不同(参见规则 5)。Gitignore 能让工作树保持 干净,但构建时需要可用的 toolchain。提交生成代码则不受未来 toolchain 损坏影响, 并使 schema diff 可供审查;但需要通过
.gitattributes
设置 diff collapse (
examples/gitattributes.example
),并且必须有 freshness gate——重新生成后运行
git diff --exit-code -- '*.g.dart' '*.freezed.dart' '*.drift.dart'
。没有 gate 的策略不算策略。两种策略、各自的 tradeoffs,以及每种策略所需的准确 gate:
references/commit-vs-gitignore.md
。

Analyzer and coverage excludes

Analyzer 和 coverage excludes

Committed OR gitignored, every emitted generated suffix must be excluded from BOTH the analyzer and the lcov coverage filter — verify the suffix the config actually emits first, do not guess. A missed analyzer glob wastes review on machine output; a missed (or mis-anchored) lcov glob inflates coverage with untested code. A migration-test baseline dir that holds generated era-correct data classes needs the analyzer exclude too — an autofix inside an exported schema snapshot would corrupt migration verification (see
run-migration
). The canonical exclude blocks and the correctly anchored lcov patterns live in
references/toolchain-and-workspace.md
.
无论是 committed 还是 gitignored,所有实际输出的生成文件后缀都必须同时从 analyzer 和 lcov coverage filter 中排除——先确认配置实际输出的后缀,不要猜。 遗漏 analyzer glob 会在审查时浪费精力处理机器输出;遗漏或锚定错误的 lcov glob 则会用未经测试的代码抬高 coverage。一个 migration-test baseline 目录,如果其中 保存的是按相应生成版本创建的数据类,也需要从 analyzer 中排除——对 exported schema snapshot 执行 autofix 会破坏 migration 验证(见
run-migration
)。标准 exclude 配置块和正确锚定的 lcov patterns 位于
references/toolchain-and-workspace.md
。

When multi-package (workspace)

多 package(workspace)场景

Only for a repo that has genuinely outgrown one package. A single-app project needs none of this.
  • Link members with a native Dart pub workspace:
    resolution: workspace
    in every member pubspec plus a
    workspace:
    list at the root, producing ONE root
    pubspec.lock
    . Never add a per-package lockfile.
  • If you layer Melos on top, use it for script orchestration only (
    melos run gen/format/analyze/test
    ), never for path linking — pub does the linking. Filter the
    gen
    script to packages that depend on
    build_runner
    .
  • Run
    build_runner
    once at the workspace root so every member regenerates in the same pass; running inside one package dir leaves the others stale.
仅适用于确实已经超出单 package 承载能力的仓库。单 app 项目不需要这些配置。
  • 使用原生 Dart pub workspace:在每个 member pubspec 中设置
    resolution: workspace
    ,并在根目录添加
    workspace:
    列表,从而生成一个根级
    pubspec.lock
    。绝不添加 per-package lockfile。
  • 如果在此基础上叠加 Melos,只能将其用于脚本编排 (
    melos run gen/format/analyze/test
    ),绝不用于路径关联——关联工作由 pub 完成。 将
    gen
    脚本限定到依赖
    build_runner
    的 packages。
  • 在 workspace 根目录运行一次
    build_runner
    ,使所有 members 在同一次流程中重新 生成;在单个 package 目录中运行会使其他 packages 的输出保持过期状态。

Anti-patterns

反模式

  • Analyzing before regenerating — every downstream error is a phantom; fix the order, not the code.
  • Omitting
    --delete-conflicting-outputs
    — turns a routine rename into a build wall.
  • Hand-editing
    .g.dart
    /
    .drift.dart
    to silence an error
    — reverted on the next build; the real fix is in the annotated source.
  • Committing generated code with no freshness gate — output silently drifts from source and reviewers trust a lie.
  • One unscoped root
    build.yaml
    — every trivial edit regenerates the whole tree and slows every build.
  • Coverage/analyzer glob that matches the wrong suffix — fails silently in the analyzer, loudly in lcov 2.x, and quietly inflates coverage.
  • CI Flutter version ≠ pinned local version — reproducible format/codegen churn nobody can explain.
  • A generated migration test left with empty data lists — passes vacuously (
    [] == []
    ) while proving nothing; fill it or delete it (see
    run-migration
    ).
  • 先 analyze 再重新生成——所有后续错误都是假象;应修复执行顺序,而不是代码。
  • 省略
    --delete-conflicting-outputs
    ——一次常规重命名就会引发构建报错潮。
  • 手动编辑
    .g.dart
    /
    .drift.dart
    来消除错误
    ——下次构建会还原这些文件; 真正的修复应落在带 annotation 的源文件中。
  • 提交生成代码却没有 freshness gate——输出会悄无声息地偏离源文件,审查者也会 相信错误的结果。
  • 只使用一个未限定范围的根
    build.yaml
    ——每次微小编辑都会重新生成整个工作树, 拖慢每次构建。
  • coverage/analyzer glob 匹配了错误的后缀——在 analyzer 中悄无声息地失效,在 lcov 2.x 中明显报错,并悄悄抬高 coverage。
  • CI Flutter 版本 ≠ 固定的本地版本——会产生无人能够解释的不可复现格式/codegen 变动。
  • 生成式 migration test 保留空数据列表——以空洞方式通过(
    [] == []
    ),却没有 证明任何内容;应填充数据或删除测试(见
    run-migration
    )。

Definition of done

完成定义

  • dart run build_runner build --delete-conflicting-outputs
    succeeds from a clean tree, then
    flutter analyze
    is clean.
  • Every codegen-carrying package has a
    build.yaml
    with scoped
    generate_for:
    globs.
  • The commit-vs-gitignore decision is made and its CI gate exists (freshness diff, or codegen-first).
  • The emitted generated suffixes are excluded from BOTH
    analysis_options.yaml
    and the lcov coverage filter.
  • SDK is pinned and the CI toolchain version matches it.
  • No generated file is hand-edited; no
    watch
    in CI.
  • dart run build_runner build --delete-conflicting-outputs
    可在干净工作树中 成功执行,随后
    flutter analyze
    无问题。
  • 每个包含 codegen 的 package 都有一个
    build.yaml
    ,其中包含已限定范围的
    generate_for:
    globs。
  • 已作出 commit-vs-gitignore 决策,且存在相应的 CI gate(freshness diff 或 codegen-first)。
  • 实际输出的生成后缀已同时从
    analysis_options.yaml
    和 lcov coverage filter 中排除。
  • SDK 已固定,且 CI 工具链版本与其一致。
  • 没有任何生成文件被手动编辑;CI 中没有使用
    watch
    。

Related skills

相关 skills

  • See
    run-codegen
    for the operational, low-freedom "run this exact command" loop and its troubleshooting table.
  • See
    run-migration
    for the Drift schema-snapshot and migration-test ritual the codegen pass produces.
  • See
    persistence-drift
    for the Drift/DAO data layer these generators feed.
  • See
    lint-and-style-config
    for the analyzer ruleset and the excludes mirrored here.
  • See
    ci-pipeline-and-gates
    for where codegen and the freshness gate sit in the pipeline.
  • See
    dependency-hygiene
    for the lockfile and SDK-pinning mechanics.
  • 参见
    run-codegen
    ,了解操作性强、自由度低的“运行这个确切命令”循环及其故障 排查表。
  • 参见
    run-migration
    ,了解 codegen 流程所产生的 Drift schema-snapshot 和 migration-test 规范流程。
  • 参见
    persistence-drift
    ,了解这些生成器所服务的 Drift/DAO 数据层。
  • 参见
    lint-and-style-config
    ,了解 analyzer 规则集以及此处同步的 excludes。
  • 参见
    ci-pipeline-and-gates
    ,了解 codegen 和 freshness gate 在 pipeline 中的位置。
  • 参见
    dependency-hygiene
    ,了解 lockfile 和 SDK 固定机制。

References

参考资料