Run spotless formatting (#958)

When we updated spotless's Java and Kotlin formatter, we changed the underlying
formatting rules.
However, due to spotless ratcheting, these formatting changes don't get applied unless a file
gets touched in a commit.

To avoid future PRs introducing lines of change that aren't related to the intention of the PR,
this is a one-time format of all files.
This commit is contained in:
Daniel Chao
2025-02-17 07:36:43 -08:00
committed by GitHub
parent d270829ed3
commit 28b128f86f
79 changed files with 679 additions and 682 deletions
+2 -2
View File
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -111,7 +111,7 @@ open class MergeSourcesJars : DefaultTask() {
relocatedPkgs: Map<String, String>, relocatedPkgs: Map<String, String>,
details: FileVisitDetails, details: FileVisitDetails,
sourceText: String, sourceText: String,
importPattern: Pattern importPattern: Pattern,
): String { ): String {
val matcher = importPattern.matcher(sourceText) val matcher = importPattern.matcher(sourceText)
val buffer = StringBuffer() val buffer = StringBuffer()
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -24,7 +24,7 @@ import org.pkl.core.packages.PackageUri
class CliPackageDownloader( class CliPackageDownloader(
baseOptions: CliBaseOptions, baseOptions: CliBaseOptions,
private val packageUris: List<PackageUri>, private val packageUris: List<PackageUri>,
private val noTransitive: Boolean private val noTransitive: Boolean,
) : CliCommand(baseOptions) { ) : CliCommand(baseOptions) {
override fun doRun() { override fun doRun() {
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -32,7 +32,7 @@ class CliProjectPackager(
private val outputPath: String, private val outputPath: String,
private val skipPublishCheck: Boolean, private val skipPublishCheck: Boolean,
private val consoleWriter: Writer = System.out.writer(), private val consoleWriter: Writer = System.out.writer(),
private val errWriter: Writer = System.err.writer() private val errWriter: Writer = System.err.writer(),
) : CliProjectCommand(baseOptions, projectDirs) { ) : CliProjectCommand(baseOptions, projectDirs) {
private fun runApiTests(project: Project) { private fun runApiTests(project: Project) {
@@ -85,7 +85,7 @@ class CliProjectPackager(
securityManager, securityManager,
httpClient, httpClient,
skipPublishCheck, skipPublishCheck,
consoleWriter consoleWriter,
) )
.createPackages() .createPackages()
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -27,7 +27,7 @@ class CliProjectResolver(
baseOptions: CliBaseOptions, baseOptions: CliBaseOptions,
projectDirs: List<Path>, projectDirs: List<Path>,
private val consoleWriter: Writer = System.out.writer(), private val consoleWriter: Writer = System.out.writer(),
private val errWriter: Writer = System.err.writer() private val errWriter: Writer = System.err.writer(),
) : CliProjectCommand(baseOptions, projectDirs) { ) : CliProjectCommand(baseOptions, projectDirs) {
override fun doRun() { override fun doRun() {
for (projectFile in normalizedProjectFiles) { for (projectFile in normalizedProjectFiles) {
@@ -38,10 +38,10 @@ class CliProjectResolver(
allowedModules, allowedModules,
allowedResources, allowedResources,
SecurityManagers.defaultTrustLevels, SecurityManagers.defaultTrustLevels,
rootDir rootDir,
), ),
httpClient, httpClient,
moduleCacheDir moduleCacheDir,
) )
val dependencies = ProjectDependenciesResolver(project, packageResolver, errWriter).resolve() val dependencies = ProjectDependenciesResolver(project, packageResolver, errWriter).resolve()
val depsFile = val depsFile =
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -34,13 +34,13 @@ internal class CliRepl(private val options: CliEvaluatorOptions) : CliCommand(op
allowedModules, allowedModules,
allowedResources, allowedResources,
SecurityManagers.defaultTrustLevels, SecurityManagers.defaultTrustLevels,
rootDir rootDir,
), ),
httpClient, httpClient,
Loggers.stdErr(), Loggers.stdErr(),
listOf( listOf(
ModuleKeyFactories.standardLibrary, ModuleKeyFactories.standardLibrary,
ModuleKeyFactories.modulePath(modulePathResolver) ModuleKeyFactories.modulePath(modulePathResolver),
) + ) +
ModuleKeyFactories.fromServiceProviders() + ModuleKeyFactories.fromServiceProviders() +
listOf( listOf(
@@ -48,7 +48,7 @@ internal class CliRepl(private val options: CliEvaluatorOptions) : CliCommand(op
ModuleKeyFactories.http, ModuleKeyFactories.http,
ModuleKeyFactories.pkg, ModuleKeyFactories.pkg,
ModuleKeyFactories.projectpackage, ModuleKeyFactories.projectpackage,
ModuleKeyFactories.genericUrl ModuleKeyFactories.genericUrl,
), ),
listOf( listOf(
ResourceReaders.environmentVariable(), ResourceReaders.environmentVariable(),
@@ -58,7 +58,7 @@ internal class CliRepl(private val options: CliEvaluatorOptions) : CliCommand(op
ResourceReaders.http(), ResourceReaders.http(),
ResourceReaders.https(), ResourceReaders.https(),
ResourceReaders.pkg(), ResourceReaders.pkg(),
ResourceReaders.projectpackage() ResourceReaders.projectpackage(),
), ),
environmentVariables, environmentVariables,
externalProperties, externalProperties,
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -31,7 +31,7 @@ constructor(
private val options: CliBaseOptions, private val options: CliBaseOptions,
private val testOptions: CliTestOptions, private val testOptions: CliTestOptions,
private val consoleWriter: Writer = System.out.writer(), private val consoleWriter: Writer = System.out.writer(),
private val errWriter: Writer = System.err.writer() private val errWriter: Writer = System.err.writer(),
) : CliCommand(options) { ) : CliCommand(options) {
override fun doRun() { override fun doRun() {
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -45,7 +45,7 @@ internal class Repl(workingDir: Path, private val server: ReplServer) {
option(Option.DISABLE_EVENT_EXPANSION, true) option(Option.DISABLE_EVENT_EXPANSION, true)
variable( variable(
org.jline.reader.LineReader.HISTORY_FILE, org.jline.reader.LineReader.HISTORY_FILE,
(IoUtils.getPklHomeDir().resolve("repl-history")) (IoUtils.getPklHomeDir().resolve("repl-history")),
) )
} }
.build() .build()
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -65,7 +65,7 @@ class CliImportAnalyzerTest {
val analyzer = val analyzer =
CliImportAnalyzer( CliImportAnalyzer(
CliImportAnalyzerOptions(baseOptions, outputFormat = OutputFormat.JSON.toString()), CliImportAnalyzerOptions(baseOptions, outputFormat = OutputFormat.JSON.toString()),
StringBuilderWriter(sb) StringBuilderWriter(sb),
) )
analyzer.run() analyzer.run()
assertThat(sb.toString()) assertThat(sb.toString())
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -115,7 +115,7 @@ class CliProjectPackagerTest {
} }
} }
""" """
.trimIndent() .trimIndent(),
) )
tempDir.writeFile( tempDir.writeFile(
"PklProject", "PklProject",
@@ -130,7 +130,7 @@ class CliProjectPackagerTest {
apiTests { "myTest.pkl" } apiTests { "myTest.pkl" }
} }
""" """
.trimIndent() .trimIndent(),
) )
val buffer = StringWriter() val buffer = StringWriter()
val packager = val packager =
@@ -140,7 +140,7 @@ class CliProjectPackagerTest {
CliTestOptions(), CliTestOptions(),
".out/%{name}@%{version}", ".out/%{name}@%{version}",
skipPublishCheck = true, skipPublishCheck = true,
consoleWriter = buffer consoleWriter = buffer,
) )
val err = assertThrows<CliException> { packager.run() } val err = assertThrows<CliException> { packager.run() }
assertThat(err).hasMessageContaining("because its API tests are failing") assertThat(err).hasMessageContaining("because its API tests are failing")
@@ -187,7 +187,7 @@ class CliProjectPackagerTest {
CliTestOptions(), CliTestOptions(),
".out/%{name}@%{version}", ".out/%{name}@%{version}",
skipPublishCheck = true, skipPublishCheck = true,
consoleWriter = buffer consoleWriter = buffer,
) )
packager.run() packager.run()
} }
@@ -286,7 +286,7 @@ class CliProjectPackagerTest {
CliTestOptions(), CliTestOptions(),
".out", ".out",
skipPublishCheck = true, skipPublishCheck = true,
consoleWriter = buffer consoleWriter = buffer,
) )
packager.run() packager.run()
} }
@@ -301,7 +301,7 @@ class CliProjectPackagerTest {
name: String name: String
""" """
.trimIndent() .trimIndent(),
) )
val fooTxt = val fooTxt =
@@ -312,7 +312,7 @@ class CliProjectPackagerTest {
bar bar
baz baz
""" """
.trimIndent() .trimIndent(),
) )
tempDir tempDir
@@ -337,7 +337,7 @@ class CliProjectPackagerTest {
CliTestOptions(), CliTestOptions(),
".out/%{name}@%{version}", ".out/%{name}@%{version}",
skipPublishCheck = true, skipPublishCheck = true,
consoleWriter = StringWriter() consoleWriter = StringWriter(),
) )
packager.run() packager.run()
val expectedMetadata = tempDir.resolve(".out/mypackage@1.0.0/mypackage@1.0.0") val expectedMetadata = tempDir.resolve(".out/mypackage@1.0.0/mypackage@1.0.0")
@@ -411,7 +411,7 @@ class CliProjectPackagerTest {
} }
} }
""" """
.trimIndent() .trimIndent(),
) )
CliProjectPackager( CliProjectPackager(
CliBaseOptions(workingDir = tempDir), CliBaseOptions(workingDir = tempDir),
@@ -419,7 +419,7 @@ class CliProjectPackagerTest {
CliTestOptions(), CliTestOptions(),
".out/%{name}@%{version}", ".out/%{name}@%{version}",
skipPublishCheck = true, skipPublishCheck = true,
consoleWriter = StringWriter() consoleWriter = StringWriter(),
) )
.run() .run()
val expectedArchive = tempDir.resolve(".out/mypackage@1.0.0/mypackage@1.0.0.zip") val expectedArchive = tempDir.resolve(".out/mypackage@1.0.0/mypackage@1.0.0.zip")
@@ -432,7 +432,7 @@ class CliProjectPackagerTest {
"/input", "/input",
"/input/foo", "/input/foo",
"/input/foo/bar.txt", "/input/foo/bar.txt",
"/main.pkl" "/main.pkl",
) )
) )
} }
@@ -460,7 +460,7 @@ class CliProjectPackagerTest {
["project2"] = import("../project2/PklProject") ["project2"] = import("../project2/PklProject")
} }
""" """
.trimIndent() .trimIndent(),
) )
projectDir.writeFile( projectDir.writeFile(
"PklProject.deps.json", "PklProject.deps.json",
@@ -483,7 +483,7 @@ class CliProjectPackagerTest {
} }
} }
""" """
.trimIndent() .trimIndent(),
) )
project2Dir.writeFile( project2Dir.writeFile(
@@ -498,7 +498,7 @@ class CliProjectPackagerTest {
packageZipUrl = "https://foo.com/project2.zip" packageZipUrl = "https://foo.com/project2.zip"
} }
""" """
.trimIndent() .trimIndent(),
) )
project2Dir.writeFile( project2Dir.writeFile(
"PklProject.deps.json", "PklProject.deps.json",
@@ -508,7 +508,7 @@ class CliProjectPackagerTest {
"resolvedDependencies": {} "resolvedDependencies": {}
} }
""" """
.trimIndent() .trimIndent(),
) )
CliProjectPackager( CliProjectPackager(
@@ -517,7 +517,7 @@ class CliProjectPackagerTest {
CliTestOptions(), CliTestOptions(),
".out/%{name}@%{version}", ".out/%{name}@%{version}",
skipPublishCheck = true, skipPublishCheck = true,
consoleWriter = StringWriter() consoleWriter = StringWriter(),
) )
.run() .run()
val expectedMetadata = tempDir.resolve(".out/mypackage@1.0.0/mypackage@1.0.0") val expectedMetadata = tempDir.resolve(".out/mypackage@1.0.0/mypackage@1.0.0")
@@ -598,7 +598,7 @@ class CliProjectPackagerTest {
["project2"] = import("../project2/PklProject") ["project2"] = import("../project2/PklProject")
} }
""" """
.trimIndent() .trimIndent(),
) )
projectDir.writeFile( projectDir.writeFile(
"PklProject.deps.json", "PklProject.deps.json",
@@ -621,7 +621,7 @@ class CliProjectPackagerTest {
} }
} }
""" """
.trimIndent() .trimIndent(),
) )
project2Dir.writeFile( project2Dir.writeFile(
@@ -636,7 +636,7 @@ class CliProjectPackagerTest {
packageZipUrl = "https://foo.com/project2.zip" packageZipUrl = "https://foo.com/project2.zip"
} }
""" """
.trimIndent() .trimIndent(),
) )
project2Dir.writeFile( project2Dir.writeFile(
"PklProject.deps.json", "PklProject.deps.json",
@@ -646,7 +646,7 @@ class CliProjectPackagerTest {
"resolvedDependencies": {} "resolvedDependencies": {}
} }
""" """
.trimIndent() .trimIndent(),
) )
assertThatCode { assertThatCode {
CliProjectPackager( CliProjectPackager(
@@ -655,7 +655,7 @@ class CliProjectPackagerTest {
CliTestOptions(), CliTestOptions(),
".out/%{name}@%{version}", ".out/%{name}@%{version}",
skipPublishCheck = true, skipPublishCheck = true,
consoleWriter = StringWriter() consoleWriter = StringWriter(),
) )
.run() .run()
} }
@@ -671,7 +671,7 @@ class CliProjectPackagerTest {
res = foo res = foo
""" """
.trimIndent() .trimIndent(),
) )
tempDir.writeFile( tempDir.writeFile(
"PklProject", "PklProject",
@@ -685,7 +685,7 @@ class CliProjectPackagerTest {
packageZipUrl = "https://foo.com" packageZipUrl = "https://foo.com"
} }
""" """
.trimIndent() .trimIndent(),
) )
val e = val e =
assertThrows<CliException> { assertThrows<CliException> {
@@ -695,7 +695,7 @@ class CliProjectPackagerTest {
CliTestOptions(), CliTestOptions(),
".out/%{name}@%{version}", ".out/%{name}@%{version}",
skipPublishCheck = true, skipPublishCheck = true,
consoleWriter = StringWriter() consoleWriter = StringWriter(),
) )
.run() .run()
} }
@@ -725,7 +725,7 @@ class CliProjectPackagerTest {
res = foo res = foo
""" """
.trimIndent() .trimIndent(),
) )
tempDir.writeFile( tempDir.writeFile(
"PklProject", "PklProject",
@@ -739,7 +739,7 @@ class CliProjectPackagerTest {
packageZipUrl = "https://foo.com" packageZipUrl = "https://foo.com"
} }
""" """
.trimIndent() .trimIndent(),
) )
val e = val e =
assertThrows<CliException> { assertThrows<CliException> {
@@ -749,7 +749,7 @@ class CliProjectPackagerTest {
CliTestOptions(), CliTestOptions(),
".out/%{name}@%{version}", ".out/%{name}@%{version}",
skipPublishCheck = true, skipPublishCheck = true,
consoleWriter = StringWriter() consoleWriter = StringWriter(),
) )
.run() .run()
} }
@@ -771,7 +771,7 @@ class CliProjectPackagerTest {
""" """
res = read("$tempDir/foo.pkl") res = read("$tempDir/foo.pkl")
""" """
.trimIndent() .trimIndent(),
) )
tempDir.writeFile( tempDir.writeFile(
"PklProject", "PklProject",
@@ -785,7 +785,7 @@ class CliProjectPackagerTest {
packageZipUrl = "https://foo.com" packageZipUrl = "https://foo.com"
} }
""" """
.trimIndent() .trimIndent(),
) )
val e = val e =
assertThrows<CliException> { assertThrows<CliException> {
@@ -795,7 +795,7 @@ class CliProjectPackagerTest {
CliTestOptions(), CliTestOptions(),
".out/%{name}@%{version}", ".out/%{name}@%{version}",
skipPublishCheck = true, skipPublishCheck = true,
consoleWriter = StringWriter() consoleWriter = StringWriter(),
) )
.run() .run()
} }
@@ -816,7 +816,7 @@ class CliProjectPackagerTest {
""" """
import "baz.pkl" import "baz.pkl"
""" """
.trimIndent() .trimIndent(),
) )
tempDir.writeFile( tempDir.writeFile(
"PklProject", "PklProject",
@@ -830,7 +830,7 @@ class CliProjectPackagerTest {
packageZipUrl = "https://foo.com" packageZipUrl = "https://foo.com"
} }
""" """
.trimIndent() .trimIndent(),
) )
CliProjectPackager( CliProjectPackager(
CliBaseOptions(workingDir = tempDir), CliBaseOptions(workingDir = tempDir),
@@ -838,7 +838,7 @@ class CliProjectPackagerTest {
CliTestOptions(), CliTestOptions(),
".out/%{name}@%{version}", ".out/%{name}@%{version}",
skipPublishCheck = true, skipPublishCheck = true,
consoleWriter = StringWriter() consoleWriter = StringWriter(),
) )
.run() .run()
} }
@@ -858,7 +858,7 @@ class CliProjectPackagerTest {
packageZipUrl = "https://foo.com" packageZipUrl = "https://foo.com"
} }
""" """
.trimIndent() .trimIndent(),
) )
tempDir.writeFile("project2/main2.pkl", "res = 2") tempDir.writeFile("project2/main2.pkl", "res = 2")
tempDir.writeFile( tempDir.writeFile(
@@ -873,7 +873,7 @@ class CliProjectPackagerTest {
packageZipUrl = "https://foo.com" packageZipUrl = "https://foo.com"
} }
""" """
.trimIndent() .trimIndent(),
) )
val out = StringWriter() val out = StringWriter()
CliProjectPackager( CliProjectPackager(
@@ -882,7 +882,7 @@ class CliProjectPackagerTest {
CliTestOptions(), CliTestOptions(),
".out/%{name}@%{version}", ".out/%{name}@%{version}",
skipPublishCheck = true, skipPublishCheck = true,
consoleWriter = out consoleWriter = out,
) )
.run() .run()
val sep = File.separatorChar val sep = File.separatorChar
@@ -923,7 +923,7 @@ class CliProjectPackagerTest {
packageZipUrl = "https://foo.com" packageZipUrl = "https://foo.com"
} }
""" """
.trimIndent() .trimIndent(),
) )
val e = val e =
assertThrows<CliException> { assertThrows<CliException> {
@@ -931,13 +931,13 @@ class CliProjectPackagerTest {
CliBaseOptions( CliBaseOptions(
workingDir = tempDir, workingDir = tempDir,
caCertificates = listOf(FileTestUtils.selfSignedCertificate), caCertificates = listOf(FileTestUtils.selfSignedCertificate),
testPort = packageServer.port testPort = packageServer.port,
), ),
listOf(tempDir.resolve("project")), listOf(tempDir.resolve("project")),
CliTestOptions(), CliTestOptions(),
".out/%{name}@%{version}", ".out/%{name}@%{version}",
skipPublishCheck = false, skipPublishCheck = false,
consoleWriter = StringWriter() consoleWriter = StringWriter(),
) )
.run() .run()
} }
@@ -968,20 +968,20 @@ class CliProjectPackagerTest {
packageZipUrl = "https://foo.com" packageZipUrl = "https://foo.com"
} }
""" """
.trimIndent() .trimIndent(),
) )
val out = StringWriter() val out = StringWriter()
CliProjectPackager( CliProjectPackager(
CliBaseOptions( CliBaseOptions(
workingDir = tempDir, workingDir = tempDir,
caCertificates = listOf(FileTestUtils.selfSignedCertificate), caCertificates = listOf(FileTestUtils.selfSignedCertificate),
testPort = packageServer.port testPort = packageServer.port,
), ),
listOf(tempDir.resolve("project")), listOf(tempDir.resolve("project")),
CliTestOptions(), CliTestOptions(),
".out/%{name}@%{version}", ".out/%{name}@%{version}",
skipPublishCheck = false, skipPublishCheck = false,
consoleWriter = out consoleWriter = out,
) )
.run() .run()
val sep = File.separatorChar val sep = File.separatorChar
@@ -1025,7 +1025,7 @@ class CliProjectPackagerTest {
CliTestOptions(), CliTestOptions(),
".out/%{name}@%{version}", ".out/%{name}@%{version}",
skipPublishCheck = true, skipPublishCheck = true,
consoleWriter = StringWriter() consoleWriter = StringWriter(),
) )
packager.run() packager.run()
val expectedMetadata = tempDir.resolve(".out/mypackage@1.0.0/mypackage@1.0.0") val expectedMetadata = tempDir.resolve(".out/mypackage@1.0.0/mypackage@1.0.0")
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -47,7 +47,7 @@ class CliProjectResolverTest {
CliBaseOptions(workingDir = tempDir, noCache = true), CliBaseOptions(workingDir = tempDir, noCache = true),
emptyList(), emptyList(),
consoleWriter = StringWriter(), consoleWriter = StringWriter(),
errWriter = StringWriter() errWriter = StringWriter(),
) )
val err = assertThrows<CliException> { packager.run() } val err = assertThrows<CliException> { packager.run() }
assertThat(err).hasMessageStartingWith("No project visible to the working directory.") assertThat(err).hasMessageStartingWith("No project visible to the working directory.")
@@ -60,7 +60,7 @@ class CliProjectResolverTest {
CliBaseOptions(noCache = true), CliBaseOptions(noCache = true),
listOf(tempDir), listOf(tempDir),
consoleWriter = StringWriter(), consoleWriter = StringWriter(),
errWriter = StringWriter() errWriter = StringWriter(),
) )
val err = assertThrows<CliException> { packager.run() } val err = assertThrows<CliException> { packager.run() }
assertThat(err).hasMessageStartingWith("Directory $tempDir does not contain a PklProject file.") assertThat(err).hasMessageStartingWith("Directory $tempDir does not contain a PklProject file.")
@@ -79,18 +79,18 @@ class CliProjectResolverTest {
} }
} }
""" """
.trimIndent() .trimIndent(),
) )
CliProjectResolver( CliProjectResolver(
CliBaseOptions( CliBaseOptions(
workingDir = tempDir, workingDir = tempDir,
caCertificates = listOf(FileTestUtils.selfSignedCertificate), caCertificates = listOf(FileTestUtils.selfSignedCertificate),
testPort = packageServer.port, testPort = packageServer.port,
noCache = true noCache = true,
), ),
listOf(tempDir), listOf(tempDir),
consoleWriter = StringWriter(), consoleWriter = StringWriter(),
errWriter = StringWriter() errWriter = StringWriter(),
) )
.run() .run()
val expectedOutput = tempDir.resolve("PklProject.deps.json") val expectedOutput = tempDir.resolve("PklProject.deps.json")
@@ -134,18 +134,18 @@ class CliProjectResolverTest {
} }
} }
""" """
.trimIndent() .trimIndent(),
) )
CliProjectResolver( CliProjectResolver(
CliBaseOptions( CliBaseOptions(
workingDir = tempDir, workingDir = tempDir,
caCertificates = listOf(FileTestUtils.selfSignedCertificate), caCertificates = listOf(FileTestUtils.selfSignedCertificate),
testPort = packageServer.port, testPort = packageServer.port,
noCache = true noCache = true,
), ),
emptyList(), emptyList(),
consoleWriter = StringWriter(), consoleWriter = StringWriter(),
errWriter = StringWriter() errWriter = StringWriter(),
) )
.run() .run()
val expectedOutput = tempDir.resolve("PklProject.deps.json") val expectedOutput = tempDir.resolve("PklProject.deps.json")
@@ -191,7 +191,7 @@ class CliProjectResolverTest {
["project2"] = import("../project2/PklProject") ["project2"] = import("../project2/PklProject")
} }
""" """
.trimIndent() .trimIndent(),
) )
projectDir.writeFile( projectDir.writeFile(
"../project2/PklProject", "../project2/PklProject",
@@ -212,7 +212,7 @@ class CliProjectResolverTest {
["project3"] = import("../project3/PklProject") ["project3"] = import("../project3/PklProject")
} }
""" """
.trimIndent() .trimIndent(),
) )
projectDir.writeFile( projectDir.writeFile(
@@ -233,17 +233,17 @@ class CliProjectResolverTest {
} }
} }
""" """
.trimIndent() .trimIndent(),
) )
CliProjectResolver( CliProjectResolver(
CliBaseOptions( CliBaseOptions(
caCertificates = listOf(FileTestUtils.selfSignedCertificate), caCertificates = listOf(FileTestUtils.selfSignedCertificate),
testPort = packageServer.port, testPort = packageServer.port,
noCache = true noCache = true,
), ),
listOf(projectDir), listOf(projectDir),
consoleWriter = StringWriter(), consoleWriter = StringWriter(),
errWriter = StringWriter() errWriter = StringWriter(),
) )
.run() .run()
val expectedOutput = projectDir.resolve("PklProject.deps.json") val expectedOutput = projectDir.resolve("PklProject.deps.json")
@@ -299,7 +299,7 @@ class CliProjectResolverTest {
["fruit"] = import("../fruit/PklProject") ["fruit"] = import("../fruit/PklProject")
} }
""" """
.trimIndent() .trimIndent(),
) )
projectDir.writeFile( projectDir.writeFile(
"../fruit/PklProject", "../fruit/PklProject",
@@ -313,7 +313,7 @@ class CliProjectResolverTest {
packageZipUrl = "https://foo.com/fruit.zip" packageZipUrl = "https://foo.com/fruit.zip"
} }
""" """
.trimIndent() .trimIndent(),
) )
val consoleOut = StringWriter() val consoleOut = StringWriter()
val errOut = StringWriter() val errOut = StringWriter()
@@ -321,11 +321,11 @@ class CliProjectResolverTest {
CliBaseOptions( CliBaseOptions(
caCertificates = listOf(FileTestUtils.selfSignedCertificate), caCertificates = listOf(FileTestUtils.selfSignedCertificate),
testPort = packageServer.port, testPort = packageServer.port,
noCache = true noCache = true,
), ),
listOf(projectDir), listOf(projectDir),
consoleWriter = consoleOut, consoleWriter = consoleOut,
errWriter = errOut errWriter = errOut,
) )
.run() .run()
val expectedOutput = projectDir.resolve("PklProject.deps.json") val expectedOutput = projectDir.resolve("PklProject.deps.json")
@@ -373,7 +373,7 @@ class CliProjectResolverTest {
} }
} }
""" """
.trimIndent() .trimIndent(),
) )
tempDir.writeFile( tempDir.writeFile(
@@ -387,7 +387,7 @@ class CliProjectResolverTest {
} }
} }
""" """
.trimIndent() .trimIndent(),
) )
val consoleOut = StringWriter() val consoleOut = StringWriter()
@@ -396,11 +396,11 @@ class CliProjectResolverTest {
CliBaseOptions( CliBaseOptions(
caCertificates = listOf(FileTestUtils.selfSignedCertificate), caCertificates = listOf(FileTestUtils.selfSignedCertificate),
testPort = packageServer.port, testPort = packageServer.port,
noCache = true noCache = true,
), ),
listOf(tempDir.resolve("project1"), tempDir.resolve("project2")), listOf(tempDir.resolve("project1"), tempDir.resolve("project2")),
consoleWriter = consoleOut, consoleWriter = consoleOut,
errWriter = errOut errWriter = errOut,
) )
.run() .run()
val sep = File.separatorChar val sep = File.separatorChar
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -73,7 +73,7 @@ data class CliJavaCodeGeneratorOptions(
* Pkl module names, you can define a rename mapping, where the key is a prefix of the original * Pkl module names, you can define a rename mapping, where the key is a prefix of the original
* Pkl module name, and the value is the desired replacement. * Pkl module name, and the value is the desired replacement.
*/ */
val renames: Map<String, String> = emptyMap() val renames: Map<String, String> = emptyMap(),
) { ) {
@Suppress("DeprecatedCallableAddReplaceWith") @Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("deprecated without replacement") @Deprecated("deprecated without replacement")
@@ -88,6 +88,6 @@ data class CliJavaCodeGeneratorOptions(
paramsAnnotation, paramsAnnotation,
nonNullAnnotation, nonNullAnnotation,
implementSerializable, implementSerializable,
renames renames,
) )
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -41,7 +41,7 @@ class CliJavaCodeGeneratorTest {
name: String name: String
age: Int age: Int
} }
""" """,
) )
val module2 = val module2 =
@@ -53,7 +53,7 @@ class CliJavaCodeGeneratorTest {
extends "mod1.pkl" extends "mod1.pkl"
parrot: Person parrot: Person
""" """,
) )
val module1File = module1.writeToDisk(tempDir.resolve("org/mod1.pkl")) val module1File = module1.writeToDisk(tempDir.resolve("org/mod1.pkl"))
@@ -64,7 +64,7 @@ class CliJavaCodeGeneratorTest {
CliJavaCodeGenerator( CliJavaCodeGenerator(
CliJavaCodeGeneratorOptions( CliJavaCodeGeneratorOptions(
CliBaseOptions(listOf(module1File.toUri(), module2File.toUri())), CliBaseOptions(listOf(module1File.toUri(), module2File.toUri())),
outputDir outputDir,
) )
) )
@@ -82,7 +82,7 @@ class CliJavaCodeGeneratorTest {
|public class Mod1 { |public class Mod1 {
| public final @NonNull Person pigeon; | public final @NonNull Person pigeon;
""", """,
module1JavaFile.readString() module1JavaFile.readString(),
) )
val module2JavaFile = javaDir.resolve("org/Mod2.java") val module2JavaFile = javaDir.resolve("org/Mod2.java")
@@ -91,7 +91,7 @@ class CliJavaCodeGeneratorTest {
|public final class Mod2 extends Mod1 { |public final class Mod2 extends Mod1 {
| public final Mod1. @NonNull Person parrot; | public final Mod1. @NonNull Person parrot;
""", """,
module2JavaFile.readString() module2JavaFile.readString(),
) )
val resourcesDir = outputDir.resolve("resources/META-INF/org/pkl/config/java/mapper/classes/") val resourcesDir = outputDir.resolve("resources/META-INF/org/pkl/config/java/mapper/classes/")
@@ -101,18 +101,18 @@ class CliJavaCodeGeneratorTest {
// use two assertions because java.util.Properties doesn't guarantee order // use two assertions because java.util.Properties doesn't guarantee order
assertContains( assertContains(
"""org.pkl.config.java.mapper.org.mod1\#Person=org.Mod1${dollar}Person""", """org.pkl.config.java.mapper.org.mod1\#Person=org.Mod1${dollar}Person""",
module1PropertiesString module1PropertiesString,
) )
assertContains( assertContains(
"""org.pkl.config.java.mapper.org.mod1\#ModuleClass=org.Mod1""", """org.pkl.config.java.mapper.org.mod1\#ModuleClass=org.Mod1""",
module1PropertiesString module1PropertiesString,
) )
val module2PropertiesFile = resourcesDir.resolve("org.mod2.properties") val module2PropertiesFile = resourcesDir.resolve("org.mod2.properties")
assertContains( assertContains(
"""org.pkl.config.java.mapper.org.mod2\#ModuleClass=org.Mod2""", """org.pkl.config.java.mapper.org.mod2\#ModuleClass=org.Mod2""",
module2PropertiesFile.readString() module2PropertiesFile.readString(),
) )
} }
@@ -127,7 +127,7 @@ class CliJavaCodeGeneratorTest {
class Person { class Person {
name: String name: String
} }
""" """,
) )
val module2 = val module2 =
@@ -144,7 +144,7 @@ class CliJavaCodeGeneratorTest {
class Person { class Person {
age: Int age: Int
} }
""" """,
) )
val module1PklFile = module1.writeToDisk(tempDir.resolve("org/mod1.pkl")) val module1PklFile = module1.writeToDisk(tempDir.resolve("org/mod1.pkl"))
@@ -155,7 +155,7 @@ class CliJavaCodeGeneratorTest {
CliJavaCodeGenerator( CliJavaCodeGenerator(
CliJavaCodeGeneratorOptions( CliJavaCodeGeneratorOptions(
CliBaseOptions(listOf(module1PklFile.toUri(), module2PklFile.toUri())), CliBaseOptions(listOf(module1PklFile.toUri(), module2PklFile.toUri())),
outputDir outputDir,
) )
) )
@@ -169,7 +169,7 @@ class CliJavaCodeGeneratorTest {
| |
| public final @NonNull Person person2; | public final @NonNull Person person2;
""", """,
module2JavaFile.readString() module2JavaFile.readString(),
) )
} }
@@ -184,7 +184,7 @@ class CliJavaCodeGeneratorTest {
class Person { class Person {
name: String name: String
} }
""" """,
) )
val module2 = val module2 =
@@ -199,7 +199,7 @@ class CliJavaCodeGeneratorTest {
owner: Module1.Person owner: Module1.Person
name: String name: String
} }
""" """,
) )
val module3 = val module3 =
@@ -213,7 +213,7 @@ class CliJavaCodeGeneratorTest {
class Supergroup { class Supergroup {
owner: Module2.Group owner: Module2.Group
} }
""" """,
) )
val module1PklFile = module1.writeToDisk(tempDir.resolve("org/foo/Module1.pkl")) val module1PklFile = module1.writeToDisk(tempDir.resolve("org/foo/Module1.pkl"))
@@ -226,7 +226,7 @@ class CliJavaCodeGeneratorTest {
CliJavaCodeGeneratorOptions( CliJavaCodeGeneratorOptions(
CliBaseOptions(listOf(module1PklFile, module2PklFile, module3PklFile).map { it.toUri() }), CliBaseOptions(listOf(module1PklFile, module2PklFile, module3PklFile).map { it.toUri() }),
outputDir, outputDir,
renames = mapOf("org.foo" to "com.foo.x", "org.baz" to "com.baz.a.b") renames = mapOf("org.foo" to "com.foo.x", "org.baz" to "com.baz.a.b"),
) )
) )
@@ -243,7 +243,7 @@ class CliJavaCodeGeneratorTest {
| public static final class Person { | public static final class Person {
| public final @NonNull String name; | public final @NonNull String name;
""", """,
it it,
) )
} }
@@ -260,7 +260,7 @@ class CliJavaCodeGeneratorTest {
| public static final class Group { | public static final class Group {
| public final Module1. @NonNull Person owner; | public final Module1. @NonNull Person owner;
""", """,
it it,
) )
} }
@@ -277,7 +277,7 @@ class CliJavaCodeGeneratorTest {
| public static final class Supergroup { | public static final class Supergroup {
| public final Module2. @NonNull Group owner; | public final Module2. @NonNull Group owner;
""", """,
it it,
) )
} }
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -87,7 +87,7 @@ private class InMemoryFileManager(delegate: JavaFileManager) :
location: JavaFileManager.Location, location: JavaFileManager.Location,
className: String, className: String,
kind: JavaFileObject.Kind, kind: JavaFileObject.Kind,
sibling: FileObject sibling: FileObject,
): JavaFileObject { ): JavaFileObject {
return WritableBinaryFileObject(className, kind).also { outputFiles[className] = it } return WritableBinaryFileObject(className, kind).also { outputFiles[className] = it }
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -104,7 +104,7 @@ class JavaCodeGeneratorTest {
private fun generateJavaCode( private fun generateJavaCode(
pklCode: String, pklCode: String,
options: JavaCodeGeneratorOptions = JavaCodeGeneratorOptions() options: JavaCodeGeneratorOptions = JavaCodeGeneratorOptions(),
): JavaSourceCode { ): JavaSourceCode {
val module = Evaluator.preconfigured().evaluateSchema(text(pklCode)) val module = Evaluator.preconfigured().evaluateSchema(text(pklCode))
val generator = JavaCodeGenerator(module, options) val generator = JavaCodeGenerator(module, options)
@@ -219,7 +219,7 @@ class JavaCodeGeneratorTest {
} }
""" """
.trimIndent(), .trimIndent(),
JavaCodeGeneratorOptions(generateJavadoc = true) JavaCodeGeneratorOptions(generateJavadoc = true),
) )
assertThat(javaCode) assertThat(javaCode)
.contains( .contains(
@@ -258,7 +258,7 @@ class JavaCodeGeneratorTest {
} }
""" """
.trimIndent(), .trimIndent(),
JavaCodeGeneratorOptions(generateGetters = true, generateJavadoc = true) JavaCodeGeneratorOptions(generateGetters = true, generateJavadoc = true),
) )
assertThat(javaCode) assertThat(javaCode)
.contains( .contains(
@@ -305,7 +305,7 @@ class JavaCodeGeneratorTest {
} }
""" """
.trimIndent(), .trimIndent(),
JavaCodeGeneratorOptions(generateJavadoc = true) JavaCodeGeneratorOptions(generateJavadoc = true),
) )
assertThat(javaCode) assertThat(javaCode)
.contains( .contains(
@@ -332,7 +332,7 @@ class JavaCodeGeneratorTest {
propertyInDeprecatedModuleClass : Int = 42 propertyInDeprecatedModuleClass : Int = 42
""" """
.trimIndent(), .trimIndent(),
JavaCodeGeneratorOptions(generateJavadoc = generateJavadoc) JavaCodeGeneratorOptions(generateJavadoc = generateJavadoc),
) )
assertThat(javaCode) assertThat(javaCode)
@@ -372,7 +372,7 @@ class JavaCodeGeneratorTest {
""" """
.trimIndent(), .trimIndent(),
// no message, so no Javadoc, regardless of flag // no message, so no Javadoc, regardless of flag
JavaCodeGeneratorOptions(generateJavadoc = generateJavadoc) JavaCodeGeneratorOptions(generateJavadoc = generateJavadoc),
) )
assertThat(javaCode) assertThat(javaCode)
@@ -407,7 +407,7 @@ class JavaCodeGeneratorTest {
} }
""" """
.trimIndent(), .trimIndent(),
JavaCodeGeneratorOptions(generateGetters = true) JavaCodeGeneratorOptions(generateGetters = true),
) )
assertThat(javaCode) assertThat(javaCode)
@@ -496,7 +496,7 @@ class JavaCodeGeneratorTest {
@Deprecated { message = "property is deprecated" } @Deprecated { message = "property is deprecated" }
deprecatedProperty: Int deprecatedProperty: Int
""", """,
JavaCodeGeneratorOptions(generateJavadoc = true) JavaCodeGeneratorOptions(generateJavadoc = true),
) )
assertThat(javaCode) assertThat(javaCode)
@@ -564,7 +564,7 @@ class JavaCodeGeneratorTest {
"digit-1" to "DIGIT_1", "digit-1" to "DIGIT_1",
"42" to "_42", "42" to "_42",
"àœü" to "ÀŒÜ", "àœü" to "ÀŒÜ",
"日本-つくば" to "日本_つくば" "日本-つくば" to "日本_つくば",
) )
val javaCode = val javaCode =
generateJavaCode( generateJavaCode(
@@ -586,7 +586,7 @@ class JavaCodeGeneratorTest {
assertThat(field.name).isEqualTo(kotlinName) assertThat(field.name).isEqualTo(kotlinName)
Unit Unit
} }
} },
) )
assertAll( assertAll(
@@ -596,7 +596,7 @@ class JavaCodeGeneratorTest {
assertThat(enumConstant.toString()).isEqualTo(pklName) assertThat(enumConstant.toString()).isEqualTo(pklName)
Unit Unit
} }
} },
) )
} }
@@ -718,7 +718,7 @@ class JavaCodeGeneratorTest {
} }
""" """
.trimIndent(), .trimIndent(),
JavaCodeGeneratorOptions(generateGetters = true) JavaCodeGeneratorOptions(generateGetters = true),
) )
assertThat(javaCode) assertThat(javaCode)
@@ -872,7 +872,7 @@ class JavaCodeGeneratorTest {
} }
""" """
.trimIndent(), .trimIndent(),
JavaCodeGeneratorOptions(generateGetters = true) JavaCodeGeneratorOptions(generateGetters = true),
) )
assertThat(javaCode).compilesSuccessfully().isEqualToResourceFile("GenerateGetters.jva") assertThat(javaCode).compilesSuccessfully().isEqualToResourceFile("GenerateGetters.jva")
@@ -985,7 +985,7 @@ class JavaCodeGeneratorTest {
} }
""" """
.trimIndent(), .trimIndent(),
JavaCodeGeneratorOptions(generateJavadoc = true) JavaCodeGeneratorOptions(generateJavadoc = true),
) )
assertThat(javaCode).compilesSuccessfully().isEqualToResourceFile("Javadoc.jva") assertThat(javaCode).compilesSuccessfully().isEqualToResourceFile("Javadoc.jva")
@@ -1009,7 +1009,7 @@ class JavaCodeGeneratorTest {
} }
""" """
.trimIndent(), .trimIndent(),
JavaCodeGeneratorOptions(generateGetters = true, generateJavadoc = true) JavaCodeGeneratorOptions(generateGetters = true, generateJavadoc = true),
) )
assertThat(javaCode) assertThat(javaCode)
@@ -1151,7 +1151,7 @@ class JavaCodeGeneratorTest {
foo: String foo: String
""" """
.trimIndent(), .trimIndent(),
JavaCodeGeneratorOptions(nonNullAnnotation = "com.example.Annotations\$NonNull") JavaCodeGeneratorOptions(nonNullAnnotation = "com.example.Annotations\$NonNull"),
) )
assertThat(javaCode) assertThat(javaCode)
@@ -1455,7 +1455,7 @@ class JavaCodeGeneratorTest {
name: String name: String
""" """
.trimIndent(), .trimIndent(),
JavaCodeGeneratorOptions(paramsAnnotation = "org.project.MyAnnotation") JavaCodeGeneratorOptions(paramsAnnotation = "org.project.MyAnnotation"),
) )
assertThat(javaCode) assertThat(javaCode)
@@ -1473,7 +1473,7 @@ class JavaCodeGeneratorTest {
name: String name: String
""" """
.trimIndent(), .trimIndent(),
JavaCodeGeneratorOptions(paramsAnnotation = null) JavaCodeGeneratorOptions(paramsAnnotation = null),
) )
assertThat(javaCode).contains("public Mod(@NonNull String name)") assertThat(javaCode).contains("public Mod(@NonNull String name)")
@@ -1494,7 +1494,7 @@ class JavaCodeGeneratorTest {
} }
""" """
.trimIndent(), .trimIndent(),
JavaCodeGeneratorOptions(generateSpringBootConfig = true) JavaCodeGeneratorOptions(generateSpringBootConfig = true),
) )
assertThat(javaCode) assertThat(javaCode)
@@ -1548,7 +1548,7 @@ class JavaCodeGeneratorTest {
pigeon: Person pigeon: Person
""" """
.trimIndent() .trimIndent(),
) )
val client = val client =
@@ -1563,7 +1563,7 @@ class JavaCodeGeneratorTest {
parrot: library.Person parrot: library.Person
""" """
.trimIndent() .trimIndent(),
) )
val javaSourceFiles = generateFiles(library, client) val javaSourceFiles = generateFiles(library, client)
@@ -1595,7 +1595,7 @@ class JavaCodeGeneratorTest {
pigeon: Person pigeon: Person
""" """
.trimIndent() .trimIndent(),
) )
val derived = val derived =
@@ -1610,7 +1610,7 @@ class JavaCodeGeneratorTest {
person1: Person person1: Person
person2: Person2 person2: Person2
""" """
.trimIndent() .trimIndent(),
) )
val javaSourceFiles = generateFiles(base, derived) val javaSourceFiles = generateFiles(base, derived)
@@ -1646,7 +1646,7 @@ class JavaCodeGeneratorTest {
typealias Version = "LATEST"|String typealias Version = "LATEST"|String
""" """
.trimIndent() .trimIndent(),
) )
val derived = val derived =
@@ -1659,7 +1659,7 @@ class JavaCodeGeneratorTest {
v: Version = "1.2.3" v: Version = "1.2.3"
""" """
.trimIndent() .trimIndent(),
) )
val javaSourceFiles = generateFiles(base, derived) val javaSourceFiles = generateFiles(base, derived)
@@ -1697,7 +1697,7 @@ class JavaCodeGeneratorTest {
prop: Int prop: Int
} }
""" """
.trimIndent() .trimIndent(),
) )
val generated = generateFiles(pklModule) val generated = generateFiles(pklModule)
val expectedPropertyFile = val expectedPropertyFile =
@@ -1730,7 +1730,7 @@ class JavaCodeGeneratorTest {
prop: Int prop: Int
} }
""" """
.trimIndent() .trimIndent(),
) )
val generated = generateFiles(pklModule) val generated = generateFiles(pklModule)
val expectedPropertyFile = val expectedPropertyFile =
@@ -1782,7 +1782,7 @@ class JavaCodeGeneratorTest {
typealias Direction = "north"|"east"|"south"|"west" typealias Direction = "north"|"east"|"south"|"west"
""" """
.trimIndent(), .trimIndent(),
JavaCodeGeneratorOptions(implementSerializable = true) JavaCodeGeneratorOptions(implementSerializable = true),
) )
assertThat(javaCode) assertThat(javaCode)
@@ -1821,7 +1821,7 @@ class JavaCodeGeneratorTest {
smallStruct, smallStruct,
Pattern.compile("(i?)\\w*"), Pattern.compile("(i?)\\w*"),
smallStruct, smallStruct,
enumValue enumValue,
) )
fun confirmSerDe(instance: Any) { fun confirmSerDe(instance: Any) {
@@ -1863,7 +1863,7 @@ class JavaCodeGeneratorTest {
abstract class Foo { str: String } abstract class Foo { str: String }
""" """
.trimIndent(), .trimIndent(),
JavaCodeGeneratorOptions(implementSerializable = true) JavaCodeGeneratorOptions(implementSerializable = true),
) )
assertThat(javaCode).doesNotContain("Serializable") assertThat(javaCode).doesNotContain("Serializable")
@@ -1874,7 +1874,7 @@ class JavaCodeGeneratorTest {
module my.mod module my.mod
""" """
.trimIndent(), .trimIndent(),
JavaCodeGeneratorOptions(implementSerializable = true) JavaCodeGeneratorOptions(implementSerializable = true),
) )
assertThat(javaCode).doesNotContain("Serializable") assertThat(javaCode).doesNotContain("Serializable")
@@ -1891,7 +1891,7 @@ class JavaCodeGeneratorTest {
class Address { city: String } class Address { city: String }
""" """
.trimIndent(), .trimIndent(),
JavaCodeGeneratorOptions(implementSerializable = true) JavaCodeGeneratorOptions(implementSerializable = true),
) )
assertThat(javaCode) assertThat(javaCode)
@@ -1977,7 +1977,7 @@ class JavaCodeGeneratorTest {
} }
""" """
.trimIndent(), .trimIndent(),
JavaCodeGeneratorOptions(generateGetters = true) JavaCodeGeneratorOptions(generateGetters = true),
) )
assertThat(javaCode) assertThat(javaCode)
@@ -2021,7 +2021,7 @@ class JavaCodeGeneratorTest {
bar: Int = 123 bar: Int = 123
""" """
.trimIndent() .trimIndent(),
) )
.toMutableMap() .toMutableMap()
@@ -2064,7 +2064,7 @@ class JavaCodeGeneratorTest {
baz: String baz: String
""" """
.trimIndent() .trimIndent(),
) )
files.validateContents( files.validateContents(
@@ -2090,7 +2090,7 @@ class JavaCodeGeneratorTest {
mapOf( mapOf(
"org.foo." to "com.foo.x.", "org.foo." to "com.foo.x.",
"org.bar.Module2" to "org.bar.RenamedModule", "org.bar.Module2" to "org.bar.RenamedModule",
"org.baz." to "com.baz.a.b." "org.baz." to "com.baz.a.b.",
) )
) )
.generateFiles( .generateFiles(
@@ -2125,7 +2125,7 @@ class JavaCodeGeneratorTest {
owner: Module2.Group owner: Module2.Group
} }
""" """
.trimIndent() .trimIndent(),
) )
files.validateContents( files.validateContents(
@@ -2141,7 +2141,7 @@ class JavaCodeGeneratorTest {
"package org.bar;", "package org.bar;",
"import com.foo.x.Module1;", "import com.foo.x.Module1;",
"public final class RenamedModule {", "public final class RenamedModule {",
"public final Module1. @NonNull Person owner;" "public final Module1. @NonNull Person owner;",
), ),
"$MAPPER_PREFIX/org.bar.Module2.properties" to "$MAPPER_PREFIX/org.bar.Module2.properties" to
listOf( listOf(
@@ -2154,7 +2154,7 @@ class JavaCodeGeneratorTest {
"package com.baz.a.b;", "package com.baz.a.b;",
"import org.bar.RenamedModule;", "import org.bar.RenamedModule;",
"public final class Module3 {", "public final class Module3 {",
"public final RenamedModule. @NonNull Group owner;" "public final RenamedModule. @NonNull Group owner;",
), ),
"$MAPPER_PREFIX/org.baz.Module3.properties" to "$MAPPER_PREFIX/org.baz.Module3.properties" to
listOf( listOf(
@@ -2184,7 +2184,7 @@ class JavaCodeGeneratorTest {
bar: Int = 123 bar: Int = 123
""" """
.trimIndent() .trimIndent(),
) )
files.validateContents( files.validateContents(
@@ -2312,7 +2312,7 @@ class JavaCodeGeneratorTest {
Pattern.compile("(i?)\\w*"), Pattern.compile("(i?)\\w*"),
other, other,
other, other,
enumValue enumValue,
) )
return other to propertyTypes return other to propertyTypes
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -45,7 +45,7 @@ data class CliKotlinCodeGeneratorOptions(
* from Pkl module names, you can define a rename mapping, where the key is a prefix of the * from Pkl module names, you can define a rename mapping, where the key is a prefix of the
* original Pkl module name, and the value is the desired replacement. * original Pkl module name, and the value is the desired replacement.
*/ */
val renames: Map<String, String> = emptyMap() val renames: Map<String, String> = emptyMap(),
) { ) {
@Suppress("DeprecatedCallableAddReplaceWith") @Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("deprecated without replacement") @Deprecated("deprecated without replacement")
@@ -57,6 +57,6 @@ data class CliKotlinCodeGeneratorOptions(
generateKdoc, generateKdoc,
generateSpringBootConfig, generateSpringBootConfig,
implementSerializable, implementSerializable,
renames renames,
) )
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -37,7 +37,7 @@ class CliKotlinCodeGeneratorTest {
name: String name: String
age: Int age: Int
} }
""" """,
) )
val module2 = val module2 =
@@ -49,7 +49,7 @@ class CliKotlinCodeGeneratorTest {
extends "mod1.pkl" extends "mod1.pkl"
parrot: Person parrot: Person
""" """,
) )
val module1File = module1.writeToDisk(tempDir.resolve("org/mod1.pkl")) val module1File = module1.writeToDisk(tempDir.resolve("org/mod1.pkl"))
@@ -60,7 +60,7 @@ class CliKotlinCodeGeneratorTest {
CliKotlinCodeGenerator( CliKotlinCodeGenerator(
CliKotlinCodeGeneratorOptions( CliKotlinCodeGeneratorOptions(
CliBaseOptions(listOf(module1File.toUri(), module2File.toUri())), CliBaseOptions(listOf(module1File.toUri(), module2File.toUri())),
outputDir outputDir,
) )
) )
@@ -79,7 +79,7 @@ class CliKotlinCodeGeneratorTest {
) { ) {
""" """
.trimIndent(), .trimIndent(),
module1KotlinFile.readString() module1KotlinFile.readString(),
) )
assertContains( assertContains(
@@ -90,7 +90,7 @@ class CliKotlinCodeGeneratorTest {
) : Mod1(pigeon) { ) : Mod1(pigeon) {
""" """
.trimIndent(), .trimIndent(),
module2KotlinFile.readString() module2KotlinFile.readString(),
) )
} }
@@ -105,7 +105,7 @@ class CliKotlinCodeGeneratorTest {
class Person { class Person {
name: String name: String
} }
""" """,
) )
val module2 = val module2 =
@@ -122,7 +122,7 @@ class CliKotlinCodeGeneratorTest {
class Person { class Person {
age: Int age: Int
} }
""" """,
) )
val module1PklFile = module1.writeToDisk(tempDir.resolve("org/mod1.pkl")) val module1PklFile = module1.writeToDisk(tempDir.resolve("org/mod1.pkl"))
@@ -133,7 +133,7 @@ class CliKotlinCodeGeneratorTest {
CliKotlinCodeGenerator( CliKotlinCodeGenerator(
CliKotlinCodeGeneratorOptions( CliKotlinCodeGeneratorOptions(
CliBaseOptions(listOf(module1PklFile.toUri(), module2PklFile.toUri())), CliBaseOptions(listOf(module1PklFile.toUri(), module2PklFile.toUri())),
outputDir outputDir,
) )
) )
@@ -148,7 +148,7 @@ class CliKotlinCodeGeneratorTest {
) )
""" """
.trimIndent(), .trimIndent(),
module2KotlinFile.readString() module2KotlinFile.readString(),
) )
} }
@@ -163,7 +163,7 @@ class CliKotlinCodeGeneratorTest {
class Person { class Person {
name: String name: String
} }
""" """,
) )
val module2 = val module2 =
@@ -178,7 +178,7 @@ class CliKotlinCodeGeneratorTest {
owner: Module1.Person owner: Module1.Person
name: String name: String
} }
""" """,
) )
val module3 = val module3 =
@@ -192,7 +192,7 @@ class CliKotlinCodeGeneratorTest {
class Supergroup { class Supergroup {
owner: Module2.Group owner: Module2.Group
} }
""" """,
) )
val module1PklFile = module1.writeToDisk(tempDir.resolve("org/foo/Module1.pkl")) val module1PklFile = module1.writeToDisk(tempDir.resolve("org/foo/Module1.pkl"))
@@ -205,7 +205,7 @@ class CliKotlinCodeGeneratorTest {
CliKotlinCodeGeneratorOptions( CliKotlinCodeGeneratorOptions(
CliBaseOptions(listOf(module1PklFile, module2PklFile, module3PklFile).map { it.toUri() }), CliBaseOptions(listOf(module1PklFile, module2PklFile, module3PklFile).map { it.toUri() }),
outputDir, outputDir,
renames = mapOf("org.foo" to "com.foo.x", "org.baz" to "com.baz.a.b") renames = mapOf("org.foo" to "com.foo.x", "org.baz" to "com.baz.a.b"),
) )
) )
@@ -223,7 +223,7 @@ class CliKotlinCodeGeneratorTest {
| val name: String | val name: String
| ) | )
""", """,
it it,
) )
} }
@@ -242,7 +242,7 @@ class CliKotlinCodeGeneratorTest {
| val name: String | val name: String
| ) | )
""", """,
it it,
) )
} }
@@ -260,7 +260,7 @@ class CliKotlinCodeGeneratorTest {
| val owner: Module2.Group | val owner: Module2.Group
| ) | )
""", """,
it it,
) )
} }
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -27,7 +27,7 @@ open class CliException(
message: String, message: String,
/** The process exit code to use. */ /** The process exit code to use. */
val exitCode: Int = 1 val exitCode: Int = 1,
) : RuntimeException(message) { ) : RuntimeException(message) {
override fun toString(): String = message!! override fun toString(): String = message!!
@@ -39,7 +39,7 @@ class CliBugException(
private val theCause: Exception, private val theCause: Exception,
/** The process exit code to use. */ /** The process exit code to use. */
exitCode: Int = 1 exitCode: Int = 1,
) : ) :
CliException("An unexpected error has occurred. Would you mind filing a bug report?", exitCode) { CliException("An unexpected error has occurred. Would you mind filing a bug report?", exitCode) {
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -36,7 +36,7 @@ fun <EachT : Any, ValueT> NullableOption<EachT, ValueT>.single(): NullableOption
*/ */
fun <EachT : Any, ValueT> NullableOption<EachT, ValueT>.splitAll( fun <EachT : Any, ValueT> NullableOption<EachT, ValueT>.splitAll(
separator: String = ",", separator: String = ",",
default: List<ValueT> = emptyList() default: List<ValueT> = emptyList(),
): OptionWithValues<List<ValueT>, List<ValueT>, ValueT> { ): OptionWithValues<List<ValueT>, List<ValueT>, ValueT> {
return copy( return copy(
transformValue = transformValue, transformValue = transformValue,
@@ -44,6 +44,6 @@ fun <EachT : Any, ValueT> NullableOption<EachT, ValueT>.splitAll(
transformAll = { it.flatten().ifEmpty { default } }, transformAll = { it.flatten().ifEmpty { default } },
validator = {}, validator = {},
nvalues = 1, nvalues = 1,
valueSplit = Regex.fromLiteral(separator) valueSplit = Regex.fromLiteral(separator),
) )
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -31,7 +31,7 @@ class ProjectOptions : OptionGroup() {
names = arrayOf("--project-dir"), names = arrayOf("--project-dir"),
metavar = "<path>", metavar = "<path>",
help = help =
"The project directory to use for this command. By default, searches up from the working directory for a PklProject file." "The project directory to use for this command. By default, searches up from the working directory for a PklProject file.",
) )
.single() .single()
.path() .path()
@@ -39,7 +39,7 @@ class ProjectOptions : OptionGroup() {
val omitProjectSettings: Boolean by val omitProjectSettings: Boolean by
option( option(
names = arrayOf("--omit-project-settings"), names = arrayOf("--omit-project-settings"),
help = "Ignores evaluator settings set in the PklProject file." help = "Ignores evaluator settings set in the PklProject file.",
) )
.single() .single()
.flag(default = false) .flag(default = false)
@@ -47,7 +47,7 @@ class ProjectOptions : OptionGroup() {
val noProject: Boolean by val noProject: Boolean by
option( option(
names = arrayOf("--no-project"), names = arrayOf("--no-project"),
help = "Disables loading settings and dependencies from the PklProject file." help = "Disables loading settings and dependencies from the PklProject file.",
) )
.single() .single()
.flag(default = false) .flag(default = false)
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -27,7 +27,7 @@ class TestOptions : OptionGroup() {
option( option(
names = arrayOf("--junit-reports"), names = arrayOf("--junit-reports"),
metavar = "<dir>", metavar = "<dir>",
help = "Directory where to store JUnit reports." help = "Directory where to store JUnit reports.",
) )
.path() .path()
+3 -3
View File
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -107,7 +107,7 @@ val generateKeys by
"-storepass", "-storepass",
"password", "password",
"-dname", "-dname",
"CN=localhost" "CN=localhost",
) )
workingDir(keystoreDir) workingDir(keystoreDir)
doFirst { doFirst {
@@ -134,7 +134,7 @@ val exportCerts by
keystoreName, keystoreName,
"-rfc", "-rfc",
"-file", "-file",
certsFileName certsFileName,
) )
workingDir(keystoreDir) workingDir(keystoreDir)
doFirst { doFirst {
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -43,14 +43,7 @@ class NameMapperTest {
@Test @Test
fun `no implicit uppercased classname if explicitly renamed`() { fun `no implicit uppercased classname if explicitly renamed`() {
val mapper = val mapper = NameMapper(mapOf("foo.bar" to "bar.bar", "foo.c" to "foo.z", "com.foo." to "x"))
NameMapper(
mapOf(
"foo.bar" to "bar.bar",
"foo.c" to "foo.z",
"com.foo." to "x",
)
)
assertThat(mapper.map("foo.bar")).isEqualTo("bar" to "bar") assertThat(mapper.map("foo.bar")).isEqualTo("bar" to "bar")
assertThat(mapper.map("foo.bar")).isEqualTo("bar" to "bar") assertThat(mapper.map("foo.bar")).isEqualTo("bar" to "bar")
assertThat(mapper.map("foo.cow")).isEqualTo("foo" to "zow") assertThat(mapper.map("foo.cow")).isEqualTo("foo" to "zow")
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -84,7 +84,7 @@ object KotlinConversions {
pIntToUShort, pIntToUShort,
pIntToUByte, pIntToUByte,
pStringToKotlinRegex, pStringToKotlinRegex,
pRegexToKotlinRegex pRegexToKotlinRegex,
) )
) )
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -44,7 +44,7 @@ internal class PPairToKotlinPair : ConverterFactory {
private class ConverterImpl<F, S>( private class ConverterImpl<F, S>(
private val firstTargetType: Type, private val firstTargetType: Type,
private val secondTargetType: Type private val secondTargetType: Type,
) : Converter<PPair<Any, Any>, Pair<F, S>> { ) : Converter<PPair<Any, Any>, Pair<F, S>> {
private var firstCachedType = PClassInfo.Unavailable private var firstCachedType = PClassInfo.Unavailable
@@ -68,7 +68,7 @@ internal class PPairToKotlinPair : ConverterFactory {
return Pair( return Pair(
firstCachedConverter!!.convert(first, valueMapper), firstCachedConverter!!.convert(first, valueMapper),
secondCachedConverter!!.convert(second, valueMapper) secondCachedConverter!!.convert(second, valueMapper),
) )
} }
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -54,7 +54,7 @@ class KotlinObjectMappingTest {
// Map & Mapping with structured keys // Map & Mapping with structured keys
val intListingStringMapping: Map<List<Int>, String>, val intListingStringMapping: Map<List<Int>, String>,
val intSetListStringMapping: Map<List<Set<Int>>, String>, val intSetListStringMapping: Map<List<Set<Int>>, String>,
val thisOneGoesToEleven: Map<List<Set<Int>>, Map<List<Int>, Map<Int, String>>> val thisOneGoesToEleven: Map<List<Set<Int>>, Map<List<Int>, Map<Int, String>>>,
) )
@Test @Test
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -49,7 +49,7 @@ class PPairToKotlinPairTest {
val mapped: Pair<Int, Duration> = val mapped: Pair<Int, Duration> =
mapper.map( mapper.map(
ex1, ex1,
Types.parameterizedType(Pair::class.java, Integer::class.java, Duration::class.java) Types.parameterizedType(Pair::class.java, Integer::class.java, Duration::class.java),
) )
assertThat(mapped).isEqualTo(Pair(1, Duration(3.0, DurationUnit.SECONDS))) assertThat(mapped).isEqualTo(Pair(1, Duration(3.0, DurationUnit.SECONDS)))
} }
@@ -60,7 +60,7 @@ class PPairToKotlinPairTest {
val mapped: Pair<PObject, PObject> = val mapped: Pair<PObject, PObject> =
mapper.map( mapper.map(
ex2, ex2,
Types.parameterizedType(Pair::class.java, PObject::class.java, PObject::class.java) Types.parameterizedType(Pair::class.java, PObject::class.java, PObject::class.java),
) )
assertThat(mapped.first.properties).containsOnly(entry("name", "pigeon"), entry("age", 40L)) assertThat(mapped.first.properties).containsOnly(entry("name", "pigeon"), entry("age", 40L))
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -80,7 +80,7 @@ class MemberRegistryGenerator : AbstractProcessor() {
if (it.enclosingElement.kind == ElementKind.PACKAGE) "" if (it.enclosingElement.kind == ElementKind.PACKAGE) ""
else it.enclosingElement.simpleName.toString() else it.enclosingElement.simpleName.toString()
}, },
{ it.simpleName.toString() } { it.simpleName.toString() },
) )
) )
.groupBy { processingEnv.elementUtils.getPackageOf(it) } .groupBy { processingEnv.elementUtils.getPackageOf(it) }
@@ -126,7 +126,7 @@ class MemberRegistryGenerator : AbstractProcessor() {
registryClassConstructor.addStatement( registryClassConstructor.addStatement(
"register(\$S, \$T::create)", "register(\$S, \$T::create)",
pklMemberNameQualified, pklMemberNameQualified,
nodeClass nodeClass,
) )
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -118,14 +118,14 @@ public final class CodeGeneratorUtils {
*/ */
private static boolean isValidIdentifierPart(int codePoint, int category) { private static boolean isValidIdentifierPart(int codePoint, int category) {
return switch (category) { return switch (category) {
// NOT Character.CURRENCY_SYMBOL, which is valid in Java, but invalid in Kotlin // NOT Character.CURRENCY_SYMBOL, which is valid in Java, but invalid in Kotlin
case Character.LOWERCASE_LETTER, case Character.LOWERCASE_LETTER,
Character.UPPERCASE_LETTER, Character.UPPERCASE_LETTER,
Character.MODIFIER_LETTER, Character.MODIFIER_LETTER,
Character.OTHER_LETTER, Character.OTHER_LETTER,
Character.TITLECASE_LETTER, Character.TITLECASE_LETTER,
Character.LETTER_NUMBER, Character.LETTER_NUMBER,
Character.DECIMAL_DIGIT_NUMBER -> Character.DECIMAL_DIGIT_NUMBER ->
true; true;
default -> codePoint == UNDERSCORE; default -> codePoint == UNDERSCORE;
}; };
@@ -133,18 +133,18 @@ public final class CodeGeneratorUtils {
private static boolean isPunctuationOrSpacing(int category) { private static boolean isPunctuationOrSpacing(int category) {
return switch (category) { return switch (category) {
// Punctuation // Punctuation
case Character.CONNECTOR_PUNCTUATION, // Pc case Character.CONNECTOR_PUNCTUATION, // Pc
Character.DASH_PUNCTUATION, // Pd Character.DASH_PUNCTUATION, // Pd
Character.START_PUNCTUATION, // Ps Character.START_PUNCTUATION, // Ps
Character.END_PUNCTUATION, // Pe Character.END_PUNCTUATION, // Pe
Character.INITIAL_QUOTE_PUNCTUATION, // Pi Character.INITIAL_QUOTE_PUNCTUATION, // Pi
Character.FINAL_QUOTE_PUNCTUATION, // Pf Character.FINAL_QUOTE_PUNCTUATION, // Pf
Character.OTHER_PUNCTUATION, // Po Character.OTHER_PUNCTUATION, // Po
// Spacing // Spacing
Character.SPACE_SEPARATOR, // Zs Character.SPACE_SEPARATOR, // Zs
Character.LINE_SEPARATOR, // Zl Character.LINE_SEPARATOR, // Zl
Character.PARAGRAPH_SEPARATOR -> // Zp Character.PARAGRAPH_SEPARATOR -> // Zp
true; true;
default -> false; default -> false;
}; };
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -227,7 +227,7 @@ public final class GlobResolver {
sb.append("!"); sb.append("!");
} }
// no special meaning in glob patterns but have special meaning in regex. // no special meaning in glob patterns but have special meaning in regex.
case '.', '(', '%', '^', '$', '|' -> sb.append("\\").append(current); case '.', '(', '%', '^', '$', '|' -> sb.append("\\").append(current);
default -> sb.append(current); default -> sb.append(current);
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -611,27 +611,27 @@ public final class IoUtils {
public static boolean isHexDigit(char ch) { public static boolean isHexDigit(char ch) {
return switch (ch) { return switch (ch) {
case '0', case '0',
'1', '1',
'2', '2',
'3', '3',
'4', '4',
'5', '5',
'6', '6',
'7', '7',
'8', '8',
'9', '9',
'A', 'A',
'B', 'B',
'C', 'C',
'D', 'D',
'E', 'E',
'F', 'F',
'a', 'a',
'b', 'b',
'c', 'c',
'd', 'd',
'e', 'e',
'f' -> 'f' ->
true; true;
default -> false; default -> false;
}; };
@@ -640,28 +640,28 @@ public final class IoUtils {
public static boolean isHexDigitOrUnderscore(char ch) { public static boolean isHexDigitOrUnderscore(char ch) {
return switch (ch) { return switch (ch) {
case '0', case '0',
'1', '1',
'2', '2',
'3', '3',
'4', '4',
'5', '5',
'6', '6',
'7', '7',
'8', '8',
'9', '9',
'A', 'A',
'B', 'B',
'C', 'C',
'D', 'D',
'E', 'E',
'F', 'F',
'a', 'a',
'b', 'b',
'c', 'c',
'd', 'd',
'e', 'e',
'f', 'f',
'_' -> '_' ->
true; true;
default -> false; default -> false;
}; };
@@ -751,46 +751,46 @@ public final class IoUtils {
public static boolean isReservedWindowsFilenameChar(char character) { public static boolean isReservedWindowsFilenameChar(char character) {
return switch (character) { return switch (character) {
case 0, case 0,
1, 1,
2, 2,
3, 3,
4, 4,
5, 5,
6, 6,
7, 7,
8, 8,
9, 9,
10, 10,
11, 11,
12, 12,
13, 13,
14, 14,
15, 15,
16, 16,
17, 17,
18, 18,
19, 19,
20, 20,
21, 21,
22, 22,
23, 23,
24, 24,
25, 25,
26, 26,
27, 27,
28, 28,
29, 29,
30, 30,
31, 31,
'<', '<',
'>', '>',
':', ':',
'"', '"',
'\\', '\\',
'/', '/',
'|', '|',
'?', '?',
'*' -> '*' ->
true; true;
default -> false; default -> false;
}; };
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -563,7 +563,7 @@ public final class JsonWriter implements Closeable, Flushable {
if (!lenient) { if (!lenient) {
throw new IllegalStateException("JSON must have only one top-level value."); throw new IllegalStateException("JSON must have only one top-level value.");
} }
// fall-through // fall-through
case EMPTY_DOCUMENT: // first in document case EMPTY_DOCUMENT: // first in document
replaceTop(NONEMPTY_DOCUMENT); replaceTop(NONEMPTY_DOCUMENT);
break; break;
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -29,28 +29,28 @@ public final class Yaml12Emitter extends YamlEmitter {
return switch (str) { return switch (str) {
case "", case "",
"~", "~",
"null", "null",
"Null", "Null",
"NULL", "NULL",
".nan", ".nan",
".NaN", ".NaN",
".NAN", ".NAN",
".inf", ".inf",
".Inf", ".Inf",
".INF", ".INF",
"+.inf", "+.inf",
"+.Inf", "+.Inf",
"+.INF", "+.INF",
"-.inf", "-.inf",
"-.Inf", "-.Inf",
"-.INF", "-.INF",
"true", "true",
"True", "True",
"TRUE", "TRUE",
"false", "false",
"False", "False",
"FALSE" -> "FALSE" ->
true; true;
default -> false; default -> false;
}; };
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -137,7 +137,7 @@ public abstract class YamlEmitter {
needsQuoting = needsQuoting =
needsQuoting || i == (length - 1) || (i + 1 < length) && str.charAt(i + 1) == ' '; needsQuoting || i == (length - 1) || (i + 1 < length) && str.charAt(i + 1) == ' ';
} }
// number chars // number chars
case '0', case '0',
'1', '1',
'2', '2',
@@ -228,44 +228,44 @@ public abstract class YamlEmitter {
return switch (str) { return switch (str) {
case "", case "",
"~", "~",
"null", "null",
"Null", "Null",
"NULL", "NULL",
".nan", ".nan",
".NaN", ".NaN",
".NAN", ".NAN",
".inf", ".inf",
".Inf", ".Inf",
".INF", ".INF",
"+.inf", "+.inf",
"+.Inf", "+.Inf",
"+.INF", "+.INF",
"-.inf", "-.inf",
"-.Inf", "-.Inf",
"-.INF", "-.INF",
"true", "true",
"True", "True",
"TRUE", "TRUE",
"false", "false",
"False", "False",
"FALSE", "FALSE",
"on", "on",
"On", "On",
"ON", "ON",
"off", "off",
"Off", "Off",
"OFF", "OFF",
"y", "y",
"Y", "Y",
"yes", "yes",
"Yes", "Yes",
"YES", "YES",
"n", "n",
"N", "N",
"no", "no",
"No", "No",
"NO" -> "NO" ->
true; true;
default -> false; default -> false;
}; };
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -47,7 +47,7 @@ class EvaluateTestsTest {
""" """
.trimIndent() .trimIndent()
), ),
true true,
) )
assertThat(results.moduleName).isEqualTo("text") assertThat(results.moduleName).isEqualTo("text")
@@ -75,7 +75,7 @@ class EvaluateTestsTest {
""" """
.trimIndent() .trimIndent()
), ),
true true,
) )
assertThat(results.totalTests()).isEqualTo(1) assertThat(results.totalTests()).isEqualTo(1)
@@ -111,7 +111,7 @@ class EvaluateTestsTest {
""" """
.trimIndent() .trimIndent()
), ),
true true,
) )
assertThat(results.totalTests()).isEqualTo(1) assertThat(results.totalTests()).isEqualTo(1)
@@ -157,7 +157,7 @@ class EvaluateTestsTest {
} }
} }
""" """
.trimIndent() .trimIndent(),
) )
Files.writeString( Files.writeString(
@@ -172,7 +172,7 @@ class EvaluateTestsTest {
} }
} }
""" """
.trimIndent() .trimIndent(),
) )
val results = evaluator.evaluateTest(path(file), false) val results = evaluator.evaluateTest(path(file), false)
@@ -207,7 +207,7 @@ class EvaluateTestsTest {
} }
} }
""" """
.trimIndent() .trimIndent(),
) )
Files.writeString( Files.writeString(
@@ -222,7 +222,7 @@ class EvaluateTestsTest {
} }
} }
""" """
.trimIndent() .trimIndent(),
) )
val results = evaluator.evaluateTest(path(file), false) val results = evaluator.evaluateTest(path(file), false)
@@ -260,7 +260,7 @@ class EvaluateTestsTest {
} }
} }
""" """
.trimIndent() .trimIndent(),
) )
Files.writeString( Files.writeString(
@@ -275,7 +275,7 @@ class EvaluateTestsTest {
} }
} }
""" """
.trimIndent() .trimIndent(),
) )
val results = evaluator.evaluateTest(path(file), false) val results = evaluator.evaluateTest(path(file), false)
@@ -314,7 +314,7 @@ class EvaluateTestsTest {
} }
} }
""" """
.trimIndent() .trimIndent(),
) )
Files.writeString( Files.writeString(
@@ -329,7 +329,7 @@ class EvaluateTestsTest {
} }
} }
""" """
.trimIndent() .trimIndent(),
) )
val results = evaluator.evaluateTest(path(file), false) val results = evaluator.evaluateTest(path(file), false)
@@ -377,7 +377,7 @@ class EvaluateTestsTest {
} }
} }
""" """
.trimIndent() .trimIndent(),
) )
evaluator.evaluateTest(path(file), false) evaluator.evaluateTest(path(file), false)
val expectedFile = file.parent.resolve(file.fileName.toString() + "-expected.pcf") val expectedFile = file.parent.resolve(file.fileName.toString() + "-expected.pcf")
@@ -411,7 +411,7 @@ class EvaluateTestsTest {
} }
} }
""" """
.trimIndent() .trimIndent(),
) )
createExpected(file) createExpected(file)
.writeString( .writeString(
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -128,7 +128,7 @@ class PModuleTest {
moduleUri, moduleUri,
moduleName, moduleName,
classInfo, classInfo,
mapOf("name" to "Pigeon", "age" to 42, "other" to true) mapOf("name" to "Pigeon", "age" to 42, "other" to true),
) )
assertThat(pigeon2).isNotEqualTo(pigeon) assertThat(pigeon2).isNotEqualTo(pigeon)
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -106,7 +106,7 @@ class PObjectTest {
val pigeon2 = val pigeon2 =
PObject( PObject(
PClassInfo.get("test", "Person", URI("repl:test")), PClassInfo.get("test", "Person", URI("repl:test")),
mapOf("name" to "Pigeon", "age" to 21) mapOf("name" to "Pigeon", "age" to 21),
) )
assertThat(pigeon2).isNotEqualTo(pigeon) assertThat(pigeon2).isNotEqualTo(pigeon)
@@ -127,7 +127,7 @@ class PObjectTest {
val pigeon2 = val pigeon2 =
PObject( PObject(
PClassInfo.get("test", "Person", URI("repl:test")), PClassInfo.get("test", "Person", URI("repl:test")),
mapOf("name" to "Pigeon", "age" to 42, "other" to true) mapOf("name" to "Pigeon", "age" to 42, "other" to true),
) )
assertThat(pigeon2).isNotEqualTo(pigeon) assertThat(pigeon2).isNotEqualTo(pigeon)
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -73,7 +73,7 @@ class PcfRendererTest {
grault = Map("garply", null, "waldo", 42, "pigeon", null) grault = Map("garply", null, "waldo", 42, "pigeon", null)
} }
""" """
.trimIndent() .trimIndent(),
) )
val module = val module =
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -48,7 +48,7 @@ class PropertiesRendererTest {
"new Mapping {}", "new Mapping {}",
"Set()", "Set()",
"new PropertiesRenderer {}", "new PropertiesRenderer {}",
"new Dynamic {}" "new Dynamic {}",
) )
unsupportedValues.forEach { unsupportedValues.forEach {
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -34,7 +34,7 @@ class ReplServerTest {
listOf( listOf(
ModuleKeyFactories.standardLibrary, ModuleKeyFactories.standardLibrary,
ModuleKeyFactories.classPath(this::class.java.classLoader), ModuleKeyFactories.classPath(this::class.java.classLoader),
ModuleKeyFactories.file ModuleKeyFactories.file,
), ),
listOf(ResourceReaders.environmentVariable(), ResourceReaders.externalProperty()), listOf(ResourceReaders.environmentVariable(), ResourceReaders.externalProperty()),
mapOf("NAME1" to "value1", "NAME2" to "value2"), mapOf("NAME1" to "value1", "NAME2" to "value2"),
@@ -72,7 +72,7 @@ class ReplServerTest {
"length()", "length()",
"getClass()", "getClass()",
"toString()", "toString()",
"toTyped(" "toTyped(",
) )
) )
} }
@@ -121,7 +121,7 @@ class ReplServerTest {
"getPropertyOrNull(", "getPropertyOrNull(",
"hasProperty(", "hasProperty(",
"relativePathTo(", "relativePathTo(",
"toString()" "toString()",
) )
) )
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -32,7 +32,7 @@ class SecurityManagersTest {
listOf(Pattern.compile("test:foo/bar")), listOf(Pattern.compile("test:foo/bar")),
listOf(Pattern.compile("env:FOO_BAR")), listOf(Pattern.compile("env:FOO_BAR")),
{ uri -> if (uri.scheme == "one") 1 else if (uri.scheme == "two") 2 else 0 }, { uri -> if (uri.scheme == "one") 1 else if (uri.scheme == "two") 2 else 0 },
null null,
) )
@Test @Test
@@ -142,7 +142,7 @@ class SecurityManagersTest {
listOf(Pattern.compile("file")), listOf(Pattern.compile("file")),
listOf(Pattern.compile("file")), listOf(Pattern.compile("file")),
SecurityManagers.defaultTrustLevels, SecurityManagers.defaultTrustLevels,
rootDir rootDir,
) )
val path = rootDir.resolve("baz.pkl") val path = rootDir.resolve("baz.pkl")
@@ -163,7 +163,7 @@ class SecurityManagersTest {
listOf(Pattern.compile("file")), listOf(Pattern.compile("file")),
listOf(Pattern.compile("file")), listOf(Pattern.compile("file")),
SecurityManagers.defaultTrustLevels, SecurityManagers.defaultTrustLevels,
rootDir rootDir,
) )
manager.checkResolveModule(Path.of("/foo/bar/baz.pkl").toUri()) manager.checkResolveModule(Path.of("/foo/bar/baz.pkl").toUri())
@@ -185,7 +185,7 @@ class SecurityManagersTest {
listOf(Pattern.compile("file")), listOf(Pattern.compile("file")),
listOf(Pattern.compile("file")), listOf(Pattern.compile("file")),
SecurityManagers.defaultTrustLevels, SecurityManagers.defaultTrustLevels,
rootDir rootDir,
) )
val path = rootDir.resolve("../baz.pkl") val path = rootDir.resolve("../baz.pkl")
@@ -210,7 +210,7 @@ class SecurityManagersTest {
listOf(Pattern.compile("file")), listOf(Pattern.compile("file")),
listOf(Pattern.compile("file")), listOf(Pattern.compile("file")),
SecurityManagers.defaultTrustLevels, SecurityManagers.defaultTrustLevels,
rootDir rootDir,
) )
assertThrows<SecurityManagerException> { assertThrows<SecurityManagerException> {
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -27,7 +27,7 @@ import org.pkl.core.util.Nullable
class ExternalReaderRuntime( class ExternalReaderRuntime(
private val moduleReaders: List<ExternalModuleReader>, private val moduleReaders: List<ExternalModuleReader>,
private val resourceReaders: List<ExternalResourceReader>, private val resourceReaders: List<ExternalResourceReader>,
private val transport: MessageTransport private val transport: MessageTransport,
) { ) {
/** Close the runtime and its transport. */ /** Close the runtime and its transport. */
fun close() { fun close() {
@@ -96,7 +96,7 @@ class ExternalReaderRuntime(
req.requestId, req.requestId,
req.evaluatorId, req.evaluatorId,
null, null,
"No module reader found for scheme " + req.uri.scheme "No module reader found for scheme " + req.uri.scheme,
) )
) )
return@start return@start
@@ -107,7 +107,7 @@ class ExternalReaderRuntime(
req.requestId, req.requestId,
req.evaluatorId, req.evaluatorId,
reader.listElements(req.uri), reader.listElements(req.uri),
null null,
) )
) )
} catch (e: Exception) { } catch (e: Exception) {
@@ -125,7 +125,7 @@ class ExternalReaderRuntime(
req.requestId, req.requestId,
req.evaluatorId, req.evaluatorId,
null, null,
"No resource reader found for scheme " + req.uri.scheme "No resource reader found for scheme " + req.uri.scheme,
) )
) )
return@start return@start
@@ -136,7 +136,7 @@ class ExternalReaderRuntime(
req.requestId, req.requestId,
req.evaluatorId, req.evaluatorId,
reader.listElements(req.uri), reader.listElements(req.uri),
null null,
) )
) )
} catch (e: Exception) { } catch (e: Exception) {
@@ -154,7 +154,7 @@ class ExternalReaderRuntime(
req.requestId, req.requestId,
req.evaluatorId, req.evaluatorId,
null, null,
"No module reader found for scheme " + req.uri.scheme "No module reader found for scheme " + req.uri.scheme,
) )
) )
return@start return@start
@@ -176,7 +176,7 @@ class ExternalReaderRuntime(
req.requestId, req.requestId,
req.evaluatorId, req.evaluatorId,
byteArrayOf(), byteArrayOf(),
"No resource reader found for scheme " + req.uri.scheme "No resource reader found for scheme " + req.uri.scheme,
) )
) )
return@start return@start
@@ -193,7 +193,7 @@ class ExternalReaderRuntime(
} }
else -> throw ProtocolException("Unexpected incoming request message: $msg") else -> throw ProtocolException("Unexpected incoming request message: $msg")
} }
} },
) )
} }
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -24,7 +24,7 @@ class RequestCapturingClient : HttpClient {
override fun <T : Any> send( override fun <T : Any> send(
request: HttpRequest, request: HttpRequest,
responseBodyHandler: HttpResponse.BodyHandler<T> responseBodyHandler: HttpResponse.BodyHandler<T>,
): HttpResponse<T> { ): HttpResponse<T> {
this.request = request this.request = request
return FakeHttpResponse() return FakeHttpResponse()
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -74,7 +74,7 @@ class BaseMessagePackCodecTest {
123, 123,
234, 234,
listOf(PathElement("foo", true), PathElement("bar", false)), listOf(PathElement("foo", true), PathElement("bar", false)),
null null,
) )
) )
roundtrip(ListModulesResponse(123, 234, null, "Something dun went wrong")) roundtrip(ListModulesResponse(123, 234, null, "Something dun went wrong"))
@@ -92,7 +92,7 @@ class BaseMessagePackCodecTest {
3851, 3851,
3019, 3019,
listOf(PathElement("foo", true), PathElement("bar", false)), listOf(PathElement("foo", true), PathElement("bar", false)),
null null,
) )
) )
roundtrip(ListResourcesResponse(3851, 3019, null, "something went wrong")) roundtrip(ListResourcesResponse(3851, 3019, null, "something went wrong"))
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -35,7 +35,7 @@ class ServiceProviderTest {
uri, uri,
"testFactoryTest", "testFactoryTest",
PClassInfo.forModuleClass("testFactoryTest", uri), PClassInfo.forModuleClass("testFactoryTest", uri),
mapOf("name" to "Pigeon", "age" to 40L) mapOf("name" to "Pigeon", "age" to 40L),
) )
) )
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -35,8 +35,8 @@ class DependencyMetadataTest {
"foo" to "foo" to
Dependency.RemoteDependency( Dependency.RemoteDependency(
PackageUri("package://example.com/foo@0.5.3"), PackageUri("package://example.com/foo@0.5.3"),
Checksums("abc123") Checksums("abc123"),
), )
), ),
"https://example.com/my/source/0.5.3/blob%{path}#L%{line}-L%{endLine}", "https://example.com/my/source/0.5.3/blob%{path}#L%{line}-L%{endLine}",
URI("https://example.com/my/source"), URI("https://example.com/my/source"),
@@ -62,9 +62,9 @@ class DependencyMetadataTest {
"map" to mapOf(true to "t", false to "f"), "map" to mapOf(true to "t", false to "f"),
"dataSize" to DataSize(1.5, DataSizeUnit.GIGABYTES), "dataSize" to DataSize(1.5, DataSizeUnit.GIGABYTES),
"duration" to Duration(2.9, DurationUnit.HOURS), "duration" to Duration(2.9, DurationUnit.HOURS),
"pair" to Pair(1L, "1") "pair" to Pair(1L, "1"),
) ),
) ),
), ),
) )
private val dependencyMetadataStr = private val dependencyMetadataStr =
@@ -204,7 +204,7 @@ class DependencyMetadataTest {
listOf( listOf(
PObject( PObject(
PClassInfo.get("myModule", "MyAnnotation", URI("pkl:fake")), PClassInfo.get("myModule", "MyAnnotation", URI("pkl:fake")),
mapOf("pattern" to Regex(".*").toPattern()) mapOf("pattern" to Regex(".*").toPattern()),
) )
), ),
) )
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -54,13 +54,13 @@ class ProjectDepsTest {
CanonicalPackageUri.of("package://localhost:0/birds@0"), CanonicalPackageUri.of("package://localhost:0/birds@0"),
Dependency.RemoteDependency( Dependency.RemoteDependency(
PackageUri.create("package://localhost:0/birds@0.5.0"), PackageUri.create("package://localhost:0/birds@0.5.0"),
Checksums("abc123") Checksums("abc123"),
), ),
CanonicalPackageUri.of("package://localhost:0/fruit@1"), CanonicalPackageUri.of("package://localhost:0/fruit@1"),
Dependency.LocalDependency( Dependency.LocalDependency(
PackageUri.create("package://localhost:0/fruit@1.1.0"), PackageUri.create("package://localhost:0/fruit@1.1.0"),
Path.of("../fruit") Path.of("../fruit"),
) ),
) )
ProjectDeps(projectDepsMap) ProjectDeps(projectDepsMap)
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -57,7 +57,7 @@ class ProjectTest {
.trimIndent(), .trimIndent(),
URI("https://example.com/my/issues"), URI("https://example.com/my/issues"),
listOf(Path.of("apiTest1.pkl"), Path.of("apiTest2.pkl")), listOf(Path.of("apiTest1.pkl"), Path.of("apiTest2.pkl")),
listOf("PklProject", "PklProject.deps.json", ".**", "*.exe") listOf("PklProject", "PklProject.deps.json", ".**", "*.exe"),
) )
val expectedSettings = val expectedSettings =
PklEvaluatorSettings( PklEvaluatorSettings(
@@ -73,13 +73,13 @@ class ProjectTest {
path, path,
null, null,
null, null,
null null,
) )
val expectedAnnotations = val expectedAnnotations =
listOf( listOf(
PObject( PObject(
PClassInfo.Deprecated, PClassInfo.Deprecated,
mapOf("since" to "1.2", "message" to "do not use", "replaceWith" to "somethingElse") mapOf("since" to "1.2", "message" to "do not use", "replaceWith" to "somethingElse"),
), ),
PObject(PClassInfo.Unlisted, mapOf()), PObject(PClassInfo.Unlisted, mapOf()),
PObject(PClassInfo.ModuleInfo, mapOf("minPklVersion" to "0.26.0")), PObject(PClassInfo.ModuleInfo, mapOf("minPklVersion" to "0.26.0")),
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -45,7 +45,7 @@ class PathSpecParserTest {
Identifier.get("prop3"), Identifier.get("prop3"),
Identifier.get("prop2"), Identifier.get("prop2"),
Identifier.get("prop1"), Identifier.get("prop1"),
TOP_LEVEL_VALUE TOP_LEVEL_VALUE,
) )
) )
@@ -98,7 +98,7 @@ class PathSpecParserTest {
"key2", "key2",
WILDCARD_PROPERTY, WILDCARD_PROPERTY,
"key1", "key1",
Identifier.get("prop1") Identifier.get("prop1"),
) )
) )
@@ -111,7 +111,7 @@ class PathSpecParserTest {
WILDCARD_PROPERTY, WILDCARD_PROPERTY,
"key1", "key1",
Identifier.get("prop1"), Identifier.get("prop1"),
TOP_LEVEL_VALUE TOP_LEVEL_VALUE,
) )
) )
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -36,7 +36,7 @@ class ReflectModuleTest {
"pkl:shell", "pkl:shell",
"pkl:test", "pkl:test",
"pkl:xml", "pkl:xml",
"pkl:yaml" "pkl:yaml",
] ]
) )
@ParameterizedTest(name = "can reflect on {0} module") @ParameterizedTest(name = "can reflect on {0} module")
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -35,9 +35,11 @@ class LongVsDoubleSpecializationTest {
fun addition() { fun addition() {
val result = val result =
evaluator.evaluate( evaluator.evaluate(
ModuleSource.text(""" ModuleSource.text(
"""
x1 = Pair(1.0 + 2.0, 1 + 2).second x1 = Pair(1.0 + 2.0, 1 + 2).second
""") """
)
) )
assertThat(result.properties["x1"]).isEqualTo(3L) assertThat(result.properties["x1"]).isEqualTo(3L)
@@ -47,9 +49,11 @@ class LongVsDoubleSpecializationTest {
fun subtraction() { fun subtraction() {
val result = val result =
evaluator.evaluate( evaluator.evaluate(
ModuleSource.text(""" ModuleSource.text(
"""
x1 = Pair(1.0 - 2.0, 1 - 2).second x1 = Pair(1.0 - 2.0, 1 - 2).second
""") """
)
) )
assertThat(result.properties["x1"]).isEqualTo(-1L) assertThat(result.properties["x1"]).isEqualTo(-1L)
@@ -59,9 +63,11 @@ class LongVsDoubleSpecializationTest {
fun multiplication() { fun multiplication() {
val result = val result =
evaluator.evaluate( evaluator.evaluate(
ModuleSource.text(""" ModuleSource.text(
"""
x1 = Pair(1.0 * 2.0, 1 * 2).second x1 = Pair(1.0 * 2.0, 1 * 2).second
""") """
)
) )
assertThat(result.properties["x1"]).isEqualTo(2L) assertThat(result.properties["x1"]).isEqualTo(2L)
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -49,7 +49,7 @@ class GlobResolverTest {
"baz.pkl", "baz.pkl",
"buzzy...baz.pkl", "buzzy...baz.pkl",
"ted_lasso.min.pkl", "ted_lasso.min.pkl",
"ted_lasso.pkl.min.pkl" "ted_lasso.pkl.min.pkl",
] ]
) )
fun `glob match`(input: String) { fun `glob match`(input: String) {
@@ -68,7 +68,7 @@ class GlobResolverTest {
"pkl", "pkl",
// crosses directory boundaries // crosses directory boundaries
"/bar/baz.pkl", "/bar/baz.pkl",
"/baz.pkl" "/baz.pkl",
] ]
) )
fun `glob non-match`(input: String) { fun `glob non-match`(input: String) {
@@ -95,13 +95,7 @@ class GlobResolverTest {
} }
@ParameterizedTest @ParameterizedTest
@ValueSource( @ValueSource(strings = ["/foo.pkl/bar/baz.pkl", "//fo///ba.pkl"])
strings =
[
"/foo.pkl/bar/baz.pkl",
"//fo///ba.pkl",
]
)
fun `globstar match 2`(input: String) { fun `globstar match 2`(input: String) {
val pattern = GlobResolver.toRegexPattern("/**/*.pkl") val pattern = GlobResolver.toRegexPattern("/**/*.pkl")
assertTrue(pattern.matcher(input).matches()) assertTrue(pattern.matcher(input).matches())
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -29,10 +29,10 @@ class ImportGraphUtilsTest {
ImportGraph( ImportGraph(
mapOf( mapOf(
fooUri to setOf(ImportGraph.Import(barUri)), fooUri to setOf(ImportGraph.Import(barUri)),
barUri to setOf(ImportGraph.Import(fooUri)) barUri to setOf(ImportGraph.Import(fooUri)),
), ),
// resolved URIs is not important // resolved URIs is not important
mapOf() mapOf(),
) )
val cycles = ImportGraphUtils.findImportCycles(graph) val cycles = ImportGraphUtils.findImportCycles(graph)
assertThat(cycles).isEqualTo(listOf(listOf(fooUri, barUri))) assertThat(cycles).isEqualTo(listOf(listOf(fooUri, barUri)))
@@ -50,10 +50,10 @@ class ImportGraphUtilsTest {
fooUri to setOf(ImportGraph.Import(barUri)), fooUri to setOf(ImportGraph.Import(barUri)),
barUri to setOf(ImportGraph.Import(fooUri)), barUri to setOf(ImportGraph.Import(fooUri)),
bizUri to setOf(ImportGraph.Import(quxUri)), bizUri to setOf(ImportGraph.Import(quxUri)),
quxUri to setOf(ImportGraph.Import(bizUri)) quxUri to setOf(ImportGraph.Import(bizUri)),
), ),
// resolved URIs is not important // resolved URIs is not important
mapOf() mapOf(),
) )
val cycles = ImportGraphUtils.findImportCycles(graph) val cycles = ImportGraphUtils.findImportCycles(graph)
assertThat(cycles).isEqualTo(listOf(listOf(fooUri, barUri), listOf(bizUri, quxUri))) assertThat(cycles).isEqualTo(listOf(listOf(fooUri, barUri), listOf(bizUri, quxUri)))
@@ -71,10 +71,10 @@ class ImportGraphUtilsTest {
barUri to setOf(ImportGraph.Import(fooUri)), barUri to setOf(ImportGraph.Import(fooUri)),
fooUri to setOf(ImportGraph.Import(bizUri)), fooUri to setOf(ImportGraph.Import(bizUri)),
bizUri to setOf(ImportGraph.Import(quxUri)), bizUri to setOf(ImportGraph.Import(quxUri)),
quxUri to setOf() quxUri to setOf(),
), ),
// resolved URIs is not important // resolved URIs is not important
mapOf() mapOf(),
) )
val cycles = ImportGraphUtils.findImportCycles(graph) val cycles = ImportGraphUtils.findImportCycles(graph)
assertThat(cycles).isEmpty() assertThat(cycles).isEmpty()
@@ -87,7 +87,7 @@ class ImportGraphUtilsTest {
ImportGraph( ImportGraph(
mapOf(fooUri to setOf(ImportGraph.Import(fooUri))), mapOf(fooUri to setOf(ImportGraph.Import(fooUri))),
// resolved URIs is not important // resolved URIs is not important
mapOf() mapOf(),
) )
val cycles = ImportGraphUtils.findImportCycles(graph) val cycles = ImportGraphUtils.findImportCycles(graph)
assertThat(cycles).isEqualTo(listOf(listOf(fooUri))) assertThat(cycles).isEqualTo(listOf(listOf(fooUri)))
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -24,7 +24,7 @@ internal class ClassPageGenerator(
docModule: DocModule, docModule: DocModule,
clazz: PClass, clazz: PClass,
pageScope: ClassScope, pageScope: ClassScope,
isTestMode: Boolean isTestMode: Boolean,
) : ModuleOrClassPageGenerator<ClassScope>(docsiteInfo, docModule, clazz, pageScope, isTestMode) { ) : ModuleOrClassPageGenerator<ClassScope>(docsiteInfo, docModule, clazz, pageScope, isTestMode) {
override val html: HTML.() -> Unit = { override val html: HTML.() -> Unit = {
renderHtmlHead() renderHtmlHead()
@@ -71,13 +71,13 @@ internal class ClassPageGenerator(
id = HtmlConstants.KNOWN_VERSIONS id = HtmlConstants.KNOWN_VERSIONS
classes = runtimeDataClasses classes = runtimeDataClasses
}, },
) ),
) )
renderMemberGroupLinks( renderMemberGroupLinks(
Triple("Overview", "#_overview", memberDocs.isExpandable), Triple("Overview", "#_overview", memberDocs.isExpandable),
Triple("Properties", "#_properties", clazz.hasListedProperty), Triple("Properties", "#_properties", clazz.hasListedProperty),
Triple("Methods", "#_methods", clazz.hasListedMethod) Triple("Methods", "#_methods", clazz.hasListedMethod),
) )
renderAnchor("_overview") renderAnchor("_overview")
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -57,7 +57,7 @@ class CliDocGenerator(private val options: CliDocGeneratorOptions) : CliCommand(
PklInfo.current() PklInfo.current()
.packageIndex .packageIndex
.getPackagePage("pkl", Release.current().version().toString()) .getPackagePage("pkl", Release.current().version().toString())
) ),
) )
private fun DependencyMetadata.getPackageDependencies(): List<DocPackageInfo.PackageDependency> { private fun DependencyMetadata.getPackageDependencies(): List<DocPackageInfo.PackageDependency> {
@@ -78,7 +78,7 @@ class CliDocGenerator(private val options: CliDocGeneratorOptions) : CliCommand(
version = metadata.version.toString(), version = metadata.version.toString(),
sourceCode = metadata.sourceCode, sourceCode = metadata.sourceCode,
sourceCodeUrlScheme = metadata.sourceCodeUrlScheme, sourceCodeUrlScheme = metadata.sourceCodeUrlScheme,
documentation = metadata.documentation documentation = metadata.documentation,
) )
add(packageDependency) add(packageDependency)
} }
@@ -269,7 +269,7 @@ class CliDocGenerator(private val options: CliDocGeneratorOptions) : CliCommand(
importedModules::getValue, importedModules::getValue,
versionComparator, versionComparator,
options.normalizedOutputDir, options.normalizedOutputDir,
options.isTestMode options.isTestMode,
) )
.run() .run()
} catch (e: DocGeneratorException) { } catch (e: DocGeneratorException) {
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -35,7 +35,7 @@ constructor(
* Generates source URLs with fixed line numbers `#L123-L456` to avoid churn in expected output * Generates source URLs with fixed line numbers `#L123-L456` to avoid churn in expected output
* files (e.g., when stdlib line numbers change). * files (e.g., when stdlib line numbers change).
*/ */
val isTestMode: Boolean = false val isTestMode: Boolean = false,
) { ) {
/** [outputDir] after undergoing normalization. */ /** [outputDir] after undergoing normalization. */
val normalizedOutputDir: Path = base.normalizedWorkingDir.resolveSafely(outputDir) val normalizedOutputDir: Path = base.normalizedWorkingDir.resolveSafely(outputDir)
+28 -25
View File
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -125,7 +125,7 @@ internal class SiteScope(
docPackages: List<DocPackage>, docPackages: List<DocPackage>,
private val overviewImports: Map<String, URI>, private val overviewImports: Map<String, URI>,
private val importResolver: (URI) -> ModuleSchema, private val importResolver: (URI) -> ModuleSchema,
outputDir: Path outputDir: Path,
) : PageScope() { ) : PageScope() {
private val pklVersion = Release.current().version().withBuild(null).toString() private val pklVersion = Release.current().version().withBuild(null).toString()
@@ -139,7 +139,7 @@ internal class SiteScope(
docPackage.docModules.map { it.schema }, docPackage.docModules.map { it.schema },
pklBaseModule, pklBaseModule,
docPackage.docPackageInfo.overviewImports, docPackage.docPackageInfo.overviewImports,
this this,
) )
} }
} }
@@ -162,7 +162,7 @@ internal class SiteScope(
name: String, name: String,
version: String, version: String,
sourceCodeUrlScheme: String?, sourceCodeUrlScheme: String?,
sourceCode: URI? sourceCode: URI?,
): PackageScope = ): PackageScope =
PackageScope( PackageScope(
DocPackageInfo( DocPackageInfo(
@@ -175,12 +175,12 @@ internal class SiteScope(
importUri = "", importUri = "",
issueTracker = null, issueTracker = null,
overview = null, overview = null,
uri = null uri = null,
), ),
emptyList(), emptyList(),
pklBaseModule, pklBaseModule,
emptyMap(), emptyMap(),
this this,
) )
override fun getMethod(name: String): MethodScope? = null override fun getMethod(name: String): MethodScope? = null
@@ -196,7 +196,7 @@ internal class SiteScope(
name.startsWith("pkl.") -> { name.startsWith("pkl.") -> {
val packagePage = val packagePage =
packageScopes["pkl"]?.url // link to locally generated stdlib docs if available packageScopes["pkl"]?.url // link to locally generated stdlib docs if available
?: PklInfo.current().packageIndex.getPackagePage("pkl", pklVersion).toUri() ?: PklInfo.current().packageIndex.getPackagePage("pkl", pklVersion).toUri()
packagePage.resolve(name.substring(4) + "/") packagePage.resolve(name.substring(4) + "/")
} }
// doesn't make much sense to search in [packageScopes] // doesn't make much sense to search in [packageScopes]
@@ -227,8 +227,7 @@ internal class SiteScope(
overviewImports[name]?.let { uri -> overviewImports[name]?.let { uri ->
val mod = resolveImport(uri) val mod = resolveImport(uri)
resolveModuleNameToDocUrl(mod.moduleName)?.let { url -> ModuleScope(mod, url, null) } resolveModuleNameToDocUrl(mod.moduleName)?.let { url -> ModuleScope(mod, url, null) }
} } ?: pklBaseScope.getProperty(name)
?: pklBaseScope.getProperty(name)
} }
internal class PackageScope( internal class PackageScope(
@@ -236,7 +235,7 @@ internal class PackageScope(
modules: List<ModuleSchema>, modules: List<ModuleSchema>,
pklBaseModule: ModuleSchema, pklBaseModule: ModuleSchema,
private val overviewImports: Map<String, URI>, private val overviewImports: Map<String, URI>,
override val parent: SiteScope override val parent: SiteScope,
) : PageScope() { ) : PageScope() {
val name = docPackageInfo.name val name = docPackageInfo.name
@@ -305,8 +304,7 @@ internal class PackageScope(
overviewImports[name]?.let { uri -> overviewImports[name]?.let { uri ->
val mod = resolveImport(uri) val mod = resolveImport(uri)
resolveModuleNameToDocUrl(mod.moduleName)?.let { url -> ModuleScope(mod, url, null) } resolveModuleNameToDocUrl(mod.moduleName)?.let { url -> ModuleScope(mod, url, null) }
} } ?: getPklBaseProperty(name)
?: getPklBaseProperty(name)
override fun equals(other: Any?): Boolean = override fun equals(other: Any?): Boolean =
other is PackageScope && docPackageInfo.name == other.docPackageInfo.name other is PackageScope && docPackageInfo.name == other.docPackageInfo.name
@@ -318,7 +316,7 @@ internal class PackageScope(
internal class ModuleScope( internal class ModuleScope(
val module: ModuleSchema, val module: ModuleSchema,
override val url: URI, override val url: URI,
override val parent: PackageScope? override val parent: PackageScope?,
) : PageScope() { ) : PageScope() {
val name: String val name: String
get() = module.moduleName get() = module.moduleName
@@ -335,7 +333,7 @@ internal class ModuleScope(
override fun getProperty(name: String): DocScope? = override fun getProperty(name: String): DocScope? =
module.moduleClass.allProperties[name]?.let { PropertyScope(it, this) } module.moduleClass.allProperties[name]?.let { PropertyScope(it, this) }
?: module.allClasses[name]?.let { ClassScope(it, url, this) } ?: module.allClasses[name]?.let { ClassScope(it, url, this) }
?: module.allTypeAliases[name]?.let { TypeAliasScope(it, url, this) } ?: module.allTypeAliases[name]?.let { TypeAliasScope(it, url, this) }
private fun resolveImport(uri: URI): ModuleSchema = parent!!.resolveImport(uri) private fun resolveImport(uri: URI): ModuleSchema = parent!!.resolveImport(uri)
@@ -358,7 +356,8 @@ internal class ModuleScope(
override fun resolveMethod(name: String): MethodScope? = override fun resolveMethod(name: String): MethodScope? =
module.moduleClass.methods[name]?.let { MethodScope(it, this) } module.moduleClass.methods[name]?.let { MethodScope(it, this) }
?: parent!!.getPklBaseMethod(name) ?: getMethod(name) ?: parent!!.getPklBaseMethod(name)
?: getMethod(name)
override fun resolveVariable(name: String): DocScope? = override fun resolveVariable(name: String): DocScope? =
name.takeIf { it == "module" }?.let { this } name.takeIf { it == "module" }?.let { this }
@@ -366,11 +365,12 @@ internal class ModuleScope(
val mod = resolveImport(uri) val mod = resolveImport(uri)
resolveModuleNameToDocUrl(mod.moduleName)?.let { url -> ModuleScope(mod, url, null) } resolveModuleNameToDocUrl(mod.moduleName)?.let { url -> ModuleScope(mod, url, null) }
} }
?: module.moduleClass.properties[name]?.let { PropertyScope(it, this) } ?: module.moduleClass.properties[name]?.let { PropertyScope(it, this) }
// inherited classes/type aliases are in scope when resolving types -> search `all` // inherited classes/type aliases are in scope when resolving types -> search `all`
?: module.allClasses[name]?.let { ClassScope(it, url, this) } ?: module.allClasses[name]?.let { ClassScope(it, url, this) }
?: module.allTypeAliases[name]?.let { TypeAliasScope(it, url, this) } ?: module.allTypeAliases[name]?.let { TypeAliasScope(it, url, this) }
?: parent!!.getPklBaseProperty(name) ?: getProperty(name) ?: parent!!.getPklBaseProperty(name)
?: getProperty(name)
override fun equals(other: Any?): Boolean = other is ModuleScope && module == other.module override fun equals(other: Any?): Boolean = other is ModuleScope && module == other.module
@@ -380,7 +380,7 @@ internal class ModuleScope(
internal class ClassScope( internal class ClassScope(
val clazz: PClass, val clazz: PClass,
private val parentUrl: URI, private val parentUrl: URI,
override val parent: ModuleScope? override val parent: ModuleScope?,
) : PageScope() { ) : PageScope() {
override val url: URI by lazy { override val url: URI by lazy {
// `isModuleClass` distinction is relevant when this scope is a link target // `isModuleClass` distinction is relevant when this scope is a link target
@@ -406,12 +406,14 @@ internal class ClassScope(
override fun resolveMethod(name: String): MethodScope? = override fun resolveMethod(name: String): MethodScope? =
clazz.methods[name]?.let { MethodScope(it, this) } clazz.methods[name]?.let { MethodScope(it, this) }
?: parent!!.resolveMethod(name) ?: getMethod(name) ?: parent!!.resolveMethod(name)
?: getMethod(name)
override fun resolveVariable(name: String): DocScope? = override fun resolveVariable(name: String): DocScope? =
clazz.typeParameters.find { it.name == name }?.let { ParameterScope(name, this) } clazz.typeParameters.find { it.name == name }?.let { ParameterScope(name, this) }
?: clazz.properties[name]?.let { PropertyScope(it, this) } ?: parent!!.resolveVariable(name) ?: clazz.properties[name]?.let { PropertyScope(it, this) }
?: clazz.allProperties[name]?.let { PropertyScope(it, this) } ?: parent!!.resolveVariable(name)
?: clazz.allProperties[name]?.let { PropertyScope(it, this) }
override fun equals(other: Any?): Boolean = other is ClassScope && clazz == other.clazz override fun equals(other: Any?): Boolean = other is ClassScope && clazz == other.clazz
@@ -421,7 +423,7 @@ internal class ClassScope(
internal class TypeAliasScope( internal class TypeAliasScope(
val typeAlias: TypeAlias, val typeAlias: TypeAlias,
private val parentDocUrl: URI, private val parentDocUrl: URI,
override val parent: ModuleScope? override val parent: ModuleScope?,
) : DocScope() { ) : DocScope() {
override val url: URI override val url: URI
get() = parentDocUrl.resolve("#${typeAlias.simpleName}") get() = parentDocUrl.resolve("#${typeAlias.simpleName}")
@@ -468,7 +470,8 @@ internal class MethodScope(val method: PClass.Method, override val parent: DocSc
override fun resolveVariable(name: String): DocScope? = override fun resolveVariable(name: String): DocScope? =
method.typeParameters.find { it.name == name }?.let { ParameterScope(name, this) } method.typeParameters.find { it.name == name }?.let { ParameterScope(name, this) }
?: method.parameters[name]?.let { ParameterScope(name, this) } ?: parent.resolveVariable(name) ?: method.parameters[name]?.let { ParameterScope(name, this) }
?: parent.resolveVariable(name)
override fun equals(other: Any?): Boolean = other is MethodScope && method == other.method override fun equals(other: Any?): Boolean = other is MethodScope && method == other.method
@@ -477,7 +480,7 @@ internal class MethodScope(val method: PClass.Method, override val parent: DocSc
internal class PropertyScope( internal class PropertyScope(
val property: PClass.Property, val property: PClass.Property,
override val parent: DocScope // ModuleScope|ClassScope override val parent: DocScope, // ModuleScope|ClassScope
) : DocScope() { ) : DocScope() {
override val url: URI override val url: URI
get() = parent.url.resolve("#${property.simpleName}") get() = parent.url.resolve("#${property.simpleName}")
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -33,7 +33,7 @@ data class DocsiteInfo(
val overview: String?, val overview: String?,
/** Imports used to resolve Pkldoc links in [overview]. */ /** Imports used to resolve Pkldoc links in [overview]. */
val overviewImports: Map<String, URI> val overviewImports: Map<String, URI>,
) { ) {
companion object { companion object {
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST")
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -24,7 +24,7 @@ internal class HtmlGenerator(
docPackages: List<DocPackage>, docPackages: List<DocPackage>,
importResolver: (URI) -> ModuleSchema, importResolver: (URI) -> ModuleSchema,
private val outputDir: Path, private val outputDir: Path,
private val isTestMode: Boolean private val isTestMode: Boolean,
) { ) {
private val siteScope = private val siteScope =
SiteScope(docPackages, docsiteInfo.overviewImports, importResolver, outputDir) SiteScope(docPackages, docsiteInfo.overviewImports, importResolver, outputDir)
@@ -50,7 +50,7 @@ internal class HtmlGenerator(
docModule, docModule,
clazz, clazz,
ClassScope(clazz, moduleScope.url, moduleScope), ClassScope(clazz, moduleScope.url, moduleScope),
isTestMode isTestMode,
) )
.run() .run()
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -20,12 +20,12 @@ import kotlinx.html.*
internal abstract class MainOrPackagePageGenerator<S>( internal abstract class MainOrPackagePageGenerator<S>(
docsiteInfo: DocsiteInfo, docsiteInfo: DocsiteInfo,
pageScope: S, pageScope: S,
private val siteScope: SiteScope private val siteScope: SiteScope,
) : PageGenerator<S>(docsiteInfo, pageScope) where S : PageScope { ) : PageGenerator<S>(docsiteInfo, pageScope) where S : PageScope {
protected fun UL.renderModuleOrPackage( protected fun UL.renderModuleOrPackage(
name: String, name: String,
moduleOrPackageScope: DocScope, moduleOrPackageScope: DocScope,
memberDocs: MemberDocs memberDocs: MemberDocs,
) { ) {
li { li {
renderAnchor(name) renderAnchor(name)
@@ -47,7 +47,7 @@ internal abstract class MainOrPackagePageGenerator<S>(
renderModifiers( renderModifiers(
setOf(), setOf(),
if (moduleOrPackageScope is PackageScope) "package" else "module" if (moduleOrPackageScope is PackageScope) "package" else "module",
) )
} }
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -30,7 +30,7 @@ internal abstract class ModuleOrClassPageGenerator<S>(
private val docModule: DocModule, private val docModule: DocModule,
protected val clazz: PClass, protected val clazz: PClass,
scope: S, scope: S,
private val isTestMode: Boolean private val isTestMode: Boolean,
) : PageGenerator<S>(docsiteInfo, scope) where S : PageScope { ) : PageGenerator<S>(docsiteInfo, scope) where S : PageScope {
protected fun HtmlBlockTag.renderProperties() { protected fun HtmlBlockTag.renderProperties() {
if (!clazz.hasListedProperty) return if (!clazz.hasListedProperty) return
@@ -279,9 +279,8 @@ internal abstract class ModuleOrClassPageGenerator<S>(
val moduleSourceUrl = val moduleSourceUrl =
pageScope.resolveModuleNameToSourceUrl( pageScope.resolveModuleNameToSourceUrl(
member.moduleName, member.moduleName,
Member.SourceLocation(startLine, endLine) Member.SourceLocation(startLine, endLine),
) ) ?: return
?: return
a { a {
classes = setOf("member-source-link") classes = setOf("member-source-link")
href = moduleSourceUrl.toString() href = moduleSourceUrl.toString()
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -46,7 +46,7 @@ class DocScopeTest {
"sourceCode".toUri(), "sourceCode".toUri(),
"https://example.com/mypackage/blob/1.2.3%{path}#L%{line}-L%{endLine}", "https://example.com/mypackage/blob/1.2.3%{path}#L%{line}-L%{endLine}",
"issueTracker".toUri(), "issueTracker".toUri(),
overview = "overview docs" overview = "overview docs",
) )
private val module: ModuleSchema by lazy { private val module: ModuleSchema by lazy {
@@ -87,7 +87,7 @@ class DocScopeTest {
listOf(DocPackage(docPackageInfo, mutableListOf(module))), listOf(DocPackage(docPackageInfo, mutableListOf(module))),
mapOf(), mapOf(),
{ evaluator.evaluateSchema(uri(it)) }, { evaluator.evaluateSchema(uri(it)) },
"/output/dir".toPath() "/output/dir".toPath(),
) )
} }
@@ -122,7 +122,7 @@ class DocScopeTest {
classScope, classScope,
typeAliasScope, typeAliasScope,
classPropertyScope, classPropertyScope,
classMethodScope classMethodScope,
) )
@JvmStatic @JvmStatic
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -45,10 +45,10 @@ class SearchTest {
base = base =
CliBaseOptions( CliBaseOptions(
sourceModules = listOf(packageModule) + inputModules, sourceModules = listOf(packageModule) + inputModules,
settings = URI("pkl:settings") settings = URI("pkl:settings"),
), ),
outputDir = pkldocDir, outputDir = pkldocDir,
true true,
) )
) )
.run() .run()
@@ -145,8 +145,8 @@ class SearchTest {
"com.package1.modulePropertyComments", "com.package1.modulePropertyComments",
"com.package1.modulePropertyModifiers", "com.package1.modulePropertyModifiers",
"com.package1.modulePropertyTypeAnnotations", "com.package1.modulePropertyTypeAnnotations",
"com.package1.modulePropertyTypeReferences" "com.package1.modulePropertyTypeReferences",
) ),
) )
} }
@@ -159,8 +159,8 @@ class SearchTest {
"com.package1.classMethodTypeReferences", "com.package1.classMethodTypeReferences",
"com.package1.classPropertyTypeReferences", "com.package1.classPropertyTypeReferences",
"com.package1.moduleMethodTypeReferences", "com.package1.moduleMethodTypeReferences",
"com.package1.modulePropertyTypeReferences" "com.package1.modulePropertyTypeReferences",
) ),
) )
} }
@@ -172,8 +172,8 @@ class SearchTest {
"prpertyWithExpandableComment", "prpertyWithExpandableComment",
"AnnotatedClssWithExpandableComment", "AnnotatedClssWithExpandableComment",
"ClassWithAnnotatedProperty", "ClassWithAnnotatedProperty",
"mthodWithExpandableComment" "mthodWithExpandableComment",
) ),
) )
} }
@@ -195,8 +195,8 @@ class SearchTest {
"com.package1.modulePropertyTypeAnnotations", "com.package1.modulePropertyTypeAnnotations",
"com.package1.modulePropertyCommentInheritance", "com.package1.modulePropertyCommentInheritance",
"com.package1.docExampleSubject1", "com.package1.docExampleSubject1",
"com.package1.docExampleSubject2" "com.package1.docExampleSubject2",
) ),
) )
} }
@@ -208,8 +208,8 @@ class SearchTest {
"com.package1.classInheritance", "com.package1.classInheritance",
"city", // disregard "city", // disregard
"com.package1.moduleMethodCommentInheritance", "com.package1.moduleMethodCommentInheritance",
"com.package1.modulePropertyCommentInheritance" "com.package1.modulePropertyCommentInheritance",
) ),
) )
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -44,7 +44,7 @@ class EmbeddedExecutorTest {
class TestExecutor( class TestExecutor(
private val executor: Executor, private val executor: Executor,
private val spiOptionsVersion: Int, private val spiOptionsVersion: Int,
private val name: String private val name: String,
) { ) {
fun evaluatePath(modulePath: Path, optionSpec: ExecutorOptions.Builder.() -> Unit): String { fun evaluatePath(modulePath: Path, optionSpec: ExecutorOptions.Builder.() -> Unit): String {
val options = val options =
@@ -66,7 +66,7 @@ class EmbeddedExecutorTest {
TestExecutor(executor2_1.value, 1, "SpiOptions1, Executor2, Distribution1"), TestExecutor(executor2_1.value, 1, "SpiOptions1, Executor2, Distribution1"),
TestExecutor(executor2_1.value, 2, "SpiOptions2, Executor2, Distribution1"), TestExecutor(executor2_1.value, 2, "SpiOptions2, Executor2, Distribution1"),
TestExecutor(executor2_2.value, 1, "SpiOptions1, Executor2, Distribution2"), TestExecutor(executor2_2.value, 1, "SpiOptions1, Executor2, Distribution2"),
TestExecutor(executor2_2.value, 2, "SpiOptions2, Executor2, Distribution2") TestExecutor(executor2_2.value, 2, "SpiOptions2, Executor2, Distribution2"),
) )
} }
@@ -239,7 +239,7 @@ class EmbeddedExecutorTest {
@MethodSource("getAllTestExecutors") @MethodSource("getAllTestExecutors")
fun `evaluate a module that is missing a ModuleInfo annotation`( fun `evaluate a module that is missing a ModuleInfo annotation`(
executor: TestExecutor, executor: TestExecutor,
@TempDir tempDir: Path @TempDir tempDir: Path,
) { ) {
val pklFile = tempDir.resolve("test.pkl") val pklFile = tempDir.resolve("test.pkl")
pklFile pklFile
@@ -270,7 +270,7 @@ class EmbeddedExecutorTest {
@MethodSource("getAllTestExecutors") @MethodSource("getAllTestExecutors")
fun `evaluate a module that requests an incompatible Pkl version`( fun `evaluate a module that requests an incompatible Pkl version`(
executor: TestExecutor, executor: TestExecutor,
@TempDir tempDir: Path @TempDir tempDir: Path,
) { ) {
val pklFile = tempDir.resolve("test.pkl") val pklFile = tempDir.resolve("test.pkl")
pklFile pklFile
@@ -302,7 +302,7 @@ class EmbeddedExecutorTest {
@MethodSource("getAllTestExecutors") @MethodSource("getAllTestExecutors")
fun `evaluate a module that reads environment variables and external properties`( fun `evaluate a module that reads environment variables and external properties`(
executor: TestExecutor, executor: TestExecutor,
@TempDir tempDir: Path @TempDir tempDir: Path,
) { ) {
val pklFile = tempDir.resolve("test.pkl") val pklFile = tempDir.resolve("test.pkl")
pklFile pklFile
@@ -328,17 +328,21 @@ class EmbeddedExecutorTest {
} }
assertThat(result.trim()) assertThat(result.trim())
.isEqualTo(""" .isEqualTo(
"""
x = "ENV_VAR" x = "ENV_VAR"
y = "property" y = "property"
""".trimIndent().trim()) """
.trimIndent()
.trim()
)
} }
@ParameterizedTest @ParameterizedTest
@MethodSource("getAllTestExecutors") @MethodSource("getAllTestExecutors")
fun `evaluate a module that depends on another module`( fun `evaluate a module that depends on another module`(
executor: TestExecutor, executor: TestExecutor,
@TempDir tempDir: Path @TempDir tempDir: Path,
) { ) {
val pklFile = tempDir.resolve("test.pkl") val pklFile = tempDir.resolve("test.pkl")
pklFile pklFile
@@ -376,11 +380,15 @@ class EmbeddedExecutorTest {
} }
assertThat(result.trim()) assertThat(result.trim())
.isEqualTo(""" .isEqualTo(
"""
foo { foo {
bar = 42 bar = 42
} }
""".trimIndent().trim()) """
.trimIndent()
.trim()
)
} }
@ParameterizedTest @ParameterizedTest
@@ -419,7 +427,7 @@ class EmbeddedExecutorTest {
@MethodSource("getAllTestExecutors") @MethodSource("getAllTestExecutors")
fun `evaluate a module whose project evaluation fails`( fun `evaluate a module whose project evaluation fails`(
executor: TestExecutor, executor: TestExecutor,
@TempDir tempDir: Path @TempDir tempDir: Path,
) { ) {
// the toRealPath is important here or the failure reason can change // the toRealPath is important here or the failure reason can change
// this happens on macOS where /tmp is a symlink to /private/tmp // this happens on macOS where /tmp is a symlink to /private/tmp
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -39,7 +39,7 @@ class AnalyzeImportsTest : AbstractTest() {
} }
} }
""" """
.trimIndent() .trimIndent(),
) )
val result = runTask("analyzeMyImports") val result = runTask("analyzeMyImports")
assertThat(result.output).contains("imports {") assertThat(result.output).contains("imports {")
@@ -66,7 +66,7 @@ class AnalyzeImportsTest : AbstractTest() {
} }
} }
""" """
.trimIndent() .trimIndent(),
) )
runTask("analyzeMyImports") runTask("analyzeMyImports")
assertThat(testProjectDir.resolve("myFile.pcf")).exists() assertThat(testProjectDir.resolve("myFile.pcf")).exists()
@@ -93,7 +93,7 @@ class AnalyzeImportsTest : AbstractTest() {
} }
} }
""" """
.trimIndent() .trimIndent(),
) )
val result = runTask("analyzeMyImports") val result = runTask("analyzeMyImports")
assertThat(result.output) assertThat(result.output)
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -42,7 +42,7 @@ class EvaluatorsTest : AbstractTest() {
age = 30 age = 30
} }
""" """
.trimIndent() .trimIndent(),
) )
} }
@@ -62,7 +62,7 @@ class EvaluatorsTest : AbstractTest() {
name: Pigeon name: Pigeon
age: 30 age: 30
""" """
.trimIndent() .trimIndent(),
) )
} }
@@ -85,7 +85,7 @@ class EvaluatorsTest : AbstractTest() {
} }
} }
""" """
.trimIndent() .trimIndent(),
) )
} }
@@ -115,7 +115,7 @@ class EvaluatorsTest : AbstractTest() {
</dict> </dict>
</plist> </plist>
""" """
.trimIndent() .trimIndent(),
) )
} }
@@ -126,7 +126,7 @@ class EvaluatorsTest : AbstractTest() {
""" """
externalProperties = [prop1: "value1", prop2: "value2"] externalProperties = [prop1: "value1", prop2: "value2"]
""" """
.trimIndent() .trimIndent(),
) )
writePklFile( writePklFile(
@@ -148,7 +148,7 @@ class EvaluatorsTest : AbstractTest() {
prop2 = "value2" prop2 = "value2"
other = null other = null
""" """
.trimIndent() .trimIndent(),
) )
} }
@@ -175,7 +175,7 @@ class EvaluatorsTest : AbstractTest() {
prop2 = null prop2 = null
prop3 = null prop3 = null
""" """
.trimIndent() .trimIndent(),
) )
} }
@@ -186,7 +186,7 @@ class EvaluatorsTest : AbstractTest() {
""" """
environmentVariables = [VAR1: "value1", VAR2: "value2"] environmentVariables = [VAR1: "value1", VAR2: "value2"]
""" """
.trimIndent() .trimIndent(),
) )
writePklFile( writePklFile(
@@ -208,7 +208,7 @@ class EvaluatorsTest : AbstractTest() {
prop2 = "value2" prop2 = "value2"
other = null other = null
""" """
.trimIndent() .trimIndent(),
) )
} }
@@ -228,7 +228,7 @@ class EvaluatorsTest : AbstractTest() {
} }
} }
} }
""" """,
) )
val result = runTask("evalTest", true) val result = runTask("evalTest", true)
@@ -244,7 +244,7 @@ class EvaluatorsTest : AbstractTest() {
name = "Pigeon" name = "Pigeon"
age = 20 + 10 age = 20 + 10
} }
""" """,
) )
writeFile( writeFile(
@@ -264,7 +264,7 @@ class EvaluatorsTest : AbstractTest() {
} }
} }
} }
""" """,
) )
runTask("evalTest") runTask("evalTest")
@@ -278,7 +278,7 @@ class EvaluatorsTest : AbstractTest() {
age = 30 age = 30
} }
""" """
.trimIndent() .trimIndent(),
) )
} }
@@ -300,7 +300,7 @@ class EvaluatorsTest : AbstractTest() {
} }
} }
} }
""" """,
) )
val result = runTask("evalTest", expectFailure = true) val result = runTask("evalTest", expectFailure = true)
@@ -314,9 +314,12 @@ class EvaluatorsTest : AbstractTest() {
@Test @Test
fun `evaluation timeout`() { fun `evaluation timeout`() {
// Gradle 4.10 doesn't automatically import Duration // Gradle 4.10 doesn't automatically import Duration
writeBuildFile("pcf", """ writeBuildFile(
"pcf",
"""
evalTimeout = java.time.Duration.ofMillis(100) evalTimeout = java.time.Duration.ofMillis(100)
""") """,
)
writePklFile( writePklFile(
""" """
@@ -349,7 +352,7 @@ class EvaluatorsTest : AbstractTest() {
} }
} }
} }
""" """,
) )
writeFile("test1.pkl", "foo = 1") writeFile("test1.pkl", "foo = 1")
@@ -363,7 +366,7 @@ class EvaluatorsTest : AbstractTest() {
// hello // hello
bar = 2 bar = 2
""" """
.trimIndent() .trimIndent(),
) )
} }
@@ -378,7 +381,7 @@ class EvaluatorsTest : AbstractTest() {
text = reflect.Module(module).uri text = reflect.Module(module).uri
} }
""" """
.trimIndent() .trimIndent(),
) )
runTask("evalTest") runTask("evalTest")
@@ -395,7 +398,7 @@ class EvaluatorsTest : AbstractTest() {
""" """
multipleFileOutputDir = layout.projectDirectory.dir("my-output") multipleFileOutputDir = layout.projectDirectory.dir("my-output")
""" """
.trimIndent() .trimIndent(),
) )
writeFile( writeFile(
"test.pkl", "test.pkl",
@@ -411,7 +414,7 @@ class EvaluatorsTest : AbstractTest() {
} }
} }
""" """
.trimIndent() .trimIndent(),
) )
runTask("evalTest") runTask("evalTest")
checkFileContents(testProjectDir.resolve("my-output/output-1.txt"), "My output 1") checkFileContents(testProjectDir.resolve("my-output/output-1.txt"), "My output 1")
@@ -426,7 +429,7 @@ class EvaluatorsTest : AbstractTest() {
expression = "metadata.name" expression = "metadata.name"
outputFile = layout.projectDirectory.file("output.txt") outputFile = layout.projectDirectory.file("output.txt")
""" """
.trimIndent() .trimIndent(),
) )
writeFile( writeFile(
"test.pkl", "test.pkl",
@@ -435,7 +438,7 @@ class EvaluatorsTest : AbstractTest() {
name = "Uni" name = "Uni"
} }
""" """
.trimIndent() .trimIndent(),
) )
runTask("evalTest") runTask("evalTest")
checkFileContents(testProjectDir.resolve("output.txt"), "Uni") checkFileContents(testProjectDir.resolve("output.txt"), "Uni")
@@ -448,7 +451,7 @@ class EvaluatorsTest : AbstractTest() {
""" """
moduleCacheDir = file("${tempDir.toUri()}") moduleCacheDir = file("${tempDir.toUri()}")
""" """
.trimIndent() .trimIndent(),
) )
writeFile( writeFile(
"test.pkl", "test.pkl",
@@ -457,7 +460,7 @@ class EvaluatorsTest : AbstractTest() {
res = new Bird { name = "Wally"; favoriteFruit { name = "bananas" } } res = new Bird { name = "Wally"; favoriteFruit { name = "bananas" } }
""" """
.trimIndent() .trimIndent(),
) )
PackageServer.populateCacheDir(tempDir) PackageServer.populateCacheDir(tempDir)
runTask("evalTest") runTask("evalTest")
@@ -483,7 +486,7 @@ class EvaluatorsTest : AbstractTest() {
packageZipUrl = "https://localhost:0/\(name)@\(version).zip" packageZipUrl = "https://localhost:0/\(name)@\(version).zip"
} }
""" """
.trimIndent() .trimIndent(),
) )
writeFile( writeFile(
@@ -498,7 +501,7 @@ class EvaluatorsTest : AbstractTest() {
packageZipUrl = "https://localhost:0/\(name)@\(version).zip" packageZipUrl = "https://localhost:0/\(name)@\(version).zip"
} }
""" """
.trimIndent() .trimIndent(),
) )
writeFile( writeFile(
@@ -515,7 +518,7 @@ class EvaluatorsTest : AbstractTest() {
} }
} }
""" """
.trimIndent() .trimIndent(),
) )
writeFile( writeFile(
@@ -526,7 +529,7 @@ class EvaluatorsTest : AbstractTest() {
"resolvedDependencies": {} "resolvedDependencies": {}
} }
""" """
.trimIndent() .trimIndent(),
) )
writeFile( writeFile(
@@ -536,7 +539,7 @@ class EvaluatorsTest : AbstractTest() {
bar: String = import("@proj2/baz.pkl").qux bar: String = import("@proj2/baz.pkl").qux
""" """
.trimIndent() .trimIndent(),
) )
writeFile( writeFile(
@@ -544,7 +547,7 @@ class EvaluatorsTest : AbstractTest() {
""" """
qux: String = "Contents of @proj2/qux" qux: String = "Contents of @proj2/qux"
""" """
.trimIndent() .trimIndent(),
) )
runTask("evalTest") runTask("evalTest")
@@ -595,7 +598,7 @@ class EvaluatorsTest : AbstractTest() {
} }
} }
""" """
.trimIndent() .trimIndent(),
) )
val result1 = runTask("printEvalFiles") val result1 = runTask("printEvalFiles")
@@ -741,7 +744,7 @@ class EvaluatorsTest : AbstractTest() {
} }
} }
""" """
.trimIndent() .trimIndent(),
) )
val result1 = runTask("printEvalDirs") val result1 = runTask("printEvalDirs")
@@ -875,7 +878,7 @@ class EvaluatorsTest : AbstractTest() {
""" """
transitiveModules.from(files("shared2.pkl")) transitiveModules.from(files("shared2.pkl"))
""" """
.trimIndent() .trimIndent(),
) )
val result1 = runTask("evalTest") val result1 = runTask("evalTest")
assertThat(result1.task(":evalTest")!!.outcome).isEqualTo(TaskOutcome.SUCCESS) assertThat(result1.task(":evalTest")!!.outcome).isEqualTo(TaskOutcome.SUCCESS)
@@ -901,7 +904,7 @@ class EvaluatorsTest : AbstractTest() {
outputFormat: String, outputFormat: String,
additionalContents: String = "", additionalContents: String = "",
sourceModules: List<String> = listOf("test.pkl"), sourceModules: List<String> = listOf("test.pkl"),
additionalBuildScript: String = "" additionalBuildScript: String = "",
) { ) {
writeFile( writeFile(
"build.gradle", "build.gradle",
@@ -922,12 +925,13 @@ class EvaluatorsTest : AbstractTest() {
} }
$additionalBuildScript $additionalBuildScript
""" """,
) )
} }
private fun writePklFile( private fun writePklFile(
contents: String = """ contents: String =
"""
person { person {
name = "Pigeon" name = "Pigeon"
age = 20 + 10 age = 20 + 10
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -43,7 +43,7 @@ class PkldocGeneratorsTest : AbstractTest() {
} }
} }
} }
""" """,
) )
writeFile( writeFile(
"doc-package-info.pkl", "doc-package-info.pkl",
@@ -57,7 +57,7 @@ class PkldocGeneratorsTest : AbstractTest() {
sourceCode = "sources.apple.com/" sourceCode = "sources.apple.com/"
issueTracker = "issues.apple.com" issueTracker = "issues.apple.com"
""" """
.trimIndent() .trimIndent(),
) )
writeFile( writeFile(
"person.pkl", "person.pkl",
@@ -76,7 +76,7 @@ class PkldocGeneratorsTest : AbstractTest() {
other = 42 other = 42
""" """
.trimIndent() .trimIndent(),
) )
runTask("pkldoc") runTask("pkldoc")
@@ -124,7 +124,7 @@ class PkldocGeneratorsTest : AbstractTest() {
} }
} }
} }
""" """,
) )
runTask("pkldoc") runTask("pkldoc")
@@ -150,7 +150,7 @@ class PkldocGeneratorsTest : AbstractTest() {
} }
} }
""" """
.trimIndent() .trimIndent(),
) )
val result = runTask("pkldoc", true) val result = runTask("pkldoc", true)
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -75,7 +75,7 @@ class ProjectPackageTest : AbstractTest() {
} }
} }
} }
""" """,
) )
} }
@@ -95,7 +95,7 @@ class ProjectPackageTest : AbstractTest() {
} }
} }
""" """
.trimIndent() .trimIndent(),
) )
writeFile( writeFile(
"proj1/PklProject.deps.json", "proj1/PklProject.deps.json",
@@ -105,7 +105,7 @@ class ProjectPackageTest : AbstractTest() {
"dependencies": {} "dependencies": {}
} }
""" """
.trimIndent() .trimIndent(),
) )
writeFile( writeFile(
"proj1/foo.pkl", "proj1/foo.pkl",
@@ -114,7 +114,7 @@ class ProjectPackageTest : AbstractTest() {
bar: String bar: String
""" """
.trimIndent() .trimIndent(),
) )
writeFile( writeFile(
"proj1/tests.pkl", "proj1/tests.pkl",
@@ -127,7 +127,7 @@ class ProjectPackageTest : AbstractTest() {
} }
} }
""" """
.trimIndent() .trimIndent(),
) )
writeFile("foo.txt", "The contents of foo.txt") writeFile("foo.txt", "The contents of foo.txt")
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -55,7 +55,7 @@ class ProjectResolveTest : AbstractTest() {
} }
} }
} }
""" """,
) )
} }
@@ -65,7 +65,7 @@ class ProjectResolveTest : AbstractTest() {
""" """
amends "pkl:Project" amends "pkl:Project"
""" """
.trimIndent() .trimIndent(),
) )
} }
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -170,7 +170,7 @@ class TestsTest : AbstractTest() {
} }
""" """
.trimIndent(), .trimIndent(),
additionalExamples = examples additionalExamples = examples,
) )
writeFile("test.pkl-expected.pcf", bigTestExpected) writeFile("test.pkl-expected.pcf", bigTestExpected)
@@ -276,7 +276,7 @@ class TestsTest : AbstractTest() {
} }
""" """
.trimIndent(), .trimIndent(),
additionalExamples = examples additionalExamples = examples,
) )
writeFile("test.pkl-expected.pcf", bigTestExpected) writeFile("test.pkl-expected.pcf", bigTestExpected)
@@ -411,7 +411,7 @@ class TestsTest : AbstractTest() {
} }
} }
} }
""" """,
) )
} }
@@ -433,7 +433,7 @@ class TestsTest : AbstractTest() {
examples { examples {
$additionalExamples $additionalExamples
} }
""" """,
): Path { ): Path {
return writeFile("test.pkl", contents) return writeFile("test.pkl", contents)
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -38,7 +38,7 @@ internal class BinaryEvaluator(
timeout: Duration?, timeout: Duration?,
moduleCacheDir: Path?, moduleCacheDir: Path?,
declaredDependencies: DeclaredDependencies?, declaredDependencies: DeclaredDependencies?,
outputFormat: String? outputFormat: String?,
) : ) :
EvaluatorImpl( EvaluatorImpl(
transformer, transformer,
@@ -53,7 +53,7 @@ internal class BinaryEvaluator(
timeout, timeout,
moduleCacheDir, moduleCacheDir,
declaredDependencies, declaredDependencies,
outputFormat outputFormat,
) { ) {
fun evaluate(moduleSource: ModuleSource, expression: String?): ByteArray { fun evaluate(moduleSource: ModuleSource, expression: String?): ByteArray {
return doEvaluate(moduleSource) { module -> return doEvaluate(moduleSource) { module ->
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -21,7 +21,7 @@ import org.pkl.core.messaging.MessageTransport
internal class ClientLogger( internal class ClientLogger(
private val evaluatorId: Long, private val evaluatorId: Long,
private val transport: MessageTransport private val transport: MessageTransport,
) : Logger { ) : Logger {
override fun trace(message: String, frame: StackFrame) { override fun trace(message: String, frame: StackFrame) {
transport.send(LogMessage(evaluatorId, 0, message, frame.moduleUri)) transport.send(LogMessage(evaluatorId, 0, message, frame.moduleUri))
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -25,7 +25,7 @@ import org.pkl.core.module.*
internal class ClientModuleKeyFactory( internal class ClientModuleKeyFactory(
private val readerSpecs: Collection<ModuleReaderSpec>, private val readerSpecs: Collection<ModuleReaderSpec>,
transport: MessageTransport, transport: MessageTransport,
evaluatorId: Long evaluatorId: Long,
) : ModuleKeyFactory { ) : ModuleKeyFactory {
private val schemes = readerSpecs.map { it.scheme } private val schemes = readerSpecs.map { it.scheme }
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -56,7 +56,7 @@ class Server(private val transport: MessageTransport) : AutoCloseable {
MessageTransports.stream( MessageTransports.stream(
ServerMessagePackDecoder(inputStream), ServerMessagePackDecoder(inputStream),
ServerMessagePackEncoder(outputStream), ServerMessagePackEncoder(outputStream),
::log ::log,
) )
) )
} }
@@ -76,7 +76,7 @@ class Server(private val transport: MessageTransport) : AutoCloseable {
is EvaluateRequest -> handleEvaluate(message) is EvaluateRequest -> handleEvaluate(message)
else -> throw ProtocolException("Unexpected incoming request message: $message") else -> throw ProtocolException("Unexpected incoming request message: $message")
} }
} },
) )
} }
@@ -147,7 +147,7 @@ class Server(private val transport: MessageTransport) : AutoCloseable {
private fun buildDeclaredDependencies( private fun buildDeclaredDependencies(
projectFileUri: URI, projectFileUri: URI,
dependencies: Map<String, Dependency>, dependencies: Map<String, Dependency>,
myPackageUri: URI? myPackageUri: URI?,
): DeclaredDependencies { ): DeclaredDependencies {
val remoteDependencies = buildMap { val remoteDependencies = buildMap {
for ((key, dep) in dependencies) { for ((key, dep) in dependencies) {
@@ -156,8 +156,8 @@ class Server(private val transport: MessageTransport) : AutoCloseable {
key, key,
org.pkl.core.packages.Dependency.RemoteDependency( org.pkl.core.packages.Dependency.RemoteDependency(
PackageUri(dep.packageUri), PackageUri(dep.packageUri),
dep.checksums dep.checksums,
) ),
) )
} }
} }
@@ -175,7 +175,7 @@ class Server(private val transport: MessageTransport) : AutoCloseable {
remoteDependencies, remoteDependencies,
localDependencies, localDependencies,
projectFileUri, projectFileUri,
myPackageUri?.let(::PackageUri) myPackageUri?.let(::PackageUri),
) )
} }
@@ -210,7 +210,7 @@ class Server(private val transport: MessageTransport) : AutoCloseable {
allowedModules, allowedModules,
allowedResources, allowedResources,
SecurityManagers.defaultTrustLevels, SecurityManagers.defaultTrustLevels,
rootDir rootDir,
), ),
httpClient, httpClient,
ClientLogger(evaluatorId, transport), ClientLogger(evaluatorId, transport),
@@ -221,14 +221,14 @@ class Server(private val transport: MessageTransport) : AutoCloseable {
timeout, timeout,
cacheDir, cacheDir,
dependencies, dependencies,
message.outputFormat message.outputFormat,
) )
} }
private fun createResourceReaders( private fun createResourceReaders(
message: CreateEvaluatorRequest, message: CreateEvaluatorRequest,
evaluatorId: Long, evaluatorId: Long,
modulePathResolver: ModulePathResolver modulePathResolver: ModulePathResolver,
): List<ResourceReader> = buildList { ): List<ResourceReader> = buildList {
add(ResourceReaders.environmentVariable()) add(ResourceReaders.environmentVariable())
add(ResourceReaders.externalProperty()) add(ResourceReaders.externalProperty())
@@ -248,7 +248,7 @@ class Server(private val transport: MessageTransport) : AutoCloseable {
add( add(
ResourceReaders.externalResolver( ResourceReaders.externalResolver(
readerSpec, readerSpec,
MessageTransportResourceResolver(transport, evaluatorId) MessageTransportResourceResolver(transport, evaluatorId),
) )
) )
} }
@@ -257,7 +257,7 @@ class Server(private val transport: MessageTransport) : AutoCloseable {
private fun createModuleKeyFactories( private fun createModuleKeyFactories(
message: CreateEvaluatorRequest, message: CreateEvaluatorRequest,
evaluatorId: Long, evaluatorId: Long,
modulePathResolver: ModulePathResolver modulePathResolver: ModulePathResolver,
): List<ModuleKeyFactory> = buildList { ): List<ModuleKeyFactory> = buildList {
// add client-side module key factory first to ensure it wins over builtin ones // add client-side module key factory first to ensure it wins over builtin ones
if (message.clientModuleReaders?.isNotEmpty() == true) { if (message.clientModuleReaders?.isNotEmpty() == true) {
@@ -268,7 +268,7 @@ class Server(private val transport: MessageTransport) : AutoCloseable {
ModuleKeyFactories.externalProcess( ModuleKeyFactories.externalProcess(
scheme, scheme,
getExternalProcess(evaluatorId, spec), getExternalProcess(evaluatorId, spec),
evaluatorId evaluatorId,
) )
) )
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -52,13 +52,13 @@ class ServerMessagePackDecoder(unpacker: MessageUnpacker) : BaseMessagePackDecod
map.unpackProject(), map.unpackProject(),
map.unpackHttp(), map.unpackHttp(),
unpackStringMapOrNull(map, "externalModuleReaders", ::unpackExternalReader), unpackStringMapOrNull(map, "externalModuleReaders", ::unpackExternalReader),
unpackStringMapOrNull(map, "externalResourceReaders", ::unpackExternalReader) unpackStringMapOrNull(map, "externalResourceReaders", ::unpackExternalReader),
) )
Message.Type.CREATE_EVALUATOR_RESPONSE -> Message.Type.CREATE_EVALUATOR_RESPONSE ->
CreateEvaluatorResponse( CreateEvaluatorResponse(
unpackLong(map, "requestId"), unpackLong(map, "requestId"),
unpackLongOrNull(map, "evaluatorId"), unpackLongOrNull(map, "evaluatorId"),
unpackStringOrNull(map, "error") unpackStringOrNull(map, "error"),
) )
Message.Type.CLOSE_EVALUATOR -> CloseEvaluator(unpackLong(map, "evaluatorId")) Message.Type.CLOSE_EVALUATOR -> CloseEvaluator(unpackLong(map, "evaluatorId"))
Message.Type.EVALUATE_REQUEST -> Message.Type.EVALUATE_REQUEST ->
@@ -67,21 +67,21 @@ class ServerMessagePackDecoder(unpacker: MessageUnpacker) : BaseMessagePackDecod
unpackLong(map, "evaluatorId"), unpackLong(map, "evaluatorId"),
URI(unpackString(map, "moduleUri")), URI(unpackString(map, "moduleUri")),
unpackStringOrNull(map, "moduleText"), unpackStringOrNull(map, "moduleText"),
unpackStringOrNull(map, "expr") unpackStringOrNull(map, "expr"),
) )
Message.Type.EVALUATE_RESPONSE -> Message.Type.EVALUATE_RESPONSE ->
EvaluateResponse( EvaluateResponse(
unpackLong(map, "requestId"), unpackLong(map, "requestId"),
unpackLong(map, "evaluatorId"), unpackLong(map, "evaluatorId"),
unpackByteArray(map, "result"), unpackByteArray(map, "result"),
unpackStringOrNull(map, "error") unpackStringOrNull(map, "error"),
) )
Message.Type.LOG_MESSAGE -> Message.Type.LOG_MESSAGE ->
LogMessage( LogMessage(
unpackLong(map, "evaluatorId"), unpackLong(map, "evaluatorId"),
unpackInt(map, "level"), unpackInt(map, "level"),
unpackString(map, "message"), unpackString(map, "message"),
unpackString(map, "frameUri") unpackString(map, "frameUri"),
) )
else -> super.decodeMessage(msgType, map) else -> super.decodeMessage(msgType, map)
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -46,7 +46,7 @@ data class CreateEvaluatorRequest(
val project: Project?, val project: Project?,
val http: Http?, val http: Http?,
val externalModuleReaders: Map<String, ExternalReader>?, val externalModuleReaders: Map<String, ExternalReader>?,
val externalResourceReaders: Map<String, ExternalReader>? val externalResourceReaders: Map<String, ExternalReader>?,
) : Message.Client.Request { ) : Message.Client.Request {
override fun type(): Message.Type = Message.Type.CREATE_EVALUATOR_REQUEST override fun type(): Message.Type = Message.Type.CREATE_EVALUATOR_REQUEST
@@ -61,11 +61,11 @@ data class CreateEvaluatorRequest(
return requestId == other.requestId && return requestId == other.requestId &&
Objects.equals( Objects.equals(
allowedModules?.map { it.pattern() }, allowedModules?.map { it.pattern() },
other.allowedModules?.map { it.pattern() } other.allowedModules?.map { it.pattern() },
) && ) &&
Objects.equals( Objects.equals(
allowedResources?.map { it.pattern() }, allowedResources?.map { it.pattern() },
other.allowedResources?.map { it.pattern() } other.allowedResources?.map { it.pattern() },
) && ) &&
clientModuleReaders.equalsNullable(other.clientModuleReaders) && clientModuleReaders.equalsNullable(other.clientModuleReaders) &&
clientResourceReaders.equalsNullable(other.clientResourceReaders) && clientResourceReaders.equalsNullable(other.clientResourceReaders) &&
@@ -108,7 +108,7 @@ data class Http(
/** PEM-format CA certificates as raw bytes. */ /** PEM-format CA certificates as raw bytes. */
val caCertificates: ByteArray?, val caCertificates: ByteArray?,
/** Proxy settings */ /** Proxy settings */
val proxy: Proxy? val proxy: Proxy?,
) { ) {
override fun equals(other: Any?): Boolean { override fun equals(other: Any?): Boolean {
if (this === other) return true if (this === other) return true
@@ -130,7 +130,7 @@ data class Http(
enum class DependencyType(val value: String) { enum class DependencyType(val value: String) {
LOCAL("local"), LOCAL("local"),
REMOTE("remote") REMOTE("remote"),
} }
sealed interface Dependency { sealed interface Dependency {
@@ -145,7 +145,7 @@ data class RemoteDependency(override val packageUri: URI, val checksums: Checksu
data class Project( data class Project(
val projectFileUri: URI, val projectFileUri: URI,
override val packageUri: URI?, override val packageUri: URI?,
val dependencies: Map<String, Dependency> val dependencies: Map<String, Dependency>,
) : Dependency { ) : Dependency {
override val type: DependencyType = DependencyType.LOCAL override val type: DependencyType = DependencyType.LOCAL
} }
@@ -169,7 +169,7 @@ data class EvaluateRequest(
val evaluatorId: Long, val evaluatorId: Long,
val moduleUri: URI, val moduleUri: URI,
val moduleText: String?, val moduleText: String?,
val expr: String? val expr: String?,
) : Message.Client.Request { ) : Message.Client.Request {
override fun type(): Message.Type = Message.Type.EVALUATE_REQUEST override fun type(): Message.Type = Message.Type.EVALUATE_REQUEST
@@ -180,7 +180,7 @@ data class EvaluateResponse(
private val requestId: Long, private val requestId: Long,
val evaluatorId: Long, val evaluatorId: Long,
val result: ByteArray?, val result: ByteArray?,
val error: String? val error: String?,
) : Message.Server.Response { ) : Message.Server.Response {
override fun type(): Message.Type = Message.Type.EVALUATE_RESPONSE override fun type(): Message.Type = Message.Type.EVALUATE_RESPONSE
@@ -212,7 +212,7 @@ data class LogMessage(
val evaluatorId: Long, val evaluatorId: Long,
val level: Int, val level: Int,
val message: String, val message: String,
val frameUri: String val frameUri: String,
) : Message.Server.OneWay { ) : Message.Server.OneWay {
override fun type(): Message.Type = Message.Type.LOG_MESSAGE override fun type(): Message.Type = Message.Type.LOG_MESSAGE
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -37,13 +37,13 @@ class JvmServerTest : AbstractServerTest() {
MessageTransports.stream( MessageTransports.stream(
ServerMessagePackDecoder(in1), ServerMessagePackDecoder(in1),
ServerMessagePackEncoder(out2), ServerMessagePackEncoder(out2),
::log ::log,
), ),
MessageTransports.stream( MessageTransports.stream(
ServerMessagePackDecoder(in2), ServerMessagePackDecoder(in2),
ServerMessagePackEncoder(out1), ServerMessagePackEncoder(out1),
::log ::log,
) ),
) )
} }
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -32,7 +32,7 @@ class NativeServerTest : AbstractServerTest() {
TestTransport( TestTransport(
MessageTransports.stream( MessageTransports.stream(
ServerMessagePackDecoder(server.inputStream), ServerMessagePackDecoder(server.inputStream),
ServerMessagePackEncoder(server.outputStream) ServerMessagePackEncoder(server.outputStream),
) { _ -> ) { _ ->
} }
) )
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -52,18 +52,8 @@ class ServerMessagePackCodecTest {
@Test @Test
fun `round-trip CreateEvaluatorRequest`() { fun `round-trip CreateEvaluatorRequest`() {
val resourceReader1 = val resourceReader1 = ResourceReaderSpec("resourceReader1", true, true)
ResourceReaderSpec( val resourceReader2 = ResourceReaderSpec("resourceReader2", true, false)
"resourceReader1",
true,
true,
)
val resourceReader2 =
ResourceReaderSpec(
"resourceReader2",
true,
false,
)
val moduleReader1 = ModuleReaderSpec("moduleReader1", true, true, true) val moduleReader1 = ModuleReaderSpec("moduleReader1", true, true, true)
val moduleReader2 = ModuleReaderSpec("moduleReader2", true, false, false) val moduleReader2 = ModuleReaderSpec("moduleReader2", true, false, false)
val externalReader = ExternalReader("external-cmd", listOf("arg1", "arg2")) val externalReader = ExternalReader("external-cmd", listOf("arg1", "arg2"))
@@ -99,18 +89,18 @@ class ServerMessagePackCodecTest {
Project( Project(
projectFileUri = URI("file:///bar"), projectFileUri = URI("file:///bar"),
packageUri = URI("package://localhost:0/bar@1.1.0"), packageUri = URI("package://localhost:0/bar@1.1.0"),
dependencies = emptyMap() dependencies = emptyMap(),
) )
) ),
), ),
"baz" to "baz" to
RemoteDependency(URI("package://localhost:0/baz@1.1.0"), Checksums("abc123")) RemoteDependency(URI("package://localhost:0/baz@1.1.0"), Checksums("abc123")),
) ),
), ),
http = http =
Http( Http(
proxy = PklEvaluatorSettings.Proxy(URI("http://foo.com:1234"), listOf("bar", "baz")), proxy = PklEvaluatorSettings.Proxy(URI("http://foo.com:1234"), listOf("bar", "baz")),
caCertificates = byteArrayOf(1, 2, 3, 4) caCertificates = byteArrayOf(1, 2, 3, 4),
), ),
externalModuleReaders = mapOf("external" to externalReader, "external2" to externalReader), externalModuleReaders = mapOf("external" to externalReader, "external2" to externalReader),
externalResourceReaders = mapOf("external" to externalReader), externalResourceReaders = mapOf("external" to externalReader),
@@ -136,7 +126,7 @@ class ServerMessagePackCodecTest {
evaluatorId = 456, evaluatorId = 456,
moduleUri = URI("some/module.pkl"), moduleUri = URI("some/module.pkl"),
moduleText = null, moduleText = null,
expr = "some + expression" expr = "some + expression",
) )
) )
} }
@@ -148,7 +138,7 @@ class ServerMessagePackCodecTest {
requestId = 123, requestId = 123,
evaluatorId = 456, evaluatorId = 456,
result = byteArrayOf(1, 2, 3, 4, 5), result = byteArrayOf(1, 2, 3, 4, 5),
error = null error = null,
) )
) )
} }
@@ -160,7 +150,7 @@ class ServerMessagePackCodecTest {
evaluatorId = 123, evaluatorId = 123,
level = 0, level = 0,
message = "Hello, world!", message = "Hello, world!",
frameUri = "file:///some/module.pkl" frameUri = "file:///some/module.pkl",
) )
) )
} }
+2 -2
View File
@@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -57,7 +57,7 @@ spotless {
target("*.pkl") target("*.pkl")
licenseHeaderFile( licenseHeaderFile(
rootProject.file("buildSrc/src/main/resources/license-header.line-comment.txt"), rootProject.file("buildSrc/src/main/resources/license-header.line-comment.txt"),
"/// " "/// ",
) )
} }
} }