kotlin-tooling-gradle-to-kotlin-toolchain-project

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Gradle → 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:
kotlin-tooling-kotlin-toolchain
for syntax,
kotlin-tooling-gradle-to-kotlin-toolchain-plugin
for the per-plugin port workflow (you will run it once per Gradle plugin without a native equivalent),
kotlin-tooling-kotlin-toolchain-plugin-authoring
for plugins written from scratch.
这项工作包含两部分:一是依赖与配置的机械性转换,二是替换所有Toolchain没有原生对应实现的Gradle插件。可适配的模板位于references/examples.md,源自一次真实的迁移实践。
对于插件类的子问题,请借助配套技能:语法问题参考
kotlin-tooling-kotlin-toolchain
,单插件移植流程参考
kotlin-tooling-gradle-to-kotlin-toolchain-plugin
(每个无原生等效实现的Gradle插件都需执行一次该流程),从零编写插件参考
kotlin-tooling-kotlin-toolchain-plugin-authoring
。

Principles

原则

  1. Preserve source code. If the migration forces edits to business logic, a local plugin can probably fill the gap instead. Code reading
    release.properties
    off the classpath should keep working — publish that exact file, don't rewrite the consumer.
  2. Every third-party Gradle plugin is drop, native, or reimplement — never "keep the Gradle plugin". Your own convention plugins are different:
    buildSrc
    /
    build-logic
    precompiled scripts are shared configuration, so they become module templates, not local plugins — see No
    buildSrc
    / convention plugins
    .
  3. 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.
  4. All dependencies should reside in version catalog.
    gradle/libs.versions.toml
    survives as the built-in
    $libs.*
    catalog. Every coordinate in every module/plugin YAML must end up as a
    $libs.*
    reference.
    [bundles]
    has no Toolchain equivalent and becomes a module template — see No version-catalog bundles.
  1. 保留源代码不变。 如果迁移迫使你修改业务逻辑,那么大概率可以通过本地插件来填补缺口。从类路径读取
    release.properties
    的代码应当继续正常工作——直接发布该文件即可,不要修改消费方代码。
  2. 所有第三方Gradle插件要么直接弃用、要么用原生能力替代、要么重新实现——绝对不能“保留Gradle插件”。你自己的约定插件则不同:
    buildSrc
    /
    build-logic
    预编译脚本是共享配置,因此它们会转化为模块模板,而非本地插件——参见无
    buildSrc
    /约定插件
    。
  3. 编写本地插件前先搜索GitHub。 很可能已经有人实现过了;复用现成的实现永远比从零移植要好。搜索位置和关键词参见第2阶段的“范围”部分。仅当搜索无果时再自行编写。接入复用的代码前请通读全文——它会在构建时运行,拥有完整的文件系统和网络访问权限。
  4. 所有依赖都应放在版本目录中。
    gradle/libs.versions.toml
    会作为内置的
    $libs.*
    目录保留下来。每个模块/插件YAML中的所有依赖坐标最终都必须改为
    $libs.*
    引用。
    [bundles]
    在Toolchain中没有对应功能,需转化为模块模板——参见无版本目录依赖束。

Workflow

工作流程

Phase 1 — Inventory the Gradle build

第1阶段 — 梳理Gradle构建清单

