kotlin-tooling-gradle-to-kotlin-toolchain-project
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGradle → Kotlin Toolchain Project Migration
Gradle → Kotlin Toolchain 项目迁移
Two jobs at once: a mechanical translation of dependencies and configuration, plus a replacement for every
Gradle plugin the Toolchain has no native answer for. Templates to adapt are in
references/examples.md, drawn from one real migration.
Lean on the companion skills for the plugin-shaped subproblems: for syntax,
for the per-plugin port workflow (you will run it once per Gradle plugin
without a native equivalent), for plugins written from scratch.
kotlin-tooling-kotlin-toolchainkotlin-tooling-gradle-to-kotlin-toolchain-pluginkotlin-tooling-kotlin-toolchain-plugin-authoring这项工作包含两部分:一是依赖与配置的机械性转换,二是替换所有Toolchain没有原生对应实现的Gradle插件。可适配的模板位于references/examples.md,源自一次真实的迁移实践。
对于插件类的子问题,请借助配套技能:语法问题参考,单插件移植流程参考(每个无原生等效实现的Gradle插件都需执行一次该流程),从零编写插件参考。
kotlin-tooling-kotlin-toolchainkotlin-tooling-gradle-to-kotlin-toolchain-pluginkotlin-tooling-kotlin-toolchain-plugin-authoringPrinciples
原则
- Preserve source code. If the migration forces edits to business logic, a local plugin can probably
fill the gap instead. Code reading off the classpath should keep working — publish that exact file, don't rewrite the consumer.
release.properties - Every third-party Gradle plugin is drop, native, or reimplement — never "keep the Gradle plugin".
Your own convention plugins are different: /
buildSrcprecompiled scripts are shared configuration, so they become module templates, not local plugins — see Nobuild-logic/ convention plugins.buildSrc - Search GitHub before authoring a local plugin. Someone has probably already written it; vendoring a working implementation beats a from-scratch port every time. Where to look and what to search for: Phase 2 "Scope". Author only after the search comes up empty. Read what you vendor end to end before wiring it in — it runs at build time with full filesystem and network access.
- All dependencies should reside in version catalog. survives as the built-in
gradle/libs.versions.tomlcatalog. Every coordinate in every module/plugin YAML must end up as a$libs.*reference.$libs.*has no Toolchain equivalent and becomes a module template — see No version-catalog bundles.[bundles]
- 保留源代码不变。 如果迁移迫使你修改业务逻辑,那么大概率可以通过本地插件来填补缺口。从类路径读取的代码应当继续正常工作——直接发布该文件即可,不要修改消费方代码。
release.properties - 所有第三方Gradle插件要么直接弃用、要么用原生能力替代、要么重新实现——绝对不能“保留Gradle插件”。你自己的约定插件则不同:/
buildSrc预编译脚本是共享配置,因此它们会转化为模块模板,而非本地插件——参见无build-logic/约定插件。buildSrc - 编写本地插件前先搜索GitHub。 很可能已经有人实现过了;复用现成的实现永远比从零移植要好。搜索位置和关键词参见第2阶段的“范围”部分。仅当搜索无果时再自行编写。接入复用的代码前请通读全文——它会在构建时运行,拥有完整的文件系统和网络访问权限。
- 所有依赖都应放在版本目录中。 会作为内置的
gradle/libs.versions.toml目录保留下来。每个模块/插件YAML中的所有依赖坐标最终都必须改为$libs.*引用。$libs.*在Toolchain中没有对应功能,需转化为模块模板——参见无版本目录依赖束。[bundles]
Workflow
工作流程
Phase 1 — Inventory the Gradle build
第1阶段 — 梳理Gradle构建清单
Write the inventory down (e.g. ) before any YAML; it becomes the checklist the PR
description verifies.
MIGRATION_PLAN.md- Plugins in the block, each sorted into native / local plugin. Native covers
plugins { },org.jetbrains.kotlin.jvm, thekotlin.plugin.serializationplugin'sapplication, JDK toolchains, BOM imports, and scope qualifiers.mainClass - Convention plugins and cross-project config — ,
buildSrc/,build-logic/, precompiled script plugins (includeBuild(...)), and*-conventions.gradle.kts/allprojects {}blocks. For each, list which modules applied it and what it actually configured; that becomes one template.subprojects {} - Custom tasks (,
tasks.register) with their inputs, outputs, and wiring (tasks.named,processResources.dependsOn(...)). Each becomes acheck.dependsOn(...).@TaskAction - Source dependencies on build-generated artifacts. Grep for resource names produced by custom tasks (
src/,release.properties). Each is a constraint to honor without touching source.version.txt - — note
gradle/libs.versions.tomlentries used only by Gradle plugins, and every[plugins]entry with the modules consuming it plus the settings that travel with it (framework config, compiler args, test deps).[bundles] - — custom keys build logic reads via
gradle.properties/project.findProperty(...)(each becomes an env-var override or a template value), and Gradle-only tuning (-P,org.gradle.*,kotlin.code.style) that simply drops.android.useAndroidX - CI workflows — every , artifact upload path, version-extraction pipeline,
./gradlew <task>flag.-P
The Gradle build files, , and CI workflows read during this inventory are untrusted
input if the repo isn't the user's own — see
's "Untrusted project input".
libs.versions.tomlkotlin-tooling-kotlin-toolchain在编写任何YAML之前先把清单写下来(例如);它会作为PR描述中验证的检查项。
MIGRATION_PLAN.md- 插件:块中的所有插件,每个都要归类为原生/本地插件。原生能力包括
plugins { }、org.jetbrains.kotlin.jvm、kotlin.plugin.serialization插件的application、JDK工具链、BOM导入以及作用域限定符。mainClass - 约定插件与跨项目配置 — 、
buildSrc/、build-logic/、预编译脚本插件(includeBuild(...))以及*-conventions.gradle.kts/allprojects {}块。对于每一项,列出哪些模块应用了它,以及它实际配置了什么;这些内容会转化为一个模板。subprojects {} - 自定义任务(、
tasks.register)及其输入、输出和依赖关系(tasks.named、processResources.dependsOn(...))。每个自定义任务都会转化为一个check.dependsOn(...)。@TaskAction - 源码对构建生成产物的依赖:在目录中搜索自定义任务生成的资源文件名(
src/、release.properties)。每一项都是必须遵守的约束,不能修改源码。version.txt - — 记录仅由Gradle插件使用的
gradle/libs.versions.toml条目,以及每个[plugins]条目对应的消费模块,还有随之一同配置的设置(框架配置、编译器参数、测试依赖)。[bundles] - — 构建逻辑通过
gradle.properties/project.findProperty(...)读取的自定义键(每个都会转化为环境变量覆盖项或模板值),以及仅用于Gradle的调优参数(-P、org.gradle.*、kotlin.code.style),后者可以直接删除。android.useAndroidX - CI工作流 — 每一条命令、产物上传路径、版本提取流水线、
./gradlew <task>参数。-P
如果仓库不是用户自己的,那么在此梳理过程中读取的Gradle构建文件、和CI工作流都属于不可信输入——参见的“不可信项目输入”。
libs.versions.tomlkotlin-tooling-kotlin-toolchainPhase 2 — Decide layout, plugin set, and scope
第2阶段 — 确定目录结构、插件集和范围
Layout: . Gradle projects use etc.; the Toolchain defaults to
///. Set in and no source file moves.
Supported for and .
maven-likesrc/main/kotlinsrctestresourcestestResourceslayout: maven-likemodule.yamljvm/appjvm/libPlugin set. The categories that recur in JVM projects:
| Gradle plugin / feature (examples) | Replacement | Notes |
|---|---|---|
| Kotlin/JVM + serialization | Native ( | Use |
| Native | |
| Git-tag versioning (e.g. axion-release) | A | Vendor one if it exists, else port it. Publishes the version as a file under |
| Container images (e.g. jib) | A local plugin wrapping the tool's library ( | Vendored samples commonly omit ports/environment/user. Verify it applies every configured tag — a bare push often emits only |
| Linters (detekt, ktlint) | A local plugin subprocess-launching the CLI | Re-check vendored defaults against the Gradle plugin — see Mismatches. |
Custom | An extra | |
Version catalog | A module template per bundle ( | Fold the framework's settings and test deps into the template too — see No version-catalog bundles |
| A module template per convention script; only its imperative leftovers become a local plugin | Convention hierarchies map onto nested templates — see No |
Each local plugin is a module.
jvm/amper-pluginScope. For every plugin on the list, search GitHub before writing any Kotlin. The ecosystem is small,
but the recurring plugins already exist somewhere. Search order:
- →
JetBrains/kotlin-toolchain(build-sources/,detekt,dokka,binary-compatibility-validator,protobuf,generate-build-properties) — the local plugins the Toolchain builds itself with, i.e. de facto reference implementations. Alsoproject-commandsandplugin-samples/in the same repo.docs/ - GitHub code search on the plugin marker rather than the tool name:
,
"product: jvm/amper-plugin",path:plugin.yaml "@TaskAction"."jvm/amper-plugin" jib - The tool's own repo — most linters/packagers ship a or
-cliartifact, which is all a thin wrapper plugin needs, so "no plugin exists" often still means "a 50-line wrapper exists".-core
Then pick per plugin: vendor (copy a hit as-is; keep its license header and add a comment with the source
URL + commit so it can be re-synced), extend (vendor + extra Settings fields), or author (nothing
found, or the need is bespoke). Sensible default for one PR: vendor what exists, author the small bespoke ones
(a plugin, a thin linter wrapper), defer the rest. Always diff a vendored plugin's behavior against
the Gradle plugin it replaces before trusting it — see
A vendored linter plugin can be stricter than the Gradle plugin.
package目录结构:。 Gradle项目使用等目录;Toolchain默认使用///。在中设置即可无需移动任何源文件。该选项支持和类型的项目。
maven-likesrc/main/kotlinsrctestresourcestestResourcesmodule.yamllayout: maven-likejvm/appjvm/lib插件集。 JVM项目中常见的插件类别:
| Gradle插件/功能(示例) | 替代方案 | 备注 |
|---|---|---|
| Kotlin/JVM + 序列化 | 原生能力( | 如需精确控制Kotlin库版本,可使用 |
| 入口点使用原生 | |
| Git标签版本控制(例如axion-release) | 一个** | 如有现成实现就复用,否则自行移植。版本号会作为文件发布到 |
| 容器镜像(例如jib) | 封装对应工具库( | 复用的示例通常会遗漏端口/环境变量/用户配置。请验证它会应用所有配置的标签——裸推送通常只会生成 |
| 代码检查工具(detekt、ktlint) | 通过子进程启动CLI的本地插件 | 对照Gradle插件重新检查复用的默认配置——参见需要注意的差异。 |
自定义 | 在相关插件上添加额外的 | |
版本目录 | 每个依赖束对应一个模块模板( | 把框架的设置和测试依赖也整合到模板中——参见无版本目录依赖束 |
| 每个约定脚本对应一个模块模板;仅其中命令式的残留逻辑才需要转化为本地插件 | 约定层级结构可映射为嵌套模板——参见无 |
每个本地插件都是一个模块。
jvm/amper-plugin范围。 对于列表中的每个插件,在编写任何Kotlin代码前先搜索GitHub。虽然生态还不大,但常见的插件基本都已经有实现了。搜索顺序:
- →
JetBrains/kotlin-toolchain(build-sources/、detekt、dokka、binary-compatibility-validator、protobuf、generate-build-properties)——Toolchain自身构建所用的本地插件,也就是事实上的参考实现。同一仓库中的project-commands和plugin-samples/也值得一看。docs/ - 使用GitHub代码搜索,搜索插件标记而非工具名称:、
"product: jvm/amper-plugin"、path:plugin.yaml "@TaskAction"。"jvm/amper-plugin" jib - 工具本身的仓库——大多数代码检查/打包工具都会发布或
-cli构件,这正是薄封装插件所需的全部,因此“没有现成插件”通常意味着“只需要写50行的封装代码”。-core
然后为每个插件选择方案:复用(原样复制找到的实现;保留其许可证头,并添加带有源URL和提交哈希的注释,以便后续重新同步)、扩展(复用+额外的设置字段),或是自研(没有找到实现,或是需求是定制化的)。单个PR的合理默认策略:复用现有实现,自研小型定制插件(比如插件、薄封装的代码检查插件),其余的延后处理。在信任复用的插件之前,一定要将其行为与它要替换的Gradle插件做对比——参见复用的代码检查插件可能比Gradle插件更严格。
packagePhase 3 — Implement
第3阶段 — 实施
- Copy /
kotlinfrom a reference Toolchain project (for example this one) orkotlin.batin a scratch dir. Pinkotlin initinkotlintoolchain=<version>to match the wrapper..sdkmanrc - Write with all plugin module paths.
project.yaml - Per plugin: search GitHub first (Phase 2 "Scope"), then vendor or author it under , running
plugins/<name>/after each to confirm the model still loads../kotlin show modules - Write the templates at the project root: one per convention script and per
<name>.module-template.yamlentry with two or more consumers (dependencies plus the settings, test deps, and repositories that travel with them), nested the way the Gradle conventions were.[bundles] - Write the root :
module.yaml,product: jvm/app,layout: maven-likedependencies, an$libs.*list for the templates, and aapply:block enabling each local plugin with its non-default settings.plugins: - Validate each plugin in isolation: or
./kotlin task :<module>:<task>@<plugin>../kotlin do <command> - Rewrite CI (Phase 4).
- Delete ,
build.gradle.kts,gradlew,gradlew.bat— but keepgradle/wrapper/.gradle/libs.versions.toml - Sweep the catalog: drop the whole block, any
[plugins]keys that only fed it, and[versions]once every consumer applies a template.[bundles] - Sweep every /
module.yamlfor literal Maven coordinates and replace them withplugin.yaml.$libs.<key>
- 从参考Toolchain项目(例如这个项目)复制/
kotlin文件,或是在临时目录中执行kotlin.bat。在kotlin init中固定.sdkmanrc版本,与wrapper保持一致。kotlintoolchain=<version> - 编写,包含所有插件模块的路径。
project.yaml - 逐个处理插件:先搜索GitHub(参见第2阶段的“范围”部分),然后在目录下复用或自研插件,每处理完一个都运行
plugins/<name>/确认模型仍能正常加载。./kotlin show modules - 在项目根目录编写模板:每个约定脚本对应一个,每个有两个及以上消费方的
<name>.module-template.yaml条目也对应一个模板(包含依赖以及随之一同配置的设置、测试依赖、仓库),按照Gradle约定的层级进行嵌套。[bundles] - 编写根目录的:包含
module.yaml、product: jvm/app、layout: maven-like依赖、模板的$libs.*列表,以及启用每个本地插件并配置非默认设置的apply:块。plugins: - 单独验证每个插件:运行或
./kotlin task :<module>:<task>@<plugin>。./kotlin do <command> - 重写CI(第4阶段)。
- 删除、
build.gradle.kts、gradlew、gradlew.bat——但保留gradle/wrapper/。gradle/libs.versions.toml - 清理版本目录:删除整个块、所有仅为它服务的
[plugins]键,以及在所有消费方都应用模板后的[versions]块。[bundles] - 检查所有/
module.yaml,将硬编码的Maven坐标替换为plugin.yaml引用。$libs.<key>
Phase 4 — Rewrite CI
第4阶段 — 重写CI
- Set .
KOTLIN_CLI_NO_WELCOME_BANNER: "1" - →
./gradlew build && ./gradlew check(which runs every plugin's./kotlin build && ./kotlin checkregistrations plus tests).checks: - →
./gradlew jib -Djib.to.tags=…, with tags passed through an env var the plugin reads. Vendored jib-style plugins usually lack that hook — add it while vendoring../kotlin do jib - Artifact upload path changes: Gradle's is gone and
build/libs/<name>.jarwrites to a Toolchain-internal path. Author ajarJvmplugin staging the JAR atpackageso uploading artifacts stays simple.${module.rootDir}/build/libs/${module.name}.jar
- 设置。
KOTLIN_CLI_NO_WELCOME_BANNER: "1" - →
./gradlew build && ./gradlew check(后者会运行每个插件注册的./kotlin build && ./kotlin check以及测试)。checks: - →
./gradlew jib -Djib.to.tags=…,标签通过插件读取的环境变量传递。复用的jib类插件通常缺少这个钩子——在复用时加上即可。./kotlin do jib - 产物上传路径变更:Gradle的不再存在,
build/libs/<name>.jar会输出到Toolchain内部路径。编写一个jarJvm插件,将JAR放到package,这样产物上传逻辑可以保持简单。${module.rootDir}/build/libs/${module.name}.jar
Phase 5 — Validate end-to-end
第5阶段 — 端到端验证
Run each user-facing command locally and record the output in the PR's test plan:
sh
./kotlin show modules # project model loads, all expected modules listed
./kotlin clean && ./kotlin build
./kotlin test
./kotlin check # linters + tests; expect zero violations after Phase 3
./kotlin do currentVersion # if applicable
./kotlin do jib # or jibBuildTar to avoid pushing locally (if applicable)
./kotlin do package # verify build/libs/<name>.jar and its Main-Class manifest (if applicable)
./kotlin do ktlintFormat # if applicable在本地运行每个面向用户的命令,并将输出记录到PR的测试计划中:
sh
./kotlin show modules # project model loads, all expected modules listed
./kotlin clean && ./kotlin build
./kotlin test
./kotlin check # linters + tests; expect zero violations after Phase 3
./kotlin do currentVersion # if applicable
./kotlin do jib # or jibBuildTar to avoid pushing locally (if applicable)
./kotlin do package # verify build/libs/<name>.jar and its Main-Class manifest (if applicable)
./kotlin do ktlintFormat # if applicableMismatches to watch
需要注意的差异
No ${...}
interpolation in module.yaml
${...}module.yamlmodule.yaml
中不支持${...}
插值
module.yaml${...}configFile: ${module.rootDir}/detekt.ymlconfigFile: detekt.ymlplugin.yamlconfigFile: ${module.rootDir}/detekt.ymlconfigFile: detekt.ymlplugin.yamlModule name comes from the directory name
模块名称来自目录名
There is no field. clones into a directory named after the GitHub repo, while a
local worktree may resolve to something else. Never hardcode the module name into a plugin
task's output path — use .
name:actions/checkout${module.name}${module.name}没有字段。会克隆到以GitHub仓库命名的目录中,而本地工作树可能会将解析为其他值。绝对不要在插件任务的输出路径中硬编码模块名称——请使用。
name:actions/checkout${module.name}${module.name}Plugin settings without enabled: true
are ignored
enabled: true没有设置enabled: true
的插件配置会被忽略
enabled: trueyaml
plugins:
release: enabled # shorthand — only valid with no other settings
jib: # long form — required as soon as any setting is present
enabled: true
container:
mainClass: com.example.AppSettings without produce only a warning ("Plugin X is not enabled, but has some explicit
configuration") and the plugin is skipped.
enabled: trueyaml
plugins:
release: enabled # shorthand — only valid with no other settings
jib: # long form — required as soon as any setting is present
enabled: true
container:
mainClass: com.example.App没有的设置只会产生一条警告(“插件X未启用,但存在显式配置”),插件会被跳过。
enabled: trueA vendored linter plugin can be stricter than the Gradle plugin
复用的代码检查插件可能比Gradle插件更严格
Diff the flags the vendored plugin passes against the Gradle plugin's default task, and gate anything
stricter behind an opt-in setting so the default matches the old behaviour.
The canonical case: the upstream detekt plugin () always passes to
, enabling type resolution, which Gradle's default task does not. Used as-is it surfaces
violations Gradle never reported (notably on elvis-with-return). Fix: add
to the plugin's Settings and gate the flag on it — patch in
references/examples.md.
amper/build-sources/detekt/--classpathdetekt-clidetektUnreachableCodeuseTypeResolution: Boolean get() = false对比复用插件传递的参数与Gradle插件默认任务的参数,将所有更严格的检查放到可选设置后面,确保默认行为与旧版一致。
典型案例:上游的detekt插件()总是会向传递参数,启用类型解析,而Gradle的默认任务不会这样做。直接使用的话,它会暴露出Gradle从未报告过的违规(特别是带return的elvis表达式上的)。修复方法:在插件的Settings中添加,并根据该值控制是否传递该参数——补丁参见references/examples.md。
amper/build-sources/detekt/detekt-cli--classpathdetektUnreachableCodeuseTypeResolution: Boolean get() = falseNo version-catalog bundles
无版本目录依赖束
Only keys resolve (). does not exist and in the
catalog is dead config the Toolchain never reads. The official answer (KTC-4759) is a module template per
bundle, applied wherever the bundle was used:
[libraries]$libs.<key>$libs.bundles.<name>[bundles]toml
undefined只有中的键可以被解析()。不存在,目录中的是Toolchain不会读取的无效配置。官方解决方案(KTC-4759)是为每个依赖束创建一个模块模板,应用到所有使用该依赖束的地方:
[libraries]$libs.<key>$libs.bundles.<name>[bundles]toml
undefinedgradle/libs.versions.toml — before
gradle/libs.versions.toml — before
[bundles]
ktor-server = ["ktor-server-core", "ktor-server-netty", "ktor-server-content-negotiation"]
```yaml[bundles]
ktor-server = ["ktor-server-core", "ktor-server-netty", "ktor-server-content-negotiation"]
```yamlktor-server.module-template.yaml — at the project root; templates cannot declare product:
ktor-server.module-template.yaml — at the project root; templates cannot declare product:
dependencies:
- $libs.ktor.server.core
- $libs.ktor.server.netty
- $libs.ktor.server.content.negotiation
settings:
kotlin:
serialization: json
test-dependencies:
- $libs.ktor.server.test.host
```yamldependencies:
- $libs.ktor.server.core
- $libs.ktor.server.netty
- $libs.ktor.server.content.negotiation
settings:
kotlin:
serialization: json
test-dependencies:
- $libs.ktor.server.test.host
```yamlmodule.yaml
module.yaml
product: jvm/app
apply:
- //ktor-server.module-template.yaml
Templates are the better target, not just a workaround: a bundle carries coordinates only, while the
framework it enables usually also needs `settings` (`kotlin.serialization`, `springBoot`, `freeCompilerArgs`),
`test-dependencies`, and sometimes `repositories`. Put all of it in the template so one `apply:` line yields a
working framework instead of a bare classpath.
Rules that might bite:
- Path notation is `//<name>.module-template.yaml`, relative to the project root (where `project.yaml` is).
- No `product:` in a template. Templates may `apply:` other templates; each is applied once even if reached
through two paths, so list dependencies appear once.
- Merge semantics: lists append, scalars are overridden, and `module.yaml` always wins regardless of where
`apply:` sits in the file.
- Two sibling templates setting the same scalar (e.g. `settings.jvm.release`) is a hard error
("Conflicting values for property"). Resolve by setting the value in the consuming `module.yaml`, or in a
third template that applies both.
- Don't convert a single-consumer bundle. Templates pay off from the second module; below that, inline the
`$libs.*` list.
- Templates express the union of platform-qualified sections too (`dependencies@jvm`, `settings@android`), so
a KMP bundle split across source sets still fits one template.product: jvm/app
apply:
- //ktor-server.module-template.yaml
模板是更优的方案,而不仅仅是 workaround:依赖束只包含坐标,而它所启用的框架通常还需要`settings`(`kotlin.serialization`、`springBoot`、`freeCompilerArgs`)、`test-dependencies`,有时还有`repositories`。把所有这些都放到模板中,这样一行`apply:`就能得到一个可用的框架,而不仅仅是一个裸类路径。
可能会踩坑的规则:
- 路径表示法为`//<name>.module-template.yaml`,相对于项目根目录(`project.yaml`所在的目录)。
- 模板中不能有`product:`。模板可以`apply:`其他模板;即使通过两条路径应用同一个模板,也只会生效一次,因此列表依赖只会出现一次。
- 合并语义:列表会追加,标量会被覆盖,无论`apply:`在文件中的什么位置,`module.yaml`的优先级总是最高。
- 两个同级模板设置了同一个标量(例如`settings.jvm.release`)会导致硬错误(“属性值冲突”)。解决方法是在消费方的`module.yaml`中设置该值,或是在一个同时应用这两个模板的第三个模板中设置。
- 不要转换只有一个消费方的依赖束。模板从第二个模块开始使用才有价值;如果只有一个消费方,直接内联`$libs.*`列表即可。
- 模板也可以表达平台限定部分的并集(`dependencies@jvm`、`settings@android`),因此跨源集拆分的KMP依赖束仍然可以放在一个模板中。No buildSrc
/ convention plugins — shared config goes in templates
buildSrc无buildSrc
/约定插件 —— 共享配置放在模板中
buildSrcbuildSrc/build-logic/includeBuild(...)project.yamlmodules:plugins:<name>.module-template.yamlplugins { id("<name>") }kotlin
// buildSrc/src/main/kotlin/service-conventions.gradle.kts
plugins {
kotlin("jvm")
kotlin("plugin.serialization")
}
kotlin { jvmToolchain(21) }
repositories { maven("https://jitpack.io") }
dependencies {
implementation(libs.ktor.server.core)
testImplementation(libs.kotest.runner.junit5)
}yaml
undefinedbuildSrc/build-logic/includeBuild(...)project.yamlmodules:plugins:<name>.module-template.yamlplugins { id("<name>") }kotlin
// buildSrc/src/main/kotlin/service-conventions.gradle.kts
plugins {
kotlin("jvm")
kotlin("plugin.serialization")
}
kotlin { jvmToolchain(21) }
repositories { maven("https://jitpack.io") }
dependencies {
implementation(libs.ktor.server.core)
testImplementation(libs.kotest.runner.junit5)
}yaml
undefinedservice-conventions.module-template.yaml
service-conventions.module-template.yaml
settings:
jvm:
jdk:
version: 21
kotlin:
serialization: json
repositories:
- id: jitpack url: https://jitpack.io
dependencies:
- $libs.ktor.server.core
test-dependencies:
- $libs.kotest.runner.junit5
| Convention script construct | Template counterpart |
|---|---|
| `plugins { kotlin("jvm"), kotlin("plugin.serialization"), id("org.springframework.boot") }` | native `settings:` (`settings.kotlin.*`, `settings.springBoot`, …) |
| `kotlin { jvmToolchain(21) }`, `java { targetCompatibility }` | `settings.jvm.jdk.version`, `settings.jvm.release` |
| `dependencies { implementation / api / testImplementation }` | `dependencies:` (`: exported` for `api`) and `test-dependencies:` |
| `repositories { }` | `repositories:` |
| `tasks.withType<Test> { useJUnitPlatform() }` | built-in / `settings.junit` |
| a convention script applying another convention script | nested templates (`apply:` inside the template) |
| `allprojects {}` / `subprojects {}` in the root script | one template that every `module.yaml` applies |
| `tasks.register(…)`, `doLast { }`, anything imperative | the residue — a local plugin, one per behavior |
Also:
- Delete `buildSrc/` outright. Its `libs` catalog accessors are replaced by `$libs.*` used directly in the
templates.
- Splitting one fat convention script into several small templates (`jvm`, `ktor-server`, `testing`) is
usually the better shape, and bundle templates fold into the same hierarchy — see
[No version-catalog bundles](#no-version-catalog-bundles) for the merge/conflict rules, which apply
identically here.
- Local-plugin enablement inside a template (a `plugins:` block in a `*.module-template.yaml`) is unverified.
If a convention script enabled a plugin you reimplemented, keep the `plugins:` block in each `module.yaml`
until you have confirmed the template form loads (`./kotlin show modules` plus an actual task run).settings:
jvm:
jdk:
version: 21
kotlin:
serialization: json
repositories:
- id: jitpack url: https://jitpack.io
dependencies:
- $libs.ktor.server.core
test-dependencies:
- $libs.kotest.runner.junit5
| 约定脚本结构 | 模板对应项 |
|---|---|
| `plugins { kotlin("jvm"), kotlin("plugin.serialization"), id("org.springframework.boot") }` | 原生`settings:`(`settings.kotlin.*`、`settings.springBoot`等) |
| `kotlin { jvmToolchain(21) }`、`java { targetCompatibility }` | `settings.jvm.jdk.version`、`settings.jvm.release` |
| `dependencies { implementation / api / testImplementation }` | `dependencies:`(`api`对应`: exported`)和`test-dependencies:` |
| `repositories { }` | `repositories:` |
| `tasks.withType<Test> { useJUnitPlatform() }` | 内置功能 / `settings.junit` |
| 一个约定脚本应用另一个约定脚本 | 嵌套模板(模板内部的`apply:`) |
| 根脚本中的`allprojects {}` / `subprojects {}` | 一个所有`module.yaml`都应用的模板 |
| `tasks.register(…)`、`doLast { }`等任何命令式逻辑 | 残留部分——转化为本地插件,每种行为对应一个 |
此外:
- 直接删除`buildSrc/`。它的`libs`目录访问器会被模板中直接使用的`$libs.*`替代。
- 将一个庞大的约定脚本拆分为多个小模板(`jvm`、`ktor-server`、`testing`)通常是更好的结构,依赖束模板也可以融入同一层级——合并/冲突规则参见[无版本目录依赖束](#no-version-catalog-bundles),这些规则在这里完全适用。
- 模板内部的本地插件启用(`*.module-template.yaml`中的`plugins:`块)是未经验证的。如果某个约定脚本启用了你重新实现的插件,请先在每个`module.yaml`中保留`plugins:`块,直到你确认模板形式可以正常加载(运行`./kotlin show modules`并实际执行一个任务)。No dependency exclusions
无依赖排除功能
There is no equivalent of Gradle's . Any transitive exclusion silently disappears and
the library lands on the runtime classpath. Note the trade-off in the PR (usually a few hundred unused KB).
exclude(group, module)没有与Gradle的等效的功能。所有传递性排除都会静默消失,对应的库会出现在运行时类路径上。请在PR中说明这一权衡(通常只是几百KB的未使用空间)。
exclude(group, module)No plugin-to-plugin dependencies
无插件间依赖
Plugins are isolated. If two plugins logically belong together, put both task actions in the same plugin
module or extract the library.
插件是相互隔离的。如果两个插件逻辑上属于一体,把两个任务的动作都放在同一个插件模块中,或是提取出公共库。
No -P
/ -D
CLI overrides
-P-D无-P
/ -D
命令行覆盖参数
-P-DRead ephemeral overrides (force-version, skip-checks, dynamic image tags) from environment variables inside
the ; don't count on a flag either (the pinned CLI may reject it). Pattern in the
skill.
@TaskAction--settingkotlin-tooling-gradle-to-kotlin-toolchain-plugin在中从环境变量读取临时覆盖值(强制版本、跳过检查、动态镜像标签);也不要依赖参数(固定版本的CLI可能会拒绝该参数)。模式参见技能。
@TaskAction--settingkotlin-tooling-gradle-to-kotlin-toolchain-pluginCapturing a command's output value
捕获命令的输出值
println@TaskAction<ts> INFO :<module>:<task>@<plugin> <value><task> successful./kotlin do currentVersion | tail -n1--log-levelerroroff- Have the task write the value to a file named by an env var and it. Moreover, other tasks can reuse this value down the line
cat - Or read the git state the command produced: .
git describe --tags --exact-match HEAD - If you must parse stdout, match the task coordinate: .
awk '/<task>@<plugin>/ { v = $NF } END { print v }'
@TaskActionprintln<ts> INFO :<module>:<task>@<plugin> <value><task> successful./kotlin do currentVersion | tail -n1--log-levelerroroff- 让任务将值写入由环境变量指定的文件,然后该文件。此外,后续的其他任务也可以复用这个值。
cat - 或者读取命令生成的git状态:。
git describe --tags --exact-match HEAD - 如果你必须解析stdout,请匹配任务坐标:。
awk '/<task>@<plugin>/ { v = $NF } END { print v }'
Test resources shadow generated.resources
generated.resources测试资源会遮蔽generated.resources
generated.resourcesWhen a plugin emits and exists, classpath
ordering puts the test fixture first. It usually does the right thing but is brittle — if a test asserts a
specific value, inject a stub service instead of relying on precedence.
release.propertiessrc/test/resources/release.properties当插件生成,而也存在时,类路径顺序会将测试固件放在前面。通常这能正常工作,但很脆弱——如果测试需要断言特定值,请注入一个存根服务,而不是依赖优先级。
release.propertiessrc/test/resources/release.propertiesDependabot needs a stub build.gradle.kts
build.gradle.ktsDependabot需要一个存根build.gradle.kts
build.gradle.ktsDependabot's gradle file fetcher requires a in the configured directory before it scans
; without one, silently no-ops. Keep an empty
at the root with a comment explaining why. The Toolchain ignores it.
build.gradle(.kts)gradle/libs.versions.tomlpackage-ecosystem: "gradle"build.gradle.ktsDependabot的gradle文件获取器在扫描之前,需要配置目录中存在;如果没有,会静默不工作。在根目录保留一个空的,并加上注释说明原因。Toolchain会忽略这个文件。
gradle/libs.versions.tomlbuild.gradle(.kts)package-ecosystem: "gradle"build.gradle.ktsamd64-only container images on Apple Silicon
Apple Silicon上仅支持amd64的容器镜像
Images like crash under Rosetta/QEMU on M-series Macs
(). Unchanged by the migration — the same
image fails under . Flag it as pre-existing; CI on is unaffected.
mongo:3.2runtime: failed to create new OS thread (have 2 already; errno=22)./gradlew checkubuntu-latest像这样的镜像在M系列Mac的Rosetta/QEMU下会崩溃()。迁移不会改变这一点——同样的镜像在下也会失败。请标记为预先存在的问题;上的CI不受影响。
mongo:3.2runtime: failed to create new OS thread (have 2 already; errno=22)./gradlew checkubuntu-latestiOS (KMP): a migrated Info.plist
loses its CFBundle*
keys
Info.plistCFBundle*iOS(KMP):迁移后的Info.plist
会丢失CFBundle*
键
Info.plistCFBundle*A Gradle/KMP iOS app keeps bundle metadata in the hand-maintained
(), so Xcode synthesizes keys and the checked-in is
intentionally partial. The Toolchain ignores that , generates its own, and uses your plist
verbatim — nothing synthesizes the keys, and the has no bundle id:
iosApp.xcodeprojGENERATE_INFOPLIST_FILE = YESCFBundle*Info.plist.xcodeproj.appSimulator device failed to install the application. Missing bundle ID.Fix: make the plist self-contained, keeping your app-specific keys alongside these:
xml
<key>CFBundleDevelopmentRegion</key><string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key><string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key><string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key><string>6.0</string>
<key>CFBundleName</key><string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key><string>APPL</string>
<key>CFBundleShortVersionString</key><string>1.0</string>
<key>CFBundleVersion</key><string>1</string>PRODUCT_BUNDLE_IDENTIFIERkotlin-tooling-kotlin-toolchainGradle/KMP iOS应用的包元数据保存在手动维护的中(),因此Xcode会合成键,而提交到仓库的是故意不完整的。Toolchain会忽略那个,自己生成项目,并直接使用你提供的plist——没有东西会合成这些键,因此会没有包ID:
iosApp.xcodeprojGENERATE_INFOPLIST_FILE = YESCFBundle*Info.plist.xcodeproj.appSimulator device failed to install the application. Missing bundle ID.修复方法:让plist自包含,在你自己的应用专属键旁边加上这些:
xml
<key>CFBundleDevelopmentRegion</key><string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key><string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key><string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key><string>6.0</string>
<key>CFBundleName</key><string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key><string>APPL</string>
<key>CFBundleShortVersionString</key><string>1.0</string>
<key>CFBundleVersion</key><string>1</string>PRODUCT_BUNDLE_IDENTIFIERkotlin-tooling-kotlin-toolchainKMP: carry over every source set's dependencies
KMP:保留每个源集的依赖
Translate each Gradle source set (, , , , , ,
…) into its Amper counterpart — , //, ,
. Don't cherry-pick the obvious library deps:
commonMainjvmMainandroidMainiosMaincommonTestjvmTestdependenciesdependencies@jvm@android@iostest-dependenciestest-dependencies@<platform>-
Adependency is also on that target's test classpath (
*MainextendsjvmTest), so dropping one can break tests with no compile error.jvmMain -
A dependency can look like it belongs to another module and still be load-bearing. Canonical case:in a shared library reads like a desktop-app dep, but it supplies the Skiko native runtime (
jvmMain { implementation(compose.desktop.currentOs) }withskiko-awt-runtime-<os>+libskiko-<os>.dylib) that the module's own JVM Compose UI tests (.sha256/compose.uiTest) load at runtime.runComposeUiTestpulls only Skiko's classes, never the natives. Dropping it compiles fine, then fails with:compose.ui:ui-testorg.jetbrains.skiko.LibraryLoadException: Cannot find libskiko-macos-arm64.dylib.sha256, proper native dependency missing.Not a Toolchain bug: Gradle fails identically without it. Restore under, or scope it todependencies@jvmto keep Skiko natives off consumers' classpaths.test-dependencies@jvm
Guard against drops: diff each Gradle source set's dependency list against its Kotlin Toolchain section (names and
count), then run and compare with the Gradle build.
./kotlin show dependencies -m <module>将每个Gradle源集(、、、、、等)转换为对应的Amper形式——、//、、。不要只挑选明显的库依赖:
commonMainjvmMainandroidMainiosMaincommonTestjvmTestdependenciesdependencies@jvm@android@iostest-dependenciestest-dependencies@<平台>-
的依赖也会出现在该目标的测试类路径上(
*Main继承自jvmTest),因此删除某个依赖可能会导致测试失败,但不会有编译错误。jvmMain -
某个依赖可能看起来属于另一个模块,但实际上是不可或缺的。典型案例:共享库中的看起来像是桌面应用的依赖,但它提供了Skiko原生运行时(
jvmMain { implementation(compose.desktop.currentOs) },包含skiko-awt-runtime-<os>+libskiko-<os>.dylib),模块自己的JVM Compose UI测试(.sha256/compose.uiTest)会在运行时加载它。runComposeUiTest只会引入Skiko的类,不会引入原生库。删除它的话编译没问题,但运行时会失败:compose.ui:ui-testorg.jetbrains.skiko.LibraryLoadException: Cannot find libskiko-macos-arm64.dylib.sha256, proper native dependency missing.这不是Toolchain的bug:没有它的话Gradle也会同样失败。可以在下恢复它,或是将其作用域限定为dependencies@jvm,避免Skiko原生库出现在消费方的类路径上。test-dependencies@jvm
防止遗漏依赖:将每个Gradle源集的依赖列表与对应的Kotlin Toolchain部分进行对比(名称和数量),然后运行,与Gradle构建的结果进行比较。
./kotlin show dependencies -m <module>Common pitfalls
常见陷阱
- No plugin. CI ends up uploading
package(an internal class-file tree) instead of a JAR. Add the plugin before swapping the upload path.build/artifacts/CompiledJvmArtifact/ - Committing . Add it to
build/early; drop the old.gitignoreentry..gradle/ - String interpolation inside Maven coordinates. in
com.example:foo:${pluginSettings.version}fails with "Value of type 'ShadowDependency' doesn't support string interpolation". Useplugin.yaml.$libs.foo
Kotlin Toolchain docs: https://kotlin-toolchain.org/dev/
- 没有插件。 CI最终会上传
package(内部的类文件树)而不是JAR。在更换上传路径之前先添加这个插件。build/artifacts/CompiledJvmArtifact/ - 提交了目录。 尽早把它加到
build/里;删除旧的.gitignore条目。.gradle/ - Maven坐标中的字符串插值。 中的
plugin.yaml会失败,报错“'ShadowDependency'类型的值不支持字符串插值”。请使用com.example:foo:${pluginSettings.version}。$libs.foo
Kotlin Toolchain文档:https://kotlin-toolchain.org/dev/