Allow command transformAll functions to perform imports (#1440)

This commit is contained in:
Jen Basch
2026-02-25 08:03:53 -08:00
committed by GitHub
parent 2e4d73b957
commit be21c34938
7 changed files with 91 additions and 19 deletions

View File

@@ -22,6 +22,7 @@ import com.github.ajalt.clikt.parameters.arguments.*
import com.github.ajalt.clikt.parameters.options.*
import com.github.ajalt.clikt.parameters.types.int
import java.io.OutputStream
import java.net.URI
import java.nio.file.Path
import kotlin.io.path.createParentDirectories
import kotlin.io.path.exists
@@ -159,7 +160,7 @@ constructor(
)
.convert {
try {
opt.transformEach.apply(it, runner.options.normalizedWorkingDir.toUri())
opt.transformEach.apply(it, workingDirUri)
} catch (e: CommandSpec.Option.BadValue) {
fail(e.message!!)
} catch (_: CommandSpec.Option.MissingOption) {
@@ -168,7 +169,7 @@ constructor(
}
.transformAll(opt.defaultValue, opt.showAsRequired) {
try {
opt.transformAll.apply(it)
opt.transformAll.apply(it, workingDirUri)
} catch (e: CommandSpec.Option.BadValue) {
fail(e.message!!)
} catch (_: CommandSpec.Option.MissingOption) {
@@ -201,7 +202,7 @@ constructor(
)
.convert {
try {
opt.transformEach.apply(it, runner.options.normalizedWorkingDir.toUri())
opt.transformEach.apply(it, workingDirUri)
} catch (e: CommandSpec.Option.BadValue) {
fail(e.message!!)
} catch (_: CommandSpec.Option.MissingOption) {
@@ -210,7 +211,7 @@ constructor(
}
.transformAll(if (opt.repeated) -1 else 1, !opt.repeated) {
try {
opt.transformAll.apply(it)
opt.transformAll.apply(it, workingDirUri)
} catch (e: CommandSpec.Option.BadValue) {
fail(e.message!!)
} catch (_: CommandSpec.Option.MissingOption) {
@@ -223,6 +224,8 @@ constructor(
spec.subcommands.forEach { subcommands(SynthesizedRunCommand(it, runner)) }
}
val workingDirUri: URI by lazy { runner.options.normalizedWorkingDir.toUri() }
override val invokeWithoutSubcommand = true
override val hiddenFromHelp: Boolean = spec.hidden

View File

@@ -867,6 +867,65 @@ class CliCommandRunnerTest {
)
}
@Test
fun `transformAll import`() {
val moduleUri =
writePklFile(
"cmd.pkl",
"""
extends "pkl:Command"
options: Options
output {
value = (options) {
fromImport {
baz = true // assert that imported modules are not forced
}
}
}
class Options {
@Flag {
convert = (it) -> new Import{ uri = it }
transformAll = (values) -> values.firstOrNull ?? new Import { uri = "./default.pkl" }
}
fromImport: Module
}
"""
.trimIndent(),
)
val importUri =
writePklFile(
"default.pkl",
"""
foo = 1
bar = "baz"
baz: Boolean
"""
.trimIndent(),
)
val output =
runToStdout(
CliBaseOptions(sourceModules = listOf(moduleUri), workingDir = tempDir),
emptyList(),
)
assertThat(output)
.isEqualTo(
"""
fromImport {
foo = 1
bar = "baz"
baz = true
}
"""
.trimIndent()
)
}
@Test
fun `convert glob import`() {
val moduleUri =