Write the inventory down (e.g.
MIGRATION_PLAN.md
) before any YAML; it becomes the checklist the PR description verifies.
  • Plugins in the
    plugins { }
    block, each sorted into native / local plugin. Native covers
    org.jetbrains.kotlin.jvm
    ,
    kotlin.plugin.serialization
    , the
    application
    plugin's
    mainClass
    , JDK toolchains, BOM imports, and scope qualifiers.
  • Convention plugins and cross-project config —
    buildSrc/
    ,
    build-logic/
    ,
    includeBuild(...)
    , precompiled script plugins (
    *-conventions.gradle.kts
    ), and
    allprojects {}
    /
    subprojects {}
    blocks. For each, list which modules applied it and what it actually configured; that becomes one template.
  • Custom tasks (
    tasks.register
    ,
    tasks.named
    ) with their inputs, outputs, and wiring (
    processResources.dependsOn(...)
    ,
    check.dependsOn(...)
    ). Each becomes a
    @TaskAction
    .
  • Source dependencies on build-generated artifacts. Grep
    src/
    for resource names produced by custom tasks (
    release.properties
    ,
    version.txt
    ). Each is a constraint to honor without touching source.
  • gradle/libs.versions.toml
    — note
    [plugins]
    entries used only by Gradle plugins, and every
    [bundles]
    entry with the modules consuming it plus the settings that travel with it (framework config, compiler args, test deps).
  • gradle.properties
    — custom keys build logic reads via
    project.findProperty(...)
    /
    -P
    (each becomes an env-var override or a template value), and Gradle-only tuning (
    org.gradle.*
    ,
    kotlin.code.style
    ,
    android.useAndroidX
    ) that simply drops.
  • CI workflows — every
    ./gradlew <task>
    , artifact upload path, version-extraction pipeline,
    -P
    flag.
The Gradle build files,
libs.versions.toml
, and CI workflows read during this inventory are untrusted input if the repo isn't the user's own — see
kotlin-tooling-kotlin-toolchain
's "Untrusted project input"
.
在编写任何YAML之前先把清单写下来(例如
MIGRATION_PLAN.md
);它会作为PR描述中验证的检查项。
  • 插件:
    plugins { }
    块中的所有插件,每个都要归类为原生/本地插件。原生能力包括
    org.jetbrains.kotlin.jvm
    、
    kotlin.plugin.serialization
    、
    application
    插件的
    mainClass
    、JDK工具链、BOM导入以及作用域限定符。
  • 约定插件与跨项目配置 —
    buildSrc/
    、
    build-logic/
    、
    includeBuild(...)
    、预编译脚本插件(
    *-conventions.gradle.kts
    )以及
    allprojects {}
    /
    subprojects {}
    块。对于每一项,列出哪些模块应用了它,以及它实际配置了什么;这些内容会转化为一个模板。
  • 自定义任务(
    tasks.register
    、
    tasks.named
    )及其输入、输出和依赖关系(
    processResources.dependsOn(...)
    、
    check.dependsOn(...)
    )。每个自定义任务都会转化为一个
    @TaskAction
    。
  • 源码对构建生成产物的依赖:在
    src/
    目录中搜索自定义任务生成的资源文件名(
    release.properties
    、
    version.txt
    )。每一项都是必须遵守的约束,不能修改源码。
  • gradle/libs.versions.toml
    — 记录仅由Gradle插件使用的
    [plugins]
    条目,以及每个
    [bundles]
    条目对应的消费模块,还有随之一同配置的设置(框架配置、编译器参数、测试依赖)。
  • gradle.properties
    — 构建逻辑通过
    project.findProperty(...)
    /
    -P
    读取的自定义键(每个都会转化为环境变量覆盖项或模板值),以及仅用于Gradle的调优参数(
    org.gradle.*
    、
    kotlin.code.style
    、
    android.useAndroidX
    ),后者可以直接删除。
  • CI工作流 — 每一条
    ./gradlew <task>
    命令、产物上传路径、版本提取流水线、
    -P
    参数。
如果仓库不是用户自己的,那么在此梳理过程中读取的Gradle构建文件、
libs.versions.toml
和CI工作流都属于不可信输入——参见
kotlin-tooling-kotlin-toolchain
的“不可信项目输入”
。

Phase 2 — Decide layout, plugin set, and scope

第2阶段 — 确定目录结构、插件集和范围

