codegen-and-toolchain
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCodegen 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 or .
build_runnergen-l10nRead the reference for the task at hand:
- — the generator inventory,
references/codegen-scoping.mdscoping tables, error-to-fix recovery map.generate_for: - — the two committed/gitignored strategies, their tradeoffs, and the exact CI gate each one requires.
references/commit-vs-gitignore.md - — SDK pinning, analyzer/coverage excludes, and the multi-package workspace layering (fenced, opt-in).
references/toolchain-and-workspace.md
Run (codegen → format → analyze) before a PR, and
to verify excludes and commit-policy parity.
scripts/regen.shscripts/check-codegen-hygiene.sh一次确定性的 codegen 流程是所有生成文件的唯一事实来源;
先运行它,将范围尽可能收窄,并一次性决定其输出是否进入 git。
适用于任何使用 或 的项目。
build_runnergen-l10n针对当前任务阅读参考资料:
- ——生成器清单、
references/codegen-scoping.md限定范围对照表,以及错误到修复方案的对照表。generate_for: - ——两种 committed/gitignored 策略、 各自的 tradeoffs,以及每种策略所需的准确 CI gate。
references/commit-vs-gitignore.md - ——SDK 固定、analyzer/coverage excludes,以及多 package workspace 分层(隔离且可选启用)。
references/toolchain-and-workspace.md
提交 PR 前运行 (codegen → format → analyze),并运行
,验证 excludes 与 commit-policy 的一致性。
scripts/regen.shscripts/check-codegen-hygiene.shNon-negotiable rules
不可妥协的规则
- Codegen runs FIRST, before . 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
flutter analyze" errors. Regenerate, then analyze — never chase the symptom at the call site._$Foo - Always pass . Without it
--delete-conflicting-outputsrefuses 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.build_runner - 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.
- Scope every builder with in a per-package
generate_for:. A change in one directory must not regenerate the whole tree. Point each glob at the narrowest directory that owns the annotation.build.yaml - Decide commit-vs-gitignore ONCE, back it with the matching CI gate.
Gitignored → CI regenerates first, before analyze. Committed → CI regenerates
then runs as a freshness gate. Either is valid; a policy without its gate is not (see
git diff --exit-code).references/commit-vs-gitignore.md - 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.
- Pin the SDK; local must equal CI. The CI Flutter/Dart version must match
the pinned local version (under FVM, or the tool the repo standardizes on). A drift here reproduces "works on my machine" format/codegen churn.
.fvmrc - is a local edit-loop tool only. CI and the pre-analyze step always use the one-shot
watchcommand.build
- Codegen 必须最先运行,在 之前。 全新克隆的仓库中, 生成文件可能不存在;编辑 annotation 后,生成文件也可能已过期。分析这样的 工作树会产生误导性的 "missing part file" 和 "undefined class
flutter analyze" 错误。重新生成后再分析——绝不要在调用点追逐这些症状。_$Foo - 始终传入 。 如果不传入,
--delete-conflicting-outputs会拒绝覆盖重命名或删除源文件后遗留的输出,并以大量 "conflicting outputs" 文本失败。这并不是需要调查的 bug。build_runner - 绝不手动编辑生成文件。 下次构建会悄无声息地将其还原,你的修改也会 随之消失。应修改带 annotation 的源文件,然后重新运行 codegen。
- 使用每个 package 自己的 ,通过
build.yaml限定每一个 builder。 一个目录中的变更不得触发整个工作树重新生成。让每个 glob 指向拥有相应 annotation 的最窄目录。generate_for: - 只做一次 commit-vs-gitignore 决策,并用匹配的 CI gate 落实。
Gitignored → CI 先重新生成,再 analyze。Committed → CI 重新生成后运行
,作为 freshness gate。两种方式都有效;但没有 gate 支撑的策略不算策略(参见
git diff --exit-code)。references/commit-vs-gitignore.md - 将生成文件 globs 同步到 analyzer 和 coverage excludes。 应排除实际输出的后缀——先验证,不要猜。
- 固定 SDK;本地版本必须与 CI 一致。 CI 的 Flutter/Dart 版本必须与
固定的本地版本一致(FVM 下的 ,或仓库统一采用的其他工具)。 版本漂移会再现“works on my machine”式的格式/codegen 变动。
.fvmrc - 只能用于本地编辑循环。 CI 和 analyze 前步骤始终使用一次性的
watch命令。build
The canonical command
标准命令
Run from the repository root:
bash
dart run build_runner build --delete-conflicting-outputsThis regenerates every builder — , , ,
, — in one pass. runs through the
Flutter tool but is treated identically (regenerated first, same commit policy):
drift_devfreezedjson_serializableriverpod_generatormockitogen-l10nbash
flutter gen-l10n # if not auto-triggered by `flutter pub get` via l10n.yamlFresh clone / after pull / after editing any annotation, the fixed order is:
build_runner build --delete-conflicting-outputs → format → analyze → testNever 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——、、
、、。 通过
Flutter 工具运行,但处理方式完全相同(先重新生成,采用相同的 commit policy):
drift_devfreezedjson_serializableriverpod_generatormockitogen-l10nbash
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-outputsScoping builders with build.yaml
使用 build.yaml 限定 builder 范围
Give every codegen-carrying package (or the single app package) its own
, and fence each builder's at the narrowest directory
that owns its annotation. An unscoped root config fans out to every annotation in
the tree, so editing one model regenerates unrelated and
outputs. Copy ; has the full
generator-to-suffix table and per-builder globs.
build.yamlgenerate_for:TaskOrderAccountexamples/build.yamlreferences/codegen-scoping.md为每个包含 codegen 的 package(或单一 app package)提供自己的 ,
并在每个 builder 的 处设置边界,将其限定到拥有相应 annotation
的最窄目录。未限定范围的根配置会扩散到工作树中的每个 annotation,因此编辑一个
模型会重新生成无关的 和 输出。复制
; 中包含完整的生成器到输出
后缀对照表,以及各 builder 的 globs。
build.yamlgenerate_for:TaskOrderAccountexamples/build.yamlreferences/codegen-scoping.mdCommit 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
diff-collapse () AND a mandatory
freshness gate — regenerate, then
. A policy
without its gate is not a policy. Both strategies, their tradeoffs, and the exact
gate each requires: .
.gitattributesexamples/gitattributes.examplegit diff --exit-code -- '*.g.dart' '*.freezed.dart' '*.drift.dart'references/commit-vs-gitignore.md两种策略都合理,但承担的风险不同(参见规则 5)。Gitignore 能让工作树保持
干净,但构建时需要可用的 toolchain。提交生成代码则不受未来 toolchain 损坏影响,
并使 schema diff 可供审查;但需要通过 设置 diff collapse
(),并且必须有 freshness gate——重新生成后运行
。没有 gate
的策略不算策略。两种策略、各自的 tradeoffs,以及每种策略所需的准确 gate:
。
.gitattributesexamples/gitattributes.examplegit diff --exit-code -- '*.g.dart' '*.freezed.dart' '*.drift.dart'references/commit-vs-gitignore.mdAnalyzer 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 ). The canonical
exclude blocks and the correctly anchored lcov patterns live in
.
run-migrationreferences/toolchain-and-workspace.md无论是 committed 还是 gitignored,所有实际输出的生成文件后缀都必须同时从
analyzer 和 lcov coverage filter 中排除——先确认配置实际输出的后缀,不要猜。
遗漏 analyzer glob 会在审查时浪费精力处理机器输出;遗漏或锚定错误的 lcov glob
则会用未经测试的代码抬高 coverage。一个 migration-test baseline 目录,如果其中
保存的是按相应生成版本创建的数据类,也需要从 analyzer 中排除——对 exported schema
snapshot 执行 autofix 会破坏 migration 验证(见 )。标准 exclude
配置块和正确锚定的 lcov patterns 位于 。
run-migrationreferences/toolchain-and-workspace.mdWhen 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: in every member pubspec plus a
resolution: workspacelist at the root, producing ONE rootworkspace:. Never add a per-package lockfile.pubspec.lock - If you layer Melos on top, use it for script orchestration only
(), never for path linking — pub does the linking. Filter the
melos run gen/format/analyze/testscript to packages that depend ongen.build_runner - Run once at the workspace root so every member regenerates in the same pass; running inside one package dir leaves the others stale.
build_runner
仅适用于确实已经超出单 package 承载能力的仓库。单 app 项目不需要这些配置。
- 使用原生 Dart pub workspace:在每个 member pubspec 中设置
,并在根目录添加
resolution: workspace列表,从而生成一个根级workspace:。绝不添加 per-package lockfile。pubspec.lock - 如果在此基础上叠加 Melos,只能将其用于脚本编排
(),绝不用于路径关联——关联工作由 pub 完成。 将
melos run gen/format/analyze/test脚本限定到依赖gen的 packages。build_runner - 在 workspace 根目录运行一次 ,使所有 members 在同一次流程中重新 生成;在单个 package 目录中运行会使其他 packages 的输出保持过期状态。
build_runner
Anti-patterns
反模式
- Analyzing before regenerating — every downstream error is a phantom; fix the order, not the code.
- Omitting — turns a routine rename into a build wall.
--delete-conflicting-outputs - Hand-editing /
.g.dartto silence an error — reverted on the next build; the real fix is in the annotated source..drift.dart - Committing generated code with no freshness gate — output silently drifts from source and reviewers trust a lie.
- One unscoped root — every trivial edit regenerates the whole tree and slows every build.
build.yaml - 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来消除错误——下次构建会还原这些文件; 真正的修复应落在带 annotation 的源文件中。.drift.dart - 提交生成代码却没有 freshness gate——输出会悄无声息地偏离源文件,审查者也会 相信错误的结果。
- 只使用一个未限定范围的根 ——每次微小编辑都会重新生成整个工作树, 拖慢每次构建。
build.yaml - coverage/analyzer glob 匹配了错误的后缀——在 analyzer 中悄无声息地失效,在 lcov 2.x 中明显报错,并悄悄抬高 coverage。
- CI Flutter 版本 ≠ 固定的本地版本——会产生无人能够解释的不可复现格式/codegen 变动。
- 生成式 migration test 保留空数据列表——以空洞方式通过(),却没有 证明任何内容;应填充数据或删除测试(见
[] == [])。run-migration
Definition of done
完成定义
- succeeds from a clean tree, then
dart run build_runner build --delete-conflicting-outputsis clean.flutter analyze - Every codegen-carrying package has a with scoped
build.yamlglobs.generate_for: - 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 and the lcov coverage filter.
analysis_options.yaml - SDK is pinned and the CI toolchain version matches it.
- No generated file is hand-edited; no in CI.
watch
- 可在干净工作树中 成功执行,随后
dart run build_runner build --delete-conflicting-outputs无问题。flutter analyze - 每个包含 codegen 的 package 都有一个 ,其中包含已限定范围的
build.yamlglobs。generate_for: - 已作出 commit-vs-gitignore 决策,且存在相应的 CI gate(freshness diff 或 codegen-first)。
- 实际输出的生成后缀已同时从 和 lcov coverage filter 中排除。
analysis_options.yaml - SDK 已固定,且 CI 工具链版本与其一致。
- 没有任何生成文件被手动编辑;CI 中没有使用 。
watch
Related skills
相关 skills
- See for the operational, low-freedom "run this exact command" loop and its troubleshooting table.
run-codegen - See for the Drift schema-snapshot and migration-test ritual the codegen pass produces.
run-migration - See for the Drift/DAO data layer these generators feed.
persistence-drift - See for the analyzer ruleset and the excludes mirrored here.
lint-and-style-config - See for where codegen and the freshness gate sit in the pipeline.
ci-pipeline-and-gates - See for the lockfile and SDK-pinning mechanics.
dependency-hygiene
- 参见 ,了解操作性强、自由度低的“运行这个确切命令”循环及其故障 排查表。
run-codegen - 参见 ,了解 codegen 流程所产生的 Drift schema-snapshot 和 migration-test 规范流程。
run-migration - 参见 ,了解这些生成器所服务的 Drift/DAO 数据层。
persistence-drift - 参见 ,了解 analyzer 规则集以及此处同步的 excludes。
lint-and-style-config - 参见 ,了解 codegen 和 freshness gate 在 pipeline 中的位置。
ci-pipeline-and-gates - 参见 ,了解 lockfile 和 SDK 固定机制。
dependency-hygiene
References
参考资料
- build_runner: https://dart.dev/tools/build_runner
- Drift codegen & build config: https://drift.simonbinder.eu/docs/advanced-features/builder_options/
- freezed: https://pub.dev/packages/freezed
- json_serializable: https://pub.dev/packages/json_serializable
- riverpod codegen: https://riverpod.dev/docs/concepts/about_code_generation
- Flutter gen-l10n: https://docs.flutter.dev/ui/accessibility-and-internationalization/internationalization
- Dart pub workspaces: https://dart.dev/tools/pub/workspaces
- build_runner: https://dart.dev/tools/build_runner
- Drift codegen & build config: https://drift.simonbinder.eu/docs/advanced-features/builder_options/
- freezed: https://pub.dev/packages/freezed
- json_serializable: https://pub.dev/packages/json_serializable
- riverpod codegen: https://riverpod.dev/docs/concepts/about_code_generation
- Flutter gen-l10n: https://docs.flutter.dev/ui/accessibility-and-internationalization/internationalization
- Dart pub workspaces: https://dart.dev/tools/pub/workspaces