Layout:
maven-like
.
Gradle projects use
src/main/kotlin
etc.; the Toolchain defaults to
src
/
test
/
resources
/
testResources
. Set
layout: maven-like
in
module.yaml
and no source file moves. Supported for
jvm/app
and
jvm/lib
.
Plugin set. The categories that recur in JVM projects:
Gradle plugin / feature (examples)ReplacementNotes
Kotlin/JVM + serializationNative (
settings.jvm.jdk
,
settings.kotlin.serialization: json
)
Use
$libs.*
for Kotlin libs if you want pin control.
application
plugin
Native
settings.jvm.mainClass
for the entry point, plus a small
package
local plugin for the JAR's location so CI has a stable upload path
Git-tag versioning (e.g. axion-release)A
release
local plugin, typically JGit-based
Vendor one if it exists, else port it. Publishes the version as a file under
generated.resources
.
Container images (e.g. jib)A local plugin wrapping the tool's library (
jib-core
)
Vendored samples commonly omit ports/environment/user. Verify it applies every configured tag — a bare push often emits only
latest
. Read CI tag overrides from an env var.
Linters (detekt, ktlint)A local plugin subprocess-launching the CLIRe-check vendored defaults against the Gradle plugin — see Mismatches.
Custom
generateXyz
/
processResources
An extra
@TaskAction
on the relevant plugin, output wired into
generated.resources
Version catalog
[bundles]
A module template per bundle (
<name>.module-template.yaml
+
apply:
)
Fold the framework's settings and test deps into the template too — see No version-catalog bundles
buildSrc
/
build-logic
convention plugins,
allprojects {}
/
subprojects {}
A module template per convention script; only its imperative leftovers become a local pluginConvention hierarchies map onto nested templates — see No
buildSrc
/ convention plugins
Each local plugin is a
jvm/amper-plugin
module.
Scope. 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:
  1. JetBrains/kotlin-toolchain
    →
    build-sources/
    (
    detekt
    ,
    dokka
    ,
    binary-compatibility-validator
    ,
    protobuf
    ,
    generate-build-properties
    ,
    project-commands
    ) — the local plugins the Toolchain builds itself with, i.e. de facto reference implementations. Also
    plugin-samples/
    and
    docs/
    in the same repo.
  2. GitHub code search on the plugin marker rather than the tool name:
    "product: jvm/amper-plugin"
    ,
    path:plugin.yaml "@TaskAction"
    ,
    "jvm/amper-plugin" jib
    .
  3. The tool's own repo — most linters/packagers ship a
    -cli
    or
    -core
    artifact, which is all a thin wrapper plugin needs, so "no plugin exists" often still means "a 50-line wrapper exists".
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
package
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.
目录结构:
maven-like
。
Gradle项目使用
src/main/kotlin
等目录;Toolchain默认使用
src
/
test
/
resources
/
testResources
。在
module.yaml
中设置
layout: maven-like
即可无需移动任何源文件。该选项支持
jvm/app
和
jvm/lib
类型的项目。
插件集。 JVM项目中常见的插件类别:
Gradle插件/功能(示例)替代方案备注
Kotlin/JVM + 序列化原生能力(
settings.jvm.jdk
、
settings.kotlin.serialization: json
)
如需精确控制Kotlin库版本,可使用
$libs.*
引用。
application
插件
入口点使用原生
settings.jvm.mainClass
,外加一个小型**
package
**本地插件来指定JAR的输出位置,确保CI有稳定的上传路径
Git标签版本控制(例如axion-release)一个**
release
**本地插件,通常基于JGit实现
如有现成实现就复用,否则自行移植。版本号会作为文件发布到
generated.resources
下。
容器镜像(例如jib)封装对应工具库(
jib-core
)的本地插件
复用的示例通常会遗漏端口/环境变量/用户配置。请验证它会应用所有配置的标签——裸推送通常只会生成
latest
标签。从环境变量读取CI的标签覆盖值。
代码检查工具(detekt、ktlint)通过子进程启动CLI的本地插件对照Gradle插件重新检查复用的默认配置——参见需要注意的差异。
自定义
generateXyz
/
processResources
在相关插件上添加额外的
@TaskAction
,输出接入
generated.resources
版本目录
[bundles]
每个依赖束对应一个模块模板(
<name>.module-template.yaml
+
apply:
)
把框架的设置和测试依赖也整合到模板中——参见无版本目录依赖束
buildSrc
/
build-logic
约定插件、
allprojects {}
/
subprojects {}
每个约定脚本对应一个模块模板;仅其中命令式的残留逻辑才需要转化为本地插件约定层级结构可映射为嵌套模板——参见无
buildSrc
/约定插件
每个本地插件都是一个
jvm/amper-plugin
模块。
范围。 对于列表中的每个插件,在编写任何Kotlin代码前先搜索GitHub。虽然生态还不大,但常见的插件基本都已经有实现了。搜索顺序:
  1. JetBrains/kotlin-toolchain
    →
    build-sources/
    (
    detekt
    、
    dokka
    、
    binary-compatibility-validator
    、
    protobuf
    、
    generate-build-properties
    、
    project-commands
    )——Toolchain自身构建所用的本地插件,也就是事实上的参考实现。同一仓库中的
    plugin-samples/
    和
    docs/
    也值得一看。
  2. 使用GitHub代码搜索,搜索插件标记而非工具名称:
    "product: jvm/amper-plugin"
    、
    path:plugin.yaml "@TaskAction"
    、
    "jvm/amper-plugin" jib
    。
  3. 工具本身的仓库——大多数代码检查/打包工具都会发布
    -cli
    或
    -core
    构件,这正是薄封装插件所需的全部,因此“没有现成插件”通常意味着“只需要写50行的封装代码”。
然后为每个插件选择方案:复用(原样复制找到的实现;保留其许可证头,并添加带有源URL和提交哈希的注释,以便后续重新同步)、扩展(复用+额外的设置字段),或是自研(没有找到实现,或是需求是定制化的)。单个PR的合理默认策略:复用现有实现,自研小型定制插件(比如
package
插件、薄封装的代码检查插件),其余的延后处理。在信任复用的插件之前,一定要将其行为与它要替换的Gradle插件做对比——参见复用的代码检查插件可能比Gradle插件更严格。

Phase 3 — Implement

第3阶段 — 实施

  1. Copy
    kotlin
    /
    kotlin.bat
    from a reference Toolchain project (for example this one) or
    kotlin init
    in a scratch dir. Pin
    kotlintoolchain=<version>
    in
    .sdkmanrc
    to match the wrapper.
  2. Write
    project.yaml
    with all plugin module paths.
  3. Per plugin: search GitHub first (Phase 2 "Scope"), then vendor or author it under
    plugins/<name>/
    , running
    ./kotlin show modules
    after each to confirm the model still loads.
  4. Write the templates at the project root: one
    <name>.module-template.yaml
    per convention script and per
    [bundles]
    entry with two or more consumers (dependencies plus the settings, test deps, and repositories that travel with them), nested the way the Gradle conventions were.
  5. Write the root
    module.yaml
    :
    product: jvm/app
    ,
    layout: maven-like
    ,
    $libs.*
    dependencies, an
    apply:
    list for the templates, and a
    plugins:
    block enabling each local plugin with its non-default settings.
  6. Validate each plugin in isolation:
    ./kotlin task :<module>:<task>@<plugin>
    or
    ./kotlin do <command>
    .
  7. Rewrite CI (Phase 4).
  8. Delete
    build.gradle.kts
    ,
    gradlew
    ,
    gradlew.bat
    ,
    gradle/wrapper/
    — but keep
    gradle/libs.versions.toml
    .
  9. Sweep the catalog: drop the whole
    [plugins]
    block, any
    [versions]
    keys that only fed it, and
    [bundles]
    once every consumer applies a template.
  10. Sweep every
    module.yaml
    /
    plugin.yaml
    for literal Maven coordinates and replace them with
    $libs.<key>
    .
  1. 从参考Toolchain项目(例如这个项目)复制
    kotlin
    /
    kotlin.bat
    文件,或是在临时目录中执行
    kotlin init
    。在
    .sdkmanrc
    中固定
    kotlintoolchain=<version>
    版本,与wrapper保持一致。
  2. 编写
    project.yaml
    ,包含所有插件模块的路径。
  3. 逐个处理插件:先搜索GitHub(参见第2阶段的“范围”部分),然后在
    plugins/<name>/
    目录下复用或自研插件,每处理完一个都运行
    ./kotlin show modules
    确认模型仍能正常加载。
  4. 在项目根目录编写模板:每个约定脚本对应一个
    <name>.module-template.yaml
    ,每个有两个及以上消费方的
    [bundles]
    条目也对应一个模板(包含依赖以及随之一同配置的设置、测试依赖、仓库),按照Gradle约定的层级进行嵌套。
  5. 编写根目录的
    module.yaml
    :包含
    product: jvm/app
    、
    layout: maven-like
    、
    $libs.*
    依赖、模板的
    apply:
    列表,以及启用每个本地插件并配置非默认设置的
    plugins:
    块。
  6. 单独验证每个插件:运行
    ./kotlin task :<module>:<task>@<plugin>
    或
    ./kotlin do <command>
    。
  7. 重写CI(第4阶段)。
  8. 删除
    build.gradle.kts
    、
    gradlew
    、
    gradlew.bat
    、
    gradle/wrapper/
    ——但保留
    gradle/libs.versions.toml
    。
  9. 清理版本目录:删除整个
    [plugins]
    块、所有仅为它服务的
    [versions]
    键,以及在所有消费方都应用模板后的
    [bundles]
    块。
  10. 检查所有
    module.yaml
    /
    plugin.yaml
    ,将硬编码的Maven坐标替换为
    $libs.<key>
    引用。

Phase 4 — Rewrite CI

第4阶段 — 重写CI

  • Set
    KOTLIN_CLI_NO_WELCOME_BANNER: "1"
    .
  • ./gradlew build && ./gradlew check
    →
    ./kotlin build && ./kotlin check
    (which runs every plugin's
    checks:
    registrations plus tests).
  • ./gradlew jib -Djib.to.tags=…
    →
    ./kotlin do jib
    , with tags passed through an env var the plugin reads. Vendored jib-style plugins usually lack that hook — add it while vendoring.
  • Artifact upload path changes: Gradle's
    build/libs/<name>.jar
    is gone and
    jarJvm
    writes to a Toolchain-internal path. Author a
    package
    plugin staging the JAR at
    ${module.rootDir}/build/libs/${module.name}.jar
    so uploading artifacts stays simple.
  • 设置
    KOTLIN_CLI_NO_WELCOME_BANNER: "1"
    。
  • ./gradlew build && ./gradlew check
    →
    ./kotlin build && ./kotlin check
    (后者会运行每个插件注册的
    checks:
    以及测试)。
  • ./gradlew jib -Djib.to.tags=…
    →
    ./kotlin do jib
    ,标签通过插件读取的环境变量传递。复用的jib类插件通常缺少这个钩子——在复用时加上即可。
  • 产物上传路径变更:Gradle的
    build/libs/<name>.jar
    不再存在,
    jarJvm
    会输出到Toolchain内部路径。编写一个
    package
    插件,将JAR放到
    ${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 applicable

Mismatches to watch

需要注意的差异

No
${...}
interpolation in
module.yaml

module.yaml
中不支持
${...}
插值

configFile: ${module.rootDir}/detekt.yml
is taken literally. Use a module-relative path (
configFile: detekt.yml
). Interpolation works only in
plugin.yaml
.
configFile: ${module.rootDir}/detekt.yml
会被当作字面量处理。请使用模块相对路径(
configFile: detekt.yml
)。插值仅在
plugin.yaml
中可用。

Module name comes from the directory name

模块名称来自目录名

There is no
name:
field.
actions/checkout
clones into a directory named after the GitHub repo, while a local worktree may resolve
${module.name}
to something else. Never hardcode the module name into a plugin task's output path — use
${module.name}
.
没有
name:
字段。
actions/checkout
会克隆到以GitHub仓库命名的目录中,而本地工作树可能会将
${module.name}
解析为其他值。绝对不要在插件任务的输出路径中硬编码模块名称——请使用
${module.name}
。

Plugin settings without
enabled: true
are ignored

没有设置
enabled: true
的插件配置会被忽略

yaml
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
Settings without
enabled: true
produce only a warning ("Plugin X is not enabled, but has some explicit configuration") and the plugin is skipped.
yaml
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
没有
enabled: true
的设置只会产生一条警告(“插件X未启用,但存在显式配置”),插件会被跳过。

A 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 (
amper/build-sources/detekt/
) always passes
--classpath
to
detekt-cli
, enabling type resolution, which Gradle's default
detekt
task does not. Used as-is it surfaces violations Gradle never reported (notably
UnreachableCode
on elvis-with-return). Fix: add
useTypeResolution: Boolean get() = false
to the plugin's Settings and gate the flag on it — patch in references/examples.md.
对比复用插件传递的参数与Gradle插件默认任务的参数,将所有更严格的检查放到可选设置后面,确保默认行为与旧版一致。
典型案例:上游的detekt插件(
amper/build-sources/detekt/
)总是会向
detekt-cli
传递
--classpath
参数,启用类型解析,而Gradle的默认
detekt
任务不会这样做。直接使用的话,它会暴露出Gradle从未报告过的违规(特别是带return的elvis表达式上的
UnreachableCode
)。修复方法:在插件的Settings中添加
useTypeResolution: Boolean get() = false
,并根据该值控制是否传递该参数——补丁参见references/examples.md。

No version-catalog bundles

无版本目录依赖束

Only
[libraries]
keys resolve (
$libs.<key>
).
$libs.bundles.<name>
does not exist and
[bundles]
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:
toml
undefined
只有
[libraries]
中的键可以被解析(
$libs.<key>
)。
$libs.bundles.<name>
不存在,目录中的
[bundles]
是Toolchain不会读取的无效配置。官方解决方案(KTC-4759)是为每个依赖束创建一个模块模板,应用到所有使用该依赖束的地方:
toml
undefined

gradle/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"]

```yaml

ktor-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

```yaml
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

```yaml

module.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/
,
build-logic/
, and
includeBuild(...)
have no counterpart, and
project.yaml
carries only
modules:
and
plugins:
— there is no root-project inheritance and nowhere to put imperative shared build logic. A local plugin is also the wrong target: plugins contribute tasks, they don't inject module configuration. A precompiled script plugin is mostly declarative, so it translates to one
<name>.module-template.yaml
, applied by the modules that used
plugins { 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
undefined
buildSrc/
、
build-logic/
和
includeBuild(...)
没有对应的实现,
project.yaml
只包含
modules:
和
plugins:
——没有根项目继承,也没有地方放置命令式的共享构建逻辑。本地插件也不是正确的选择:插件贡献的是任务,它们不会注入模块配置。预编译脚本插件大多是声明式的,因此它会转化为一个
<name>.module-template.yaml
,由之前使用
plugins { 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
undefined

service-conventions.module-template.yaml

service-conventions.module-template.yaml

settings: jvm: jdk: version: 21 kotlin: serialization: json
repositories:
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:
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
exclude(group, module)
. 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).
没有与Gradle的
exclude(group, module)
等效的功能。所有传递性排除都会静默消失,对应的库会出现在运行时类路径上。请在PR中说明这一权衡(通常只是几百KB的未使用空间)。

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
命令行覆盖参数

Read ephemeral overrides (force-version, skip-checks, dynamic image tags) from environment variables inside the
@TaskAction
; don't count on a
--setting
flag either (the pinned CLI may reject it). Pattern in the
kotlin-tooling-gradle-to-kotlin-toolchain-plugin
skill
.
在
@TaskAction
中从环境变量读取临时覆盖值(强制版本、跳过检查、动态镜像标签);也不要依赖
--setting
参数(固定版本的CLI可能会拒绝该参数)。模式参见
kotlin-tooling-gradle-to-kotlin-toolchain-plugin
技能
。

Capturing a command's output value

捕获命令的输出值

println
from a
@TaskAction
is not a machine-readable channel. The Toolchain wraps it as
<ts> INFO :<module>:<task>@<plugin> <value>
and appends a
<task> successful
banner, so
./kotlin do currentVersion | tail -n1
yields the banner — and lowering
--log-level
to
error
/
off
drops the value line entirely, since it is emitted at INFO. Instead:
  • Have the task write the value to a file named by an env var and
    cat
    it. Moreover, other tasks can reuse this value down the line
  • 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 }'
    .
@TaskAction
中的
println
不是机器可读的通道。Toolchain会将其包装为
<ts> INFO :<module>:<task>@<plugin> <value>
,并追加一个
<task> successful
的横幅,因此
./kotlin do currentVersion | tail -n1
得到的会是横幅——而如果把
--log-level
降到
error
/
off
,值的行就会完全消失,因为它是在INFO级别输出的。正确的做法是:
  • 让任务将值写入由环境变量指定的文件,然后
    cat
    该文件。此外,后续的其他任务也可以复用这个值。
  • 或者读取命令生成的git状态:
    git describe --tags --exact-match HEAD
    。
  • 如果你必须解析stdout,请匹配任务坐标:
    awk '/<task>@<plugin>/ { v = $NF } END { print v }'
    。

Test resources shadow
generated.resources

测试资源会遮蔽
generated.resources

When a plugin emits
release.properties
and
src/test/resources/release.properties
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.properties
,而
src/test/resources/release.properties
也存在时,类路径顺序会将测试固件放在前面。通常这能正常工作,但很脆弱——如果测试需要断言特定值,请注入一个存根服务,而不是依赖优先级。

Dependabot needs a stub
build.gradle.kts

Dependabot需要一个存根
build.gradle.kts

Dependabot's gradle file fetcher requires a
build.gradle(.kts)
in the configured directory before it scans
gradle/libs.versions.toml
; without one,
package-ecosystem: "gradle"
silently no-ops. Keep an empty
build.gradle.kts
at the root with a comment explaining why. The Toolchain ignores it.
Dependabot的gradle文件获取器在扫描
gradle/libs.versions.toml
之前,需要配置目录中存在
build.gradle(.kts)
;如果没有,
package-ecosystem: "gradle"
会静默不工作。在根目录保留一个空的
build.gradle.kts
,并加上注释说明原因。Toolchain会忽略这个文件。

amd64-only container images on Apple Silicon

Apple Silicon上仅支持amd64的容器镜像

Images like
mongo:3.2
crash under Rosetta/QEMU on M-series Macs (
runtime: failed to create new OS thread (have 2 already; errno=22)
). Unchanged by the migration — the same image fails under
./gradlew check
. Flag it as pre-existing; CI on
ubuntu-latest
is unaffected.
像
mongo:3.2
这样的镜像在M系列Mac的Rosetta/QEMU下会崩溃(
runtime: failed to create new OS thread (have 2 already; errno=22)
)。迁移不会改变这一点——同样的镜像在
./gradlew check
下也会失败。请标记为预先存在的问题;
ubuntu-latest
上的CI不受影响。

iOS (KMP): a migrated
Info.plist
loses its
CFBundle*
keys

iOS(KMP):迁移后的
Info.plist
会丢失
CFBundle*
键

A Gradle/KMP iOS app keeps bundle metadata in the hand-maintained
iosApp.xcodeproj
(
GENERATE_INFOPLIST_FILE = YES
), so Xcode synthesizes
CFBundle*
keys and the checked-in
Info.plist
is intentionally partial. The Toolchain ignores that
.xcodeproj
, generates its own, and uses your plist verbatim — nothing synthesizes the keys, and the
.app
has no bundle id:
Simulator 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_IDENTIFIER
is set on the generated target. Underlying behaviour: the
kotlin-tooling-kotlin-toolchain
skill's "iOS apps" section
.
Gradle/KMP iOS应用的包元数据保存在手动维护的
iosApp.xcodeproj
中(
GENERATE_INFOPLIST_FILE = YES
),因此Xcode会合成
CFBundle*
键,而提交到仓库的
Info.plist
是故意不完整的。Toolchain会忽略那个
.xcodeproj
,自己生成项目,并直接使用你提供的plist——没有东西会合成这些键,因此
.app
会没有包ID:
Simulator 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_IDENTIFIER
会在生成的目标上设置。底层行为参见
kotlin-tooling-kotlin-toolchain
技能的“iOS应用”部分
。

KMP: carry over every source set's dependencies

KMP:保留每个源集的依赖

Translate each Gradle source set (
commonMain
,
jvmMain
,
androidMain
,
iosMain
,
commonTest
,
jvmTest
, …) into its Amper counterpart —
dependencies
,
dependencies@jvm
/
@android
/
@ios
,
test-dependencies
,
test-dependencies@<platform>
. Don't cherry-pick the obvious library deps:
  • A
    *Main
    dependency is also on that target's test classpath (
    jvmTest
    extends
    jvmMain
    ), so dropping one can break tests with no compile error.
  • A dependency can look like it belongs to another module and still be load-bearing. Canonical case:
    jvmMain { implementation(compose.desktop.currentOs) }
    in a shared library reads like a desktop-app dep, but it supplies the Skiko native runtime (
    skiko-awt-runtime-<os>
    with
    libskiko-<os>.dylib
    +
    .sha256
    ) that the module's own JVM Compose UI tests (
    compose.uiTest
    /
    runComposeUiTest
    ) load at runtime.
    compose.ui:ui-test
    pulls only Skiko's classes, never the natives. Dropping it compiles fine, then fails with:
    org.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
    dependencies@jvm
    , or scope it to
    test-dependencies@jvm
    to keep Skiko natives off consumers' classpaths.
Guard against drops: diff each Gradle source set's dependency list against its Kotlin Toolchain section (names and count), then run
./kotlin show dependencies -m <module>
and compare with the Gradle build.
将每个Gradle源集(
commonMain
、
jvmMain
、
androidMain
、
iosMain
、
commonTest
、
jvmTest
等)转换为对应的Amper形式——
dependencies
、
dependencies@jvm
/
@android
/
@ios
、
test-dependencies
、
test-dependencies@<平台>
。不要只挑选明显的库依赖:
  • *Main
    的依赖也会出现在该目标的测试类路径上(
    jvmTest
    继承自
    jvmMain
    ),因此删除某个依赖可能会导致测试失败,但不会有编译错误。
  • 某个依赖可能看起来属于另一个模块,但实际上是不可或缺的。典型案例:共享库中的
    jvmMain { implementation(compose.desktop.currentOs) }
    看起来像是桌面应用的依赖,但它提供了Skiko原生运行时(
    skiko-awt-runtime-<os>
    ,包含
    libskiko-<os>.dylib
    +
    .sha256
    ),模块自己的JVM Compose UI测试(
    compose.uiTest
    /
    runComposeUiTest
    )会在运行时加载它。
    compose.ui:ui-test
    只会引入Skiko的类,不会引入原生库。删除它的话编译没问题,但运行时会失败:
    org.jetbrains.skiko.LibraryLoadException: Cannot find libskiko-macos-arm64.dylib.sha256, proper native dependency missing.
    这不是Toolchain的bug:没有它的话Gradle也会同样失败。可以在
    dependencies@jvm
    下恢复它,或是将其作用域限定为
    test-dependencies@jvm
    ,避免Skiko原生库出现在消费方的类路径上。
防止遗漏依赖:将每个Gradle源集的依赖列表与对应的Kotlin Toolchain部分进行对比(名称和数量),然后运行
./kotlin show dependencies -m <module>
,与Gradle构建的结果进行比较。

Common pitfalls

常见陷阱

  • No
    package
    plugin.
    CI ends up uploading
    build/artifacts/CompiledJvmArtifact/
    (an internal class-file tree) instead of a JAR. Add the plugin before swapping the upload path.
  • Committing
    build/
    .
    Add it to
    .gitignore
    early; drop the old
    .gradle/
    entry.
  • String interpolation inside Maven coordinates.
    com.example:foo:${pluginSettings.version}
    in
    plugin.yaml
    fails with "Value of type 'ShadowDependency' doesn't support string interpolation". Use
    $libs.foo
    .
Kotlin Toolchain docs: https://kotlin-toolchain.org/dev/
  • 没有
    package
    插件。
    CI最终会上传
    build/artifacts/CompiledJvmArtifact/
    (内部的类文件树)而不是JAR。在更换上传路径之前先添加这个插件。
  • 提交了
    build/
    目录。
    尽早把它加到
    .gitignore
    里;删除旧的
    .gradle/
    条目。
  • Maven坐标中的字符串插值。
    plugin.yaml
    中的
    com.example:foo:${pluginSettings.version}
    会失败,报错“'ShadowDependency'类型的值不支持字符串插值”。请使用
    $libs.foo
    。
Kotlin Toolchain文档:https://kotlin-toolchain.org/dev/