From 8c1c10528fd5d544dcb9f5853da4990fd8764772 Mon Sep 17 00:00:00 2001 From: Dan Chao Date: Mon, 1 Jul 2024 09:08:06 -0700 Subject: [PATCH] Run spotless apply --- bench/bench.gradle.kts | 37 +- build.gradle.kts | 32 +- buildSrc/build.gradle.kts | 4 +- buildSrc/settings.gradle.kts | 21 +- buildSrc/src/main/kotlin/BuildInfo.kt | 56 +-- buildSrc/src/main/kotlin/ExecutableJar.kt | 35 +- buildSrc/src/main/kotlin/GradlePluginTests.kt | 17 +- buildSrc/src/main/kotlin/GradleVersionInfo.kt | 34 +- buildSrc/src/main/kotlin/HtmlValidator.kt | 17 +- buildSrc/src/main/kotlin/MergeSourcesJars.kt | 37 +- .../src/main/kotlin/ResolveSourcesJars.kt | 45 +- buildSrc/src/main/kotlin/pklFatJar.gradle.kts | 212 ++++---- .../src/main/kotlin/pklGraalVm.gradle.kts | 114 +++-- .../kotlin/pklGradlePluginTest.gradle.kts | 57 ++- .../main/kotlin/pklHtmlValidator.gradle.kts | 77 +-- .../main/kotlin/pklKotlinLibrary.gradle.kts | 15 + .../src/main/kotlin/pklKotlinTest.gradle.kts | 73 +-- .../src/main/kotlin/pklNativeBuild.gradle.kts | 23 +- .../main/kotlin/pklPublishLibrary.gradle.kts | 106 ++-- docs/docs.gradle.kts | 27 +- pkl-cli/pkl-cli.gradle.kts | 344 ++++++------- pkl-codegen-java/pkl-codegen-java.gradle.kts | 32 +- .../pkl-codegen-kotlin.gradle.kts | 30 +- pkl-commons-cli/pkl-commons-cli.gradle.kts | 15 + pkl-commons-test/pkl-commons-test.gradle.kts | 161 ++++--- pkl-commons/pkl-commons.gradle.kts | 15 + pkl-config-java/pkl-config-java.gradle.kts | 103 ++-- .../pkl/config/java/mapper/PolymorphicTest.kt | 24 +- .../pkl-config-kotlin.gradle.kts | 71 +-- pkl-core/pkl-core.gradle.kts | 204 ++++---- .../core/generator/MemberRegistryGenerator.kt | 154 +++--- .../org/pkl/core/ClassInheritanceTest.kt | 39 +- .../test/kotlin/org/pkl/core/DataSizeTest.kt | 15 + .../kotlin/org/pkl/core/DataSizeUnitTest.kt | 15 + .../test/kotlin/org/pkl/core/DurationTest.kt | 259 +++++----- .../kotlin/org/pkl/core/DurationUnitTest.kt | 15 + .../test/kotlin/org/pkl/core/DynamicTest.kt | 23 +- .../kotlin/org/pkl/core/ErrorColoringTest.kt | 37 +- .../org/pkl/core/EvaluateExpressionTest.kt | 52 +- .../core/EvaluateMultipleFileOutputTest.kt | 50 +- .../org/pkl/core/EvaluateOutputTextTest.kt | 26 +- .../kotlin/org/pkl/core/EvaluateSchemaTest.kt | 61 +-- .../kotlin/org/pkl/core/EvaluateTestsTest.kt | 161 +++++-- .../org/pkl/core/EvaluatorBuilderTest.kt | 55 ++- .../test/kotlin/org/pkl/core/EvaluatorTest.kt | 333 +++++++------ .../kotlin/org/pkl/core/JsonRendererTest.kt | 26 +- .../org/pkl/core/LanguageSnippetTests.kt | 30 +- .../pkl/core/LanguageSnippetTestsEngine.kt | 183 +++---- .../kotlin/org/pkl/core/PClassInfoTest.kt | 17 +- .../kotlin/org/pkl/core/PListRendererTest.kt | 61 ++- .../test/kotlin/org/pkl/core/PModuleTest.kt | 87 ++-- .../src/test/kotlin/org/pkl/core/PNullTest.kt | 15 + .../test/kotlin/org/pkl/core/PObjectTest.kt | 75 +-- .../src/test/kotlin/org/pkl/core/PairTest.kt | 15 + .../kotlin/org/pkl/core/PcfRendererTest.kt | 57 ++- .../test/kotlin/org/pkl/core/PklInfoTest.kt | 15 + .../test/kotlin/org/pkl/core/PlatformTest.kt | 15 + .../org/pkl/core/PropertiesRendererTest.kt | 41 +- .../test/kotlin/org/pkl/core/ReleaseTest.kt | 15 + .../kotlin/org/pkl/core/ReplServerTest.kt | 116 +++-- .../kotlin/org/pkl/core/RepositoryHygiene.kt | 49 +- .../org/pkl/core/SecurityManagersTest.kt | 159 +++--- .../pkl/core/StackFrameTransformersTest.kt | 39 +- .../test/kotlin/org/pkl/core/VersionTest.kt | 185 +++---- .../kotlin/org/pkl/core/YamlRendererTest.kt | 67 ++- .../ast/builder/ImportsAndReadsParserTest.kt | 53 +- .../org/pkl/core/http/DummyHttpClientTest.kt | 29 +- .../org/pkl/core/http/HttpClientTest.kt | 62 ++- .../org/pkl/core/http/LazyHttpClientTest.kt | 41 +- .../org/pkl/core/http/NoProxyRuleTest.kt | 25 +- .../pkl/core/http/RequestCapturingClient.kt | 19 +- .../core/http/RequestRewritingClientTest.kt | 80 ++-- .../pkl/core/module/ModuleKeyFactoriesTest.kt | 27 +- .../org/pkl/core/module/ModuleKeysTest.kt | 106 ++-- .../pkl/core/module/ModulePathResolverTest.kt | 15 + .../pkl/core/module/ResolvedModuleKeysTest.kt | 19 +- .../pkl/core/module/ServiceProviderTest.kt | 40 +- .../pkl/core/module/TestModuleKeyFactory.kt | 15 + .../core/packages/DependencyMetadataTest.kt | 79 +-- .../pkl/core/packages/PackageResolversTest.kt | 190 +++++--- .../kotlin/org/pkl/core/parser/LexerTest.kt | 15 + .../core/parser/MultiLineStringLiteralTest.kt | 32 +- .../kotlin/org/pkl/core/parser/ShebangTest.kt | 31 +- .../ProjectDependenciesResolverTest.kt | 63 ++- .../org/pkl/core/project/ProjectDepsTest.kt | 54 ++- .../org/pkl/core/project/ProjectTest.kt | 140 +++--- .../resource/ResourceReadersEvaluatorTest.kt | 42 +- .../pkl/core/resource/ResourceReadersTest.kt | 27 +- .../pkl/core/resource/TestResourceReader.kt | 15 + .../core/runtime/DefaultModuleResolverTest.kt | 80 ++-- .../pkl/core/runtime/FileSystemManagerTest.kt | 22 +- .../org/pkl/core/runtime/IteratorsTest.kt | 15 + .../org/pkl/core/runtime/ModuleKeyTest.kt | 46 +- .../core/runtime/StackTraceRendererTest.kt | 104 ++-- .../org/pkl/core/runtime/VmClassTest.kt | 15 + .../org/pkl/core/runtime/VmDataSizeTest.kt | 15 + .../org/pkl/core/runtime/VmDurationTest.kt | 15 + .../org/pkl/core/runtime/VmSafeMathTest.kt | 44 +- .../org/pkl/core/runtime/VmUtilsTest.kt | 18 +- .../pkl/core/runtime/VmValueRendererTest.kt | 15 + .../org/pkl/core/settings/PklSettingsTest.kt | 72 ++- .../core/stdlib/PathConverterSupportTest.kt | 24 +- .../org/pkl/core/stdlib/PathSpecParserTest.kt | 178 +++---- .../org/pkl/core/stdlib/ReflectModuleTest.kt | 40 +- .../truffle/LongVsDoubleSpecializationTest.kt | 71 +-- .../org/pkl/core/util/ArrayCharEscaperTest.kt | 35 +- .../org/pkl/core/util/ExceptionsTest.kt | 19 +- .../org/pkl/core/util/GlobResolverTest.kt | 134 ++++-- .../kotlin/org/pkl/core/util/HttpUtilsTest.kt | 47 +- .../kotlin/org/pkl/core/util/IoUtilsTest.kt | 323 ++++++------- pkl-doc/pkl-doc.gradle.kts | 30 +- pkl-executor/pkl-executor.gradle.kts | 95 ++-- .../org/pkl/executor/EmbeddedExecutorTest.kt | 451 +++++++++++------- .../kotlin/org/pkl/executor/VersionTest.kt | 185 +++---- pkl-gradle/pkl-gradle.gradle.kts | 25 +- .../kotlin/org/pkl/gradle/AbstractTest.kt | 50 +- .../kotlin/org/pkl/gradle/EvaluatorsTest.kt | 249 ++++++---- .../org/pkl/gradle/JavaCodeGeneratorsTest.kt | 45 +- .../pkl/gradle/KotlinCodeGeneratorsTest.kt | 44 +- .../org/pkl/gradle/PkldocGeneratorsTest.kt | 38 +- .../org/pkl/gradle/ProjectPackageTest.kt | 64 ++- .../org/pkl/gradle/ProjectResolveTest.kt | 34 +- .../test/kotlin/org/pkl/gradle/TestsTest.kt | 87 +++- pkl-server/pkl-server.gradle.kts | 76 ++- pkl-tools/pkl-tools.gradle.kts | 62 ++- settings.gradle.kts | 43 +- stdlib/stdlib.gradle.kts | 46 +- 127 files changed, 5325 insertions(+), 3450 deletions(-) diff --git a/bench/bench.gradle.kts b/bench/bench.gradle.kts index 16d9e240..5b088da7 100644 --- a/bench/bench.gradle.kts +++ b/bench/bench.gradle.kts @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ plugins { pklAllProjects pklJavaLibrary @@ -18,14 +33,15 @@ dependencies { } jmh { - //include = ["fib_class_java"] - //include = ["fib_class_constrained1", "fib_class_constrained2"] + // include = ["fib_class_java"] + // include = ["fib_class_constrained1", "fib_class_constrained2"] jmhVersion.set(libs.versions.jmh) // jvmArgsAppend = "-Dgraal.TruffleCompilationExceptionsAreFatal=true " + // "-Dgraal.Dump=Truffle,TruffleTree -Dgraal.TraceTruffleCompilation=true " + // "-Dgraal.TruffleFunctionInlining=false" jvm.set("${buildInfo.graalVmAmd64.baseDir}/bin/java") - // see: https://docs.oracle.com/en/graalvm/enterprise/20/docs/graalvm-as-a-platform/implement-language/#disable-class-path-separation + // see: + // https://docs.oracle.com/en/graalvm/enterprise/20/docs/graalvm-as-a-platform/implement-language/#disable-class-path-separation jvmArgs.set( listOf( // one JVM arg per list element doesn't work, but the following does @@ -33,16 +49,13 @@ jmh { ) ) includeTests.set(false) - //threads = Runtime.runtime.availableProcessors() / 2 + 1 - //synchronizeIterations = false + // threads = Runtime.runtime.availableProcessors() / 2 + 1 + // synchronizeIterations = false } -tasks.named("jmh") { - dependsOn(":installGraalVmAmd64") -} +tasks.named("jmh") { dependsOn(":installGraalVmAmd64") } // Prevent this error which occurs when building in IntelliJ: -// "Entry org/pkl/core/fib_class_typed.pkl is a duplicate but no duplicate handling strategy has been set." -tasks.processJmhResources { - duplicatesStrategy = DuplicatesStrategy.EXCLUDE -} +// "Entry org/pkl/core/fib_class_typed.pkl is a duplicate but no duplicate handling strategy has +// been set." +tasks.processJmhResources { duplicatesStrategy = DuplicatesStrategy.EXCLUDE } diff --git a/build.gradle.kts b/build.gradle.kts index 675a37ab..61452df6 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,5 +1,20 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ // https://youtrack.jetbrains.com/issue/KTIJ-19369 -@file:Suppress("DSL_SCOPE_VIOLATION") +@file:Suppress("DSL_SCOPE_VIOLATION") import org.jetbrains.gradle.ext.ActionDelegationConfig import org.jetbrains.gradle.ext.ActionDelegationConfig.TestRunner.PLATFORM @@ -40,15 +55,12 @@ idea { } } -val clean by tasks.existing { - delete(layout.buildDirectory) -} +val clean by tasks.existing { delete(layout.buildDirectory) } -val printVersion by tasks.registering { - doFirst { println(buildInfo.pklVersion) } -} +val printVersion by tasks.registering { doFirst { println(buildInfo.pklVersion) } } -val message = """ +val message = + """ ==== Gradle version : ${gradle.gradleVersion} Java version : ${System.getProperty("java.version")} @@ -63,5 +75,7 @@ Git Commit ID : ${buildInfo.commitId} ==== """ -val formattedMessage = message.replace("\n====", "\n" + "=".repeat(message.lines().maxByOrNull { it.length }!!.length)) +val formattedMessage = + message.replace("\n====", "\n" + "=".repeat(message.lines().maxByOrNull { it.length }!!.length)) + logger.info(formattedMessage) diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts index b9efd016..f964fc40 100644 --- a/buildSrc/build.gradle.kts +++ b/buildSrc/build.gradle.kts @@ -13,9 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -plugins { - `kotlin-dsl` -} +plugins { `kotlin-dsl` } dependencies { implementation(libs.downloadTaskPlugin) diff --git a/buildSrc/settings.gradle.kts b/buildSrc/settings.gradle.kts index 730ef0d9..11ebbed0 100644 --- a/buildSrc/settings.gradle.kts +++ b/buildSrc/settings.gradle.kts @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ @file:Suppress("UnstableApiUsage") rootProject.name = "buildSrc" @@ -12,11 +27,7 @@ pluginManagement { // makes ~/.gradle/init.gradle unnecessary and ~/.gradle/gradle.properties optional dependencyResolutionManagement { // use same version catalog as main build - versionCatalogs { - register("libs") { - from(files("../gradle/libs.versions.toml")) - } - } + versionCatalogs { register("libs") { from(files("../gradle/libs.versions.toml")) } } repositories { repositoriesMode.set(RepositoriesMode.PREFER_SETTINGS) diff --git a/buildSrc/src/main/kotlin/BuildInfo.kt b/buildSrc/src/main/kotlin/BuildInfo.kt index 0264375d..1e4877a0 100644 --- a/buildSrc/src/main/kotlin/BuildInfo.kt +++ b/buildSrc/src/main/kotlin/BuildInfo.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ @file:Suppress("MemberVisibilityCanBePrivate") import java.io.File @@ -14,13 +29,9 @@ open class BuildInfo(project: Project) { System.getenv("GRAALVM_HOME") ?: "${System.getProperty("user.home")}/.graalvm" } - val version: String by lazy { - libs.findVersion("graalVm").get().toString() - } + val version: String by lazy { libs.findVersion("graalVm").get().toString() } - val graalVmJdkVersion: String by lazy { - libs.findVersion("graalVmJdkVersion").get().toString() - } + val graalVmJdkVersion: String by lazy { libs.findVersion("graalVmJdkVersion").get().toString() } val osName: String by lazy { when { @@ -31,9 +42,7 @@ open class BuildInfo(project: Project) { } } - val baseName: String by lazy { - "graalvm-jdk-${graalVmJdkVersion}_${osName}-${arch}_bin" - } + val baseName: String by lazy { "graalvm-jdk-${graalVmJdkVersion}_${osName}-${arch}_bin" } val downloadUrl: String by lazy { val jdkMajor = graalVmJdkVersion.takeWhile { it != '.' } @@ -41,18 +50,14 @@ open class BuildInfo(project: Project) { "https://download.oracle.com/graalvm/$jdkMajor/archive/$baseName.$extension" } - val installDir: File by lazy { - File(homeDir, baseName) - } + val installDir: File by lazy { File(homeDir, baseName) } val baseDir: String by lazy { if (os.isMacOsX) "$installDir/Contents/Home" else installDir.toString() } } - /** - * Same logic as [org.gradle.internal.os.OperatingSystem#arch], which is protected. - */ + /** Same logic as [org.gradle.internal.os.OperatingSystem#arch], which is protected. */ val arch: String by lazy { when (val arch = System.getProperty("os.arch")) { "x86" -> "i386" @@ -66,13 +71,9 @@ open class BuildInfo(project: Project) { val graalVmAmd64: GraalVm = GraalVm("x64") - val isCiBuild: Boolean by lazy { - System.getenv("CI") != null - } + val isCiBuild: Boolean by lazy { System.getenv("CI") != null } - val isReleaseBuild: Boolean by lazy { - java.lang.Boolean.getBoolean("releaseBuild") - } + val isReleaseBuild: Boolean by lazy { java.lang.Boolean.getBoolean("releaseBuild") } val hasMuslToolchain: Boolean by lazy { // see "install musl" in .circleci/jobs/BuildNativeJob.pkl @@ -87,10 +88,11 @@ open class BuildInfo(project: Project) { val commitId: String by lazy { // only run command once per build invocation if (project === project.rootProject) { - val process = ProcessBuilder() - .command("git", "rev-parse", "--short", "HEAD") - .directory(project.rootDir) - .start() + val process = + ProcessBuilder() + .command("git", "rev-parse", "--short", "HEAD") + .directory(project.rootDir) + .start() process.waitFor().also { exitCode -> if (exitCode == -1) throw RuntimeException(process.errorStream.reader().readText()) } @@ -100,9 +102,7 @@ open class BuildInfo(project: Project) { } } - val commitish: String by lazy { - if (isReleaseBuild) project.version.toString() else commitId - } + val commitish: String by lazy { if (isReleaseBuild) project.version.toString() else commitId } val pklVersion: String by lazy { if (isReleaseBuild) { diff --git a/buildSrc/src/main/kotlin/ExecutableJar.kt b/buildSrc/src/main/kotlin/ExecutableJar.kt index ed63a284..c763ef8d 100644 --- a/buildSrc/src/main/kotlin/ExecutableJar.kt +++ b/buildSrc/src/main/kotlin/ExecutableJar.kt @@ -1,39 +1,52 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ import org.gradle.api.DefaultTask import org.gradle.api.file.RegularFileProperty import org.gradle.api.provider.ListProperty -import org.gradle.api.provider.Property import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputFile import org.gradle.api.tasks.OutputFile import org.gradle.api.tasks.TaskAction /** - * Builds a self-contained Pkl CLI Jar that is directly executable on *nix - * and executable with `java -jar` on Windows. + * Builds a self-contained Pkl CLI Jar that is directly executable on *nix and executable with `java + * -jar` on Windows. * * For direct execution, the `java` command must be on the PATH. * * https://skife.org/java/unix/2011/06/20/really_executable_jars.html */ abstract class ExecutableJar : DefaultTask() { - @get:InputFile - abstract val inJar: RegularFileProperty + @get:InputFile abstract val inJar: RegularFileProperty - @get:OutputFile - abstract val outJar: RegularFileProperty + @get:OutputFile abstract val outJar: RegularFileProperty - @get:Input - abstract val jvmArgs: ListProperty + @get:Input abstract val jvmArgs: ListProperty @TaskAction fun buildJar() { val inFile = inJar.get().asFile val outFile = outJar.get().asFile val escapedJvmArgs = jvmArgs.get().joinToString(separator = " ") { "\"$it\"" } - val startScript = """ + val startScript = + """ #!/bin/sh exec java $escapedJvmArgs -jar $0 "$@" - """.trimIndent() + "\n\n\n" + """ + .trimIndent() + "\n\n\n" outFile.outputStream().use { outStream -> startScript.byteInputStream().use { it.copyTo(outStream) } inFile.inputStream().use { it.copyTo(outStream) } diff --git a/buildSrc/src/main/kotlin/GradlePluginTests.kt b/buildSrc/src/main/kotlin/GradlePluginTests.kt index 35c9e867..fce2d777 100644 --- a/buildSrc/src/main/kotlin/GradlePluginTests.kt +++ b/buildSrc/src/main/kotlin/GradlePluginTests.kt @@ -1,7 +1,22 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ import org.gradle.util.GradleVersion open class GradlePluginTests { lateinit var minGradleVersion: GradleVersion lateinit var maxGradleVersion: GradleVersion var skippedGradleVersions: List = listOf() -} \ No newline at end of file +} diff --git a/buildSrc/src/main/kotlin/GradleVersionInfo.kt b/buildSrc/src/main/kotlin/GradleVersionInfo.kt index 0327a7b8..d94e5c80 100644 --- a/buildSrc/src/main/kotlin/GradleVersionInfo.kt +++ b/buildSrc/src/main/kotlin/GradleVersionInfo.kt @@ -1,6 +1,21 @@ -import org.gradle.util.GradleVersion +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ import groovy.json.JsonSlurper import java.net.URI +import org.gradle.util.GradleVersion @Suppress("unused") class GradleVersionInfo(json: Map) { @@ -38,15 +53,19 @@ class GradleVersionInfo(json: Map) { val wrapperChecksumUrl: String by json companion object { - private fun fetchAll(): List = fetchMultiple("https://services.gradle.org/versions/all") + private fun fetchAll(): List = + fetchMultiple("https://services.gradle.org/versions/all") fun fetchReleases(): List = fetchAll().filter { it.isReleaseVersion } - fun fetchCurrent(): GradleVersionInfo = fetchSingle("https://services.gradle.org/versions/current") + fun fetchCurrent(): GradleVersionInfo = + fetchSingle("https://services.gradle.org/versions/current") - fun fetchRc(): GradleVersionInfo? = fetchSingleOrNull("https://services.gradle.org/versions/release-candidate") + fun fetchRc(): GradleVersionInfo? = + fetchSingleOrNull("https://services.gradle.org/versions/release-candidate") - fun fetchNightly(): GradleVersionInfo = fetchSingle("https://services.gradle.org/versions/nightly") + fun fetchNightly(): GradleVersionInfo = + fetchSingle("https://services.gradle.org/versions/nightly") private fun fetchSingle(url: String): GradleVersionInfo { @Suppress("UNCHECKED_CAST") @@ -61,8 +80,9 @@ class GradleVersionInfo(json: Map) { private fun fetchMultiple(url: String): List { @Suppress("UNCHECKED_CAST") - return (JsonSlurper().parse(URI(url).toURL()) as List>) - .map { GradleVersionInfo(it) } + return (JsonSlurper().parse(URI(url).toURL()) as List>).map { + GradleVersionInfo(it) + } } } } diff --git a/buildSrc/src/main/kotlin/HtmlValidator.kt b/buildSrc/src/main/kotlin/HtmlValidator.kt index 07eca124..582abad9 100644 --- a/buildSrc/src/main/kotlin/HtmlValidator.kt +++ b/buildSrc/src/main/kotlin/HtmlValidator.kt @@ -1,6 +1,21 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ import org.gradle.api.Project import org.gradle.api.file.FileCollection open class HtmlValidator(project: Project) { var sources: FileCollection = project.files() -} \ No newline at end of file +} diff --git a/buildSrc/src/main/kotlin/MergeSourcesJars.kt b/buildSrc/src/main/kotlin/MergeSourcesJars.kt index e5defc49..159346f0 100644 --- a/buildSrc/src/main/kotlin/MergeSourcesJars.kt +++ b/buildSrc/src/main/kotlin/MergeSourcesJars.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ import java.io.File import java.util.regex.Matcher import java.util.regex.Pattern @@ -15,21 +30,18 @@ import org.gradle.kotlin.dsl.listProperty import org.gradle.kotlin.dsl.mapProperty open class MergeSourcesJars : DefaultTask() { - @get:InputFiles - val inputJars: ConfigurableFileCollection = project.objects.fileCollection() + @get:InputFiles val inputJars: ConfigurableFileCollection = project.objects.fileCollection() @get:InputFiles val mergedBinaryJars: ConfigurableFileCollection = project.objects.fileCollection() - @get:Input - val relocatedPackages: MapProperty = project.objects.mapProperty() + @get:Input val relocatedPackages: MapProperty = project.objects.mapProperty() @get:Input - var sourceFileExtensions: ListProperty = project.objects.listProperty() - .convention(listOf(".java", ".kt")) + var sourceFileExtensions: ListProperty = + project.objects.listProperty().convention(listOf(".java", ".kt")) - @get:OutputFile - val outputJar: RegularFileProperty = project.objects.fileProperty() + @get:OutputFile val outputJar: RegularFileProperty = project.objects.fileProperty() @TaskAction @Suppress("unused") @@ -38,12 +50,15 @@ open class MergeSourcesJars : DefaultTask() { val relocatedPkgs = relocatedPackages.get() - val relocatedPaths = relocatedPkgs.entries.associate { (key, value) -> toPath(key) to toPath(value) } + val relocatedPaths = + relocatedPkgs.entries.associate { (key, value) -> toPath(key) to toPath(value) } // use negative lookbehind to match any that don't precede with // a word or a period character. should catch most cases. - val importPattern = Pattern.compile("(? = project.objects.property() + @get:InputFiles val configuration: Property = project.objects.property() - @get:OutputDirectory - val outputDir: DirectoryProperty = project.objects.directoryProperty() + @get:OutputDirectory val outputDir: DirectoryProperty = project.objects.directoryProperty() @TaskAction @Suppress("UnstableApiUsage", "unused") fun resolve() { - val componentIds = configuration.get().incoming.resolutionResult.allDependencies.map { - (it as ResolvedDependencyResult).selected.id - } + val componentIds = + configuration.get().incoming.resolutionResult.allDependencies.map { + (it as ResolvedDependencyResult).selected.id + } - val resolutionResult = project.dependencies.createArtifactResolutionQuery() - .forComponents(componentIds) - .withArtifacts(JvmLibrary::class.java, SourcesArtifact::class.java) - .execute() + val resolutionResult = + project.dependencies + .createArtifactResolutionQuery() + .forComponents(componentIds) + .withArtifacts(JvmLibrary::class.java, SourcesArtifact::class.java) + .execute() - val resolvedJars = resolutionResult.resolvedComponents - .flatMap { it.getArtifacts(SourcesArtifact::class.java) } - .map { (it as ResolvedArtifactResult).file } + val resolvedJars = + resolutionResult.resolvedComponents + .flatMap { it.getArtifacts(SourcesArtifact::class.java) } + .map { (it as ResolvedArtifactResult).file } // copying to an output dir because I don't know how else to describe task outputs project.sync { diff --git a/buildSrc/src/main/kotlin/pklFatJar.gradle.kts b/buildSrc/src/main/kotlin/pklFatJar.gradle.kts index 675e2dbf..2afc632d 100644 --- a/buildSrc/src/main/kotlin/pklFatJar.gradle.kts +++ b/buildSrc/src/main/kotlin/pklFatJar.gradle.kts @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ import org.gradle.api.GradleException import org.gradle.api.artifacts.Configuration import org.gradle.api.component.AdhocComponentWithVariants @@ -18,41 +33,43 @@ val fatJarConfiguration: Configuration = configurations.create("fatJar") val fatJarPublication: MavenPublication = publishing.publications.create("fatJar") // ideally we'd configure this automatically based on project dependencies -val firstPartySourcesJarsConfiguration: Configuration = configurations.create("firstPartySourcesJars") +val firstPartySourcesJarsConfiguration: Configuration = + configurations.create("firstPartySourcesJars") -val relocations = mapOf( - // pkl-core dependencies - "org.antlr.v4." to "org.pkl.thirdparty.antlr.v4.", - "com.oracle.truffle" to "org.pkl.thirdparty.truffle", - "org.graalvm." to "org.pkl.thirdparty.graalvm.", - "org.organicdesign.fp." to "org.pkl.thirdparty.paguro.", - "org.snakeyaml.engine." to "org.pkl.thirdparty.snakeyaml.engine.", - "org.msgpack." to "org.pkl.thirdparty.msgpack.", - "org.w3c.dom." to "org.pkl.thirdparty.w3c.dom", - "com.oracle.svm.core." to "org.pkl.thirdparty.svm.", +val relocations = + mapOf( + // pkl-core dependencies + "org.antlr.v4." to "org.pkl.thirdparty.antlr.v4.", + "com.oracle.truffle" to "org.pkl.thirdparty.truffle", + "org.graalvm." to "org.pkl.thirdparty.graalvm.", + "org.organicdesign.fp." to "org.pkl.thirdparty.paguro.", + "org.snakeyaml.engine." to "org.pkl.thirdparty.snakeyaml.engine.", + "org.msgpack." to "org.pkl.thirdparty.msgpack.", + "org.w3c.dom." to "org.pkl.thirdparty.w3c.dom", + "com.oracle.svm.core." to "org.pkl.thirdparty.svm.", - // pkl-cli dependencies - "org.jline." to "org.pkl.thirdparty.jline.", - "com.github.ajalt.clikt." to "org.pkl.thirdparty.clikt.", - "kotlin." to "org.pkl.thirdparty.kotlin.", - "kotlinx." to "org.pkl.thirdparty.kotlinx.", - "org.intellij." to "org.pkl.thirdparty.intellij.", - "org.fusesource.jansi." to "org.pkl.thirdparty.jansi", - "org.fusesource.hawtjni." to "org.pkl.thirdparty.hawtjni", + // pkl-cli dependencies + "org.jline." to "org.pkl.thirdparty.jline.", + "com.github.ajalt.clikt." to "org.pkl.thirdparty.clikt.", + "kotlin." to "org.pkl.thirdparty.kotlin.", + "kotlinx." to "org.pkl.thirdparty.kotlinx.", + "org.intellij." to "org.pkl.thirdparty.intellij.", + "org.fusesource.jansi." to "org.pkl.thirdparty.jansi", + "org.fusesource.hawtjni." to "org.pkl.thirdparty.hawtjni", - // pkl-doc dependencies - "org.commonmark." to "org.pkl.thirdparty.commonmark.", - "org.jetbrains." to "org.pkl.thirdparty.jetbrains.", - - // pkl-config-java dependencies - "io.leangen.geantyref." to "org.pkl.thirdparty.geantyref.", + // pkl-doc dependencies + "org.commonmark." to "org.pkl.thirdparty.commonmark.", + "org.jetbrains." to "org.pkl.thirdparty.jetbrains.", - // pkl-codegen-java dependencies - "com.squareup.javapoet." to "org.pkl.thirdparty.javapoet.", + // pkl-config-java dependencies + "io.leangen.geantyref." to "org.pkl.thirdparty.geantyref.", - // pkl-codegen-kotlin dependencies - "com.squareup.kotlinpoet." to "org.pkl.thirdparty.kotlinpoet.", -) + // pkl-codegen-java dependencies + "com.squareup.javapoet." to "org.pkl.thirdparty.javapoet.", + + // pkl-codegen-kotlin dependencies + "com.squareup.kotlinpoet." to "org.pkl.thirdparty.kotlinpoet.", + ) val nonRelocations = listOf("com/oracle/truffle/") @@ -82,82 +99,81 @@ tasks.shadowJar { // workaround for https://github.com/johnrengelman/shadow/issues/651 components.withType(AdhocComponentWithVariants::class.java).forEach { c -> - c.withVariantsFromConfiguration(project.configurations.shadowRuntimeElements.get()) { - skip() + c.withVariantsFromConfiguration(project.configurations.shadowRuntimeElements.get()) { skip() } +} + +val testFatJar by + tasks.registering(Test::class) { + testClassesDirs = files(tasks.test.get().testClassesDirs) + classpath = + // compiled test classes + sourceSets.test.get().output + + // fat Jar + tasks.shadowJar.get().outputs.files + + // test-only dependencies + // (test dependencies that are also main dependencies must already be contained in fat Jar; + // to verify that, we don't want to include them here) + (configurations.testRuntimeClasspath.get() - configurations.runtimeClasspath.get()) } -} -val testFatJar by tasks.registering(Test::class) { - testClassesDirs = files(tasks.test.get().testClassesDirs) - classpath = - // compiled test classes - sourceSets.test.get().output + - // fat Jar - tasks.shadowJar.get().outputs.files + - // test-only dependencies - // (test dependencies that are also main dependencies must already be contained in fat Jar; - // to verify that, we don't want to include them here) - (configurations.testRuntimeClasspath.get() - configurations.runtimeClasspath.get()) -} +tasks.check { dependsOn(testFatJar) } -tasks.check { - dependsOn(testFatJar) -} +val validateFatJar by + tasks.registering { + val outputFile = layout.buildDirectory.file("validateFatJar/result.txt") + inputs.files(tasks.shadowJar) + inputs.property("nonRelocations", nonRelocations) + outputs.file(outputFile) -val validateFatJar by tasks.registering { - val outputFile = layout.buildDirectory.file("validateFatJar/result.txt") - inputs.files(tasks.shadowJar) - inputs.property("nonRelocations", nonRelocations) - outputs.file(outputFile) - - doLast { - val unshadowedFiles = mutableListOf() - zipTree(tasks.shadowJar.get().outputs.files.singleFile).visit { - val fileDetails = this - val path = fileDetails.relativePath.pathString - if (!(fileDetails.isDirectory || - path.startsWith("org/pkl/") || - path.startsWith("META-INF/") || - nonRelocations.any { path.startsWith(it) })) { - // don't throw exception inside `visit` - // as this gives a misleading "Could not expand ZIP" error message - unshadowedFiles.add(path) + doLast { + val unshadowedFiles = mutableListOf() + zipTree(tasks.shadowJar.get().outputs.files.singleFile).visit { + val fileDetails = this + val path = fileDetails.relativePath.pathString + if ( + !(fileDetails.isDirectory || + path.startsWith("org/pkl/") || + path.startsWith("META-INF/") || + nonRelocations.any { path.startsWith(it) }) + ) { + // don't throw exception inside `visit` + // as this gives a misleading "Could not expand ZIP" error message + unshadowedFiles.add(path) + } + } + if (unshadowedFiles.isEmpty()) { + outputFile.get().asFile.writeText("SUCCESS") + } else { + outputFile.get().asFile.writeText("FAILURE") + throw GradleException("Found unshadowed files:\n" + unshadowedFiles.joinToString("\n")) } } - if (unshadowedFiles.isEmpty()) { - outputFile.get().asFile.writeText("SUCCESS") - } else { - outputFile.get().asFile.writeText("FAILURE") - throw GradleException("Found unshadowed files:\n" + unshadowedFiles.joinToString("\n")) - } } -} -tasks.check { - dependsOn(validateFatJar) -} -val resolveSourcesJars by tasks.registering(ResolveSourcesJars::class) { - configuration.set(configurations.runtimeClasspath) - outputDir.set(layout.buildDirectory.dir("resolveSourcesJars")) -} +tasks.check { dependsOn(validateFatJar) } -val fatSourcesJar by tasks.registering(MergeSourcesJars::class) { - plugins.withId("pklJavaLibrary") { - inputJars.from(tasks.named("sourcesJar")) +val resolveSourcesJars by + tasks.registering(ResolveSourcesJars::class) { + configuration.set(configurations.runtimeClasspath) + outputDir.set(layout.buildDirectory.dir("resolveSourcesJars")) } - inputJars.from(firstPartySourcesJarsConfiguration) - inputJars.from(resolveSourcesJars.map { fileTree(it.outputDir) }) - mergedBinaryJars.from(tasks.shadowJar) - relocatedPackages.set(relocations) - outputJar.fileProvider(provider { - file(tasks.shadowJar.get().archiveFile.get().asFile.path.replace(".jar", "-sources.jar")) - }) -} +val fatSourcesJar by + tasks.registering(MergeSourcesJars::class) { + plugins.withId("pklJavaLibrary") { inputJars.from(tasks.named("sourcesJar")) } + inputJars.from(firstPartySourcesJarsConfiguration) + inputJars.from(resolveSourcesJars.map { fileTree(it.outputDir) }) -artifacts { - add("fatJar", tasks.shadowJar) -} + mergedBinaryJars.from(tasks.shadowJar) + relocatedPackages.set(relocations) + outputJar.fileProvider( + provider { + file(tasks.shadowJar.get().archiveFile.get().asFile.path.replace(".jar", "-sources.jar")) + } + ) + } + +artifacts { add("fatJar", tasks.shadowJar) } publishing { publications { @@ -165,16 +181,12 @@ publishing { project.shadow.component(this) // sources Jar is fat - artifact(fatSourcesJar.flatMap { it.outputJar.asFile }) { - classifier = "sources" - } + artifact(fatSourcesJar.flatMap { it.outputJar.asFile }) { classifier = "sources" } plugins.withId("pklJavaLibrary") { val javadocJar by tasks.existing(Jar::class) // Javadoc Jar is not fat (didn't invest effort) - artifact(javadocJar.flatMap { it.archiveFile }) { - classifier = "javadoc" - } + artifact(javadocJar.flatMap { it.archiveFile }) { classifier = "javadoc" } } } } diff --git a/buildSrc/src/main/kotlin/pklGraalVm.gradle.kts b/buildSrc/src/main/kotlin/pklGraalVm.gradle.kts index eaf5a632..d58d4ea5 100644 --- a/buildSrc/src/main/kotlin/pklGraalVm.gradle.kts +++ b/buildSrc/src/main/kotlin/pklGraalVm.gradle.kts @@ -1,36 +1,44 @@ -import java.nio.file.* -import java.util.UUID +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ import de.undercouch.gradle.tasks.download.Download import de.undercouch.gradle.tasks.download.Verify +import java.nio.file.* +import java.util.UUID import kotlin.io.path.createDirectories -plugins { - id("de.undercouch.download") -} +plugins { id("de.undercouch.download") } val buildInfo = project.extensions.getByType() -val BuildInfo.GraalVm.downloadFile get(): File { - val extension = if (buildInfo.os.isWindows) "zip" else "tar.gz" - return file(homeDir).resolve("${baseName}.$extension") -} +val BuildInfo.GraalVm.downloadFile + get(): File { + val extension = if (buildInfo.os.isWindows) "zip" else "tar.gz" + return file(homeDir).resolve("${baseName}.$extension") + } // tries to minimize chance of corruption by download-to-temp-file-and-move -val downloadGraalVmAarch64 by tasks.registering(Download::class) { - configureDownloadGraalVm(buildInfo.graalVmAarch64) -} +val downloadGraalVmAarch64 by + tasks.registering(Download::class) { configureDownloadGraalVm(buildInfo.graalVmAarch64) } -val downloadGraalVmAmd64 by tasks.registering(Download::class) { - configureDownloadGraalVm(buildInfo.graalVmAmd64) -} +val downloadGraalVmAmd64 by + tasks.registering(Download::class) { configureDownloadGraalVm(buildInfo.graalVmAmd64) } fun Download.configureDownloadGraalVm(graalvm: BuildInfo.GraalVm) { - onlyIf { - !graalvm.installDir.exists() - } - doLast { - println("Downloaded GraalVm to ${graalvm.downloadFile}") - } + onlyIf { !graalvm.installDir.exists() } + doLast { println("Downloaded GraalVm to ${graalvm.downloadFile}") } src(graalvm.downloadUrl) dest(graalvm.downloadFile) @@ -38,42 +46,44 @@ fun Download.configureDownloadGraalVm(graalvm: BuildInfo.GraalVm) { tempAndMove(true) } -val verifyGraalVmAarch64 by tasks.registering(Verify::class) { - configureVerifyGraalVm(buildInfo.graalVmAarch64) - dependsOn(downloadGraalVmAarch64) -} - -val verifyGraalVmAmd64 by tasks.registering(Verify::class) { - configureVerifyGraalVm(buildInfo.graalVmAmd64) - dependsOn(downloadGraalVmAmd64) -} - -fun Verify.configureVerifyGraalVm(graalvm: BuildInfo.GraalVm) { - onlyIf { - !graalvm.installDir.exists() +val verifyGraalVmAarch64 by + tasks.registering(Verify::class) { + configureVerifyGraalVm(buildInfo.graalVmAarch64) + dependsOn(downloadGraalVmAarch64) } +val verifyGraalVmAmd64 by + tasks.registering(Verify::class) { + configureVerifyGraalVm(buildInfo.graalVmAmd64) + dependsOn(downloadGraalVmAmd64) + } + +fun Verify.configureVerifyGraalVm(graalvm: BuildInfo.GraalVm) { + onlyIf { !graalvm.installDir.exists() } + src(graalvm.downloadFile) - checksum(buildInfo.libs.findVersion("graalVmSha256-${graalvm.osName}-${graalvm.arch}").get().toString()) + checksum( + buildInfo.libs.findVersion("graalVmSha256-${graalvm.osName}-${graalvm.arch}").get().toString() + ) algorithm("SHA-256") } // minimize chance of corruption by extract-to-random-dir-and-flip-symlink -val installGraalVmAarch64 by tasks.registering { - dependsOn(verifyGraalVmAarch64) - configureInstallGraalVm(buildInfo.graalVmAarch64) -} +val installGraalVmAarch64 by + tasks.registering { + dependsOn(verifyGraalVmAarch64) + configureInstallGraalVm(buildInfo.graalVmAarch64) + } // minimize chance of corruption by extract-to-random-dir-and-flip-symlink -val installGraalVmAmd64 by tasks.registering { - dependsOn(verifyGraalVmAmd64) - configureInstallGraalVm(buildInfo.graalVmAmd64) -} +val installGraalVmAmd64 by + tasks.registering { + dependsOn(verifyGraalVmAmd64) + configureInstallGraalVm(buildInfo.graalVmAmd64) + } fun Task.configureInstallGraalVm(graalVm: BuildInfo.GraalVm) { - onlyIf { - !graalVm.installDir.exists() - } + onlyIf { !graalVm.installDir.exists() } doLast { val distroDir = Paths.get(graalVm.homeDir, UUID.randomUUID().toString()) @@ -88,7 +98,9 @@ fun Task.configureInstallGraalVm(graalVm: BuildInfo.GraalVm) { args("--strip-components=1", "-xzf", graalVm.downloadFile) } - val distroBinDir = if (buildInfo.os.isMacOsX) distroDir.resolve("Contents/Home/bin") else distroDir.resolve("bin") + val distroBinDir = + if (buildInfo.os.isMacOsX) distroDir.resolve("Contents/Home/bin") + else distroDir.resolve("bin") println("Installing native-image into $distroDir") exec { @@ -103,11 +115,15 @@ fun Task.configureInstallGraalVm(graalVm: BuildInfo.GraalVm) { try { Files.move(tempLink, graalVm.installDir.toPath(), StandardCopyOption.ATOMIC_MOVE) } catch (e: Exception) { - try { delete(tempLink.toFile()) } catch (ignored: Exception) {} + try { + delete(tempLink.toFile()) + } catch (ignored: Exception) {} throw e } } catch (e: Exception) { - try { delete(distroDir) } catch (ignored: Exception) {} + try { + delete(distroDir) + } catch (ignored: Exception) {} throw e } } diff --git a/buildSrc/src/main/kotlin/pklGradlePluginTest.gradle.kts b/buildSrc/src/main/kotlin/pklGradlePluginTest.gradle.kts index 189b19ed..3a572df1 100644 --- a/buildSrc/src/main/kotlin/pklGradlePluginTest.gradle.kts +++ b/buildSrc/src/main/kotlin/pklGradlePluginTest.gradle.kts @@ -1,19 +1,19 @@ /** - * Allows to run Gradle plugin tests against different Gradle versions. + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * - * Adds a `compatibilityTestX` task for every Gradle version X - * between `ext.minSupportedGradleVersion` and `ext.maxSupportedGradleVersion` - * that is not in `ext.gradleVersionsExcludedFromTesting`. - * The list of available Gradle versions is obtained from services.gradle.org. - * Adds lifecycle tasks to test against multiple Gradle versions at once, for example all Gradle release versions. - * Compatibility test tasks run the same tests and use the same task configuration as the project's `test` task. - * They set system properties for the Gradle version and distribution URL to be used. - * These properties are consumed by the `AbstractTest` class. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ - -plugins { - java -} +plugins { java } val gradlePluginTests = extensions.create("gradlePluginTests") @@ -24,18 +24,23 @@ tasks.addRule("Pattern: compatibilityTest[All|Releases|Latest|Candidate|Nightly| when (val taskNameSuffix = matchResult.groupValues[1]) { "All" -> task("compatibilityTestAll") { - dependsOn("compatibilityTestReleases", "compatibilityTestCandidate", "compatibilityTestNightly") + dependsOn( + "compatibilityTestReleases", + "compatibilityTestCandidate", + "compatibilityTestNightly" + ) } // releases in configured range "Releases" -> task("compatibilityTestReleases") { val versionInfos = GradleVersionInfo.fetchReleases() - val versionsToTestAgainst = versionInfos.filter { versionInfo -> - val v = versionInfo.gradleVersion - !versionInfo.broken && + val versionsToTestAgainst = + versionInfos.filter { versionInfo -> + val v = versionInfo.gradleVersion + !versionInfo.broken && v in gradlePluginTests.minGradleVersion..gradlePluginTests.maxGradleVersion && v !in gradlePluginTests.skippedGradleVersions - } + } dependsOn(versionsToTestAgainst.map { createCompatibilityTestTask(it) }) } @@ -45,8 +50,10 @@ tasks.addRule("Pattern: compatibilityTest[All|Releases|Latest|Candidate|Nightly| val versionInfo = GradleVersionInfo.fetchCurrent() if (versionInfo.version == gradle.gradleVersion) { doLast { - println("No new Gradle release available. " + - "(Run `gradlew test` to test against ${versionInfo.version}.)") + println( + "No new Gradle release available. " + + "(Run `gradlew test` to test against ${versionInfo.version}.)" + ) } } else { dependsOn(createCompatibilityTestTask(versionInfo)) @@ -59,9 +66,7 @@ tasks.addRule("Pattern: compatibilityTest[All|Releases|Latest|Candidate|Nightly| if (versionInfo?.activeRc == true) { dependsOn(createCompatibilityTestTask(versionInfo)) } else { - doLast { - println("No active Gradle release candidate available.") - } + doLast { println("No active Gradle release candidate available.") } } } // latest nightly @@ -73,14 +78,14 @@ tasks.addRule("Pattern: compatibilityTest[All|Releases|Latest|Candidate|Nightly| // explicit version else -> createCompatibilityTestTask( - taskNameSuffix, - "https://services.gradle.org/distributions-snapshots/gradle-$taskNameSuffix-bin.zip" + taskNameSuffix, + "https://services.gradle.org/distributions-snapshots/gradle-$taskNameSuffix-bin.zip" ) } } fun createCompatibilityTestTask(versionInfo: GradleVersionInfo): Task = - createCompatibilityTestTask(versionInfo.version, versionInfo.downloadUrl) + createCompatibilityTestTask(versionInfo.version, versionInfo.downloadUrl) fun createCompatibilityTestTask(version: String, downloadUrl: String): Task { return tasks.create("compatibilityTest$version", Test::class.java) { diff --git a/buildSrc/src/main/kotlin/pklHtmlValidator.gradle.kts b/buildSrc/src/main/kotlin/pklHtmlValidator.gradle.kts index 65a8ecb1..3f7d2d2c 100644 --- a/buildSrc/src/main/kotlin/pklHtmlValidator.gradle.kts +++ b/buildSrc/src/main/kotlin/pklHtmlValidator.gradle.kts @@ -1,20 +1,33 @@ -plugins { - base -} +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +plugins { base } val htmlValidator = extensions.create("htmlValidator", project) val buildInfo = project.extensions.getByType() -val validatorConfiguration: Configuration = configurations.create("validator") { - resolutionStrategy.eachDependency { - if (requested.group == "log4j" && requested.name == "log4j") { - @Suppress("UnstableApiUsage") - useTarget(buildInfo.libs.findLibrary("log4j12Api").get()) - because("mitigate critical security vulnerabilities") +val validatorConfiguration: Configuration = + configurations.create("validator") { + resolutionStrategy.eachDependency { + if (requested.group == "log4j" && requested.name == "log4j") { + @Suppress("UnstableApiUsage") useTarget(buildInfo.libs.findLibrary("log4j12Api").get()) + because("mitigate critical security vulnerabilities") + } } } -} dependencies { @Suppress("UnstableApiUsage") @@ -32,27 +45,29 @@ dependencies { } } -val validateHtml by tasks.registering(JavaExec::class) { - val resultFile = layout.buildDirectory.file("validateHtml/result.txt") - inputs.files(htmlValidator.sources) - outputs.file(resultFile) +val validateHtml by + tasks.registering(JavaExec::class) { + val resultFile = layout.buildDirectory.file("validateHtml/result.txt") + inputs.files(htmlValidator.sources) + outputs.file(resultFile) - classpath = validatorConfiguration - mainClass.set("nu.validator.client.SimpleCommandLineValidator") - args("--skip-non-html") // --also-check-css doesn't work (still checks css as html), so limit to html files - args("--filterpattern", "(.*)Consider adding “lang=(.*)") - args("--filterpattern", "(.*)Consider adding a “lang” attribute(.*)") - args("--filterpattern", "(.*)unrecognized media “amzn-kf8”(.*)") // kindle - // for debugging - // args "--verbose" - args(htmlValidator.sources) + classpath = validatorConfiguration + mainClass.set("nu.validator.client.SimpleCommandLineValidator") + args( + "--skip-non-html" + ) // --also-check-css doesn't work (still checks css as html), so limit to html files + args("--filterpattern", "(.*)Consider adding “lang=(.*)") + args("--filterpattern", "(.*)Consider adding a “lang” attribute(.*)") + args("--filterpattern", "(.*)unrecognized media “amzn-kf8”(.*)") // kindle + // for debugging + // args "--verbose" + args(htmlValidator.sources) - // write a basic result file s.t. gradle can consider task up-to-date - // writing a result file in case validation fails is not easily possible with JavaExec, but also not strictly necessary - doFirst { project.delete(resultFile) } - doLast { resultFile.get().asFile.writeText("Success.") } -} + // write a basic result file s.t. gradle can consider task up-to-date + // writing a result file in case validation fails is not easily possible with JavaExec, but also + // not strictly necessary + doFirst { project.delete(resultFile) } + doLast { resultFile.get().asFile.writeText("Success.") } + } -tasks.check { - dependsOn(validateHtml) -} +tasks.check { dependsOn(validateHtml) } diff --git a/buildSrc/src/main/kotlin/pklKotlinLibrary.gradle.kts b/buildSrc/src/main/kotlin/pklKotlinLibrary.gradle.kts index 64040d2c..a84a6b37 100644 --- a/buildSrc/src/main/kotlin/pklKotlinLibrary.gradle.kts +++ b/buildSrc/src/main/kotlin/pklKotlinLibrary.gradle.kts @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ import org.gradle.accessors.dm.LibrariesForLibs plugins { diff --git a/buildSrc/src/main/kotlin/pklKotlinTest.gradle.kts b/buildSrc/src/main/kotlin/pklKotlinTest.gradle.kts index 6e0a6059..6061fa23 100644 --- a/buildSrc/src/main/kotlin/pklKotlinTest.gradle.kts +++ b/buildSrc/src/main/kotlin/pklKotlinTest.gradle.kts @@ -1,9 +1,22 @@ -import org.gradle.api.tasks.testing.logging.TestExceptionFormat +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ import java.net.URI +import org.gradle.api.tasks.testing.logging.TestExceptionFormat -plugins { - kotlin("jvm") -} +plugins { kotlin("jvm") } val buildInfo = project.extensions.getByType() @@ -23,38 +36,40 @@ tasks.withType().configureEach { // enable checking of stdlib return types systemProperty("org.pkl.testMode", "true") - + // Disable colour output in tests systemProperty("org.fusesource.jansi.Ansi.disable", "true") - reports.named("html") { - enabled = true - } + reports.named("html") { enabled = true } - testLogging { - exceptionFormat = TestExceptionFormat.FULL - } + testLogging { exceptionFormat = TestExceptionFormat.FULL } - addTestListener(object : TestListener { - override fun beforeSuite(suite: TestDescriptor) {} - override fun beforeTest(testDescriptor: TestDescriptor) {} - override fun afterTest(testDescriptor: TestDescriptor, result: TestResult) {} + addTestListener( + object : TestListener { + override fun beforeSuite(suite: TestDescriptor) {} - // print report link at end of task, not just at end of build - override fun afterSuite(descriptor: TestDescriptor, result: TestResult) { - if (descriptor.parent != null) return // only interested in overall result + override fun beforeTest(testDescriptor: TestDescriptor) {} - if (result.resultType == TestResult.ResultType.FAILURE) { - println("\nThere were failing tests. See the report at: ${fixFileUri(testTask.reports.html.entryPoint.toURI())}") + override fun afterTest(testDescriptor: TestDescriptor, result: TestResult) {} + + // print report link at end of task, not just at end of build + override fun afterSuite(descriptor: TestDescriptor, result: TestResult) { + if (descriptor.parent != null) return // only interested in overall result + + if (result.resultType == TestResult.ResultType.FAILURE) { + println( + "\nThere were failing tests. See the report at: ${fixFileUri(testTask.reports.html.entryPoint.toURI())}" + ) + } + } + + // makes links clickable on macOS + private fun fixFileUri(uri: URI): URI { + if ("file" == uri.scheme && !uri.schemeSpecificPart.startsWith("//")) { + return URI.create("file://" + uri.schemeSpecificPart) + } + return uri } } - - // makes links clickable on macOS - private fun fixFileUri(uri: URI): URI { - if ("file" == uri.scheme && !uri.schemeSpecificPart.startsWith("//")) { - return URI.create("file://" + uri.schemeSpecificPart) - } - return uri - } - }) + ) } diff --git a/buildSrc/src/main/kotlin/pklNativeBuild.gradle.kts b/buildSrc/src/main/kotlin/pklNativeBuild.gradle.kts index 60d5d72e..5dcb26fa 100644 --- a/buildSrc/src/main/kotlin/pklNativeBuild.gradle.kts +++ b/buildSrc/src/main/kotlin/pklNativeBuild.gradle.kts @@ -1,11 +1,22 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ val assembleNative by tasks.registering {} val testNative by tasks.registering {} -val checkNative by tasks.registering { - dependsOn(testNative) -} +val checkNative by tasks.registering { dependsOn(testNative) } -val buildNative by tasks.registering { - dependsOn(assembleNative, checkNative) -} +val buildNative by tasks.registering { dependsOn(assembleNative, checkNative) } diff --git a/buildSrc/src/main/kotlin/pklPublishLibrary.gradle.kts b/buildSrc/src/main/kotlin/pklPublishLibrary.gradle.kts index ffab443f..f3266305 100644 --- a/buildSrc/src/main/kotlin/pklPublishLibrary.gradle.kts +++ b/buildSrc/src/main/kotlin/pklPublishLibrary.gradle.kts @@ -1,6 +1,21 @@ -import org.gradle.api.publish.maven.tasks.GenerateMavenPom +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ import java.nio.charset.StandardCharsets import java.util.Base64 +import org.gradle.api.publish.maven.tasks.GenerateMavenPom plugins { `maven-publish` @@ -10,9 +25,7 @@ plugins { publishing { publications { components.findByName("java")?.let { javaComponent -> - create("library") { - from(javaComponent) - } + create("library") { from(javaComponent) } } withType().configureEach { pom { @@ -49,63 +62,66 @@ publishing { } } -val validatePom by tasks.registering { - if (tasks.findByName("generatePomFileForLibraryPublication") == null) { - return@registering - } - val generatePomFileForLibraryPublication by tasks.existing(GenerateMavenPom::class) - val outputFile = layout.buildDirectory.file("validatePom") // dummy output to satisfy up-to-date check +val validatePom by + tasks.registering { + if (tasks.findByName("generatePomFileForLibraryPublication") == null) { + return@registering + } + val generatePomFileForLibraryPublication by tasks.existing(GenerateMavenPom::class) + val outputFile = + layout.buildDirectory.file("validatePom") // dummy output to satisfy up-to-date check - dependsOn(generatePomFileForLibraryPublication) - inputs.file(generatePomFileForLibraryPublication.get().destination) - outputs.file(outputFile) + dependsOn(generatePomFileForLibraryPublication) + inputs.file(generatePomFileForLibraryPublication.get().destination) + outputs.file(outputFile) - doLast { - outputFile.get().asFile.delete() + doLast { + outputFile.get().asFile.delete() - val pomFile = generatePomFileForLibraryPublication.get().destination - assert(pomFile.exists()) + val pomFile = generatePomFileForLibraryPublication.get().destination + assert(pomFile.exists()) - val text = pomFile.readText() + val text = pomFile.readText() - run { - val unresolvedVersion = Regex(".*[+,()\\[\\]].*") - val matches = unresolvedVersion.findAll(text).toList() - if (matches.isNotEmpty()) { - throw GradleException( - """ + run { + val unresolvedVersion = Regex(".*[+,()\\[\\]].*") + val matches = unresolvedVersion.findAll(text).toList() + if (matches.isNotEmpty()) { + throw GradleException( + """ Found unresolved version selector(s) in generated POM: ${matches.joinToString("\n") { it.groupValues[0] }} - """.trimIndent() - ) + """ + .trimIndent() + ) + } } - } - val buildInfo = project.extensions.getByType() - if (buildInfo.isReleaseBuild) { - val snapshotVersion = Regex(".*-SNAPSHOT") - val matches = snapshotVersion.findAll(text).toList() - if (matches.isNotEmpty()) { - throw GradleException( - """ + val buildInfo = project.extensions.getByType() + if (buildInfo.isReleaseBuild) { + val snapshotVersion = Regex(".*-SNAPSHOT") + val matches = snapshotVersion.findAll(text).toList() + if (matches.isNotEmpty()) { + throw GradleException( + """ Found snapshot version(s) in generated POM of Pkl release version: ${matches.joinToString("\n") { it.groupValues[0] }} - """.trimIndent() - ) + """ + .trimIndent() + ) + } } + + outputFile.get().asFile.writeText("OK") } - - outputFile.get().asFile.writeText("OK") } -} -tasks.publish { - dependsOn(validatePom) -} +tasks.publish { dependsOn(validatePom) } // Workaround for maven publish plugin not setting up dependencies correctly. // Taken from https://github.com/gradle/gradle/issues/26091#issuecomment-1798137734 val dependsOnTasks = mutableListOf() + tasks.withType().configureEach { dependsOnTasks.add(name.replace("publish", "sign").replaceAfter("Publication", "")) dependsOn(dependsOnTasks) @@ -114,8 +130,10 @@ tasks.withType().configureEach { signing { // provided as env vars `ORG_GRADLE_PROJECT_signingKey` and `ORG_GRADLE_PROJECT_signingPassword` // in CI. - val signingKey = (findProperty("signingKey") as String?) - ?.let { Base64.getDecoder().decode(it).toString(StandardCharsets.US_ASCII) } + val signingKey = + (findProperty("signingKey") as String?)?.let { + Base64.getDecoder().decode(it).toString(StandardCharsets.US_ASCII) + } val signingPassword = findProperty("signingPassword") as String? if (signingKey != null && signingPassword != null) { useInMemoryPgpKeys(signingKey, signingPassword) diff --git a/docs/docs.gradle.kts b/docs/docs.gradle.kts index 221c6f90..e6d2abb3 100644 --- a/docs/docs.gradle.kts +++ b/docs/docs.gradle.kts @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ import org.jetbrains.kotlin.gradle.dsl.KotlinJvmProjectExtension plugins { @@ -12,10 +27,7 @@ sourceSets { srcDir(file("modules/pkl-config-java/examples")) srcDir(file("modules/java-binding/examples")) } - val kotlin = project.extensions - .getByType() - .sourceSets[name] - .kotlin + val kotlin = project.extensions.getByType().sourceSets[name].kotlin kotlin.srcDir(file("modules/kotlin-binding/examples")) } } @@ -30,7 +42,8 @@ dependencies { } tasks.test { - inputs.files(fileTree("modules").matching { - include("**/pages/*.adoc") - }).withPropertyName("asciiDocFiles").withPathSensitivity(PathSensitivity.RELATIVE) + inputs + .files(fileTree("modules").matching { include("**/pages/*.adoc") }) + .withPropertyName("asciiDocFiles") + .withPathSensitivity(PathSensitivity.RELATIVE) } diff --git a/pkl-cli/pkl-cli.gradle.kts b/pkl-cli/pkl-cli.gradle.kts index c43199a0..5f86e99d 100644 --- a/pkl-cli/pkl-cli.gradle.kts +++ b/pkl-cli/pkl-cli.gradle.kts @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ plugins { pklAllProjects pklKotlinLibrary @@ -7,11 +22,9 @@ plugins { // already on build script class path (see buildSrc/build.gradle.kts), // hence must only specify plugin ID here - @Suppress("DSL_SCOPE_VIOLATION") - id(libs.plugins.shadow.get().pluginId) + @Suppress("DSL_SCOPE_VIOLATION") id(libs.plugins.shadow.get().pluginId) - @Suppress("DSL_SCOPE_VIOLATION") - alias(libs.plugins.checksum) + @Suppress("DSL_SCOPE_VIOLATION") alias(libs.plugins.checksum) } // make Java executable available to other subprojects @@ -54,7 +67,7 @@ dependencies { exclude(group = "org.jetbrains.kotlin", module = "kotlin-stdlib-jdk8") exclude(group = "org.jetbrains.kotlin", module = "kotlin-stdlib-common") } - + testImplementation(projects.pklCommonsTest) testImplementation(libs.wiremock) @@ -69,17 +82,13 @@ dependencies { } tasks.jar { - manifest { - attributes += mapOf("Main-Class" to "org.pkl.cli.Main") - } + manifest { attributes += mapOf("Main-Class" to "org.pkl.cli.Main") } // not required at runtime exclude("org/pkl/cli/svm/**") } -tasks.javadoc { - enabled = false -} +tasks.javadoc { enabled = false } tasks.shadowJar { archiveFileName.set("jpkl") @@ -93,72 +102,74 @@ tasks.shadowJar { exclude("module-info.*") } -val javaExecutable by tasks.registering(ExecutableJar::class) { - inJar.set(tasks.shadowJar.flatMap { it.archiveFile }) - outJar.set(layout.buildDirectory.file("executable/jpkl")) +val javaExecutable by + tasks.registering(ExecutableJar::class) { + inJar.set(tasks.shadowJar.flatMap { it.archiveFile }) + outJar.set(layout.buildDirectory.file("executable/jpkl")) - // uncomment for debugging - //jvmArgs.addAll("-ea", "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005") -} + // uncomment for debugging + // jvmArgs.addAll("-ea", "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005") + } -val testJavaExecutable by tasks.registering(Test::class) { - testClassesDirs = tasks.test.get().testClassesDirs - classpath = - // compiled test classes - sourceSets.test.get().output + - // java executable - javaExecutable.get().outputs.files + - // test-only dependencies - // (test dependencies that are also main dependencies must already be contained in java executable; - // to verify that, we don't want to include them here) - (configurations.testRuntimeClasspath.get() - configurations.runtimeClasspath.get()) -} +val testJavaExecutable by + tasks.registering(Test::class) { + testClassesDirs = tasks.test.get().testClassesDirs + classpath = + // compiled test classes + sourceSets.test.get().output + + // java executable + javaExecutable.get().outputs.files + + // test-only dependencies + // (test dependencies that are also main dependencies must already be contained in java + // executable; + // to verify that, we don't want to include them here) + (configurations.testRuntimeClasspath.get() - configurations.runtimeClasspath.get()) + } -tasks.check { - dependsOn(testJavaExecutable) -} +tasks.check { dependsOn(testJavaExecutable) } // 0.14 Java executable was broken because javaExecutable.jvmArgs wasn't commented out. // To catch this and similar problems, test that Java executable starts successfully. -val testStartJavaExecutable by tasks.registering(Exec::class) { - dependsOn(javaExecutable) - val outputFile = - layout.buildDirectory.file("testStartJavaExecutable") // dummy output to satisfy up-to-date check - outputs.file(outputFile) +val testStartJavaExecutable by + tasks.registering(Exec::class) { + dependsOn(javaExecutable) + val outputFile = + layout.buildDirectory.file( + "testStartJavaExecutable" + ) // dummy output to satisfy up-to-date check + outputs.file(outputFile) - if (buildInfo.os.isWindows) { - executable = "java" - args("-jar", javaExecutable.get().outputs.files.singleFile.toString(), "--version") - } else { - executable = javaExecutable.get().outputs.files.singleFile.toString() - args("--version") + if (buildInfo.os.isWindows) { + executable = "java" + args("-jar", javaExecutable.get().outputs.files.singleFile.toString(), "--version") + } else { + executable = javaExecutable.get().outputs.files.singleFile.toString() + args("--version") + } + + doFirst { outputFile.get().asFile.delete() } + + doLast { outputFile.get().asFile.writeText("OK") } } - doFirst { outputFile.get().asFile.delete() } - - doLast { outputFile.get().asFile.writeText("OK") } -} - -tasks.check { - dependsOn(testStartJavaExecutable) -} +tasks.check { dependsOn(testStartJavaExecutable) } fun Exec.configureExecutable( graalVm: BuildInfo.GraalVm, outputFile: Provider, extraArgs: List = listOf() ) { - inputs.files(sourceSets.main.map { it.output }) + inputs + .files(sourceSets.main.map { it.output }) .withPropertyName("mainSourceSets") .withPathSensitivity(PathSensitivity.RELATIVE) - inputs.files(configurations.runtimeClasspath) + inputs + .files(configurations.runtimeClasspath) .withPropertyName("runtimeClasspath") .withNormalizer(ClasspathNormalizer::class) val nativeImageCommandName = if (buildInfo.os.isWindows) "native-image.cmd" else "native-image" - inputs.files( - file(graalVm.baseDir) - .resolve("bin/$nativeImageCommandName") - ) + inputs + .files(file(graalVm.baseDir).resolve("bin/$nativeImageCommandName")) .withPropertyName("graalVmNativeImage") .withPathSensitivity(PathSensitivity.ABSOLUTE) outputs.file(outputFile) @@ -170,99 +181,108 @@ fun Exec.configureExecutable( // JARs to exclude from the class path for the native-image build. val exclusions = listOf(libs.truffleApi, libs.graalSdk).map { it.get().module.name } // https://www.graalvm.org/22.0/reference-manual/native-image/Options/ - argumentProviders.add(CommandLineArgumentProvider { - buildList { - // currently gives a deprecation warning, but we've been told - // that the "initialize everything at build time" *CLI* option is likely here to stay - add("--initialize-at-build-time=") - // needed for messagepack-java (see https://github.com/msgpack/msgpack-java/issues/600) - // needed for jansi (see https://github.com/fusesource/jansi/issues/199#issuecomment-1252268229) - add("--initialize-at-run-time=org.msgpack.core.buffer.DirectBufferAccess,org.fusesource.jansi.internal") - add("--no-fallback") - add("-H:IncludeResources=org/pkl/core/stdlib/.*\\.pkl") - add("-H:IncludeResources=org/jline/utils/.*") - add("-H:IncludeResourceBundles=org.pkl.core.errorMessages") - add("-H:IncludeResources=org/pkl/commons/cli/PklCARoots.pem") - add("--macro:truffle") - add("-H:Class=org.pkl.cli.Main") - add("-H:Name=${outputFile.get().asFile.name}") - // the actual limit (currently) used by native-image is this number + 1400 (idea is to compensate for Truffle's own nodes) - add("-H:MaxRuntimeCompileMethods=1800") - add("-H:+EnforceMaxRuntimeCompileMethods") - add("--enable-url-protocols=http,https") - add("-H:+ReportExceptionStackTraces") - // disable automatic support for JVM CLI options (puts our main class in full control of argument parsing) - add("-H:-ParseRuntimeOptions") - // quick build mode: 40% faster compilation, 20% smaller (but presumably also slower) executable - if (!buildInfo.isReleaseBuild) { - add("-Ob") + argumentProviders.add( + CommandLineArgumentProvider { + buildList { + // currently gives a deprecation warning, but we've been told + // that the "initialize everything at build time" *CLI* option is likely here to stay + add("--initialize-at-build-time=") + // needed for messagepack-java (see https://github.com/msgpack/msgpack-java/issues/600) + // needed for jansi (see + // https://github.com/fusesource/jansi/issues/199#issuecomment-1252268229) + add( + "--initialize-at-run-time=org.msgpack.core.buffer.DirectBufferAccess,org.fusesource.jansi.internal" + ) + add("--no-fallback") + add("-H:IncludeResources=org/pkl/core/stdlib/.*\\.pkl") + add("-H:IncludeResources=org/jline/utils/.*") + add("-H:IncludeResourceBundles=org.pkl.core.errorMessages") + add("-H:IncludeResources=org/pkl/commons/cli/PklCARoots.pem") + add("--macro:truffle") + add("-H:Class=org.pkl.cli.Main") + add("-H:Name=${outputFile.get().asFile.name}") + // the actual limit (currently) used by native-image is this number + 1400 (idea is to + // compensate for Truffle's own nodes) + add("-H:MaxRuntimeCompileMethods=1800") + add("-H:+EnforceMaxRuntimeCompileMethods") + add("--enable-url-protocols=http,https") + add("-H:+ReportExceptionStackTraces") + // disable automatic support for JVM CLI options (puts our main class in full control of + // argument parsing) + add("-H:-ParseRuntimeOptions") + // quick build mode: 40% faster compilation, 20% smaller (but presumably also slower) + // executable + if (!buildInfo.isReleaseBuild) { + add("-Ob") + } + add("-march=compatibility") + // native-image rejects non-existing class path entries -> filter + add("--class-path") + val pathInput = + sourceSets.main.get().output + + configurations.runtimeClasspath.get().filter { + it.exists() && !exclusions.any { exclude -> it.name.contains(exclude) } + } + add(pathInput.asPath) + // make sure dev machine stays responsive (15% slowdown on my laptop) + val processors = + Runtime.getRuntime().availableProcessors() / + if (buildInfo.os.isMacOsX && !buildInfo.isCiBuild) 4 else 1 + add("-J-XX:ActiveProcessorCount=${processors}") + // Pass through all `HOMEBREW_` prefixed environment variables to allow build with shimmed + // tools. + addAll(environment.keys.filter { it.startsWith("HOMEBREW_") }.map { "-E$it" }) + addAll(extraArgs) } - add("-march=compatibility") - // native-image rejects non-existing class path entries -> filter - add("--class-path") - val pathInput = sourceSets.main.get().output + configurations.runtimeClasspath.get() - .filter { it.exists() && !exclusions.any { exclude -> it.name.contains(exclude) } } - add(pathInput.asPath) - // make sure dev machine stays responsive (15% slowdown on my laptop) - val processors = Runtime.getRuntime().availableProcessors() / - if (buildInfo.os.isMacOsX && !buildInfo.isCiBuild) 4 else 1 - add("-J-XX:ActiveProcessorCount=${processors}") - // Pass through all `HOMEBREW_` prefixed environment variables to allow build with shimmed tools. - addAll(environment.keys.filter { it.startsWith("HOMEBREW_") }.map { "-E$it" }) - addAll(extraArgs) } - }) -} - -/** - * Builds the pkl CLI for macOS/amd64. - */ -val macExecutableAmd64: TaskProvider by tasks.registering(Exec::class) { - dependsOn(":installGraalVmAmd64") - configureExecutable( - buildInfo.graalVmAmd64, - layout.buildDirectory.file("executable/pkl-macos-amd64") ) } -/** - * Builds the pkl CLI for macOS/aarch64. - */ -val macExecutableAarch64: TaskProvider by tasks.registering(Exec::class) { - dependsOn(":installGraalVmAarch64") - configureExecutable( - buildInfo.graalVmAarch64, - layout.buildDirectory.file("executable/pkl-macos-aarch64"), - listOf( - "-H:+AllowDeprecatedBuilderClassesOnImageClasspath" +/** Builds the pkl CLI for macOS/amd64. */ +val macExecutableAmd64: TaskProvider by + tasks.registering(Exec::class) { + dependsOn(":installGraalVmAmd64") + configureExecutable( + buildInfo.graalVmAmd64, + layout.buildDirectory.file("executable/pkl-macos-amd64") ) - ) -} + } -/** - * Builds the pkl CLI for linux/amd64. - */ -val linuxExecutableAmd64: TaskProvider by tasks.registering(Exec::class) { - dependsOn(":installGraalVmAmd64") - configureExecutable( - buildInfo.graalVmAmd64, - layout.buildDirectory.file("executable/pkl-linux-amd64") - ) -} +/** Builds the pkl CLI for macOS/aarch64. */ +val macExecutableAarch64: TaskProvider by + tasks.registering(Exec::class) { + dependsOn(":installGraalVmAarch64") + configureExecutable( + buildInfo.graalVmAarch64, + layout.buildDirectory.file("executable/pkl-macos-aarch64"), + listOf("-H:+AllowDeprecatedBuilderClassesOnImageClasspath") + ) + } + +/** Builds the pkl CLI for linux/amd64. */ +val linuxExecutableAmd64: TaskProvider by + tasks.registering(Exec::class) { + dependsOn(":installGraalVmAmd64") + configureExecutable( + buildInfo.graalVmAmd64, + layout.buildDirectory.file("executable/pkl-linux-amd64") + ) + } /** * Builds the pkl CLI for linux/aarch64. * - * Right now, this is built within a container on Mac using emulation because CI does not have - * ARM instances. + * Right now, this is built within a container on Mac using emulation because CI does not have ARM + * instances. */ -val linuxExecutableAarch64: TaskProvider by tasks.registering(Exec::class) { - dependsOn(":installGraalVmAarch64") - configureExecutable( - buildInfo.graalVmAarch64, - layout.buildDirectory.file("executable/pkl-linux-aarch64") - ) -} +val linuxExecutableAarch64: TaskProvider by + tasks.registering(Exec::class) { + dependsOn(":installGraalVmAarch64") + configureExecutable( + buildInfo.graalVmAarch64, + layout.buildDirectory.file("executable/pkl-linux-aarch64") + ) + } /** * Builds a statically linked CLI for linux/amd64. @@ -270,23 +290,25 @@ val linuxExecutableAarch64: TaskProvider by tasks.registering(Exec::class) * Note: we don't publish the same for linux/aarch64 because native-image doesn't support this. * Details: https://www.graalvm.org/22.0/reference-manual/native-image/ARM64/ */ -val alpineExecutableAmd64: TaskProvider by tasks.registering(Exec::class) { - dependsOn(":installGraalVmAmd64") - configureExecutable( - buildInfo.graalVmAmd64, - layout.buildDirectory.file("executable/pkl-alpine-linux-amd64"), - listOf("--static", "--libc=musl") - ) -} +val alpineExecutableAmd64: TaskProvider by + tasks.registering(Exec::class) { + dependsOn(":installGraalVmAmd64") + configureExecutable( + buildInfo.graalVmAmd64, + layout.buildDirectory.file("executable/pkl-alpine-linux-amd64"), + listOf("--static", "--libc=musl") + ) + } -val windowsExecutableAmd64: TaskProvider by tasks.registering(Exec::class) { - dependsOn(":installGraalVmAmd64") - configureExecutable( - buildInfo.graalVmAmd64, - layout.buildDirectory.file("executable/pkl-windows-amd64"), - listOf("-Dfile.encoding=UTF-8") - ) -} +val windowsExecutableAmd64: TaskProvider by + tasks.registering(Exec::class) { + dependsOn(":installGraalVmAmd64") + configureExecutable( + buildInfo.graalVmAmd64, + layout.buildDirectory.file("executable/pkl-windows-amd64"), + listOf("-Dfile.encoding=UTF-8") + ) + } tasks.assembleNative { when { @@ -296,15 +318,12 @@ tasks.assembleNative { dependsOn(macExecutableAarch64) } } - buildInfo.os.isWindows -> { dependsOn(windowsExecutableAmd64) } - buildInfo.os.isLinux && buildInfo.arch == "aarch64" -> { dependsOn(linuxExecutableAarch64) } - buildInfo.os.isLinux && buildInfo.arch == "amd64" -> { dependsOn(linuxExecutableAmd64) if (buildInfo.hasMuslToolchain) { @@ -315,7 +334,8 @@ tasks.assembleNative { } // make Java executable available to other subprojects -// (we don't do the same for native executables because we don't want tasks assemble/build to build them) +// (we don't do the same for native executables because we don't want tasks assemble/build to build +// them) artifacts { add("javaExecutable", javaExecutable.map { it.outputs.files.singleFile }) { name = "pkl-cli-java" @@ -325,7 +345,7 @@ artifacts { } } -//region Maven Publishing +// region Maven Publishing publishing { publications { register("javaExecutable") { @@ -344,7 +364,8 @@ publishing { Pkl CLI executable for Java. Can be executed directly on *nix (if the `java` command is found on the PATH) and with `java -jar` otherwise. Requires Java 17 or higher. - """.trimIndent() + """ + .trimIndent() ) } } @@ -438,5 +459,4 @@ signing { sign(publishing.publications["macExecutableAmd64"]) sign(publishing.publications["alpineLinuxExecutableAmd64"]) sign(publishing.publications["windowsExecutableAmd64"]) -} -//endregion +} // endregion diff --git a/pkl-codegen-java/pkl-codegen-java.gradle.kts b/pkl-codegen-java/pkl-codegen-java.gradle.kts index 17087a12..92dba819 100644 --- a/pkl-codegen-java/pkl-codegen-java.gradle.kts +++ b/pkl-codegen-java/pkl-codegen-java.gradle.kts @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ plugins { pklAllProjects pklKotlinLibrary @@ -19,25 +34,22 @@ dependencies { // with `org.gradle.parallel=true` and without the line below, `test` strangely runs into: // java.lang.NoClassDefFoundError: Lorg/pkl/config/java/ConfigEvaluator; // perhaps somehow related to InMemoryJavaCompiler? -tasks.test { - mustRunAfter(":pkl-config-java:testFatJar") -} +tasks.test { mustRunAfter(":pkl-config-java:testFatJar") } -tasks.jar { - manifest { - attributes += mapOf("Main-Class" to "org.pkl.codegen.java.Main") - } -} +tasks.jar { manifest { attributes += mapOf("Main-Class" to "org.pkl.codegen.java.Main") } } publishing { publications { named("library") { pom { url.set("https://github.com/apple/pkl/tree/main/pkl-codegen-java") - description.set(""" + description.set( + """ Java source code generator that generates corresponding Java classes for Pkl classes, simplifying consumption of Pkl configuration as statically typed Java objects. - """.trimIndent()) + """ + .trimIndent() + ) } } } diff --git a/pkl-codegen-kotlin/pkl-codegen-kotlin.gradle.kts b/pkl-codegen-kotlin/pkl-codegen-kotlin.gradle.kts index fb1d09dc..519c4c3b 100644 --- a/pkl-codegen-kotlin/pkl-codegen-kotlin.gradle.kts +++ b/pkl-codegen-kotlin/pkl-codegen-kotlin.gradle.kts @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ plugins { pklAllProjects pklKotlinLibrary @@ -9,26 +24,25 @@ publishing { named("library") { pom { url.set("https://github.com/apple/pkl/tree/main/pkl-codegen-kotlin") - description.set(""" + description.set( + """ Kotlin source code generator that generates corresponding Kotlin classes for Pkl classes, simplifying consumption of Pkl configuration as statically typed Kotlin objects. - """.trimIndent()) + """ + .trimIndent() + ) } } } } -tasks.jar { - manifest { - attributes += mapOf("Main-Class" to "org.pkl.codegen.kotlin.Main") - } -} +tasks.jar { manifest { attributes += mapOf("Main-Class" to "org.pkl.codegen.kotlin.Main") } } dependencies { implementation(projects.pklCommons) api(projects.pklCommonsCli) api(projects.pklCore) - + implementation(libs.kotlinPoet) implementation(libs.kotlinReflect) diff --git a/pkl-commons-cli/pkl-commons-cli.gradle.kts b/pkl-commons-cli/pkl-commons-cli.gradle.kts index a718de00..7181d2d5 100644 --- a/pkl-commons-cli/pkl-commons-cli.gradle.kts +++ b/pkl-commons-cli/pkl-commons-cli.gradle.kts @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ plugins { pklAllProjects pklKotlinLibrary diff --git a/pkl-commons-test/pkl-commons-test.gradle.kts b/pkl-commons-test/pkl-commons-test.gradle.kts index 72f290d0..240fc513 100644 --- a/pkl-commons-test/pkl-commons-test.gradle.kts +++ b/pkl-commons-test/pkl-commons-test.gradle.kts @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ import java.security.MessageDigest plugins { @@ -19,8 +34,8 @@ dependencies { /** * Creates test packages from the `src/test/files/packages` directory. * - * These packages are used by PackageServer to serve assets when running - * LanguageSnippetTests and PackageResolversTest. + * These packages are used by PackageServer to serve assets when running LanguageSnippetTests and + * PackageResolversTest. */ val createTestPackages by tasks.registering @@ -38,38 +53,38 @@ for (packageDir in file("src/main/files/packages").listFiles()!!) { val zipFileName = "${packageDir.name}.zip" val archiveFile = destinationDir.map { it.file(zipFileName) } - val zipTask = tasks.register("zip-${packageDir.name}", Zip::class) { - destinationDirectory.set(destinationDir) - archiveFileName.set(zipFileName) - from(packageContents) - // required so that checksums are reproducible - isPreserveFileTimestamps = false - isReproducibleFileOrder = true - } - - val copyTask = tasks.register("copy-${packageDir.name}", Copy::class) { - dependsOn(zipTask) - from(metadataJson) - into(destinationDir) - val shasumFile = destinationDir.map { it.file("${packageDir.name}.json.sha256") } - outputs.file(shasumFile) - filter { line -> - line.replaceFirst("\$computedChecksum", archiveFile.get().asFile.computeChecksum()) + val zipTask = + tasks.register("zip-${packageDir.name}", Zip::class) { + destinationDirectory.set(destinationDir) + archiveFileName.set(zipFileName) + from(packageContents) + // required so that checksums are reproducible + isPreserveFileTimestamps = false + isReproducibleFileOrder = true } - doLast { - val outputFile = destinationDir.get().asFile.resolve("${packageDir.name}.json") - if (buildInfo.os.isWindows) { - val contents = outputFile.readText() - // workaround for https://github.com/gradle/gradle/issues/1151 - outputFile.writeText(contents.replace("\r\n", "\n")) + + val copyTask = + tasks.register("copy-${packageDir.name}", Copy::class) { + dependsOn(zipTask) + from(metadataJson) + into(destinationDir) + val shasumFile = destinationDir.map { it.file("${packageDir.name}.json.sha256") } + outputs.file(shasumFile) + filter { line -> + line.replaceFirst("\$computedChecksum", archiveFile.get().asFile.computeChecksum()) + } + doLast { + val outputFile = destinationDir.get().asFile.resolve("${packageDir.name}.json") + if (buildInfo.os.isWindows) { + val contents = outputFile.readText() + // workaround for https://github.com/gradle/gradle/issues/1151 + outputFile.writeText(contents.replace("\r\n", "\n")) + } + shasumFile.get().asFile.writeText(outputFile.computeChecksum()) } - shasumFile.get().asFile.writeText(outputFile.computeChecksum()) } - } - createTestPackages.configure { - dependsOn(copyTask) - } + createTestPackages.configure { dependsOn(copyTask) } } val keystoreDir = layout.buildDirectory.dir("keystore") @@ -77,47 +92,61 @@ val keystoreName = "localhost.p12" val keystoreFile = keystoreDir.map { it.file(keystoreName) } val certsFileName = "localhost.pem" -val generateKeys by tasks.registering(JavaExec::class) { - outputs.file(keystoreFile) - mainClass.set("sun.security.tools.keytool.Main") - args = listOf( - "-genkeypair", - "-keyalg", "RSA", - "-alias", "integ_tests", - "-keystore", keystoreName, - "-storepass", "password", - "-dname", "CN=localhost" - ) - workingDir(keystoreDir) - doFirst { - workingDir.mkdirs() - keystoreFile.get().asFile.delete() +val generateKeys by + tasks.registering(JavaExec::class) { + outputs.file(keystoreFile) + mainClass.set("sun.security.tools.keytool.Main") + args = + listOf( + "-genkeypair", + "-keyalg", + "RSA", + "-alias", + "integ_tests", + "-keystore", + keystoreName, + "-storepass", + "password", + "-dname", + "CN=localhost" + ) + workingDir(keystoreDir) + doFirst { + workingDir.mkdirs() + keystoreFile.get().asFile.delete() + } } -} -val exportCerts by tasks.registering(JavaExec::class) { - val outputFile = keystoreDir.map { it.file(certsFileName) } - dependsOn(generateKeys) - inputs.file(keystoreFile) - outputs.file(outputFile) - mainClass.set("sun.security.tools.keytool.Main") - args = listOf( - "-exportcert", - "-alias", "integ_tests", - "-storepass", "password", - "-keystore", keystoreName, - "-rfc", - "-file", certsFileName - ) - workingDir(keystoreDir) - doFirst { - workingDir.mkdirs() - outputFile.get().asFile.delete() +val exportCerts by + tasks.registering(JavaExec::class) { + val outputFile = keystoreDir.map { it.file(certsFileName) } + dependsOn(generateKeys) + inputs.file(keystoreFile) + outputs.file(outputFile) + mainClass.set("sun.security.tools.keytool.Main") + args = + listOf( + "-exportcert", + "-alias", + "integ_tests", + "-storepass", + "password", + "-keystore", + keystoreName, + "-rfc", + "-file", + certsFileName + ) + workingDir(keystoreDir) + doFirst { + workingDir.mkdirs() + outputFile.get().asFile.delete() + } } -} fun toHex(hash: ByteArray): String { - val hexDigitTable = charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f') + val hexDigitTable = + charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f') return buildString(hash.size * 2) { for (b in hash) { append(hexDigitTable[b.toInt() shr 4 and 0xF]) diff --git a/pkl-commons/pkl-commons.gradle.kts b/pkl-commons/pkl-commons.gradle.kts index 8d3fdd93..276aebc0 100644 --- a/pkl-commons/pkl-commons.gradle.kts +++ b/pkl-commons/pkl-commons.gradle.kts @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ plugins { pklAllProjects pklKotlinLibrary diff --git a/pkl-config-java/pkl-config-java.gradle.kts b/pkl-config-java/pkl-config-java.gradle.kts index 134c1b3e..d0573317 100644 --- a/pkl-config-java/pkl-config-java.gradle.kts +++ b/pkl-config-java/pkl-config-java.gradle.kts @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ plugins { pklAllProjects pklJavaLibrary @@ -9,55 +24,53 @@ plugins { val pklCodegenJava: Configuration by configurations.creating val firstPartySourcesJars by configurations.existing -val generateTestConfigClasses by tasks.registering(JavaExec::class) { - val outputDir = layout.buildDirectory.dir("testConfigClasses") - outputs.dir(outputDir) - inputs.dir("src/test/resources/codegenPkl") +val generateTestConfigClasses by + tasks.registering(JavaExec::class) { + val outputDir = layout.buildDirectory.dir("testConfigClasses") + outputs.dir(outputDir) + inputs.dir("src/test/resources/codegenPkl") - classpath = pklCodegenJava - mainClass.set("org.pkl.codegen.java.Main") - argumentProviders.add(CommandLineArgumentProvider { - listOf( - "--output-dir", outputDir.get().asFile.path, - "--generate-javadoc" - ) + fileTree("src/test/resources/codegenPkl").map { it.path } - }) -} + classpath = pklCodegenJava + mainClass.set("org.pkl.codegen.java.Main") + argumentProviders.add( + CommandLineArgumentProvider { + listOf("--output-dir", outputDir.get().asFile.path, "--generate-javadoc") + + fileTree("src/test/resources/codegenPkl").map { it.path } + } + ) + } -tasks.processTestResources { - dependsOn(generateTestConfigClasses) -} +tasks.processTestResources { dependsOn(generateTestConfigClasses) } -tasks.compileTestKotlin { - dependsOn(generateTestConfigClasses) -} +tasks.compileTestKotlin { dependsOn(generateTestConfigClasses) } -val bundleTests by tasks.registering(Jar::class) { - from(sourceSets.test.get().output) -} +val bundleTests by tasks.registering(Jar::class) { from(sourceSets.test.get().output) } // Runs unit tests using jar'd class files as a source. -// This is to test loading the ClassRegistry from within a jar, as opposed to directly from the file system. -val testFromJar by tasks.registering(Test::class) { - dependsOn(bundleTests) +// This is to test loading the ClassRegistry from within a jar, as opposed to directly from the file +// system. +val testFromJar by + tasks.registering(Test::class) { + dependsOn(bundleTests) - testClassesDirs = files(tasks.test.get().testClassesDirs) + testClassesDirs = files(tasks.test.get().testClassesDirs) - classpath = - // compiled test classes - bundleTests.get().outputs.files + - // fat Jar - tasks.shadowJar.get().outputs.files + - // test-only dependencies - // (test dependencies that are also main dependencies must already be contained in fat Jar; - // to verify that, we don't want to include them here) - (configurations.testRuntimeClasspath.get() - configurations.runtimeClasspath.get()) -} + classpath = + // compiled test classes + bundleTests.get().outputs.files + + // fat Jar + tasks.shadowJar.get().outputs.files + + // test-only dependencies + // (test dependencies that are also main dependencies must already be contained in fat Jar; + // to verify that, we don't want to include them here) + (configurations.testRuntimeClasspath.get() - configurations.runtimeClasspath.get()) + } -// TODO: the below snippet causes `./gradlew check` to fail specifically on `pkl-codegen-java:check`. Why? -//tasks.test { +// TODO: the below snippet causes `./gradlew check` to fail specifically on +// `pkl-codegen-java:check`. Why? +// tasks.test { // dependsOn(testFromJar) -//} +// } sourceSets.getByName("test") { java.srcDir(layout.buildDirectory.dir("testConfigClasses/java")) @@ -77,9 +90,7 @@ dependencies { pklCodegenJava(projects.pklCodegenJava) } -tasks.shadowJar { - archiveBaseName.set("pkl-config-java-all") -} +tasks.shadowJar { archiveBaseName.set("pkl-config-java-all") } publishing { publications { @@ -94,12 +105,12 @@ publishing { artifactId = "pkl-config-java-all" pom { url.set("https://github.com/apple/pkl/tree/main/pkl-config-java") - description.set("Shaded fat Jar for pkl-config-java, a Java config library based on the Pkl config language.") + description.set( + "Shaded fat Jar for pkl-config-java, a Java config library based on the Pkl config language." + ) } } } } -signing { - sign(publishing.publications["fatJar"]) -} +signing { sign(publishing.publications["fatJar"]) } diff --git a/pkl-config-java/src/test/java/org/pkl/config/java/mapper/PolymorphicTest.kt b/pkl-config-java/src/test/java/org/pkl/config/java/mapper/PolymorphicTest.kt index 22f1b839..1a83403d 100644 --- a/pkl-config-java/src/test/java/org/pkl/config/java/mapper/PolymorphicTest.kt +++ b/pkl-config-java/src/test/java/org/pkl/config/java/mapper/PolymorphicTest.kt @@ -1,19 +1,37 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.config.java.mapper -import org.pkl.config.java.ConfigEvaluator -import org.pkl.core.ModuleSource import com.example.Lib import com.example.PolymorphicModuleTest import com.example.PolymorphicModuleTest.Strudel import com.example.PolymorphicModuleTest.TurkishDelight import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test +import org.pkl.config.java.ConfigEvaluator +import org.pkl.core.ModuleSource class PolymorphicTest { @Test fun `deserializing polymorphic objects`() { val evaluator = ConfigEvaluator.preconfigured() - val module = evaluator.evaluate(ModuleSource.modulePath("/codegenPkl/PolymorphicModuleTest.pkl")).`as`(PolymorphicModuleTest::class.java) + val module = + evaluator + .evaluate(ModuleSource.modulePath("/codegenPkl/PolymorphicModuleTest.pkl")) + .`as`(PolymorphicModuleTest::class.java) assertThat(module.desserts[0]).isInstanceOf(Strudel::class.java) assertThat(module.desserts[1]).isInstanceOf(TurkishDelight::class.java) assertThat(module.planes[0]).isInstanceOf(Lib.Jet::class.java) diff --git a/pkl-config-kotlin/pkl-config-kotlin.gradle.kts b/pkl-config-kotlin/pkl-config-kotlin.gradle.kts index 731f224f..797f8000 100644 --- a/pkl-config-kotlin/pkl-config-kotlin.gradle.kts +++ b/pkl-config-kotlin/pkl-config-kotlin.gradle.kts @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ plugins { pklAllProjects pklKotlinLibrary @@ -23,61 +38,61 @@ dependencies { pklCodegenKotlin(projects.pklCodegenKotlin) implementation(libs.kotlinReflect) - + testImplementation(libs.geantyref) } -val generateTestConfigClasses by tasks.registering(JavaExec::class) { - val outputDir = layout.buildDirectory.dir("testConfigClasses") - outputs.dir(outputDir) - inputs.dir("src/test/resources/codegenPkl") +val generateTestConfigClasses by + tasks.registering(JavaExec::class) { + val outputDir = layout.buildDirectory.dir("testConfigClasses") + outputs.dir(outputDir) + inputs.dir("src/test/resources/codegenPkl") - classpath = pklCodegenKotlin - mainClass.set("org.pkl.codegen.kotlin.Main") - argumentProviders.add(CommandLineArgumentProvider { - listOf("--output-dir", outputDir.get().asFile.absolutePath) + - fileTree("src/test/resources/codegenPkl").map { it.absolutePath } - }) -} + classpath = pklCodegenKotlin + mainClass.set("org.pkl.codegen.kotlin.Main") + argumentProviders.add( + CommandLineArgumentProvider { + listOf("--output-dir", outputDir.get().asFile.absolutePath) + + fileTree("src/test/resources/codegenPkl").map { it.absolutePath } + } + ) + } sourceSets.getByName("test") { java.srcDir(layout.buildDirectory.dir("testConfigClasses/kotlin")) resources.srcDir(layout.buildDirectory.dir("testConfigClasses/resources")) } -tasks.processTestResources { - dependsOn(generateTestConfigClasses) -} +tasks.processTestResources { dependsOn(generateTestConfigClasses) } -tasks.compileTestKotlin { - dependsOn(generateTestConfigClasses) -} +tasks.compileTestKotlin { dependsOn(generateTestConfigClasses) } // use pkl-config-java-all for testing (same as for publishing) -tasks.test { - classpath = classpath - pklConfigJava + pklConfigJavaAll -} +tasks.test { classpath = classpath - pklConfigJava + pklConfigJavaAll } -// disable publishing of .module until we find a way to manipulate it like POM (or ideally both together) -tasks.withType { - enabled = false -} +// disable publishing of .module until we find a way to manipulate it like POM (or ideally both +// together) +tasks.withType { enabled = false } publishing { publications { named("library") { pom { url.set("https://github.com/apple/pkl/tree/main/pkl-config-kotlin") - description.set("Kotlin extensions for pkl-config-java, a Java config library based on the Pkl config language.") + description.set( + "Kotlin extensions for pkl-config-java, a Java config library based on the Pkl config language." + ) // change dependency pkl-config-java to pkl-config-java-all withXml { val projectElement = asElement() - val dependenciesElement = projectElement.getElementsByTagName("dependencies").item(0) as org.w3c.dom.Element + val dependenciesElement = + projectElement.getElementsByTagName("dependencies").item(0) as org.w3c.dom.Element val dependencyElements = dependenciesElement.getElementsByTagName("dependency") for (idx in 0 until dependencyElements.length) { val dependencyElement = dependencyElements.item(idx) as org.w3c.dom.Element - val artifactIdElement = dependencyElement.getElementsByTagName("artifactId").item(0) as org.w3c.dom.Element + val artifactIdElement = + dependencyElement.getElementsByTagName("artifactId").item(0) as org.w3c.dom.Element if (artifactIdElement.textContent == "pkl-config-java") { artifactIdElement.textContent = "pkl-config-java-all" return@withXml diff --git a/pkl-core/pkl-core.gradle.kts b/pkl-core/pkl-core.gradle.kts index 4d77ae74..9cffebde 100644 --- a/pkl-core/pkl-core.gradle.kts +++ b/pkl-core/pkl-core.gradle.kts @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ import org.apache.tools.ant.filters.ReplaceTokens plugins { @@ -12,13 +27,7 @@ plugins { val generatorSourceSet = sourceSets.register("generator") -sourceSets { - main { - java { - srcDir(file("generated/antlr")) - } - } -} +sourceSets { main { java { srcDir(file("generated/antlr")) } } } idea { module { @@ -51,16 +60,14 @@ dependencies { implementation(libs.truffleApi) implementation(libs.graalSdk) - implementation(libs.paguro) { - exclude(group = "org.jetbrains", module = "annotations") - } + implementation(libs.paguro) { exclude(group = "org.jetbrains", module = "annotations") } implementation(libs.snakeYaml) - + implementation(libs.jansi) testImplementation(projects.pklCommonsTest) - + add("generatorImplementation", libs.javaPoet) add("generatorImplementation", libs.truffleApi) add("generatorImplementation", libs.kotlinStdLib) @@ -73,11 +80,14 @@ publishing { named("library") { pom { url.set("https://github.com/apple/pkl/tree/main/pkl-core") - description.set(""" + description.set( + """ Core implementation of the Pkl configuration language. Includes Java APIs for embedding the language into JVM applications, and for building libraries and tools on top of the language. - """.trimIndent()) + """ + .trimIndent() + ) } } } @@ -97,63 +107,52 @@ tasks.generateGrammarSource { outputDirectory = file("generated/antlr/org/pkl/core/parser/antlr") } -tasks.compileJava { - dependsOn(tasks.generateGrammarSource) -} +tasks.compileJava { dependsOn(tasks.generateGrammarSource) } -tasks.sourcesJar { - dependsOn(tasks.generateGrammarSource) -} +tasks.sourcesJar { dependsOn(tasks.generateGrammarSource) } -tasks.generateTestGrammarSource { - enabled = false -} -tasks.named("generateGeneratorGrammarSource") { - enabled = false -} +tasks.generateTestGrammarSource { enabled = false } + +tasks.named("generateGeneratorGrammarSource") { enabled = false } // Satisfy expectations of IntelliJ ANTLR plugin, // which can't otherwise cope with our ANTLR setup. -val makeIntelliJAntlrPluginHappy by tasks.registering(Copy::class) { - dependsOn(tasks.generateGrammarSource) - into("src/main/antlr") - from("generated/antlr/org/pkl/core/parser/antlr") { - include("PklLexer.tokens") +val makeIntelliJAntlrPluginHappy by + tasks.registering(Copy::class) { + dependsOn(tasks.generateGrammarSource) + into("src/main/antlr") + from("generated/antlr/org/pkl/core/parser/antlr") { include("PklLexer.tokens") } } -} tasks.processResources { inputs.property("version", buildInfo.pklVersion) inputs.property("commitId", buildInfo.commitId) filesMatching("org/pkl/core/Release.properties") { - val stdlibModules = fileTree("$rootDir/stdlib") { - include("*.pkl") - exclude("doc-package-info.pkl") - }.map { "pkl:" + it.nameWithoutExtension } - .sortedBy { it.lowercase() } - - filter("tokens" to mapOf( - "version" to buildInfo.pklVersion, - "commitId" to buildInfo.commitId, - "stdlibModules" to stdlibModules.joinToString(",") - )) + val stdlibModules = + fileTree("$rootDir/stdlib") { + include("*.pkl") + exclude("doc-package-info.pkl") + } + .map { "pkl:" + it.nameWithoutExtension } + .sortedBy { it.lowercase() } + + filter( + "tokens" to + mapOf( + "version" to buildInfo.pklVersion, + "commitId" to buildInfo.commitId, + "stdlibModules" to stdlibModules.joinToString(",") + ) + ) } - into("org/pkl/core/stdlib") { - from("$rootDir/stdlib") { - include("*.pkl") - } - } + into("org/pkl/core/stdlib") { from("$rootDir/stdlib") { include("*.pkl") } } } -tasks.compileJava { - options.generatedSourceOutputDirectory.set(file("generated/truffle")) -} +tasks.compileJava { options.generatedSourceOutputDirectory.set(file("generated/truffle")) } -tasks.compileKotlin { - enabled = false -} +tasks.compileKotlin { enabled = false } tasks.test { configureTest() @@ -166,52 +165,58 @@ tasks.test { } } -val testJavaExecutable by tasks.registering(Test::class) { - configureExecutableTest("LanguageSnippetTestsEngine") - classpath = - // compiled test classes - sourceSets.test.get().output + - // java executable - javaExecutableConfiguration + - // test-only dependencies - // (test dependencies that are also main dependencies must already be contained in java executable; - // to verify that we don't want to include them here) - (configurations.testRuntimeClasspath.get() - configurations.runtimeClasspath.get()) -} +val testJavaExecutable by + tasks.registering(Test::class) { + configureExecutableTest("LanguageSnippetTestsEngine") + classpath = + // compiled test classes + sourceSets.test.get().output + + // java executable + javaExecutableConfiguration + + // test-only dependencies + // (test dependencies that are also main dependencies must already be contained in java + // executable; + // to verify that we don't want to include them here) + (configurations.testRuntimeClasspath.get() - configurations.runtimeClasspath.get()) + } -tasks.check { - dependsOn(testJavaExecutable) -} +tasks.check { dependsOn(testJavaExecutable) } -val testMacExecutableAmd64 by tasks.registering(Test::class) { - dependsOn(":pkl-cli:macExecutableAmd64") - configureExecutableTest("MacAmd64LanguageSnippetTestsEngine") -} +val testMacExecutableAmd64 by + tasks.registering(Test::class) { + dependsOn(":pkl-cli:macExecutableAmd64") + configureExecutableTest("MacAmd64LanguageSnippetTestsEngine") + } -val testMacExecutableAarch64 by tasks.registering(Test::class) { - dependsOn(":pkl-cli:macExecutableAarch64") - configureExecutableTest("MacAarch64LanguageSnippetTestsEngine") -} +val testMacExecutableAarch64 by + tasks.registering(Test::class) { + dependsOn(":pkl-cli:macExecutableAarch64") + configureExecutableTest("MacAarch64LanguageSnippetTestsEngine") + } -val testLinuxExecutableAmd64 by tasks.registering(Test::class) { - dependsOn(":pkl-cli:linuxExecutableAmd64") - configureExecutableTest("LinuxAmd64LanguageSnippetTestsEngine") -} +val testLinuxExecutableAmd64 by + tasks.registering(Test::class) { + dependsOn(":pkl-cli:linuxExecutableAmd64") + configureExecutableTest("LinuxAmd64LanguageSnippetTestsEngine") + } -val testLinuxExecutableAarch64 by tasks.registering(Test::class) { - dependsOn(":pkl-cli:linuxExecutableAarch64") - configureExecutableTest("LinuxAarch64LanguageSnippetTestsEngine") -} +val testLinuxExecutableAarch64 by + tasks.registering(Test::class) { + dependsOn(":pkl-cli:linuxExecutableAarch64") + configureExecutableTest("LinuxAarch64LanguageSnippetTestsEngine") + } -val testAlpineExecutableAmd64 by tasks.registering(Test::class) { - dependsOn(":pkl-cli:alpineExecutableAmd64") - configureExecutableTest("AlpineLanguageSnippetTestsEngine") -} +val testAlpineExecutableAmd64 by + tasks.registering(Test::class) { + dependsOn(":pkl-cli:alpineExecutableAmd64") + configureExecutableTest("AlpineLanguageSnippetTestsEngine") + } -val testWindowsExecutableAmd64 by tasks.registering(Test::class) { - dependsOn(":pkl-cli:windowsExecutableAmd64") - configureExecutableTest("WindowsLanguageSnippetTestsEngine") -} +val testWindowsExecutableAmd64 by + tasks.registering(Test::class) { + dependsOn(":pkl-cli:windowsExecutableAmd64") + configureExecutableTest("WindowsLanguageSnippetTestsEngine") + } tasks.testNative { when { @@ -249,13 +254,16 @@ spotless { } private fun Test.configureTest() { - inputs.dir("src/test/files/LanguageSnippetTests/input") + inputs + .dir("src/test/files/LanguageSnippetTests/input") .withPropertyName("languageSnippetTestsInput") .withPathSensitivity(PathSensitivity.RELATIVE) - inputs.dir("src/test/files/LanguageSnippetTests/input-helper") + inputs + .dir("src/test/files/LanguageSnippetTests/input-helper") .withPropertyName("languageSnippetTestsInputHelper") .withPathSensitivity(PathSensitivity.RELATIVE) - inputs.dir("src/test/files/LanguageSnippetTests/output") + inputs + .dir("src/test/files/LanguageSnippetTests/output") .withPropertyName("languageSnippetTestsOutput") .withPathSensitivity(PathSensitivity.RELATIVE) } @@ -264,7 +272,5 @@ private fun Test.configureExecutableTest(engineName: String) { configureTest() testClassesDirs = files(tasks.test.get().testClassesDirs) classpath = tasks.test.get().classpath - useJUnitPlatform { - includeEngines(engineName) - } + useJUnitPlatform { includeEngines(engineName) } } diff --git a/pkl-core/src/generator/kotlin/org/pkl/core/generator/MemberRegistryGenerator.kt b/pkl-core/src/generator/kotlin/org/pkl/core/generator/MemberRegistryGenerator.kt index cc866ccf..f3e2e37a 100644 --- a/pkl-core/src/generator/kotlin/org/pkl/core/generator/MemberRegistryGenerator.kt +++ b/pkl-core/src/generator/kotlin/org/pkl/core/generator/MemberRegistryGenerator.kt @@ -1,26 +1,41 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.generator import com.oracle.truffle.api.dsl.GeneratedBy import com.squareup.javapoet.ClassName -import javax.lang.model.SourceVersion -import javax.annotation.processing.RoundEnvironment -import com.squareup.javapoet.MethodSpec import com.squareup.javapoet.JavaFile +import com.squareup.javapoet.MethodSpec import com.squareup.javapoet.TypeSpec import javax.annotation.processing.AbstractProcessor +import javax.annotation.processing.RoundEnvironment +import javax.lang.model.SourceVersion import javax.lang.model.element.* import javax.lang.model.type.TypeMirror /** - * Generates a subclass of `org.pkl.core.stdlib.registry.ExternalMemberRegistry` - * for each stdlib module and a factory to instantiate them. - * Generated classes are written to `generated/truffle/org/pkl/core/stdlib/registry`. - * + * Generates a subclass of `org.pkl.core.stdlib.registry.ExternalMemberRegistry` for each stdlib + * module and a factory to instantiate them. Generated classes are written to + * `generated/truffle/org/pkl/core/stdlib/registry`. + * * Inputs: - * - Generated Truffle node classes for stdlib members. - * These classes are located in subpackages of `org.pkl.core.stdlib` - * and identified via their `@GeneratedBy` annotations. - * - `@PklName` annotations on handwritten node classes from which Truffle node classes are generated. + * - Generated Truffle node classes for stdlib members. These classes are located in subpackages of + * `org.pkl.core.stdlib` and identified via their `@GeneratedBy` annotations. + * - `@PklName` annotations on handwritten node classes from which Truffle node classes are + * generated. */ class MemberRegistryGenerator : AbstractProcessor() { private val truffleNodeClassSuffix = "NodeGen" @@ -35,10 +50,8 @@ class MemberRegistryGenerator : AbstractProcessor() { ClassName.get(registryPackageName, "EmptyMemberRegistry") private val memberRegistryFactoryClassName: ClassName = ClassName.get(registryPackageName, "MemberRegistryFactory") - private val moduleKeyClassName: ClassName = - ClassName.get(modulePackageName, "ModuleKey") - private val moduleKeysClassName: ClassName = - ClassName.get(modulePackageName, "ModuleKeys") + private val moduleKeyClassName: ClassName = ClassName.get(modulePackageName, "ModuleKey") + private val moduleKeysClassName: ClassName = ClassName.get(modulePackageName, "ModuleKeys") override fun getSupportedAnnotationTypes(): Set = setOf(GeneratedBy::class.java.name) @@ -54,19 +67,27 @@ class MemberRegistryGenerator : AbstractProcessor() { return true } - private fun collectNodeClasses(roundEnv: RoundEnvironment) = roundEnv - .getElementsAnnotatedWith(GeneratedBy::class.java) - .asSequence() - .filterIsInstance() - .filter { it.qualifiedName.toString().startsWith(stdLibPackageName) } - .filter { it.simpleName.toString().endsWith(truffleNodeClassSuffix) } - .sortedWith(compareBy( - { if (it.enclosingElement.kind == ElementKind.PACKAGE) "" else it.enclosingElement.simpleName.toString() }, - { it.simpleName.toString() } - )) - .groupBy { processingEnv.elementUtils.getPackageOf(it) } + private fun collectNodeClasses(roundEnv: RoundEnvironment) = + roundEnv + .getElementsAnnotatedWith(GeneratedBy::class.java) + .asSequence() + .filterIsInstance() + .filter { it.qualifiedName.toString().startsWith(stdLibPackageName) } + .filter { it.simpleName.toString().endsWith(truffleNodeClassSuffix) } + .sortedWith( + compareBy( + { + if (it.enclosingElement.kind == ElementKind.PACKAGE) "" + else it.enclosingElement.simpleName.toString() + }, + { it.simpleName.toString() } + ) + ) + .groupBy { processingEnv.elementUtils.getPackageOf(it) } - private fun generateRegistryClasses(nodeClassesByPackage: Map>) { + private fun generateRegistryClasses( + nodeClassesByPackage: Map> + ) { for ((pkg, nodeClasses) in nodeClassesByPackage) { generateRegistryClass(pkg, nodeClasses) } @@ -75,32 +96,38 @@ class MemberRegistryGenerator : AbstractProcessor() { private fun generateRegistryClass(pkg: PackageElement, nodeClasses: List) { val pklModuleName = getAnnotatedPklName(pkg) ?: pkg.simpleName.toString() val pklModuleNameCapitalized = pklModuleName.capitalize() - val registryClassName = ClassName.get(registryPackageName, "${pklModuleNameCapitalized}MemberRegistry") + val registryClassName = + ClassName.get(registryPackageName, "${pklModuleNameCapitalized}MemberRegistry") - val registryClass = TypeSpec.classBuilder(registryClassName) - .addJavadoc("Generated by {@link ${this::class.qualifiedName}}.") - .addModifiers(Modifier.FINAL) - .superclass(externalMemberRegistryClassName) + val registryClass = + TypeSpec.classBuilder(registryClassName) + .addJavadoc("Generated by {@link ${this::class.qualifiedName}}.") + .addModifiers(Modifier.FINAL) + .superclass(externalMemberRegistryClassName) val registryClassConstructor = MethodSpec.constructorBuilder() for (nodeClass in nodeClasses) { val enclosingClass = nodeClass.enclosingElement - val pklClassName = getAnnotatedPklName(enclosingClass) - ?: enclosingClass.simpleName.toString().removeSuffix(truffleNodeFactorySuffix) - val pklMemberName = getAnnotatedPklName(nodeClass) - ?: nodeClass.simpleName.toString().removeSuffix(truffleNodeClassSuffix) - val pklMemberNameQualified = when (pklClassName) { - // By convention, the top-level class containing node classes - // for *module* members is named `Nodes`. - // Example: `BaseNodes` for pkl.base - pklModuleNameCapitalized -> - "pkl.$pklModuleName#$pklMemberName" - else -> - "pkl.$pklModuleName#$pklClassName.$pklMemberName" - } + val pklClassName = + getAnnotatedPklName(enclosingClass) + ?: enclosingClass.simpleName.toString().removeSuffix(truffleNodeFactorySuffix) + val pklMemberName = + getAnnotatedPklName(nodeClass) + ?: nodeClass.simpleName.toString().removeSuffix(truffleNodeClassSuffix) + val pklMemberNameQualified = + when (pklClassName) { + // By convention, the top-level class containing node classes + // for *module* members is named `Nodes`. + // Example: `BaseNodes` for pkl.base + pklModuleNameCapitalized -> "pkl.$pklModuleName#$pklMemberName" + else -> "pkl.$pklModuleName#$pklClassName.$pklMemberName" + } registryClass.addOriginatingElement(nodeClass) - registryClassConstructor - .addStatement("register(\$S, \$T::create)", pklMemberNameQualified, nodeClass) + registryClassConstructor.addStatement( + "register(\$S, \$T::create)", + pklMemberNameQualified, + nodeClass + ) } registryClass.addMethod(registryClassConstructor.build()) @@ -109,25 +136,27 @@ class MemberRegistryGenerator : AbstractProcessor() { } private fun generateRegistryFactoryClass(packages: Collection) { - val registryFactoryClass = TypeSpec.classBuilder(memberRegistryFactoryClassName) - .addJavadoc("Generated by {@link ${this::class.qualifiedName}}.") - .addModifiers(Modifier.PUBLIC, Modifier.FINAL) - val registryFactoryConstructor = MethodSpec.constructorBuilder() - .addModifiers(Modifier.PRIVATE) + val registryFactoryClass = + TypeSpec.classBuilder(memberRegistryFactoryClassName) + .addJavadoc("Generated by {@link ${this::class.qualifiedName}}.") + .addModifiers(Modifier.PUBLIC, Modifier.FINAL) + val registryFactoryConstructor = MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE) registryFactoryClass.addMethod(registryFactoryConstructor.build()) - val registryFactoryGetMethod = MethodSpec.methodBuilder("get") - .addModifiers(Modifier.PUBLIC, Modifier.STATIC) - .addParameter(moduleKeyClassName, "moduleKey") - .returns(externalMemberRegistryClassName) - .beginControlFlow("if (!\$T.isStdLibModule(moduleKey))", moduleKeysClassName) - .addStatement("return \$T.INSTANCE", emptyMemberRegistryClassName) - .endControlFlow() - .beginControlFlow("switch (moduleKey.getUri().getSchemeSpecificPart())") + val registryFactoryGetMethod = + MethodSpec.methodBuilder("get") + .addModifiers(Modifier.PUBLIC, Modifier.STATIC) + .addParameter(moduleKeyClassName, "moduleKey") + .returns(externalMemberRegistryClassName) + .beginControlFlow("if (!\$T.isStdLibModule(moduleKey))", moduleKeysClassName) + .addStatement("return \$T.INSTANCE", emptyMemberRegistryClassName) + .endControlFlow() + .beginControlFlow("switch (moduleKey.getUri().getSchemeSpecificPart())") for (pkg in packages) { val pklModuleName = getAnnotatedPklName(pkg) ?: pkg.simpleName.toString() val pklModuleNameCapitalized = pklModuleName.capitalize() - val registryClassName = ClassName.get(registryPackageName, "${pklModuleNameCapitalized}MemberRegistry") + val registryClassName = + ClassName.get(registryPackageName, "${pklModuleNameCapitalized}MemberRegistry") // declare dependency on package-info.java (for `@PklName`) registryFactoryClass.addOriginatingElement(pkg) @@ -148,8 +177,7 @@ class MemberRegistryGenerator : AbstractProcessor() { private fun getAnnotatedPklName(element: Element): String? { for (annotation in element.annotationMirrors) { when (annotation.annotationType.asElement().simpleName.toString()) { - "PklName" -> - return annotation.elementValues.values.iterator().next().value.toString() + "PklName" -> return annotation.elementValues.values.iterator().next().value.toString() "GeneratedBy" -> { val annotationValue = annotation.elementValues.values.first().value as TypeMirror return getAnnotatedPklName(processingEnv.typeUtils.asElement(annotationValue)) diff --git a/pkl-core/src/test/kotlin/org/pkl/core/ClassInheritanceTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/ClassInheritanceTest.kt index a100ce02..44b958a9 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/ClassInheritanceTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/ClassInheritanceTest.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core import org.assertj.core.api.Assertions.assertThat @@ -8,9 +23,10 @@ class ClassInheritanceTest { @Test fun `property override without type annotation is considered an object property definition`() { - val module = evaluator.evaluateSchema( - ModuleSource.text( - """ + val module = + evaluator.evaluateSchema( + ModuleSource.text( + """ class Thing open class Base { hidden thing: Thing @@ -18,9 +34,10 @@ class ClassInheritanceTest { class Derived extends Base { thing {} } - """.trimIndent() + """ + .trimIndent() + ) ) - ) val derivedClass = module.classes["Derived"]!! assertThat(derivedClass.properties["thing"]).isNull() @@ -33,9 +50,10 @@ class ClassInheritanceTest { @Test fun `property override with type annotation is considered a class property definition`() { - val module = evaluator.evaluateSchema( - ModuleSource.text( - """ + val module = + evaluator.evaluateSchema( + ModuleSource.text( + """ class Thing open class Base { hidden thing: Thing @@ -43,9 +61,10 @@ class ClassInheritanceTest { class Derived extends Base { thing: Thing = new {} } - """.trimIndent() + """ + .trimIndent() + ) ) - ) val derivedClass = module.classes["Derived"]!! val thingProperty = derivedClass.properties["thing"] diff --git a/pkl-core/src/test/kotlin/org/pkl/core/DataSizeTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/DataSizeTest.kt index e56bbeab..081a7c15 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/DataSizeTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/DataSizeTest.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core import org.assertj.core.api.Assertions.assertThat diff --git a/pkl-core/src/test/kotlin/org/pkl/core/DataSizeUnitTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/DataSizeUnitTest.kt index 9449d783..2827d102 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/DataSizeUnitTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/DataSizeUnitTest.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core import org.assertj.core.api.Assertions.assertThat diff --git a/pkl-core/src/test/kotlin/org/pkl/core/DurationTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/DurationTest.kt index 5a01ba8e..ce7bd0ba 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/DurationTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/DurationTest.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core import kotlin.math.nextDown @@ -68,10 +83,9 @@ class DurationTest { assertThat(duration1.convertTo(MILLIS)).isEqualTo(duration2) assertThat(duration2.convertTo(SECONDS)).isEqualTo(duration1) - assertThat(duration4.convertTo(NANOS)) - .isEqualTo(Duration(0.0, NANOS)) + assertThat(duration4.convertTo(NANOS)).isEqualTo(Duration(0.0, NANOS)) } - + @Test fun toIsoString() { assertThat(duration1.toIsoString()).isEqualTo("PT0.3S") @@ -79,8 +93,10 @@ class DurationTest { assertThat(duration3.toIsoString()).isEqualTo("PT0.3001S") assertThat(duration4.toIsoString()).isEqualTo("PT0S") assertThat(Duration(1.0, NANOS).toIsoString()).isEqualTo("PT0.000000001S") - // Although ISO8601 allows for durations (P) denoted in days, months and years, it is not recommended. - // The day notation can express an hour more or less, depending on whether it crosses a daylight savings transition, + // Although ISO8601 allows for durations (P) denoted in days, months and years, it is not + // recommended. + // The day notation can express an hour more or less, depending on whether it crosses a daylight + // savings transition, // when added to "now" (at the time of evaluation). assertThat(Duration(100.0, DAYS).toIsoString()).isEqualTo("PT2400H") } @@ -96,165 +112,132 @@ class DurationTest { @Test fun `toJavaDuration() - positive`() { assertThat(Duration(999.0, NANOS).toJavaDuration()).isEqualTo(java.time.Duration.ofNanos(999)) - assertThat(Duration(999999.0, NANOS).toJavaDuration()).isEqualTo(java.time.Duration.ofNanos(999999)) - assertThat(Duration(999999999.0, NANOS).toJavaDuration()).isEqualTo(java.time.Duration.ofNanos(999999999)) - assertThat(Duration(999999999999.0, NANOS).toJavaDuration()).isEqualTo(java.time.Duration.ofNanos(999999999999)) - assertThat( - Duration( - 999999999999999.0, - NANOS - ).toJavaDuration() - ).isEqualTo(java.time.Duration.ofNanos(999999999999999)) - assertThat(Duration(9999999999999999.0, NANOS).toJavaDuration()).isNotEqualTo( - java.time.Duration.ofNanos( - 9999999999999999 - ) - ) + assertThat(Duration(999999.0, NANOS).toJavaDuration()) + .isEqualTo(java.time.Duration.ofNanos(999999)) + assertThat(Duration(999999999.0, NANOS).toJavaDuration()) + .isEqualTo(java.time.Duration.ofNanos(999999999)) + assertThat(Duration(999999999999.0, NANOS).toJavaDuration()) + .isEqualTo(java.time.Duration.ofNanos(999999999999)) + assertThat(Duration(999999999999999.0, NANOS).toJavaDuration()) + .isEqualTo(java.time.Duration.ofNanos(999999999999999)) + assertThat(Duration(9999999999999999.0, NANOS).toJavaDuration()) + .isNotEqualTo(java.time.Duration.ofNanos(9999999999999999)) - assertThat(Duration(999.0, SECONDS).toJavaDuration()).isEqualTo(java.time.Duration.ofSeconds(999)) - assertThat(Duration(999999.0, SECONDS).toJavaDuration()).isEqualTo(java.time.Duration.ofSeconds(999999)) - assertThat(Duration(999999999.0, SECONDS).toJavaDuration()).isEqualTo(java.time.Duration.ofSeconds(999999999)) - assertThat(Duration(999999999999.0, SECONDS).toJavaDuration()).isEqualTo(java.time.Duration.ofSeconds(999999999999)) - assertThat(Duration(999999999999999.0, SECONDS).toJavaDuration()).isEqualTo( - java.time.Duration.ofSeconds( - 999999999999999 - ) - ) - assertThat(Duration(9999999999999999.0, SECONDS).toJavaDuration()).isNotEqualTo( - java.time.Duration.ofSeconds( - 9999999999999999 - ) - ) + assertThat(Duration(999.0, SECONDS).toJavaDuration()) + .isEqualTo(java.time.Duration.ofSeconds(999)) + assertThat(Duration(999999.0, SECONDS).toJavaDuration()) + .isEqualTo(java.time.Duration.ofSeconds(999999)) + assertThat(Duration(999999999.0, SECONDS).toJavaDuration()) + .isEqualTo(java.time.Duration.ofSeconds(999999999)) + assertThat(Duration(999999999999.0, SECONDS).toJavaDuration()) + .isEqualTo(java.time.Duration.ofSeconds(999999999999)) + assertThat(Duration(999999999999999.0, SECONDS).toJavaDuration()) + .isEqualTo(java.time.Duration.ofSeconds(999999999999999)) + assertThat(Duration(9999999999999999.0, SECONDS).toJavaDuration()) + .isNotEqualTo(java.time.Duration.ofSeconds(9999999999999999)) - assertThat(Duration(999.0, MINUTES).toJavaDuration()).isEqualTo(java.time.Duration.ofMinutes(999)) - assertThat(Duration(999999.0, MINUTES).toJavaDuration()).isEqualTo(java.time.Duration.ofMinutes(999999)) - assertThat(Duration(999999999.0, MINUTES).toJavaDuration()).isEqualTo(java.time.Duration.ofMinutes(999999999)) - assertThat(Duration(999999999999.0, MINUTES).toJavaDuration()).isEqualTo(java.time.Duration.ofMinutes(999999999999)) - assertThat(Duration(999999999999999.0, MINUTES).toJavaDuration()).isEqualTo( - java.time.Duration.ofMinutes( - 999999999999999 - ) - ) - assertThat(Duration(9999999999999999.0, MINUTES).toJavaDuration()).isNotEqualTo( - java.time.Duration.ofMinutes( - 9999999999999999 - ) - ) + assertThat(Duration(999.0, MINUTES).toJavaDuration()) + .isEqualTo(java.time.Duration.ofMinutes(999)) + assertThat(Duration(999999.0, MINUTES).toJavaDuration()) + .isEqualTo(java.time.Duration.ofMinutes(999999)) + assertThat(Duration(999999999.0, MINUTES).toJavaDuration()) + .isEqualTo(java.time.Duration.ofMinutes(999999999)) + assertThat(Duration(999999999999.0, MINUTES).toJavaDuration()) + .isEqualTo(java.time.Duration.ofMinutes(999999999999)) + assertThat(Duration(999999999999999.0, MINUTES).toJavaDuration()) + .isEqualTo(java.time.Duration.ofMinutes(999999999999999)) + assertThat(Duration(9999999999999999.0, MINUTES).toJavaDuration()) + .isNotEqualTo(java.time.Duration.ofMinutes(9999999999999999)) assertThat(Duration(999.0, HOURS).toJavaDuration()).isEqualTo(java.time.Duration.ofHours(999)) - assertThat(Duration(999999.0, HOURS).toJavaDuration()).isEqualTo(java.time.Duration.ofHours(999999)) - assertThat(Duration(999999999.0, HOURS).toJavaDuration()).isEqualTo(java.time.Duration.ofHours(999999999)) - assertThat(Duration(999999999999.0, HOURS).toJavaDuration()).isEqualTo(java.time.Duration.ofHours(999999999999)) - assertThat( - Duration( - 999999999999999.0, - HOURS - ).toJavaDuration() - ).isEqualTo(java.time.Duration.ofHours(999999999999999)) + assertThat(Duration(999999.0, HOURS).toJavaDuration()) + .isEqualTo(java.time.Duration.ofHours(999999)) + assertThat(Duration(999999999.0, HOURS).toJavaDuration()) + .isEqualTo(java.time.Duration.ofHours(999999999)) + assertThat(Duration(999999999999.0, HOURS).toJavaDuration()) + .isEqualTo(java.time.Duration.ofHours(999999999999)) + assertThat(Duration(999999999999999.0, HOURS).toJavaDuration()) + .isEqualTo(java.time.Duration.ofHours(999999999999999)) assertThrows { Duration(9999999999999999.0, HOURS).toJavaDuration() } assertThat(Duration(999.0, DAYS).toJavaDuration()).isEqualTo(java.time.Duration.ofDays(999)) - assertThat(Duration(999999.0, DAYS).toJavaDuration()).isEqualTo(java.time.Duration.ofDays(999999)) - assertThat(Duration(999999999.0, DAYS).toJavaDuration()).isEqualTo(java.time.Duration.ofDays(999999999)) - assertThat(Duration(999999999999.0, DAYS).toJavaDuration()).isEqualTo(java.time.Duration.ofDays(999999999999)) + assertThat(Duration(999999.0, DAYS).toJavaDuration()) + .isEqualTo(java.time.Duration.ofDays(999999)) + assertThat(Duration(999999999.0, DAYS).toJavaDuration()) + .isEqualTo(java.time.Duration.ofDays(999999999)) + assertThat(Duration(999999999999.0, DAYS).toJavaDuration()) + .isEqualTo(java.time.Duration.ofDays(999999999999)) assertThrows { Duration(999999999999999.0, DAYS).toJavaDuration() } } @Test fun `toJavaDuration() - negative`() { assertThat(Duration(-999.0, NANOS).toJavaDuration()).isEqualTo(java.time.Duration.ofNanos(-999)) - assertThat(Duration(-999999.0, NANOS).toJavaDuration()).isEqualTo(java.time.Duration.ofNanos(-999999)) - assertThat(Duration(-999999999.0, NANOS).toJavaDuration()).isEqualTo(java.time.Duration.ofNanos(-999999999)) - assertThat(Duration(-999999999999.0, NANOS).toJavaDuration()).isEqualTo(java.time.Duration.ofNanos(-999999999999)) - assertThat( - Duration( - -999999999999999.0, - NANOS - ).toJavaDuration() - ).isEqualTo(java.time.Duration.ofNanos(-999999999999999)) - assertThat( - Duration( - -9999999999999999.0, - NANOS - ).toJavaDuration() - ).isNotEqualTo(java.time.Duration.ofNanos(-9999999999999999)) + assertThat(Duration(-999999.0, NANOS).toJavaDuration()) + .isEqualTo(java.time.Duration.ofNanos(-999999)) + assertThat(Duration(-999999999.0, NANOS).toJavaDuration()) + .isEqualTo(java.time.Duration.ofNanos(-999999999)) + assertThat(Duration(-999999999999.0, NANOS).toJavaDuration()) + .isEqualTo(java.time.Duration.ofNanos(-999999999999)) + assertThat(Duration(-999999999999999.0, NANOS).toJavaDuration()) + .isEqualTo(java.time.Duration.ofNanos(-999999999999999)) + assertThat(Duration(-9999999999999999.0, NANOS).toJavaDuration()) + .isNotEqualTo(java.time.Duration.ofNanos(-9999999999999999)) - assertThat(Duration(-999.0, SECONDS).toJavaDuration()).isEqualTo(java.time.Duration.ofSeconds(-999)) - assertThat(Duration(-999999.0, SECONDS).toJavaDuration()).isEqualTo(java.time.Duration.ofSeconds(-999999)) - assertThat(Duration(-999999999.0, SECONDS).toJavaDuration()).isEqualTo(java.time.Duration.ofSeconds(-999999999)) - assertThat( - Duration( - -999999999999.0, - SECONDS - ).toJavaDuration() - ).isEqualTo(java.time.Duration.ofSeconds(-999999999999)) - assertThat( - Duration( - -999999999999999.0, - SECONDS - ).toJavaDuration() - ).isEqualTo(java.time.Duration.ofSeconds(-999999999999999)) - assertThat( - Duration( - -9999999999999999.0, - SECONDS - ).toJavaDuration() - ).isNotEqualTo(java.time.Duration.ofSeconds(-9999999999999999)) + assertThat(Duration(-999.0, SECONDS).toJavaDuration()) + .isEqualTo(java.time.Duration.ofSeconds(-999)) + assertThat(Duration(-999999.0, SECONDS).toJavaDuration()) + .isEqualTo(java.time.Duration.ofSeconds(-999999)) + assertThat(Duration(-999999999.0, SECONDS).toJavaDuration()) + .isEqualTo(java.time.Duration.ofSeconds(-999999999)) + assertThat(Duration(-999999999999.0, SECONDS).toJavaDuration()) + .isEqualTo(java.time.Duration.ofSeconds(-999999999999)) + assertThat(Duration(-999999999999999.0, SECONDS).toJavaDuration()) + .isEqualTo(java.time.Duration.ofSeconds(-999999999999999)) + assertThat(Duration(-9999999999999999.0, SECONDS).toJavaDuration()) + .isNotEqualTo(java.time.Duration.ofSeconds(-9999999999999999)) - assertThat(Duration(-999.0, MINUTES).toJavaDuration()).isEqualTo(java.time.Duration.ofMinutes(-999)) - assertThat(Duration(-999999.0, MINUTES).toJavaDuration()).isEqualTo(java.time.Duration.ofMinutes(-999999)) - assertThat(Duration(-999999999.0, MINUTES).toJavaDuration()).isEqualTo(java.time.Duration.ofMinutes(-999999999)) - assertThat( - Duration( - -999999999999.0, - MINUTES - ).toJavaDuration() - ).isEqualTo(java.time.Duration.ofMinutes(-999999999999)) - assertThat( - Duration( - -999999999999999.0, - MINUTES - ).toJavaDuration() - ).isEqualTo(java.time.Duration.ofMinutes(-999999999999999)) - assertThat( - Duration( - -9999999999999999.0, - MINUTES - ).toJavaDuration() - ).isNotEqualTo(java.time.Duration.ofMinutes(-9999999999999999)) + assertThat(Duration(-999.0, MINUTES).toJavaDuration()) + .isEqualTo(java.time.Duration.ofMinutes(-999)) + assertThat(Duration(-999999.0, MINUTES).toJavaDuration()) + .isEqualTo(java.time.Duration.ofMinutes(-999999)) + assertThat(Duration(-999999999.0, MINUTES).toJavaDuration()) + .isEqualTo(java.time.Duration.ofMinutes(-999999999)) + assertThat(Duration(-999999999999.0, MINUTES).toJavaDuration()) + .isEqualTo(java.time.Duration.ofMinutes(-999999999999)) + assertThat(Duration(-999999999999999.0, MINUTES).toJavaDuration()) + .isEqualTo(java.time.Duration.ofMinutes(-999999999999999)) + assertThat(Duration(-9999999999999999.0, MINUTES).toJavaDuration()) + .isNotEqualTo(java.time.Duration.ofMinutes(-9999999999999999)) assertThat(Duration(-999.0, HOURS).toJavaDuration()).isEqualTo(java.time.Duration.ofHours(-999)) - assertThat(Duration(-999999.0, HOURS).toJavaDuration()).isEqualTo(java.time.Duration.ofHours(-999999)) - assertThat(Duration(-999999999.0, HOURS).toJavaDuration()).isEqualTo(java.time.Duration.ofHours(-999999999)) - assertThat(Duration(-999999999999.0, HOURS).toJavaDuration()).isEqualTo(java.time.Duration.ofHours(-999999999999)) - assertThat( - Duration( - -999999999999999.0, - HOURS - ).toJavaDuration() - ).isEqualTo(java.time.Duration.ofHours(-999999999999999)) + assertThat(Duration(-999999.0, HOURS).toJavaDuration()) + .isEqualTo(java.time.Duration.ofHours(-999999)) + assertThat(Duration(-999999999.0, HOURS).toJavaDuration()) + .isEqualTo(java.time.Duration.ofHours(-999999999)) + assertThat(Duration(-999999999999.0, HOURS).toJavaDuration()) + .isEqualTo(java.time.Duration.ofHours(-999999999999)) + assertThat(Duration(-999999999999999.0, HOURS).toJavaDuration()) + .isEqualTo(java.time.Duration.ofHours(-999999999999999)) assertThrows { Duration(-9999999999999999.0, HOURS).toJavaDuration() } assertThat(Duration(-999.0, DAYS).toJavaDuration()).isEqualTo(java.time.Duration.ofDays(-999)) - assertThat(Duration(-999999.0, DAYS).toJavaDuration()).isEqualTo(java.time.Duration.ofDays(-999999)) - assertThat(Duration(-999999999.0, DAYS).toJavaDuration()).isEqualTo(java.time.Duration.ofDays(-999999999)) - assertThat(Duration(-999999999999.0, DAYS).toJavaDuration()).isEqualTo(java.time.Duration.ofDays(-999999999999)) + assertThat(Duration(-999999.0, DAYS).toJavaDuration()) + .isEqualTo(java.time.Duration.ofDays(-999999)) + assertThat(Duration(-999999999.0, DAYS).toJavaDuration()) + .isEqualTo(java.time.Duration.ofDays(-999999999)) + assertThat(Duration(-999999999999.0, DAYS).toJavaDuration()) + .isEqualTo(java.time.Duration.ofDays(-999999999999)) assertThrows { Duration(-999999999999999.0, DAYS).toJavaDuration() } } @Test fun `toJavaDuration() - edge cases`() { assertThat(Duration(0.0, NANOS).toJavaDuration()).isEqualTo(java.time.Duration.ofNanos(0)) - assertThat(Duration(Long.MAX_VALUE.toDouble(), SECONDS).toJavaDuration()).isEqualTo( - java.time.Duration.ofSeconds( - Long.MAX_VALUE - ) - ) - assertThat(Duration(Long.MIN_VALUE.toDouble(), SECONDS).toJavaDuration()).isEqualTo( - java.time.Duration.ofSeconds( - Long.MIN_VALUE - ) - ) + assertThat(Duration(Long.MAX_VALUE.toDouble(), SECONDS).toJavaDuration()) + .isEqualTo(java.time.Duration.ofSeconds(Long.MAX_VALUE)) + assertThat(Duration(Long.MIN_VALUE.toDouble(), SECONDS).toJavaDuration()) + .isEqualTo(java.time.Duration.ofSeconds(Long.MIN_VALUE)) val justTooLarge = Duration(Long.MAX_VALUE.toDouble().nextUp(), SECONDS) assertThrows { justTooLarge.toJavaDuration() } diff --git a/pkl-core/src/test/kotlin/org/pkl/core/DurationUnitTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/DurationUnitTest.kt index 59dd8ad1..b822e2ed 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/DurationUnitTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/DurationUnitTest.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core import java.time.temporal.ChronoUnit diff --git a/pkl-core/src/test/kotlin/org/pkl/core/DynamicTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/DynamicTest.kt index 465575c1..3de073e8 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/DynamicTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/DynamicTest.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core import org.junit.jupiter.api.Test @@ -5,19 +20,21 @@ import org.junit.jupiter.api.assertDoesNotThrow import org.junit.jupiter.api.assertThrows class DynamicTest { - private fun brokenInput(value: String): String = """ + private fun brokenInput(value: String): String = + """ class Person { name: String; age: Int } person: Person = new { name = 42; age = "Pigeon" } // oops output { value = $value } - """.trimIndent() + """ + .trimIndent() @Test fun `property access respects type`() { // Does not involve Dynamic, but is a baseline for the other cases. val evaluator = Evaluator.preconfigured() - assertThrows { + assertThrows { evaluator.evaluateOutputText(ModuleSource.text(brokenInput("person.name"))) } } diff --git a/pkl-core/src/test/kotlin/org/pkl/core/ErrorColoringTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/ErrorColoringTest.kt index 298a4d33..d8337ab7 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/ErrorColoringTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/ErrorColoringTest.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core import org.assertj.core.api.Assertions.assertThat @@ -18,33 +33,41 @@ class ErrorColoringTest { private fun evaluate(program: String, expression: String): Any { return evaluator.evaluateExpression(ModuleSource.text(program), expression) } - + @BeforeEach fun setup() { // Enable colouring before each test Ansi.setEnabled(true) } - + @AfterEach fun teardown() { // Disable colouring after each test Ansi.setEnabled(false) } - + @Test fun `simple error`() { val error = assertThrows { evaluate("bar = 2", "bar = 15") } - assertThat(error).message() + assertThat(error) + .message() .contains("\u001B[31m–– Pkl Error ––\u001B[m") .contains("\u001B[94m1 | \u001B[m") .contains("\u001B[0;31m^") } - + @Test fun `repeated error`() { - val error = assertThrows { evaluate("""self: String = "Strings; if they were lazy, you could tie the knot on \(self.take(7))"""", "self") } - assertThat(error).message() + val error = + assertThrows { + evaluate( + """self: String = "Strings; if they were lazy, you could tie the knot on \(self.take(7))"""", + "self" + ) + } + assertThat(error) + .message() .contains("A stack overflow occurred.") .contains("┌─ ") .contains(" repetitions of:") diff --git a/pkl-core/src/test/kotlin/org/pkl/core/EvaluateExpressionTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/EvaluateExpressionTest.kt index 8efba944..0ad29f9f 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/EvaluateExpressionTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/EvaluateExpressionTest.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core import org.assertj.core.api.Assertions.assertThat @@ -22,13 +37,15 @@ class EvaluateExpressionTest { @Test fun `evaluate expression`() { - val program = """ + val program = + """ res1 = 1 res2 { res3 = 3 res4 = 4 } - """.trimIndent() + """ + .trimIndent() assertThat(evaluate(program, "res1")).isEqualTo(1L) val res2 = evaluate(program, "res2") assertThat(res2).isInstanceOf(PObject::class.java) @@ -39,18 +56,25 @@ class EvaluateExpressionTest { @Test fun `evaluate subpath`() { - val resp = evaluate(""" + val resp = + evaluate( + """ foo { bar = 2 } - """.trimIndent(), "foo.bar") + """ + .trimIndent(), + "foo.bar" + ) assertThat(resp).isEqualTo(2L) } @Test fun `evaluate output text`() { - val result = evaluate(""" + val result = + evaluate( + """ foo { bar = 2 } @@ -58,13 +82,20 @@ class EvaluateExpressionTest { output { renderer = new YamlRenderer {} } - """.trimIndent(), "output.text") + """ + .trimIndent(), + "output.text" + ) - assertThat(result).isEqualTo(""" + assertThat(result) + .isEqualTo( + """ foo: bar: 2 - """.trimIndent()) + """ + .trimIndent() + ) } @Test @@ -76,10 +107,7 @@ class EvaluateExpressionTest { @Test fun `evaluate import expression`() { - val result = evaluate( - "", - """import("pkl:release").current.documentation.homepage""" - ) + val result = evaluate("", """import("pkl:release").current.documentation.homepage""") assertThat(result as String).startsWith("https://pkl-lang.org/") } diff --git a/pkl-core/src/test/kotlin/org/pkl/core/EvaluateMultipleFileOutputTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/EvaluateMultipleFileOutputTest.kt index eec31046..84afcbef 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/EvaluateMultipleFileOutputTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/EvaluateMultipleFileOutputTest.kt @@ -1,9 +1,24 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core -import org.pkl.core.ModuleSource.text import org.assertj.core.api.Assertions.* import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows +import org.pkl.core.ModuleSource.text class EvaluateMultipleFileOutputTest { @@ -11,7 +26,8 @@ class EvaluateMultipleFileOutputTest { @Test fun `output files`() { - val program = """ + val program = + """ output { files { ["foo.yml"] { @@ -28,14 +44,10 @@ class EvaluateMultipleFileOutputTest { } } } - """.trimIndent() + """ + .trimIndent() val output = evaluator.evaluateOutputFiles(text(program)) - assertThat(output.keys).isEqualTo(setOf( - "foo.yml", - "bar.yml", - "bar/biz.yml", - "bar/../bark.yml" - )) + assertThat(output.keys).isEqualTo(setOf("foo.yml", "bar.yml", "bar/biz.yml", "bar/../bark.yml")) assertThat(output["foo.yml"]?.text).isEqualTo("foo: foo text") assertThat(output["bar.yml"]?.text).isEqualTo("bar: bar text") assertThat(output["bar/biz.yml"]?.text).isEqualTo("biz: bar biz") @@ -45,7 +57,8 @@ class EvaluateMultipleFileOutputTest { @Test fun `using a renderer`() { val evaluator = Evaluator.preconfigured() - val program = """ + val program = + """ output { files { ["foo.json"] { @@ -57,21 +70,27 @@ class EvaluateMultipleFileOutputTest { } } } - """.trimIndent() + """ + .trimIndent() val output = evaluator.evaluateOutputFiles(text(program)) - assertThat(output["foo.json"]?.text).isEqualTo(""" + assertThat(output["foo.json"]?.text) + .isEqualTo( + """ { "foo": "fooey", "bar": "barrey" } - """.trimIndent()) + """ + .trimIndent() + ) } @Test fun `reading files after the evaluator is closed`() { val evaluator = Evaluator.preconfigured() - val program = """ + val program = + """ output { files { ["foo.json"] { @@ -83,7 +102,8 @@ class EvaluateMultipleFileOutputTest { } } } - """.trimIndent() + """ + .trimIndent() val output = evaluator.evaluateOutputFiles(text(program)) evaluator.close() assertThrows { output["foo.json"]!!.text } diff --git a/pkl-core/src/test/kotlin/org/pkl/core/EvaluateOutputTextTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/EvaluateOutputTextTest.kt index fdd28394..967b5ec8 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/EvaluateOutputTextTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/EvaluateOutputTextTest.kt @@ -1,8 +1,23 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core -import org.pkl.core.util.IoUtils import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test +import org.pkl.core.util.IoUtils // tests language-internal renderers // uses same input/output files as Pcf/Json/Yaml/PListRendererTest @@ -28,13 +43,10 @@ class EvaluateOutputTextTest { } private fun checkRenderedOutput(format: OutputFormat) { - val evaluator = EvaluatorBuilder.preconfigured() - .setOutputFormat(format) - .build() + val evaluator = EvaluatorBuilder.preconfigured().setOutputFormat(format).build() - val output = evaluator.evaluateOutputText( - ModuleSource.modulePath("org/pkl/core/rendererTest.pkl") - ) + val output = + evaluator.evaluateOutputText(ModuleSource.modulePath("org/pkl/core/rendererTest.pkl")) val expected = IoUtils.readClassPathResourceAsString(javaClass, "rendererTest.$format") assertThat(output.trim()).isEqualTo(expected.trim()) diff --git a/pkl-core/src/test/kotlin/org/pkl/core/EvaluateSchemaTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/EvaluateSchemaTest.kt index 21398f37..a12a14a1 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/EvaluateSchemaTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/EvaluateSchemaTest.kt @@ -1,10 +1,25 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core -import org.pkl.core.ModuleSource.* import java.net.URI import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Test +import org.pkl.core.ModuleSource.* import org.pkl.core.runtime.BaseModule class EvaluateSchemaTest { @@ -17,9 +32,7 @@ class EvaluateSchemaTest { @Test fun `evaluate test schema`() { - val module = evaluator.evaluateSchema( - modulePath("org/pkl/core/EvaluateSchemaTest.pkl") - ) + val module = evaluator.evaluateSchema(modulePath("org/pkl/core/EvaluateSchemaTest.pkl")) checkModuleMetadata(module) @@ -35,28 +48,27 @@ class EvaluateSchemaTest { @Test fun `evaluate pkl_base schema`() { val module = evaluator.evaluateSchema(uri(URI("pkl:base"))) - assertThat(module.moduleClass.superclass) - .isEqualTo(BaseModule.getModuleClass().export()) + assertThat(module.moduleClass.superclass).isEqualTo(BaseModule.getModuleClass().export()) } @Test fun `does not export local classes`() { - val module = evaluator.evaluateSchema( - text( - """ + val module = + evaluator.evaluateSchema( + text( + """ class Foo {} local class Baz {} - """.trimIndent() + """ + .trimIndent() + ) ) - ) - assertThat(module.classes.keys) - .containsExactly("Foo") + assertThat(module.classes.keys).containsExactly("Foo") } private fun checkModuleMetadata(module: ModuleSchema) { - assertThat(module.moduleUri) - .isEqualTo(URI("modulepath:/org/pkl/core/EvaluateSchemaTest.pkl")) + assertThat(module.moduleUri).isEqualTo(URI("modulepath:/org/pkl/core/EvaluateSchemaTest.pkl")) assertThat(module.moduleName).isEqualTo("test") @@ -79,9 +91,8 @@ class EvaluateSchemaTest { val paramType = propertyb2.type assertThat(paramType).isInstanceOf(PType.Class::class.java) paramType as PType.Class - assertThat(paramType.pClass) - .isEqualTo(BaseModule.getIntClass().export()) - + assertThat(paramType.pClass).isEqualTo(BaseModule.getIntClass().export()) + val propertyb3 = properties.getValue("propertyb3") assertThat(propertyb3.sourceLocation.startLine).isEqualTo(24) assertThat(propertyb3.sourceLocation.endLine).isEqualTo(24) @@ -106,10 +117,8 @@ class EvaluateSchemaTest { val paramBaseType = paramType.baseType assertThat(paramBaseType).isInstanceOf(PType.Class::class.java) paramBaseType as PType.Class - assertThat(paramBaseType.pClass) - .isEqualTo(BaseModule.getStringClass().export()) - assertThat(paramType.constraints) - .isEqualTo(listOf("!isEmpty", "startsWith(\"a\")")) + assertThat(paramBaseType.pClass).isEqualTo(BaseModule.getStringClass().export()) + assertThat(paramType.constraints).isEqualTo(listOf("!isEmpty", "startsWith(\"a\")")) val returnType = methodb2.returnType assertThat(returnType).isInstanceOf(PType.Constrained::class.java) @@ -119,7 +128,7 @@ class EvaluateSchemaTest { returnBaseType as PType.Class assertThat(returnBaseType.pClass).isEqualTo(BaseModule.getIntClass().export()) assertThat(returnType.constraints).isEqualTo(listOf("isPositive")) - + val methodb3 = methods.getValue("methodb3") assertThat(methodb3.sourceLocation.startLine).isEqualTo(26) assertThat(methodb3.sourceLocation.endLine).isEqualTo(26) @@ -141,10 +150,8 @@ class EvaluateSchemaTest { assertThat(supermodule).isNotNull assertThat(supermodule!!.supermodule).isNull() - assertThat(module.moduleClass.superclass) - .isEqualTo(supermodule.moduleClass) - assertThat(supermodule.moduleClass.superclass) - .isEqualTo(BaseModule.getModuleClass().export()) + assertThat(module.moduleClass.superclass).isEqualTo(supermodule.moduleClass) + assertThat(supermodule.moduleClass.superclass).isEqualTo(BaseModule.getModuleClass().export()) assertThat(supermodule.moduleUri) .isEqualTo(URI("modulepath:/org/pkl/core/EvaluateSchemaTestBaseModule.pkl")) diff --git a/pkl-core/src/test/kotlin/org/pkl/core/EvaluateTestsTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/EvaluateTestsTest.kt index 2b725d57..15f99d6b 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/EvaluateTestsTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/EvaluateTestsTest.kt @@ -1,15 +1,30 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core -import org.pkl.commons.createTempFile +import java.nio.file.Files +import java.nio.file.Path +import kotlin.io.path.createFile import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir +import org.pkl.commons.createTempFile import org.pkl.commons.writeString import org.pkl.core.ModuleSource.* -import java.nio.file.Files -import java.nio.file.Path -import kotlin.io.path.createFile class EvaluateTestsTest { @@ -17,7 +32,10 @@ class EvaluateTestsTest { @Test fun `test successful module`() { - val results = evaluator.evaluateTest(text(""" + val results = + evaluator.evaluateTest( + text( + """ amends "pkl:test" facts { @@ -26,7 +44,11 @@ class EvaluateTestsTest { "foo" == "foo" } } - """.trimIndent()), true) + """ + .trimIndent() + ), + true + ) assertThat(results.moduleName).isEqualTo("text") assertThat(results.displayUri).isEqualTo("repl:text") @@ -38,9 +60,10 @@ class EvaluateTestsTest { @Test fun `test module failure`() { - val results = evaluator.evaluateTest( - text( - """ + val results = + evaluator.evaluateTest( + text( + """ amends "pkl:test" facts { @@ -49,19 +72,20 @@ class EvaluateTestsTest { "foo" == "bar" } } - """.trimIndent() - ), - true - ) + """ + .trimIndent() + ), + true + ) assertThat(results.totalTests()).isEqualTo(1) assertThat(results.totalFailures()).isEqualTo(2) assertThat(results.failed()).isTrue - + val res = results.results[0] assertThat(res.name).isEqualTo("should fail") assertThat(res.errors).isEmpty() - + val fail1 = res.failures[0] assertThat(fail1.rendered).isEqualTo("1 == 2 ❌ (repl:text)") @@ -71,9 +95,10 @@ class EvaluateTestsTest { @Test fun `test module error`() { - val results = evaluator.evaluateTest( - text( - """ + val results = + evaluator.evaluateTest( + text( + """ amends "pkl:test" facts { @@ -82,10 +107,11 @@ class EvaluateTestsTest { throw("got an error") } } - """.trimIndent() - ), - true - ) + """ + .trimIndent() + ), + true + ) assertThat(results.totalTests()).isEqualTo(1) assertThat(results.totalFailures()).isEqualTo(0) @@ -95,10 +121,12 @@ class EvaluateTestsTest { assertThat(res.name).isEqualTo("text") assertThat(res.failures).isEmpty() assertThat(res.errors.size).isEqualTo(1) - + val error = res.errors[0] assertThat(error.message).isEqualTo("got an error") - assertThat(error.exception.message).isEqualTo(""" + assertThat(error.exception.message) + .isEqualTo( + """ –– Pkl Error –– got an error @@ -110,13 +138,17 @@ class EvaluateTestsTest { ^^^^^^^ at text#facts (repl:text) - """.trimIndent()) + """ + .trimIndent() + ) } - + @Test fun `test successful example`(@TempDir tempDir: Path) { val file = tempDir.createTempFile(prefix = "example", suffix = ".pkl") - Files.writeString(file, """ + Files.writeString( + file, + """ amends "pkl:test" examples { @@ -127,9 +159,13 @@ class EvaluateTestsTest { } } } - """.trimIndent()) - - Files.writeString(createExpected(file), """ + """ + .trimIndent() + ) + + Files.writeString( + createExpected(file), + """ examples { ["user"] { new { @@ -138,7 +174,9 @@ class EvaluateTestsTest { } } } - """.trimIndent()) + """ + .trimIndent() + ) val results = evaluator.evaluateTest(path(file), false) assertThat(results.moduleName).startsWith("example") @@ -151,7 +189,9 @@ class EvaluateTestsTest { @Test fun `test example failure`(@TempDir tempDir: Path) { val file = tempDir.createTempFile(prefix = "example", suffix = ".pkl") - Files.writeString(file, """ + Files.writeString( + file, + """ amends "pkl:test" examples { @@ -162,9 +202,13 @@ class EvaluateTestsTest { } } } - """.trimIndent()) + """ + .trimIndent() + ) - Files.writeString(createExpected(file), """ + Files.writeString( + createExpected(file), + """ examples { ["user"] { new { @@ -173,7 +217,9 @@ class EvaluateTestsTest { } } } - """.trimIndent()) + """ + .trimIndent() + ) val results = evaluator.evaluateTest(path(file), false) assertThat(results.moduleName).startsWith("example") @@ -187,7 +233,9 @@ class EvaluateTestsTest { assertThat(res.errors.isEmpty()).isTrue val fail1 = res.failures[0] - assertThat(fail1.rendered.stripFileAndLines(tempDir)).isEqualTo(""" + assertThat(fail1.rendered.stripFileAndLines(tempDir)) + .isEqualTo( + """ (/tempDir/example.pkl) Expected: (/tempDir/example.pkl-expected.pcf) new { @@ -199,13 +247,17 @@ class EvaluateTestsTest { name = "Bob" age = 33 } - """.trimIndent()) + """ + .trimIndent() + ) } @Test fun `written examples use custom string delimiters`(@TempDir tempDir: Path) { val file = tempDir.createTempFile(prefix = "example", suffix = ".pkl") - Files.writeString(file, """ + Files.writeString( + file, + """ amends "pkl:test" examples { @@ -213,25 +265,33 @@ class EvaluateTestsTest { "my \"string\"" } } - """.trimIndent()) + """ + .trimIndent() + ) evaluator.evaluateTest(path(file), false) val expectedFile = file.parent.resolve(file.fileName.toString() + "-expected.pcf") assertThat(expectedFile).exists() - assertThat(expectedFile).hasContent(""" + assertThat(expectedFile) + .hasContent( + """ examples { ["myStr"] { #"my "string""# } } - """.trimIndent()) + """ + .trimIndent() + ) } // test for backwards compatibility @Test fun `examples that don't use custom string delimiters still pass`(@TempDir tempDir: Path) { val file = tempDir.createTempFile(prefix = "example", suffix = ".pkl") - Files.writeString(file, """ + Files.writeString( + file, + """ amends "pkl:test" examples { @@ -239,25 +299,28 @@ class EvaluateTestsTest { "my \"string\"" } } - """.trimIndent()) - createExpected(file).writeString(""" + """ + .trimIndent() + ) + createExpected(file) + .writeString( + """ examples { ["myStr"] { "my \"string\"" } } - """.trimIndent()) + """ + .trimIndent() + ) val result = evaluator.evaluateTest(path(file), false) assertFalse(result.failed()) } companion object { private fun createExpected(path: Path): Path { - return path - .parent - .resolve(path.fileName.toString() + "-expected.pcf") - .createFile() + return path.parent.resolve(path.fileName.toString() + "-expected.pcf").createFile() } private fun String.stripFileAndLines(tmpDir: Path) = diff --git a/pkl-core/src/test/kotlin/org/pkl/core/EvaluatorBuilderTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/EvaluatorBuilderTest.kt index 1f8cac6f..77b3c9da 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/EvaluatorBuilderTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/EvaluatorBuilderTest.kt @@ -1,11 +1,26 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core +import java.nio.file.Path +import java.time.Duration import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import org.pkl.core.project.Project -import java.nio.file.Path -import java.time.Duration class EvaluatorBuilderTest { @Test @@ -34,40 +49,32 @@ class EvaluatorBuilderTest { @Test fun `enforces that security manager is set`() { - val e1 = assertThrows { - EvaluatorBuilder.unconfigured() - .setStackFrameTransformer(StackFrameTransformers.empty) - .build() - } + val e1 = + assertThrows { + EvaluatorBuilder.unconfigured() + .setStackFrameTransformer(StackFrameTransformers.empty) + .build() + } assertThat(e1).hasMessage("No security manager set.") } @Test fun `enforces that stack frame transformer is set`() { - val e1 = assertThrows { - EvaluatorBuilder.unconfigured() - .setSecurityManager(SecurityManagers.defaultManager) - .build() - } + val e1 = + assertThrows { + EvaluatorBuilder.unconfigured().setSecurityManager(SecurityManagers.defaultManager).build() + } assertThat(e1).hasMessage("No stack frame transformer set.") } @Test fun `sets evaluator settings from project`() { val projectPath = Path.of(javaClass.getResource("project/project1/PklProject")!!.toURI()) - val project = Project.loadFromPath( - projectPath, - SecurityManagers.defaultManager, - null - ) + val project = Project.loadFromPath(projectPath, SecurityManagers.defaultManager, null) val projectDir = Path.of(javaClass.getResource("project/project1/PklProject")!!.toURI()).parent - val builder = EvaluatorBuilder - .unconfigured() - .applyFromProject(project) - assertThat(builder.allowedResources.map { it.pattern() }) - .isEqualTo(listOf("foo:", "bar:")) - assertThat(builder.allowedModules.map { it.pattern() }) - .isEqualTo(listOf("baz:", "biz:")) + val builder = EvaluatorBuilder.unconfigured().applyFromProject(project) + assertThat(builder.allowedResources.map { it.pattern() }).isEqualTo(listOf("foo:", "bar:")) + assertThat(builder.allowedModules.map { it.pattern() }).isEqualTo(listOf("baz:", "biz:")) assertThat(builder.externalProperties).isEqualTo(mapOf("one" to "1")) assertThat(builder.environmentVariables).isEqualTo(mapOf("two" to "2")) assertThat(builder.moduleCacheDir).isEqualTo(projectDir.resolve("my-cache-dir/")) diff --git a/pkl-core/src/test/kotlin/org/pkl/core/EvaluatorTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/EvaluatorTest.kt index 7f30218a..2a5bef33 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/EvaluatorTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/EvaluatorTest.kt @@ -1,32 +1,47 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core -import org.pkl.commons.createParentDirectories import java.io.File import java.net.URI +import java.nio.charset.StandardCharsets +import java.nio.file.FileSystems import java.nio.file.Files import java.nio.file.Path +import java.util.* +import java.util.regex.Pattern +import kotlin.io.path.writeText import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatCode +import org.junit.jupiter.api.AfterAll import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import org.junit.jupiter.api.io.TempDir +import org.pkl.commons.createParentDirectories import org.pkl.commons.createTempFile +import org.pkl.commons.test.PackageServer import org.pkl.commons.toPath import org.pkl.commons.writeString import org.pkl.core.ModuleSource.* -import org.pkl.core.util.IoUtils -import org.junit.jupiter.api.AfterAll -import org.pkl.commons.test.PackageServer import org.pkl.core.module.ModuleKey import org.pkl.core.module.ModuleKeyFactories import org.pkl.core.module.ModuleKeyFactory import org.pkl.core.module.ResolvedModuleKey import org.pkl.core.project.Project -import java.nio.charset.StandardCharsets -import java.nio.file.FileSystems -import java.util.* -import java.util.regex.Pattern -import kotlin.io.path.writeText +import org.pkl.core.util.IoUtils class EvaluatorTest { companion object { @@ -50,8 +65,10 @@ class EvaluatorTest { override fun getUri(): URI = uri - override fun loadSource(): String = javaClass.classLoader.getResourceAsStream(uri.path.drop(1))!!.use { it.readAllBytes().toString( - StandardCharsets.UTF_8) } + override fun loadSource(): String = + javaClass.classLoader.getResourceAsStream(uri.path.drop(1))!!.use { + it.readAllBytes().toString(StandardCharsets.UTF_8) + } override fun resolve(securityManager: SecurityManager): ResolvedModuleKey = this } @@ -71,28 +88,20 @@ class EvaluatorTest { @Test fun `evaluate text with relative import`() { - val e = assertThrows { - evaluator.evaluate(text("import \"foo.bar\"")) - } - assertThat(e) - .hasMessageContaining("Module `repl:text` cannot have a relative import URI.") + val e = assertThrows { evaluator.evaluate(text("import \"foo.bar\"")) } + assertThat(e).hasMessageContaining("Module `repl:text` cannot have a relative import URI.") } @Test fun `evaluate named module`() { - val module = evaluator.evaluate( - modulePath("org/pkl/core/EvaluatorTest.pkl") - ) + val module = evaluator.evaluate(modulePath("org/pkl/core/EvaluatorTest.pkl")) checkModule(module) } @Test fun `evaluate non-existing named module`() { - val e = assertThrows { - evaluator.evaluate(modulePath("non/existing.pkl")) - } - assertThat(e) - .hasMessageContaining("Cannot find module `modulepath:/non/existing.pkl`.") + val e = assertThrows { evaluator.evaluate(modulePath("non/existing.pkl")) } + assertThat(e).hasMessageContaining("Cannot find module `modulepath:/non/existing.pkl`.") } @Test @@ -107,11 +116,8 @@ class EvaluatorTest { @Test fun `evaluate non-existing file`() { val file = File("/non/existing") - val e = assertThrows { - evaluator.evaluate(file(file)) - } - assertThat(e) - .hasMessageContaining("Cannot find module `${file.toPath().toUri()}`.") + val e = assertThrows { evaluator.evaluate(file(file)) } + assertThat(e).hasMessageContaining("Cannot find module `${file.toPath().toUri()}`.") } @Test @@ -126,11 +132,8 @@ class EvaluatorTest { @Test fun `evaluate non-existing path`() { val path = "/non/existing".toPath() - val e = assertThrows { - evaluator.evaluate(path(path)) - } - assertThat(e) - .hasMessageContaining("Cannot find module `${path.toUri()}`.") + val e = assertThrows { evaluator.evaluate(path(path)) } + assertThat(e).hasMessageContaining("Cannot find module `${path.toUri()}`.") } @Test @@ -150,9 +153,7 @@ class EvaluatorTest { // cast required to compile on JDK 14+ (which adds new overload) FileSystems.newFileSystem(zipFile, null as ClassLoader?).use { zipFs -> val file = zipFs.getPath("non/existing") - val e = assertThrows { - evaluator.evaluate(path(file)) - } + val e = assertThrows { evaluator.evaluate(path(file)) } assertThat(e) .hasMessageContaining("Cannot find module `jar:file:") .hasMessageContaining("non/existing") @@ -170,11 +171,9 @@ class EvaluatorTest { @Test fun `evaluate non-existing URI`() { - val e = assertThrows { - evaluator.evaluate(uri(URI("https://localhost/non/existing"))) - } - assertThat(e) - .hasMessageContaining("I/O error loading module `https://localhost/non/existing`.") + val e = + assertThrows { evaluator.evaluate(uri(URI("https://localhost/non/existing"))) } + assertThat(e).hasMessageContaining("I/O error loading module `https://localhost/non/existing`.") } @Test @@ -187,112 +186,117 @@ class EvaluatorTest { @Test fun `evaluate jar URI with non-existing archive`() { val moduleUri = URI("jar:file:///non/existing!/bar.pkl") - val e = assertThrows { - evaluator.evaluate(uri(moduleUri)) - } - assertThat(e) - .hasMessageContaining("Cannot find module `$moduleUri`.") + val e = assertThrows { evaluator.evaluate(uri(moduleUri)) } + assertThat(e).hasMessageContaining("Cannot find module `$moduleUri`.") } @Test fun `evaluate jar URI with non-existing archive path`(@TempDir tempDir: Path) { val zipFile = createModulesZip(tempDir) val moduleUri = URI("jar:${zipFile.toUri()}!/non/existing") - val e = assertThrows { - evaluator.evaluate(uri(moduleUri)) - } - assertThat(e) - .hasMessageContaining("Cannot find module `$moduleUri`.") + val e = assertThrows { evaluator.evaluate(uri(moduleUri)) } + assertThat(e).hasMessageContaining("Cannot find module `$moduleUri`.") } @Test fun `evaluate module with relative URI`() { - val e = assertThrows { - evaluator.evaluate(create(URI("foo.bar"), "")) - } + val e = assertThrows { evaluator.evaluate(create(URI("foo.bar"), "")) } - assertThat(e) - .hasMessageContaining("Cannot evaluate relative module URI `foo.bar`.") + assertThat(e).hasMessageContaining("Cannot evaluate relative module URI `foo.bar`.") } @Test fun `evaluating a broken module multiple times results in the same error every time`() { - val e1 = assertThrows { - evaluator.evaluate(modulePath("org/pkl/core/brokenModule1.pkl")) - } - val e2 = assertThrows { - evaluator.evaluate(modulePath("org/pkl/core/brokenModule1.pkl")) - } + val e1 = + assertThrows { + evaluator.evaluate(modulePath("org/pkl/core/brokenModule1.pkl")) + } + val e2 = + assertThrows { + evaluator.evaluate(modulePath("org/pkl/core/brokenModule1.pkl")) + } assertThat(e2.message).isEqualTo(e1.message) - val e3 = assertThrows { - evaluator.evaluate(modulePath("org/pkl/core/brokenModule2.pkl")) - } - val e4 = assertThrows { - evaluator.evaluate(modulePath("org/pkl/core/brokenModule2.pkl")) - } + val e3 = + assertThrows { + evaluator.evaluate(modulePath("org/pkl/core/brokenModule2.pkl")) + } + val e4 = + assertThrows { + evaluator.evaluate(modulePath("org/pkl/core/brokenModule2.pkl")) + } assertThat(e4.message).isEqualTo(e3.message) } @Test fun `evaluation timeout`() { - val evaluator = EvaluatorBuilder.preconfigured() - .setTimeout(java.time.Duration.ofMillis(100)) - .build() - val e = assertThrows { - evaluator.evaluate(text( - """ + val evaluator = + EvaluatorBuilder.preconfigured().setTimeout(java.time.Duration.ofMillis(100)).build() + val e = + assertThrows { + evaluator.evaluate( + text( + """ function fib(n) = if (n < 2) 0 else fib(n - 1) + fib(n - 2) x = fib(100) - """.trimIndent() - )) - } + """ + .trimIndent() + ) + ) + } assertThat(e.message).contains("timed out") } @Test fun `stack overflow`() { val evaluator = Evaluator.preconfigured() - val e = assertThrows { - evaluator.evaluate(text(""" + val e = + assertThrows { + evaluator.evaluate( + text( + """ a = b b = c c = a - """.trimIndent())) - } + """ + .trimIndent() + ) + ) + } assertThat(e.message).contains("A stack overflow occurred.") } @Test fun `cannot import module located outside root dir`(@TempDir tempDir: Path) { - val evaluator = EvaluatorBuilder.preconfigured() - .setSecurityManager( - SecurityManagers.standard( - SecurityManagers.defaultAllowedModules, - SecurityManagers.defaultAllowedResources, - SecurityManagers.defaultTrustLevels, - tempDir + val evaluator = + EvaluatorBuilder.preconfigured() + .setSecurityManager( + SecurityManagers.standard( + SecurityManagers.defaultAllowedModules, + SecurityManagers.defaultAllowedResources, + SecurityManagers.defaultTrustLevels, + tempDir + ) ) - ) - .build() + .build() val module = tempDir.resolve("test.pkl") module.writeString( """ amends "/non/existing.pkl" - """.trimIndent() + """ + .trimIndent() ) - val e = assertThrows { - evaluator.evaluate(path(module)) - } + val e = assertThrows { evaluator.evaluate(path(module)) } assertThat(e.message).contains("Refusing to load module `file:///non/existing.pkl`") } @Test fun `multiple-file output`() { val evaluator = Evaluator.preconfigured() - val program = """ + val program = + """ output { files { ["foo.yml"] { @@ -309,14 +313,10 @@ class EvaluatorTest { } } } - """.trimIndent() + """ + .trimIndent() val output = evaluator.evaluateOutputFiles(ModuleSource.text(program)) - assertThat(output.keys).isEqualTo(setOf( - "foo.yml", - "bar.yml", - "bar/biz.yml", - "bar/../bark.yml" - )) + assertThat(output.keys).isEqualTo(setOf("foo.yml", "bar.yml", "bar/biz.yml", "bar/../bark.yml")) assertThat(output["foo.yml"]?.text).isEqualTo("foo: foo text") assertThat(output["bar.yml"]?.text).isEqualTo("bar: bar text") assertThat(output["bar/biz.yml"]?.text).isEqualTo("biz: bar biz") @@ -328,10 +328,13 @@ class EvaluatorTest { PackageServer.populateCacheDir(cacheDir) val evaluatorBuilder = EvaluatorBuilder.preconfigured().setModuleCacheDir(cacheDir) val project = Project.load(modulePath("/org/pkl/core/project/project5/PklProject")) - val result = evaluatorBuilder.setProjectDependencies(project.dependencies).build().use { evaluator -> - evaluator.evaluateOutputText(modulePath("/org/pkl/core/project/project5/main.pkl")) - } - assertThat(result).isEqualTo(""" + val result = + evaluatorBuilder.setProjectDependencies(project.dependencies).build().use { evaluator -> + evaluator.evaluateOutputText(modulePath("/org/pkl/core/project/project5/main.pkl")) + } + assertThat(result) + .isEqualTo( + """ prop1 { name = "Apple" } @@ -339,30 +342,37 @@ class EvaluatorTest { res = 1 } - """.trimIndent()) + """ + .trimIndent() + ) } @Test fun `project set from custom ModuleKeyFactory`(@TempDir cacheDir: Path) { PackageServer.populateCacheDir(cacheDir) - val evaluatorBuilder = with(EvaluatorBuilder.preconfigured()) { - setAllowedModules(SecurityManagers.defaultAllowedModules + Pattern.compile("custom:")) - setAllowedResources(SecurityManagers.defaultAllowedResources + Pattern.compile("custom:")) - setModuleCacheDir(cacheDir) - setModuleKeyFactories( - listOf( - CustomModuleKeyFactory, - ModuleKeyFactories.standardLibrary, - ModuleKeyFactories.pkg, - ModuleKeyFactories.projectpackage, - ModuleKeyFactories.file + val evaluatorBuilder = + with(EvaluatorBuilder.preconfigured()) { + setAllowedModules(SecurityManagers.defaultAllowedModules + Pattern.compile("custom:")) + setAllowedResources(SecurityManagers.defaultAllowedResources + Pattern.compile("custom:")) + setModuleCacheDir(cacheDir) + setModuleKeyFactories( + listOf( + CustomModuleKeyFactory, + ModuleKeyFactories.standardLibrary, + ModuleKeyFactories.pkg, + ModuleKeyFactories.projectpackage, + ModuleKeyFactories.file + ) ) - ) - } - val project = evaluatorBuilder.build().use { Project.load(it, uri("custom:/org/pkl/core/project/project5/PklProject")) } + } + val project = + evaluatorBuilder.build().use { + Project.load(it, uri("custom:/org/pkl/core/project/project5/PklProject")) + } val evaluator = evaluatorBuilder.setProjectDependencies(project.dependencies).build() - val output = evaluator.use { it.evaluateOutputText(uri("custom:/org/pkl/core/project/project5/main.pkl")) } + val output = + evaluator.use { it.evaluateOutputText(uri("custom:/org/pkl/core/project/project5/main.pkl")) } assertThat(output) .isEqualTo( """ @@ -382,45 +392,55 @@ class EvaluatorTest { fun `project base path set to non-hierarchical scheme`() { class FooBarModuleKey(val moduleUri: URI) : ModuleKey, ResolvedModuleKey { override fun hasHierarchicalUris(): Boolean = false + override fun isGlobbable(): Boolean = false + override fun getOriginal(): ModuleKey = this + override fun getUri(): URI = moduleUri + override fun loadSource(): String = if (uri.schemeSpecificPart.endsWith("PklProject")) { """ amends "pkl:Project" - """.trimIndent() - } else """ + """ + .trimIndent() + } else + """ birds = import("@birds/catalog/Ostritch.pkl") - """.trimIndent() + """ + .trimIndent() + override fun resolve(securityManager: SecurityManager): ResolvedModuleKey { return this } } val fooBayModuleKeyFactory = ModuleKeyFactory { uri -> - if (uri.scheme == "foobar") Optional.of(FooBarModuleKey(uri)) - else Optional.empty() + if (uri.scheme == "foobar") Optional.of(FooBarModuleKey(uri)) else Optional.empty() } - val evaluatorBuilder = with(EvaluatorBuilder.preconfigured()) { - setAllowedModules(SecurityManagers.defaultAllowedModules + Pattern.compile("foobar:")) - setAllowedResources(SecurityManagers.defaultAllowedResources + Pattern.compile("foobar:")) - setModuleKeyFactories( - listOf( - fooBayModuleKeyFactory, - ModuleKeyFactories.standardLibrary, - ModuleKeyFactories.pkg, - ModuleKeyFactories.projectpackage, - ModuleKeyFactories.file + val evaluatorBuilder = + with(EvaluatorBuilder.preconfigured()) { + setAllowedModules(SecurityManagers.defaultAllowedModules + Pattern.compile("foobar:")) + setAllowedResources(SecurityManagers.defaultAllowedResources + Pattern.compile("foobar:")) + setModuleKeyFactories( + listOf( + fooBayModuleKeyFactory, + ModuleKeyFactories.standardLibrary, + ModuleKeyFactories.pkg, + ModuleKeyFactories.projectpackage, + ModuleKeyFactories.file + ) ) - ) - } + } val project = evaluatorBuilder.build().use { Project.load(it, uri("foobar:foo/PklProject")) } val evaluator = evaluatorBuilder.setProjectDependencies(project.dependencies).build() assertThatCode { evaluator.use { it.evaluateOutputText(uri("foobar:baz")) } } - .hasMessageContaining("Cannot import dependency because project URI `foobar:foo/PklProject` does not have a hierarchical path.") + .hasMessageContaining( + "Cannot import dependency because project URI `foobar:foo/PklProject` does not have a hierarchical path." + ) } @Test @@ -430,22 +450,34 @@ class EvaluatorTest { val project = Project.load(modulePath("/org/pkl/core/project/project6/PklProject")) evaluatorBuilder.setProjectDependencies(project.dependencies).build().use { evaluator -> assertThatCode { - evaluator.evaluateOutputText(modulePath("/org/pkl/core/project/project6/globWithinDependency.pkl")) - }.hasMessageContaining(""" + evaluator.evaluateOutputText( + modulePath("/org/pkl/core/project/project6/globWithinDependency.pkl") + ) + } + .hasMessageContaining( + """ Cannot resolve import in local dependency because scheme `modulepath` is not globbable. 1 | res = import*("*.pkl") ^^^^^^^^^^^^^^^^ - """.trimIndent()) + """ + .trimIndent() + ) assertThatCode { - evaluator.evaluateOutputText(modulePath("/org/pkl/core/project/project6/globIntoDependency.pkl")) - }.hasMessageContaining(""" + evaluator.evaluateOutputText( + modulePath("/org/pkl/core/project/project6/globIntoDependency.pkl") + ) + } + .hasMessageContaining( + """ –– Pkl Error –– Cannot resolve import in local dependency because scheme `modulepath` is not globbable. 1 | import* "@project7/*.pkl" as proj7Files ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - """.trimIndent()) + """ + .trimIndent() + ) } } @@ -460,13 +492,16 @@ class EvaluatorTest { val module1 = modulesDir.resolve("foo/bar/module1.pkl").createParentDirectories() val module2 = modulesDir.resolve("foo/baz/module2.pkl").createParentDirectories() - module1.writeText(""" + module1.writeText( + """ // verify that relative import is resolved correctly import "../baz/module2.pkl" name = module2.name age = module2.age - """.trimIndent()) + """ + .trimIndent() + ) module2.writeText(sourceText) diff --git a/pkl-core/src/test/kotlin/org/pkl/core/JsonRendererTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/JsonRendererTest.kt index 9d7ea39a..549dd087 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/JsonRendererTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/JsonRendererTest.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core import java.io.StringWriter @@ -12,9 +27,7 @@ class JsonRendererTest { @Test fun `render document`() { val evaluator = Evaluator.preconfigured() - val module = evaluator.evaluate( - ModuleSource.modulePath("org/pkl/core/rendererTest.pkl") - ) + val module = evaluator.evaluate(ModuleSource.modulePath("org/pkl/core/rendererTest.pkl")) val writer = StringWriter() val renderer = ValueRenderers.json(writer, " ", true) @@ -23,14 +36,13 @@ class JsonRendererTest { val expected = IoUtils.readClassPathResourceAsString(javaClass, "rendererTest.json") assertThat(output).isEqualTo(expected) - assertThatCode { JsonParser(object : JsonHandler() {}).parse(output) }.doesNotThrowAnyException() + assertThatCode { JsonParser(object : JsonHandler() {}).parse(output) } + .doesNotThrowAnyException() } @Test fun `rendered document ends in newline`() { - val module: PModule = Evaluator - .preconfigured() - .evaluate(ModuleSource.text("foo { bar = 0 }")) + val module: PModule = Evaluator.preconfigured().evaluate(ModuleSource.text("foo { bar = 0 }")) for (omitNullProperties in listOf(false, true)) { val writer = StringWriter() diff --git a/pkl-core/src/test/kotlin/org/pkl/core/LanguageSnippetTests.kt b/pkl-core/src/test/kotlin/org/pkl/core/LanguageSnippetTests.kt index 1d2c788e..80552fc1 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/LanguageSnippetTests.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/LanguageSnippetTests.kt @@ -1,18 +1,28 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core import org.junit.platform.commons.annotation.Testable -@Testable -class LanguageSnippetTests +@Testable class LanguageSnippetTests -@Testable -class MacLanguageSnippetTests +@Testable class MacLanguageSnippetTests -@Testable -class LinuxLanguageSnippetTests +@Testable class LinuxLanguageSnippetTests -@Testable -class AlpineLanguageSnippetTests +@Testable class AlpineLanguageSnippetTests -@Testable -class WindowsLanguageSnippetTests +@Testable class WindowsLanguageSnippetTests diff --git a/pkl-core/src/test/kotlin/org/pkl/core/LanguageSnippetTestsEngine.kt b/pkl-core/src/test/kotlin/org/pkl/core/LanguageSnippetTestsEngine.kt index cc93d83a..1aca859a 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/LanguageSnippetTestsEngine.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/LanguageSnippetTestsEngine.kt @@ -1,5 +1,27 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core +import java.io.PrintWriter +import java.io.StringWriter +import java.nio.file.Files +import java.nio.file.Path +import kotlin.io.path.exists +import kotlin.io.path.isRegularFile +import kotlin.reflect.KClass import org.junit.platform.engine.EngineDiscoveryRequest import org.junit.platform.engine.TestDescriptor import org.junit.platform.engine.UniqueId @@ -11,13 +33,6 @@ import org.pkl.commons.test.PklExecutablePaths import org.pkl.core.http.HttpClient import org.pkl.core.project.Project import org.pkl.core.util.IoUtils -import java.io.PrintWriter -import java.io.StringWriter -import java.nio.file.Files -import java.nio.file.Path -import kotlin.io.path.exists -import kotlin.io.path.isRegularFile -import kotlin.reflect.KClass abstract class AbstractLanguageSnippetTestsEngine : InputOutputTestEngine() { private val lineNumberRegex = Regex("(?m)^(( ║ )*)(\\d+) \\|") @@ -31,17 +46,17 @@ abstract class AbstractLanguageSnippetTestsEngine : InputOutputTestEngine() { private val expectedOutputDir: Path = snippetsDir.resolve("output") /** - * Convenience for development; this selects which snippet test(s) to run. - * There is a (non-language-snippet) test to make sure this is `""` before commit. + * Convenience for development; this selects which snippet test(s) to run. There is a + * (non-language-snippet) test to make sure this is `""` before commit. */ - //language=regexp + // language=regexp internal val selection: String = "" protected val packageServer: PackageServer = PackageServer() override val includedTests: List = listOf(Regex(".*$selection\\.pkl")) - override val excludedTests: List = buildList { + override val excludedTests: List = buildList { add(Regex(".*/native/.*")) if (IoUtils.isWindows()) { addAll(windowsExcludedTests) @@ -53,8 +68,7 @@ abstract class AbstractLanguageSnippetTestsEngine : InputOutputTestEngine() { override val isInputFile: (Path) -> Boolean = { it.isRegularFile() } protected tailrec fun Path.getProjectDir(): Path? = - if (Files.exists(this.resolve("PklProject"))) this - else parent?.getProjectDir() + if (Files.exists(this.resolve("PklProject"))) this else parent?.getProjectDir() override fun expectedOutputFileFor(inputFile: Path): Path { val relativePath = IoUtils.relativize(inputFile, inputDir).toString() @@ -75,17 +89,19 @@ abstract class AbstractLanguageSnippetTestsEngine : InputOutputTestEngine() { private val replacement by lazy { if (snippetsDir.root.toString() != "/") "\$snippetsDir" else "/\$snippetsDir" - } + } protected fun String.stripFilePaths(): String = replace(IoUtils.toNormalizedPathString(snippetsDir), replacement) - protected fun String.stripLineNumbers() = replace(lineNumberRegex) { result -> - // replace line number with equivalent number of 'x' characters to keep formatting intact - (result.groups[1]!!.value) + "x".repeat(result.groups[3]!!.value.length) + " |" - } + protected fun String.stripLineNumbers() = + replace(lineNumberRegex) { result -> + // replace line number with equivalent number of 'x' characters to keep formatting intact + (result.groups[1]!!.value) + "x".repeat(result.groups[3]!!.value.length) + " |" + } - protected fun String.stripWebsite() = replace(Release.current().documentation().homepage(), "https://\$pklWebsite/") + protected fun String.stripWebsite() = + replace(Release.current().documentation().homepage(), "https://\$pklWebsite/") // can't think of a better solution right now protected fun String.stripVersionCheckErrorMessage() = @@ -103,8 +119,7 @@ abstract class AbstractLanguageSnippetTestsEngine : InputOutputTestEngine() { } protected fun String.withUnixLineEndings(): String { - return if (System.lineSeparator() == "\r\n") replace("\r\n", "\n") - else this + return if (System.lineSeparator() == "\r\n") replace("\r\n", "\n") else this } } @@ -123,16 +138,16 @@ class LanguageSnippetTestsEngine : AbstractLanguageSnippetTestsEngine() { "file:///foo/bar" to "file:///foo/bar" ) ) - .setExternalProperties(mapOf( - "name1" to "value1", - "name2" to "value2", - "/foo/bar" to "foobar" - )) + .setExternalProperties( + mapOf("name1" to "value1", "name2" to "value2", "/foo/bar" to "foobar") + ) .setModuleCacheDir(null) - .setHttpClient(HttpClient.builder() - .setTestPort(packageServer.port) - .addCertificates(FileTestUtils.selfSignedCertificate) - .buildLazily()) + .setHttpClient( + HttpClient.builder() + .setTestPort(packageServer.port) + .addCertificates(FileTestUtils.selfSignedCertificate) + .buildLazily() + ) } override val testClass: KClass<*> = LanguageSnippetTests::class @@ -140,60 +155,65 @@ class LanguageSnippetTestsEngine : AbstractLanguageSnippetTestsEngine() { override fun generateOutputFor(inputFile: Path): kotlin.Pair { val logWriter = StringWriter() - val (success, output) = try { - val evaluator = evaluatorBuilder() - .setLogger(Loggers.writer(PrintWriter(logWriter))) - .apply { - if (inputFile.startsWith(projectsDir)) { - val projectDir = inputFile.getProjectDir() ?: return@apply - val project = Project.loadFromPath( - projectDir.resolve("PklProject"), - SecurityManagers.defaultManager, - null, - StackFrameTransformers.empty, - mapOf() - ) - securityManager = null - applyFromProject(project) - } - } - .build() - evaluator.use { true to it.evaluateOutputText(ModuleSource.path(inputFile)) } - } catch (e: PklBugException) { - false to e.stackTraceToString() - } catch (e: PklException) { - false to e.message!! - .stripLineNumbers() - .stripVersionCheckErrorMessage() - } + val (success, output) = + try { + val evaluator = + evaluatorBuilder() + .setLogger(Loggers.writer(PrintWriter(logWriter))) + .apply { + if (inputFile.startsWith(projectsDir)) { + val projectDir = inputFile.getProjectDir() ?: return@apply + val project = + Project.loadFromPath( + projectDir.resolve("PklProject"), + SecurityManagers.defaultManager, + null, + StackFrameTransformers.empty, + mapOf() + ) + securityManager = null + applyFromProject(project) + } + } + .build() + evaluator.use { true to it.evaluateOutputText(ModuleSource.path(inputFile)) } + } catch (e: PklBugException) { + false to e.stackTraceToString() + } catch (e: PklException) { + false to e.message!!.stripLineNumbers().stripVersionCheckErrorMessage() + } val stderr = logWriter.toString().withUnixLineEndings() - return (success && stderr.isBlank()) to (output + stderr).stripFilePaths().stripWebsite().stripStdlibLocationSha() + return (success && stderr.isBlank()) to + (output + stderr).stripFilePaths().stripWebsite().stripStdlibLocationSha() } } abstract class AbstractNativeLanguageSnippetTestsEngine : AbstractLanguageSnippetTestsEngine() { abstract val pklExecutablePath: Path - override val excludedTests: List = listOf( - // exclude test that loads module from class path (there is no class path when using native executable) - // on the other hand, don't exclude /native/ - Regex(".*/import1b\\.pkl"), - ) + override val excludedTests: List = + listOf( + // exclude test that loads module from class path (there is no class path when using native + // executable) + // on the other hand, don't exclude /native/ + Regex(".*/import1b\\.pkl"), + ) - /** - * Avoid running tests for native binaries when those native binaries have not been built. - */ - override fun discover(discoveryRequest: EngineDiscoveryRequest, uniqueId: UniqueId): TestDescriptor { + /** Avoid running tests for native binaries when those native binaries have not been built. */ + override fun discover( + discoveryRequest: EngineDiscoveryRequest, + uniqueId: UniqueId + ): TestDescriptor { if (!pklExecutablePath.exists()) { // return empty descriptor w/o children return EngineDescriptor(uniqueId, javaClass.simpleName) } - + return super.discover(discoveryRequest, uniqueId) } - + override fun generateOutputFor(inputFile: Path): kotlin.Pair { val args = buildList { add(pklExecutablePath.toString()) @@ -234,20 +254,22 @@ abstract class AbstractNativeLanguageSnippetTestsEngine : AbstractLanguageSnippe add(inputFile.toString()) } - val builder = ProcessBuilder() - .command(args) + val builder = ProcessBuilder().command(args) val process = builder.start() return try { - val (out, err) = listOf(process.inputStream, process.errorStream) - .map { it.reader().readText().withUnixLineEndings() } + val (out, err) = + listOf(process.inputStream, process.errorStream).map { + it.reader().readText().withUnixLineEndings() + } val success = process.waitFor() == 0 && err.isBlank() - success to (out + err) - .stripFilePaths() - .stripLineNumbers() - .stripWebsite() - .stripVersionCheckErrorMessage() - .stripStdlibLocationSha() + success to + (out + err) + .stripFilePaths() + .stripLineNumbers() + .stripWebsite() + .stripVersionCheckErrorMessage() + .stripStdlibLocationSha() } finally { process.destroy() } @@ -280,11 +302,12 @@ class AlpineLanguageSnippetTestsEngine : AbstractNativeLanguageSnippetTestsEngin } // error message contains different file path on Windows -private val windowsExcludedTests get() = listOf(Regex(".*missingProjectDeps/bug\\.pkl")) +private val windowsExcludedTests + get() = listOf(Regex(".*missingProjectDeps/bug\\.pkl")) class WindowsLanguageSnippetTestsEngine : AbstractNativeLanguageSnippetTestsEngine() { override val pklExecutablePath: Path = PklExecutablePaths.windowsAmd64 override val testClass: KClass<*> = WindowsLanguageSnippetTests::class - override val excludedTests: List + override val excludedTests: List get() = super.excludedTests + windowsExcludedTests } diff --git a/pkl-core/src/test/kotlin/org/pkl/core/PClassInfoTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/PClassInfoTest.kt index 4f137b53..2f4b2121 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/PClassInfoTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/PClassInfoTest.kt @@ -1,8 +1,23 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core +import java.net.URI import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -import java.net.URI class PClassInfoTest { @Test diff --git a/pkl-core/src/test/kotlin/org/pkl/core/PListRendererTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/PListRendererTest.kt index 8478a8d2..fe44fe7c 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/PListRendererTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/PListRendererTest.kt @@ -1,13 +1,28 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core import java.io.StringWriter import javax.xml.parsers.DocumentBuilderFactory import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test +import org.pkl.core.util.IoUtils import org.xml.sax.ErrorHandler import org.xml.sax.InputSource import org.xml.sax.SAXParseException -import org.pkl.core.util.IoUtils class PListRendererTest { @Test @@ -28,8 +43,7 @@ class PListRendererTest { @Test fun `rendered document ends in newline`() { - val module = Evaluator.preconfigured() - .evaluate(ModuleSource.text("foo { bar = 0 }")) + val module = Evaluator.preconfigured().evaluate(ModuleSource.text("foo { bar = 0 }")) val writer = StringWriter() ValueRenderers.plist(writer, " ").renderDocument(module) @@ -37,28 +51,29 @@ class PListRendererTest { } private fun parseAndValidateRenderedDocument(output: String) { - val builderFactory = DocumentBuilderFactory.newInstance().apply { - isValidating = true - } + val builderFactory = DocumentBuilderFactory.newInstance().apply { isValidating = true } - val builder = builderFactory.newDocumentBuilder().apply { - setEntityResolver { _, _ -> - InputSource(PListRendererTest::class.java.getResourceAsStream("PropertyList-1.0.dtd")) + val builder = + builderFactory.newDocumentBuilder().apply { + setEntityResolver { _, _ -> + InputSource(PListRendererTest::class.java.getResourceAsStream("PropertyList-1.0.dtd")) + } + setErrorHandler( + object : ErrorHandler { + override fun warning(exception: SAXParseException) { + throw exception + } + + override fun error(exception: SAXParseException) { + throw exception + } + + override fun fatalError(exception: SAXParseException) { + throw exception + } + } + ) } - setErrorHandler(object : ErrorHandler { - override fun warning(exception: SAXParseException) { - throw exception - } - - override fun error(exception: SAXParseException) { - throw exception - } - - override fun fatalError(exception: SAXParseException) { - throw exception - } - }) - } builder.parse(output.byteInputStream()) } diff --git a/pkl-core/src/test/kotlin/org/pkl/core/PModuleTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/PModuleTest.kt index 15453f2d..c36e08cf 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/PModuleTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/PModuleTest.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core import java.net.URI @@ -25,14 +40,12 @@ class PModuleTest { @Test fun `get unknown property`() { - val e = assertThrows { - pigeon.getProperty("other") - } + val e = assertThrows { pigeon.getProperty("other") } assertThat(e) .hasMessage( "Module `test.module` does not have a property " + - "named `other`. Available properties: [name, age]" + "named `other`. Available properties: [name, age]" ) } @@ -48,15 +61,16 @@ class PModuleTest { var objectVisited = false var moduleVisited = false - val visitor = object : ValueVisitor { - override fun visitObject(value: PObject) { - objectVisited = true - } + val visitor = + object : ValueVisitor { + override fun visitObject(value: PObject) { + objectVisited = true + } - override fun visitModule(value: PModule) { - moduleVisited = true + override fun visitModule(value: PModule) { + moduleVisited = true + } } - } pigeon.accept(visitor) @@ -69,12 +83,7 @@ class PModuleTest { assertThat(pigeon).isEqualTo(pigeon) assertThat(pigeon.hashCode()).isEqualTo(pigeon.hashCode()) - val pigeon2 = PModule( - moduleUri, - moduleName, - classInfo, - HashMap(properties) - ) + val pigeon2 = PModule(moduleUri, moduleName, classInfo, HashMap(properties)) assertThat(pigeon2).isEqualTo(pigeon) assertThat(pigeon2.hashCode()).isEqualTo(pigeon.hashCode()) @@ -82,12 +91,7 @@ class PModuleTest { @Test fun `non-equal - different module uri`() { - val pigeon2 = PModule( - URI("other/module"), - moduleName, - classInfo, - properties - ) + val pigeon2 = PModule(URI("other/module"), moduleName, classInfo, properties) assertThat(pigeon2).isNotEqualTo(pigeon) assertThat(pigeon2.hashCode()).isNotEqualTo(pigeon.hashCode()) @@ -95,12 +99,7 @@ class PModuleTest { @Test fun `non-equal - different module name`() { - val pigeon2 = PModule( - moduleUri, - "other.module", - classInfo, - properties - ) + val pigeon2 = PModule(moduleUri, "other.module", classInfo, properties) assertThat(pigeon2).isNotEqualTo(pigeon) assertThat(pigeon2.hashCode()).isNotEqualTo(pigeon.hashCode()) @@ -108,12 +107,7 @@ class PModuleTest { @Test fun `non-equal - different property value`() { - val pigeon2 = PModule( - moduleUri, - moduleName, - classInfo, - mapOf("name" to "Pigeon", "age" to 21) - ) + val pigeon2 = PModule(moduleUri, moduleName, classInfo, mapOf("name" to "Pigeon", "age" to 21)) assertThat(pigeon2).isNotEqualTo(pigeon) assertThat(pigeon2.hashCode()).isNotEqualTo(pigeon.hashCode()) @@ -121,12 +115,7 @@ class PModuleTest { @Test fun `non-equal - missing property`() { - val pigeon2 = PModule( - moduleUri, - moduleName, - classInfo, - mapOf("name" to "Pigeon") - ) + val pigeon2 = PModule(moduleUri, moduleName, classInfo, mapOf("name" to "Pigeon")) assertThat(pigeon2).isNotEqualTo(pigeon) assertThat(pigeon2.hashCode()).isNotEqualTo(pigeon.hashCode()) @@ -134,12 +123,13 @@ class PModuleTest { @Test fun `non-equal - extra property`() { - val pigeon2 = PModule( - moduleUri, - moduleName, - classInfo, - mapOf("name" to "Pigeon", "age" to 42, "other" to true) - ) + val pigeon2 = + PModule( + moduleUri, + moduleName, + classInfo, + mapOf("name" to "Pigeon", "age" to 42, "other" to true) + ) assertThat(pigeon2).isNotEqualTo(pigeon) assertThat(pigeon2.hashCode()).isNotEqualTo(pigeon.hashCode()) @@ -147,7 +137,6 @@ class PModuleTest { @Test fun `toString()`() { - assertThat(pigeon.toString()) - .isEqualTo("test.module { name = Pigeon; age = 42 }") + assertThat(pigeon.toString()).isEqualTo("test.module { name = Pigeon; age = 42 }") } } diff --git a/pkl-core/src/test/kotlin/org/pkl/core/PNullTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/PNullTest.kt index 189f003a..868eb1f0 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/PNullTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/PNullTest.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core import org.assertj.core.api.Assertions.assertThat diff --git a/pkl-core/src/test/kotlin/org/pkl/core/PObjectTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/PObjectTest.kt index c25b09e5..2f5030a4 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/PObjectTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/PObjectTest.kt @@ -1,9 +1,24 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core +import java.net.URI import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows -import java.net.URI class PObjectTest { private val testUri = URI("repl:test") @@ -29,14 +44,12 @@ class PObjectTest { @Test fun `get unknown property`() { - val e = assertThrows { - pigeon.getProperty("other") - } + val e = assertThrows { pigeon.getProperty("other") } assertThat(e) .hasMessage( "Object of type `test#Person` does not have a property " + - "named `other`. Available properties: [name, age]" + "named `other`. Available properties: [name, age]" ) } @@ -52,15 +65,16 @@ class PObjectTest { var objectVisited = false var moduleVisited = false - val visitor = object : ValueVisitor { - override fun visitObject(value: PObject) { - objectVisited = true - } + val visitor = + object : ValueVisitor { + override fun visitObject(value: PObject) { + objectVisited = true + } - override fun visitModule(value: PModule) { - moduleVisited = true + override fun visitModule(value: PModule) { + moduleVisited = true + } } - } pigeon.accept(visitor) @@ -73,10 +87,7 @@ class PObjectTest { assertThat(pigeon).isEqualTo(pigeon) assertThat(pigeon.hashCode()).isEqualTo(pigeon.hashCode()) - val pigeon2 = PObject( - PClassInfo.get("test", "Person", URI("repl:test")), - HashMap(properties) - ) + val pigeon2 = PObject(PClassInfo.get("test", "Person", URI("repl:test")), HashMap(properties)) assertThat(pigeon2).isEqualTo(pigeon) assertThat(pigeon2.hashCode()).isEqualTo(pigeon.hashCode()) @@ -84,10 +95,7 @@ class PObjectTest { @Test fun `non-equal - different type`() { - val pigeon2 = PObject( - PClassInfo.get("test", "Other", URI("repl:Other")), - properties - ) + val pigeon2 = PObject(PClassInfo.get("test", "Other", URI("repl:Other")), properties) assertThat(pigeon2).isNotEqualTo(pigeon) assertThat(pigeon2.hashCode()).isNotEqualTo(pigeon.hashCode()) @@ -95,10 +103,11 @@ class PObjectTest { @Test fun `non-equal - different property value`() { - val pigeon2 = PObject( - PClassInfo.get("test", "Person", URI("repl:test")), - mapOf("name" to "Pigeon", "age" to 21) - ) + val pigeon2 = + PObject( + PClassInfo.get("test", "Person", URI("repl:test")), + mapOf("name" to "Pigeon", "age" to 21) + ) assertThat(pigeon2).isNotEqualTo(pigeon) assertThat(pigeon2.hashCode()).isNotEqualTo(pigeon.hashCode()) @@ -106,10 +115,8 @@ class PObjectTest { @Test fun `non-equal - missing property`() { - val pigeon2 = PObject( - PClassInfo.get("test", "Person", URI("repl:test")), - mapOf("name" to "Pigeon") - ) + val pigeon2 = + PObject(PClassInfo.get("test", "Person", URI("repl:test")), mapOf("name" to "Pigeon")) assertThat(pigeon2).isNotEqualTo(pigeon) assertThat(pigeon2.hashCode()).isNotEqualTo(pigeon.hashCode()) @@ -117,10 +124,11 @@ class PObjectTest { @Test fun `non-equal - extra property`() { - val pigeon2 = PObject( - PClassInfo.get("test", "Person", URI("repl:test")), - mapOf("name" to "Pigeon", "age" to 42, "other" to true) - ) + val pigeon2 = + PObject( + PClassInfo.get("test", "Person", URI("repl:test")), + mapOf("name" to "Pigeon", "age" to 42, "other" to true) + ) assertThat(pigeon2).isNotEqualTo(pigeon) assertThat(pigeon2.hashCode()).isNotEqualTo(pigeon.hashCode()) @@ -128,7 +136,6 @@ class PObjectTest { @Test fun `toString()`() { - assertThat(pigeon.toString()) - .isEqualTo("test#Person { name = Pigeon; age = 42 }") + assertThat(pigeon.toString()).isEqualTo("test#Person { name = Pigeon; age = 42 }") } } diff --git a/pkl-core/src/test/kotlin/org/pkl/core/PairTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/PairTest.kt index 53153b27..aa4b0686 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/PairTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/PairTest.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core import org.assertj.core.api.Assertions.assertThat diff --git a/pkl-core/src/test/kotlin/org/pkl/core/PcfRendererTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/PcfRendererTest.kt index 6449ac49..8445e976 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/PcfRendererTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/PcfRendererTest.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core import java.io.StringWriter @@ -21,14 +36,13 @@ class PcfRendererTest { assertThat(output.trim()).isEqualTo(expected.trim()) // TODO: make pcf a pkl subset again - //assertThatCode { evaluator.evaluateText(output) }.doesNotThrowAnyException() + // assertThatCode { evaluator.evaluateText(output) }.doesNotThrowAnyException() } @Test fun `rendered document ends in newline`() { - val module = EvaluatorBuilder.preconfigured() - .build() - .evaluate(ModuleSource.text("foo { bar = 0 }")) + val module = + EvaluatorBuilder.preconfigured().build().evaluate(ModuleSource.text("foo { bar = 0 }")) val writer = StringWriter() ValueRenderers.pcf(writer, " ", false, false).renderDocument(module) @@ -37,16 +51,19 @@ class PcfRendererTest { @Test fun `rendering with and without null properties`() { - val cases = listOf( - true to """ + val cases = + listOf( + true to + """ baz { qux = 42 corge = List(null, 1337, null, "Hello World") grault = Map("garply", null, "waldo", 42, "pigeon", null) } - """.trimIndent(), - - false to """ + """ + .trimIndent(), + false to + """ foo = null bar = null baz { @@ -55,12 +72,15 @@ class PcfRendererTest { corge = List(null, 1337, null, "Hello World") grault = Map("garply", null, "waldo", 42, "pigeon", null) } - """.trimIndent() - ) - - val module = Evaluator.preconfigured().evaluate( - ModuleSource.text( """ + .trimIndent() + ) + + val module = + Evaluator.preconfigured() + .evaluate( + ModuleSource.text( + """ foo = null bar = null baz { @@ -78,9 +98,10 @@ class PcfRendererTest { ["pigeon"] = null } } - """.trimIndent() - ) - ) + """ + .trimIndent() + ) + ) for ((omitNullProperties, expected) in cases) { val writer = StringWriter() ValueRenderers.pcf(writer, " ", omitNullProperties, false).renderDocument(module) @@ -90,7 +111,7 @@ class PcfRendererTest { // TODO: ada // can happen in REPL or when rendering manually constructed container -/* @Test + /* @Test fun `render container with unevaluated element`() { renderer.renderValue(PObject(PClassInfo.Mapping, mapOf("one" to 1L, "two" to null))) diff --git a/pkl-core/src/test/kotlin/org/pkl/core/PklInfoTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/PklInfoTest.kt index 7c91b9f0..3f4e7272 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/PklInfoTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/PklInfoTest.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core import org.assertj.core.api.Assertions.* diff --git a/pkl-core/src/test/kotlin/org/pkl/core/PlatformTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/PlatformTest.kt index 894d4b94..26aaf504 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/PlatformTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/PlatformTest.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core import org.assertj.core.api.Assertions.* diff --git a/pkl-core/src/test/kotlin/org/pkl/core/PropertiesRendererTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/PropertiesRendererTest.kt index 45b39edc..f0192424 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/PropertiesRendererTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/PropertiesRendererTest.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core import java.io.StringWriter @@ -10,23 +25,31 @@ class PropertiesRendererTest { @Test fun `render document`() { val evaluator = Evaluator.preconfigured() - val module = evaluator.evaluate(ModuleSource.modulePath("org/pkl/core/propertiesRendererTest.pkl")) + val module = + evaluator.evaluate(ModuleSource.modulePath("org/pkl/core/propertiesRendererTest.pkl")) val writer = StringWriter() val renderer = ValueRenderers.properties(writer, true, false) renderer.renderDocument(module) val output = writer.toString() - val expected = IoUtils.readClassPathResourceAsString(javaClass, "propertiesRendererTest.properties") + val expected = + IoUtils.readClassPathResourceAsString(javaClass, "propertiesRendererTest.properties") assertThat(output).isEqualTo(expected) } @Test fun `render unsupported document values`() { - val unsupportedValues = listOf( - "List()", "new Listing {}", "Map()", "new Mapping {}", "Set()", - "new PropertiesRenderer {}", "new Dynamic {}" - ) + val unsupportedValues = + listOf( + "List()", + "new Listing {}", + "Map()", + "new Mapping {}", + "Set()", + "new PropertiesRenderer {}", + "new Dynamic {}" + ) unsupportedValues.forEach { val evaluator = Evaluator.preconfigured() @@ -39,13 +62,13 @@ class PropertiesRendererTest { @Test fun `rendered document ends in newline`() { - val module = Evaluator.preconfigured() - .evaluate(ModuleSource.text("foo { bar = 0 }")) + val module = Evaluator.preconfigured().evaluate(ModuleSource.text("foo { bar = 0 }")) for (omitNullProperties in listOf(false, true)) { for (restrictCharSet in listOf(false, true)) { val writer = StringWriter() - ValueRenderers.properties(writer, omitNullProperties, restrictCharSet).renderDocument(module) + ValueRenderers.properties(writer, omitNullProperties, restrictCharSet) + .renderDocument(module) assertThat(writer.toString()).endsWith("\n") } } diff --git a/pkl-core/src/test/kotlin/org/pkl/core/ReleaseTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/ReleaseTest.kt index ff760109..4e4609e8 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/ReleaseTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/ReleaseTest.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core import org.assertj.core.api.Assertions.* diff --git a/pkl-core/src/test/kotlin/org/pkl/core/ReplServerTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/ReplServerTest.kt index 3a6adc79..f5b8316f 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/ReplServerTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/ReplServerTest.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core import org.assertj.core.api.Assertions.assertThat @@ -11,36 +26,30 @@ import org.pkl.core.repl.ReplServer import org.pkl.core.resource.ResourceReaders class ReplServerTest { - private val server = ReplServer( - SecurityManagers.defaultManager, - HttpClient.dummyClient(), - Loggers.stdErr(), - listOf( - ModuleKeyFactories.standardLibrary, - ModuleKeyFactories.classPath(this::class.java.classLoader), - ModuleKeyFactories.file - ), - listOf( - ResourceReaders.environmentVariable(), - ResourceReaders.externalProperty() - ), - mapOf("NAME1" to "value1", "NAME2" to "value2"), - mapOf("name1" to "value1", "name2" to "value2"), - null, - null, - null, - "/".toPath(), - StackFrameTransformers.defaultTransformer - ) + private val server = + ReplServer( + SecurityManagers.defaultManager, + HttpClient.dummyClient(), + Loggers.stdErr(), + listOf( + ModuleKeyFactories.standardLibrary, + ModuleKeyFactories.classPath(this::class.java.classLoader), + ModuleKeyFactories.file + ), + listOf(ResourceReaders.environmentVariable(), ResourceReaders.externalProperty()), + mapOf("NAME1" to "value1", "NAME2" to "value2"), + mapOf("name1" to "value1", "name2" to "value2"), + null, + null, + null, + "/".toPath(), + StackFrameTransformers.defaultTransformer + ) @Test fun `complete members of local property`() { - server.handleRequest( - ReplRequest.Eval("id", "local foo = new { bar = 10 }", false, false) - ) - val responses = server.handleRequest( - ReplRequest.Completion("id", "foo") - ) + server.handleRequest(ReplRequest.Eval("id", "local foo = new { bar = 10 }", false, false)) + val responses = server.handleRequest(ReplRequest.Completion("id", "foo")) assertThat(responses.size).isEqualTo(1) @@ -51,9 +60,18 @@ class ReplServerTest { assertThat(completionResponse.members.toSortedSet()) .isEqualTo( sortedSetOf( - "default", "bar", "toList()", "toMap()", "getProperty(", - "getPropertyOrNull(", "hasProperty(", "ifNonNull(", - "length()", "getClass()", "toString()", "toTyped(" + "default", + "bar", + "toList()", + "toMap()", + "getProperty(", + "getPropertyOrNull(", + "hasProperty(", + "ifNonNull(", + "length()", + "getClass()", + "toString()", + "toTyped(" ) ) } @@ -61,9 +79,7 @@ class ReplServerTest { @Test fun `complete members of module import`() { server.handleRequest(ReplRequest.Eval("id", "import \"pkl:test\"", false, false)) - val responses = server.handleRequest( - ReplRequest.Completion("id", "test") - ) + val responses = server.handleRequest(ReplRequest.Completion("id", "test")) assertThat(responses.size).isEqualTo(1) @@ -79,14 +95,11 @@ class ReplServerTest { @Test fun `complete members of 'this' expression`() { - val responses1 = server.handleRequest( - ReplRequest.Eval("id", "x = 1; function f() = 3", false, false) - ) + val responses1 = + server.handleRequest(ReplRequest.Eval("id", "x = 1; function f() = 3", false, false)) assertThat(responses1.size).isEqualTo(0) - val responses2 = server.handleRequest( - ReplRequest.Completion("id", "this") - ) + val responses2 = server.handleRequest(ReplRequest.Completion("id", "this")) assertThat(responses2.size).isEqualTo(1) val response = responses2[0] @@ -96,8 +109,18 @@ class ReplServerTest { assertThat(completionResponse.members.toSortedSet()) .isEqualTo( sortedSetOf( - "output", "toDynamic()", "toMap()", "f()", "x", "ifNonNull(", "getClass()", - "getProperty(", "getPropertyOrNull(", "hasProperty(", "relativePathTo(", "toString()" + "output", + "toDynamic()", + "toMap()", + "f()", + "x", + "ifNonNull(", + "getClass()", + "getProperty(", + "getPropertyOrNull(", + "hasProperty(", + "relativePathTo(", + "toString()" ) ) } @@ -156,7 +179,10 @@ class ReplServerTest { val result2 = makeEvalRequest("""greet(42)""") assertThat(result2).isEqualTo("\"Hello, 42!\"") - val result3 = makeEvalRequest("function greet(name: String): String = \"Hello, \\(name)!\"; greet(\"Pigeon\") ") + val result3 = + makeEvalRequest( + "function greet(name: String): String = \"Hello, \\(name)!\"; greet(\"Pigeon\") " + ) assertThat(result3).isEqualTo("\"Hello, Pigeon!\"") val result4 = makeFailingEvalRequest("""greet(44)""") @@ -164,8 +190,7 @@ class ReplServerTest { } private fun makeEvalRequest(text: String): String { - val responses = - server.handleRequest(ReplRequest.Eval("id", text, false, false)) + val responses = server.handleRequest(ReplRequest.Eval("id", text, false, false)) assertThat(responses).hasSize(1) val response = responses[0] @@ -176,8 +201,7 @@ class ReplServerTest { } private fun makeFailingEvalRequest(text: String): String { - val responses = - server.handleRequest(ReplRequest.Eval("id", text, false, false)) + val responses = server.handleRequest(ReplRequest.Eval("id", text, false, false)) assertThat(responses).hasSize(1) val response = responses[0] diff --git a/pkl-core/src/test/kotlin/org/pkl/core/RepositoryHygiene.kt b/pkl-core/src/test/kotlin/org/pkl/core/RepositoryHygiene.kt index bd1159c1..bf3fa6f4 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/RepositoryHygiene.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/RepositoryHygiene.kt @@ -1,13 +1,28 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test -import org.pkl.commons.test.FileTestUtils -import org.pkl.commons.walk import java.nio.file.Path import java.util.stream.Collectors import kotlin.io.path.extension import kotlin.io.path.isRegularFile +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test +import org.pkl.commons.test.FileTestUtils +import org.pkl.commons.walk /** * These tests don't assert Pkl's implementation correctness, but rather that no debugging settings @@ -22,18 +37,24 @@ class RepositoryHygiene { @Test fun `no output files exists for language snippets without an input`() { val input = snippetsFolder.resolve("input") - val inputs = input.walk().filter { - it.extension == "pkl" - }.map { - val path = input.relativize(it).toString() - inputRegex.replace(path, "$1$2") - }.collect(Collectors.toSet()) + val inputs = + input + .walk() + .filter { it.extension == "pkl" } + .map { + val path = input.relativize(it).toString() + inputRegex.replace(path, "$1$2") + } + .collect(Collectors.toSet()) val output = snippetsFolder.resolve("output") - output.walk().filter { it.isRegularFile() }.forEach { - val out = output.relativize(it).toString() - checkOutputHasInput(inputs, out) - } + output + .walk() + .filter { it.isRegularFile() } + .forEach { + val out = output.relativize(it).toString() + checkOutputHasInput(inputs, out) + } } private fun checkOutputHasInput(inputs: Set, output: String) { diff --git a/pkl-core/src/test/kotlin/org/pkl/core/SecurityManagersTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/SecurityManagersTest.kt index 62615879..42a8f7f1 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/SecurityManagersTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/SecurityManagersTest.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core import java.net.URI @@ -12,116 +27,84 @@ import org.junit.jupiter.api.io.TempDir import org.pkl.commons.toPath class SecurityManagersTest { - private val manager = SecurityManagers.standard( - listOf(Pattern.compile("test:foo/bar")), - listOf(Pattern.compile("env:FOO_BAR")), - { uri -> if (uri.scheme == "one") 1 else if (uri.scheme == "two") 2 else 0 }, - null - ) + private val manager = + SecurityManagers.standard( + listOf(Pattern.compile("test:foo/bar")), + listOf(Pattern.compile("env:FOO_BAR")), + { uri -> if (uri.scheme == "one") 1 else if (uri.scheme == "two") 2 else 0 }, + null + ) @Test fun `checkResolveModule() - complete match`() { - val e = catchThrowable { - manager.checkResolveModule(URI("test:foo/bar")) - } + val e = catchThrowable { manager.checkResolveModule(URI("test:foo/bar")) } assertThat(e).doesNotThrowAnyException() } @Test fun `checkResolveModule() - partial match from start`() { - val e = catchThrowable { - manager.checkResolveModule(URI("test:foo/bar/baz")) - } + val e = catchThrowable { manager.checkResolveModule(URI("test:foo/bar/baz")) } assertThat(e).doesNotThrowAnyException() } @Test fun `checkResolveModule() - partial match not from start`() { - assertThrows { - manager.checkResolveModule(URI("other:test:foo/bar")) - } + assertThrows { manager.checkResolveModule(URI("other:test:foo/bar")) } } @Test fun `checkResolveModule() - no match`() { - assertThrows { - manager.checkResolveModule(URI("other:uri")) - } + assertThrows { manager.checkResolveModule(URI("other:uri")) } } @Test fun `checkResolveModule() - no match #2`() { - assertThrows { - manager.checkResolveModule(URI("test:foo/baz")) - } + assertThrows { manager.checkResolveModule(URI("test:foo/baz")) } } @Test fun `checkReadResource() - complete match`() { - val e = catchThrowable { - manager.checkReadResource(URI("env:FOO_BAR")) - } + val e = catchThrowable { manager.checkReadResource(URI("env:FOO_BAR")) } assertThat(e).doesNotThrowAnyException() } @Test fun `checkReadResource() - partial match from start`() { - val e = catchThrowable { - manager.checkReadResource(URI("env:FOO_BAR_BAZ")) - } + val e = catchThrowable { manager.checkReadResource(URI("env:FOO_BAR_BAZ")) } assertThat(e).doesNotThrowAnyException() } @Test fun `checkReadResource() - partial match not from start`() { - assertThrows { - manager.checkReadResource(URI("other:env:FOO_BAR")) - } + assertThrows { manager.checkReadResource(URI("other:env:FOO_BAR")) } } @Test fun `checkReadResource() - no match`() { - assertThrows { - manager.checkReadResource(URI("other:uri")) - } + assertThrows { manager.checkReadResource(URI("other:uri")) } } @Test fun `checkReadResource() - no match #2`() { - assertThrows { - manager.checkReadResource(URI("env:FOO_BAZ")) - } + assertThrows { manager.checkReadResource(URI("env:FOO_BAZ")) } } @Test fun `checkImportModule() - same trust level`() { - val e = catchThrowable { - manager.checkImportModule( - URI("one:foo"), - URI("one:bar") - ) - } + val e = catchThrowable { manager.checkImportModule(URI("one:foo"), URI("one:bar")) } assertThat(e).doesNotThrowAnyException() } @Test fun `checkImportModule() - higher trust level`() { assertThrows { - manager.checkImportModule( - URI("one:foo"), - URI("two:bar") - ) + manager.checkImportModule(URI("one:foo"), URI("two:bar")) } } @Test fun `checkImportModule() - lower trust level`() { - val e = catchThrowable { - manager.checkImportModule( - URI("two:foo"), - URI("one:bar") - ) - } + val e = catchThrowable { manager.checkImportModule(URI("two:foo"), URI("one:bar")) } assertThat(e).doesNotThrowAnyException() } @@ -154,12 +137,13 @@ class SecurityManagersTest { val rootDir = tempDir.resolve("root") Files.createDirectory(rootDir) - val manager = SecurityManagers.standard( - listOf(Pattern.compile("file")), - listOf(Pattern.compile("file")), - SecurityManagers.defaultTrustLevels, - rootDir - ) + val manager = + SecurityManagers.standard( + listOf(Pattern.compile("file")), + listOf(Pattern.compile("file")), + SecurityManagers.defaultTrustLevels, + rootDir + ) val path = rootDir.resolve("baz.pkl") Files.createFile(path) @@ -174,12 +158,13 @@ class SecurityManagersTest { fun `can resolve modules and resources under root dir - files don't exist`() { val rootDir = "/foo/bar".toPath() - val manager = SecurityManagers.standard( - listOf(Pattern.compile("file")), - listOf(Pattern.compile("file")), - SecurityManagers.defaultTrustLevels, - rootDir - ) + val manager = + SecurityManagers.standard( + listOf(Pattern.compile("file")), + listOf(Pattern.compile("file")), + SecurityManagers.defaultTrustLevels, + rootDir + ) manager.checkResolveModule(Path.of("/foo/bar/baz.pkl").toUri()) manager.checkReadResource(Path.of("/foo/bar/baz.pkl").toUri()) @@ -189,48 +174,44 @@ class SecurityManagersTest { } @Test - fun `cannot resolve modules and resources outside root dir - files do exist`(@TempDir tempDir: Path) { + fun `cannot resolve modules and resources outside root dir - files do exist`( + @TempDir tempDir: Path + ) { val rootDir = tempDir.resolve("root") Files.createDirectory(rootDir) - val manager = SecurityManagers.standard( - listOf(Pattern.compile("file")), - listOf(Pattern.compile("file")), - SecurityManagers.defaultTrustLevels, - rootDir - ) + val manager = + SecurityManagers.standard( + listOf(Pattern.compile("file")), + listOf(Pattern.compile("file")), + SecurityManagers.defaultTrustLevels, + rootDir + ) val path = rootDir.resolve("../baz.pkl") Files.createFile(path) - assertThrows { - manager.checkResolveModule(path.toUri()) - } - assertThrows { - manager.checkReadResource(path.toUri()) - } + assertThrows { manager.checkResolveModule(path.toUri()) } + assertThrows { manager.checkReadResource(path.toUri()) } val symlink = rootDir.resolve("qux") Files.createSymbolicLink(symlink, tempDir) val path2 = symlink.resolve("baz2.pkl") Files.createFile(path2) - assertThrows { - manager.checkResolveModule(path2.toUri()) - } - assertThrows { - manager.checkReadResource(path2.toUri()) - } + assertThrows { manager.checkResolveModule(path2.toUri()) } + assertThrows { manager.checkReadResource(path2.toUri()) } } @Test fun `cannot resolve modules and resources outside root dir - files don't exist`() { val rootDir = "/foo/bar".toPath() - val manager = SecurityManagers.standard( - listOf(Pattern.compile("file")), - listOf(Pattern.compile("file")), - SecurityManagers.defaultTrustLevels, - rootDir - ) + val manager = + SecurityManagers.standard( + listOf(Pattern.compile("file")), + listOf(Pattern.compile("file")), + SecurityManagers.defaultTrustLevels, + rootDir + ) assertThrows { manager.checkResolveModule(Path.of("/foo/baz.pkl").toUri()) diff --git a/pkl-core/src/test/kotlin/org/pkl/core/StackFrameTransformersTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/StackFrameTransformersTest.kt index eff38f5f..6fe8997b 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/StackFrameTransformersTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/StackFrameTransformersTest.kt @@ -1,9 +1,24 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core -import org.pkl.commons.test.PackageServer import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Test +import org.pkl.commons.test.PackageServer import org.pkl.core.http.HttpClient class StackFrameTransformersTest { @@ -13,21 +28,13 @@ class StackFrameTransformersTest { fun replacePackageUriWithSourceCodeUrl() { PackageServer().use { server -> val httpClient = HttpClient.builder().setTestPort(server.port).build() - EvaluatorBuilder.preconfigured() - .setHttpClient(httpClient) - .build().use { - val frame = StackFrame( - "package://localhost:0/birds@0.5.0#/Bird.pkl", - null, - listOf(), - 1, - 1, - 2, - 2) - val transformed = - StackFrameTransformers.replacePackageUriWithSourceCodeUrl.apply(frame) - assertThat(transformed.moduleUri).isEqualTo("https://example.com/birds/v0.5.0/blob/Bird.pkl#L1-L2") - } + EvaluatorBuilder.preconfigured().setHttpClient(httpClient).build().use { + val frame = + StackFrame("package://localhost:0/birds@0.5.0#/Bird.pkl", null, listOf(), 1, 1, 2, 2) + val transformed = StackFrameTransformers.replacePackageUriWithSourceCodeUrl.apply(frame) + assertThat(transformed.moduleUri) + .isEqualTo("https://example.com/birds/v0.5.0/blob/Bird.pkl#L1-L2") + } } } } diff --git a/pkl-core/src/test/kotlin/org/pkl/core/VersionTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/VersionTest.kt index 154ffcd6..632e9073 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/VersionTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/VersionTest.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core import org.assertj.core.api.Assertions.assertThat @@ -37,23 +52,16 @@ class VersionTest { @Test fun `parse invalid version`() { - assertThat(Version.parseOrNull("not a version number")) - .isNull() + assertThat(Version.parseOrNull("not a version number")).isNull() - assertThrows { - Version.parse("not a version number") - } + assertThrows { Version.parse("not a version number") } } @Test fun `parse too large version`() { - assertThrows { - Version.parse("not a version number") - } + assertThrows { Version.parse("not a version number") } - assertThrows { - Version.parse("999999999999999.0.0") - } + assertThrows { Version.parse("999999999999999.0.0") } } @Test @@ -66,137 +74,80 @@ class VersionTest { @Test fun withMethods() { - val version = Version.parse("0.0.0") - .withMajor(1) - .withMinor(2) - .withPatch(3) - .withPreRelease("rc.1") - .withBuild("456.789") + val version = + Version.parse("0.0.0") + .withMajor(1) + .withMinor(2) + .withPatch(3) + .withPreRelease("rc.1") + .withBuild("456.789") assertThat(version).isEqualTo(Version.parse("1.2.3-rc.1+456.789")) - val version2 = Version.parse("0.0.0") - .withBuild("456.789") - .withPreRelease("rc.1") - .withPatch(3) - .withMinor(2) - .withMajor(1) + val version2 = + Version.parse("0.0.0") + .withBuild("456.789") + .withPreRelease("rc.1") + .withPatch(3) + .withMinor(2) + .withMajor(1) assertThat(version2).isEqualTo(version) } @Test fun `compareTo()`() { - assertThat( - Version(1, 2, 3, null, null).compareTo( - Version(1, 2, 3, null, null) - ) - ).isEqualTo(0) - assertThat( - Version(1, 2, 3, "SNAPSHOT", null).compareTo( - Version(1, 2, 3, "SNAPSHOT", null) - ) - ).isEqualTo(0) - assertThat( - Version(1, 2, 3, "alpha", null).compareTo( - Version(1, 2, 3, "alpha", null) - ) - ).isEqualTo(0) - assertThat( - Version(1, 2, 3, "alpha", null).compareTo( - Version(1, 2, 3, "alpha", "build123") - ) - ).isEqualTo(0) + assertThat(Version(1, 2, 3, null, null).compareTo(Version(1, 2, 3, null, null))).isEqualTo(0) + assertThat(Version(1, 2, 3, "SNAPSHOT", null).compareTo(Version(1, 2, 3, "SNAPSHOT", null))) + .isEqualTo(0) + assertThat(Version(1, 2, 3, "alpha", null).compareTo(Version(1, 2, 3, "alpha", null))) + .isEqualTo(0) + assertThat(Version(1, 2, 3, "alpha", null).compareTo(Version(1, 2, 3, "alpha", "build123"))) + .isEqualTo(0) - assertThat( - Version(1, 2, 3, null, null).compareTo( - Version(2, 2, 3, null, null) - ) - ).isLessThan(0) - assertThat( - Version(1, 2, 3, null, null).compareTo( - Version(1, 3, 3, null, null) - ) - ).isLessThan(0) - assertThat( - Version(1, 2, 3, null, null).compareTo( - Version(1, 2, 4, null, null) - ) - ).isLessThan(0) + assertThat(Version(1, 2, 3, null, null).compareTo(Version(2, 2, 3, null, null))).isLessThan(0) + assertThat(Version(1, 2, 3, null, null).compareTo(Version(1, 3, 3, null, null))).isLessThan(0) + assertThat(Version(1, 2, 3, null, null).compareTo(Version(1, 2, 4, null, null))).isLessThan(0) - assertThat( - Version(2, 2, 3, null, null).compareTo( - Version(1, 2, 3, null, null) - ) - ).isGreaterThan(0) - assertThat( - Version(1, 3, 3, null, null).compareTo( - Version(1, 2, 3, null, null) - ) - ).isGreaterThan(0) - assertThat( - Version(1, 2, 4, null, null).compareTo( - Version(1, 2, 3, null, null) - ) - ).isGreaterThan(0) + assertThat(Version(2, 2, 3, null, null).compareTo(Version(1, 2, 3, null, null))) + .isGreaterThan(0) + assertThat(Version(1, 3, 3, null, null).compareTo(Version(1, 2, 3, null, null))) + .isGreaterThan(0) + assertThat(Version(1, 2, 4, null, null).compareTo(Version(1, 2, 3, null, null))) + .isGreaterThan(0) - assertThat( - Version(1, 2, 3, "SNAPSHOT", null).compareTo( - Version(1, 2, 3, null, null) - ) - ).isLessThan(0) - assertThat( - Version(1, 2, 3, "alpha", null).compareTo( - Version(1, 2, 3, "beta", null) - ) - ).isLessThan(0) - assertThat( - Version(1, 2, 3, "alpha", "build123").compareTo( - Version(1, 2, 3, "beta", null) - ) - ).isLessThan(0) + assertThat(Version(1, 2, 3, "SNAPSHOT", null).compareTo(Version(1, 2, 3, null, null))) + .isLessThan(0) + assertThat(Version(1, 2, 3, "alpha", null).compareTo(Version(1, 2, 3, "beta", null))) + .isLessThan(0) + assertThat(Version(1, 2, 3, "alpha", "build123").compareTo(Version(1, 2, 3, "beta", null))) + .isLessThan(0) - assertThat( - Version(1, 2, 3, null, null).compareTo( - Version(1, 2, 3, "SNAPSHOT", null) - ) - ).isGreaterThan(0) - assertThat( - Version(1, 2, 3, "beta", null).compareTo( - Version(1, 2, 3, "alpha", "build123") - ) - ).isGreaterThan(0) + assertThat(Version(1, 2, 3, null, null).compareTo(Version(1, 2, 3, "SNAPSHOT", null))) + .isGreaterThan(0) + assertThat(Version(1, 2, 3, "beta", null).compareTo(Version(1, 2, 3, "alpha", "build123"))) + .isGreaterThan(0) } @Test fun `compare version with too large numeric pre-release identifier`() { // error is deferred until compareTo(), but should be good enough assertThrows { - Version(1, 2, 3, "999", null).compareTo( - Version(1, 2, 3, "9999999999999999999", null) - ) + Version(1, 2, 3, "999", null).compareTo(Version(1, 2, 3, "9999999999999999999", null)) } } @Test fun `equals()`() { - assertThat(Version(1, 2, 3, null, null)) - .isEqualTo(Version(1, 2, 3, null, null)) - assertThat(Version(1, 2, 3, "SNAPSHOT", null)) - .isEqualTo(Version(1, 2, 3, "SNAPSHOT", null)) - assertThat(Version(1, 2, 3, "alpha", null)) - .isEqualTo(Version(1, 2, 3, "alpha", null)) - assertThat(Version(1, 2, 3, "beta", "build123")) - .isEqualTo(Version(1, 2, 3, "beta", "build456")) + assertThat(Version(1, 2, 3, null, null)).isEqualTo(Version(1, 2, 3, null, null)) + assertThat(Version(1, 2, 3, "SNAPSHOT", null)).isEqualTo(Version(1, 2, 3, "SNAPSHOT", null)) + assertThat(Version(1, 2, 3, "alpha", null)).isEqualTo(Version(1, 2, 3, "alpha", null)) + assertThat(Version(1, 2, 3, "beta", "build123")).isEqualTo(Version(1, 2, 3, "beta", "build456")) - assertThat(Version(1, 3, 3, null, null)) - .isNotEqualTo(Version(1, 2, 3, null, null)) - assertThat(Version(1, 2, 4, null, null)) - .isNotEqualTo(Version(1, 2, 3, null, null)) - assertThat(Version(1, 2, 3, "SNAPSHOT", null)) - .isNotEqualTo(Version(1, 2, 3, null, null)) - assertThat(Version(1, 2, 3, "beta", null)) - .isNotEqualTo(Version(1, 2, 3, "alpha", null)) + assertThat(Version(1, 3, 3, null, null)).isNotEqualTo(Version(1, 2, 3, null, null)) + assertThat(Version(1, 2, 4, null, null)).isNotEqualTo(Version(1, 2, 3, null, null)) + assertThat(Version(1, 2, 3, "SNAPSHOT", null)).isNotEqualTo(Version(1, 2, 3, null, null)) + assertThat(Version(1, 2, 3, "beta", null)).isNotEqualTo(Version(1, 2, 3, "alpha", null)) } @Test diff --git a/pkl-core/src/test/kotlin/org/pkl/core/YamlRendererTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/YamlRendererTest.kt index d2f2b3ef..b2c36ada 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/YamlRendererTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/YamlRendererTest.kt @@ -1,12 +1,27 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core import java.io.StringWriter import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatCode import org.junit.jupiter.api.Test +import org.pkl.core.util.IoUtils import org.snakeyaml.engine.v2.api.Load import org.snakeyaml.engine.v2.api.LoadSettings -import org.pkl.core.util.IoUtils class YamlRendererTest { @Test @@ -21,15 +36,17 @@ class YamlRendererTest { val expected = IoUtils.readClassPathResourceAsString(javaClass, "rendererTest.yaml") assertThat(output.trim()).isEqualTo(expected.trim()) - assertThatCode { Load(LoadSettings.builder().build()).loadFromString(output) }.doesNotThrowAnyException() + assertThatCode { Load(LoadSettings.builder().build()).loadFromString(output) } + .doesNotThrowAnyException() } @Test fun `render YAML stream`() { val evaluator = Evaluator.preconfigured() - val module = evaluator.evaluate( - ModuleSource.text( - """ + val module = + evaluator.evaluate( + ModuleSource.text( + """ stream = new Listing { new Dynamic { name = "Pigeon" @@ -48,9 +65,10 @@ class YamlRendererTest { "Blue Rock Ltd." 12345 } - """.trimIndent() + """ + .trimIndent() + ) ) - ) val writer = StringWriter() val renderer = ValueRenderers.yaml(writer, 2, true, true) @@ -58,8 +76,9 @@ class YamlRendererTest { renderer.renderDocument(module.getProperty("stream")) val output = writer.toString() - assertThat(output.trim()).isEqualTo( - """ + assertThat(output.trim()) + .isEqualTo( + """ name: Pigeon age: 42 --- @@ -72,14 +91,14 @@ class YamlRendererTest { three: 3 --- Blue Rock Ltd. --- 12345 - """.trimIndent() - ) + """ + .trimIndent() + ) } @Test fun `rendered document ends in newline`() { - val module = Evaluator.preconfigured() - .evaluate(ModuleSource.text("foo { bar = 0 }")) + val module = Evaluator.preconfigured().evaluate(ModuleSource.text("foo { bar = 0 }")) for (omitNullProperties in listOf(false, true)) { for (isStream in listOf(false, true)) { @@ -93,18 +112,20 @@ class YamlRendererTest { @Test fun `render truthy strings, octals and number-like strings`() { val evaluator = Evaluator.preconfigured() - val module = evaluator.evaluate( - ModuleSource.text( - """ + val module = + evaluator.evaluate( + ModuleSource.text( + """ num1 = "50" num2 = "50.123" `60.123` = "60.123" yes = "yes" truth = "true" octalNumber = "0777" - """.trimIndent() + """ + .trimIndent() + ) ) - ) val writer = StringWriter() val renderer = ValueRenderers.yaml(writer, 2, true, false) @@ -112,15 +133,17 @@ class YamlRendererTest { renderer.renderDocument(module) val output = writer.toString() - assertThat(output.trim()).isEqualTo( - """ + assertThat(output.trim()) + .isEqualTo( + """ num1: '50' num2: '50.123' '60.123': '60.123' 'yes': 'yes' truth: 'true' octalNumber: '0777' - """.trimIndent() - ) + """ + .trimIndent() + ) } } diff --git a/pkl-core/src/test/kotlin/org/pkl/core/ast/builder/ImportsAndReadsParserTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/ast/builder/ImportsAndReadsParserTest.kt index 8e08bc83..6f5be5b1 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/ast/builder/ImportsAndReadsParserTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/ast/builder/ImportsAndReadsParserTest.kt @@ -1,15 +1,31 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.ast.builder -import org.pkl.core.SecurityManagers -import org.pkl.core.module.ModuleKeys +import java.net.URI import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -import java.net.URI +import org.pkl.core.SecurityManagers +import org.pkl.core.module.ModuleKeys class ImportsAndReadsParserTest { @Test fun parse() { - val moduleText = """ + val moduleText = + """ amends "foo.pkl" import "bar.pkl" @@ -27,18 +43,23 @@ class ImportsAndReadsParserTest { } } } - """.trimIndent() + """ + .trimIndent() val moduleKey = ModuleKeys.synthetic(URI("repl:text"), moduleText) - val imports = ImportsAndReadsParser.parse(moduleKey, moduleKey.resolve(SecurityManagers.defaultManager)) - assertThat(imports?.map { it.first }).hasSameElementsAs(listOf( - "foo.pkl", - "bar.pkl", - "bazzy/buz.pkl", - "qux.pkl", - "qux/*.pkl", - "/some/dir/chown.txt", - "/some/dir/chowner.txt", - "/some/dir/*.txt" - )) + val imports = + ImportsAndReadsParser.parse(moduleKey, moduleKey.resolve(SecurityManagers.defaultManager)) + assertThat(imports?.map { it.first }) + .hasSameElementsAs( + listOf( + "foo.pkl", + "bar.pkl", + "bazzy/buz.pkl", + "qux.pkl", + "qux/*.pkl", + "/some/dir/chown.txt", + "/some/dir/chowner.txt", + "/some/dir/*.txt" + ) + ) } } diff --git a/pkl-core/src/test/kotlin/org/pkl/core/http/DummyHttpClientTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/http/DummyHttpClientTest.kt index c4fc9449..e71ce131 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/http/DummyHttpClientTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/http/DummyHttpClientTest.kt @@ -1,11 +1,26 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.http -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.assertDoesNotThrow -import org.junit.jupiter.api.assertThrows import java.net.URI import java.net.http.HttpRequest import java.net.http.HttpResponse +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertDoesNotThrow +import org.junit.jupiter.api.assertThrows class DummyHttpClientTest { @Test @@ -13,13 +28,9 @@ class DummyHttpClientTest { val client = HttpClient.dummyClient() val request = HttpRequest.newBuilder(URI("https://example.com")).build() - assertThrows { - client.send(request, HttpResponse.BodyHandlers.discarding()) - } + assertThrows { client.send(request, HttpResponse.BodyHandlers.discarding()) } - assertThrows { - client.send(request, HttpResponse.BodyHandlers.discarding()) - } + assertThrows { client.send(request, HttpResponse.BodyHandlers.discarding()) } } @Test diff --git a/pkl-core/src/test/kotlin/org/pkl/core/http/HttpClientTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/http/HttpClientTest.kt index d0399906..13b7ed97 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/http/HttpClientTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/http/HttpClientTest.kt @@ -1,12 +1,20 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.http -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.assertDoesNotThrow -import org.junit.jupiter.api.assertThrows -import org.junit.jupiter.api.io.TempDir -import org.pkl.commons.test.FileTestUtils -import org.pkl.core.Release import java.net.URI import java.net.http.HttpRequest import java.net.http.HttpResponse @@ -14,19 +22,25 @@ import java.nio.file.Path import java.time.Duration import kotlin.io.path.createFile import kotlin.io.path.readBytes +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertDoesNotThrow +import org.junit.jupiter.api.assertThrows +import org.junit.jupiter.api.io.TempDir +import org.pkl.commons.test.FileTestUtils +import org.pkl.core.Release class HttpClientTest { @Test fun `can build default client`() { - val client = assertDoesNotThrow { - HttpClient.builder().build() - } + val client = assertDoesNotThrow { HttpClient.builder().build() } assertThat(client).isInstanceOf(RequestRewritingClient::class.java) client as RequestRewritingClient val release = Release.current() - assertThat(client.userAgent).isEqualTo("Pkl/${release.version()} (${release.os()}; ${release.flavor()})") + assertThat(client.userAgent) + .isEqualTo("Pkl/${release.version()} (${release.os()}; ${release.flavor()})") assertThat(client.requestTimeout).isEqualTo(Duration.ofSeconds(60)) assertThat(client.delegate).isInstanceOf(JdkHttpClient::class.java) @@ -37,11 +51,12 @@ class HttpClientTest { @Test fun `can build custom client`() { - val client = HttpClient.builder() - .setUserAgent("Agent 1") - .setRequestTimeout(Duration.ofHours(86)) - .setConnectTimeout(Duration.ofMinutes(42)) - .build() as RequestRewritingClient + val client = + HttpClient.builder() + .setUserAgent("Agent 1") + .setRequestTimeout(Duration.ofHours(86)) + .setConnectTimeout(Duration.ofMinutes(42)) + .build() as RequestRewritingClient assertThat(client.userAgent).isEqualTo("Agent 1") assertThat(client.requestTimeout).isEqualTo(Duration.ofHours(86)) @@ -68,27 +83,24 @@ class HttpClientTest { fun `certificate file cannot be empty`(@TempDir tempDir: Path) { val file = tempDir.resolve("certs.pem").createFile() - val e = assertThrows { - HttpClient.builder().addCertificates(file).build() - } + val e = + assertThrows { HttpClient.builder().addCertificates(file).build() } assertThat(e).hasMessageContaining("empty") } @Test fun `can load built-in certificates`() { - assertDoesNotThrow { - HttpClient.builder().build() - } + assertDoesNotThrow { HttpClient.builder().build() } } @Test fun `can be closed multiple times`() { val client = HttpClient.builder().build() - assertDoesNotThrow { - client.close() - client.close() + assertDoesNotThrow { + client.close() + client.close() } } diff --git a/pkl-core/src/test/kotlin/org/pkl/core/http/LazyHttpClientTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/http/LazyHttpClientTest.kt index a6204024..2a1f7128 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/http/LazyHttpClientTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/http/LazyHttpClientTest.kt @@ -1,37 +1,46 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.http +import java.net.URI +import java.net.http.HttpRequest +import java.net.http.HttpResponse.BodyHandlers +import java.nio.file.Path import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertDoesNotThrow import org.junit.jupiter.api.assertThrows import org.junit.jupiter.api.io.TempDir import org.pkl.commons.createTempFile import org.pkl.commons.writeString -import java.net.URI -import java.net.http.HttpRequest -import java.net.http.HttpResponse.BodyHandlers -import java.nio.file.Path class LazyHttpClientTest { @Test fun `builds underlying client on first send`(@TempDir tempDir: Path) { val certFile = tempDir.resolve("cert.pem").apply { writeString("broken") } - val client = HttpClient.builder() - .addCertificates(certFile) - .buildLazily() + val client = HttpClient.builder().addCertificates(certFile).buildLazily() val request = HttpRequest.newBuilder(URI("https://example.com")).build() - - assertThrows { - client.send(request, BodyHandlers.discarding()) - } + + assertThrows { client.send(request, BodyHandlers.discarding()) } } - + @Test fun `does not build underlying client unnecessarily`(@TempDir tempDir: Path) { val certFile = tempDir.createTempFile().apply { writeString("broken") } - val client = HttpClient.builder() - .addCertificates(certFile) - .buildLazily() - + val client = HttpClient.builder().addCertificates(certFile).buildLazily() + assertDoesNotThrow { client.close() client.close() diff --git a/pkl-core/src/test/kotlin/org/pkl/core/http/NoProxyRuleTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/http/NoProxyRuleTest.kt index 5c165a26..c372e633 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/http/NoProxyRuleTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/http/NoProxyRuleTest.kt @@ -1,9 +1,24 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.http +import java.net.URI import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test -import java.net.URI @Suppress("HttpUrlsUsage") class NoProxyRuleTest { @@ -44,7 +59,7 @@ class NoProxyRuleTest { assertFalse(noProxyRule.matches(URI("https://ooofoo.com"))) assertFalse(noProxyRule.matches(URI("pkl:foo.com"))) } - + @Test fun `hostname matching, with port`() { val noProxyRule = NoProxyRule("foo.com:5000") @@ -52,7 +67,7 @@ class NoProxyRuleTest { assertFalse(noProxyRule.matches(URI("https://foo.com"))) assertFalse(noProxyRule.matches(URI("https://foo.com:3000"))) } - + @Test fun `ipv4 address literal matching`() { val noProxyRule = NoProxyRule("192.168.1.1") @@ -95,7 +110,7 @@ class NoProxyRuleTest { assertFalse(noProxyRule.matches(URI("https://[::2]"))) assertFalse(noProxyRule.matches(URI("https://[::2]:5000"))) } - + @Test fun `ipv4 port from protocol`() { val noProxyRuleHttp = NoProxyRule("192.168.1.1:80") @@ -104,7 +119,7 @@ class NoProxyRuleTest { assertTrue(noProxyRuleHttp.matches(URI("https://192.168.1.1:80"))) assertFalse(noProxyRuleHttp.matches(URI("https://192.168.1.1"))) assertFalse(noProxyRuleHttp.matches(URI("https://192.168.1.1:5000"))) - + val noProxyRuleHttps = NoProxyRule("192.168.1.1:443") assertTrue(noProxyRuleHttps.matches(URI("https://192.168.1.1"))) assertTrue(noProxyRuleHttps.matches(URI("http://192.168.1.1:443"))) diff --git a/pkl-core/src/test/kotlin/org/pkl/core/http/RequestCapturingClient.kt b/pkl-core/src/test/kotlin/org/pkl/core/http/RequestCapturingClient.kt index a5aee9cb..e9a7778e 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/http/RequestCapturingClient.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/http/RequestCapturingClient.kt @@ -1,12 +1,27 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.http -import org.pkl.commons.test.FakeHttpResponse import java.net.http.HttpRequest import java.net.http.HttpResponse +import org.pkl.commons.test.FakeHttpResponse class RequestCapturingClient : HttpClient { lateinit var request: HttpRequest - + override fun send( request: HttpRequest, responseBodyHandler: HttpResponse.BodyHandler diff --git a/pkl-core/src/test/kotlin/org/pkl/core/http/RequestRewritingClientTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/http/RequestRewritingClientTest.kt index 3f027c83..f5bcd7b8 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/http/RequestRewritingClientTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/http/RequestRewritingClientTest.kt @@ -1,14 +1,29 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.http -import org.assertj.core.api.Assertions.assertThat -import org.assertj.core.api.Assertions.assertThatList -import org.junit.jupiter.api.Test import java.net.URI +import java.net.http.HttpClient as JdkHttpClient import java.net.http.HttpRequest import java.net.http.HttpRequest.BodyPublishers import java.net.http.HttpResponse.BodyHandlers import java.time.Duration -import java.net.http.HttpClient as JdkHttpClient +import org.assertj.core.api.Assertions.assertThat +import org.assertj.core.api.Assertions.assertThatList +import org.junit.jupiter.api.Test class RequestRewritingClientTest { private val captured = RequestCapturingClient() @@ -19,17 +34,18 @@ class RequestRewritingClientTest { @Test fun `fills in missing User-Agent header`() { client.send(exampleRequest, BodyHandlers.discarding()) - + assertThatList(captured.request.headers().allValues("User-Agent")).containsOnly("Pkl") } @Test fun `overrides existing User-Agent headers`() { - val request = HttpRequest.newBuilder(exampleUri) - .header("User-Agent", "Agent 1") - .header("User-Agent", "Agent 2") - .build() - + val request = + HttpRequest.newBuilder(exampleUri) + .header("User-Agent", "Agent 1") + .header("User-Agent", "Agent 2") + .build() + client.send(request, BodyHandlers.discarding()) assertThatList(captured.request.headers().allValues("User-Agent")).containsOnly("Pkl") @@ -38,16 +54,14 @@ class RequestRewritingClientTest { @Test fun `fills in missing request timeout`() { client.send(exampleRequest, BodyHandlers.discarding()) - + assertThat(captured.request.timeout()).hasValue(Duration.ofSeconds(42)) } @Test fun `leaves existing request timeout intact`() { - val request = HttpRequest.newBuilder(exampleUri) - .timeout(Duration.ofMinutes(33)) - .build() - + val request = HttpRequest.newBuilder(exampleUri).timeout(Duration.ofMinutes(33)).build() + client.send(request, BodyHandlers.discarding()) assertThat(captured.request.timeout()).hasValue(Duration.ofMinutes(33)) @@ -62,12 +76,10 @@ class RequestRewritingClientTest { @Test fun `leaves existing HTTP version intact`() { - val request = HttpRequest.newBuilder(exampleUri) - .version(JdkHttpClient.Version.HTTP_1_1) - .build() - + val request = HttpRequest.newBuilder(exampleUri).version(JdkHttpClient.Version.HTTP_1_1).build() + client.send(request, BodyHandlers.discarding()) - + assertThat(captured.request.version()).hasValue(JdkHttpClient.Version.HTTP_1_1) } @@ -79,30 +91,26 @@ class RequestRewritingClientTest { assertThat(captured.request.method()).isEqualTo("GET") } - + @Test fun `leaves explicit method intact`() { - val request = HttpRequest.newBuilder(exampleUri) - .DELETE() - .build() - + val request = HttpRequest.newBuilder(exampleUri).DELETE().build() + client.send(request, BodyHandlers.discarding()) - + assertThat(captured.request.method()).isEqualTo("DELETE") } - + @Test fun `leaves body publisher intact`() { val publisher = BodyPublishers.ofString("body") - val request = HttpRequest.newBuilder(exampleUri) - .PUT(publisher) - .build() - + val request = HttpRequest.newBuilder(exampleUri).PUT(publisher).build() + client.send(request, BodyHandlers.discarding()) - + assertThat(captured.request.bodyPublisher().get()).isSameAs(publisher) } - + @Test fun `rewrites port 0 if test port is set`() { val captured = RequestCapturingClient() @@ -113,15 +121,13 @@ class RequestRewritingClientTest { assertThat(captured.request.uri().port).isEqualTo(5000) } - + @Test fun `leaves port 0 intact if no test port is set`() { val request = HttpRequest.newBuilder(URI("https://example.com:0")).build() client.send(request, BodyHandlers.discarding()) - + assertThat(captured.request.uri().port).isEqualTo(0) } } - - diff --git a/pkl-core/src/test/kotlin/org/pkl/core/module/ModuleKeyFactoriesTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/module/ModuleKeyFactoriesTest.kt index 1bdfa551..169bd691 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/module/ModuleKeyFactoriesTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/module/ModuleKeyFactoriesTest.kt @@ -1,5 +1,24 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.module +import java.net.URI +import java.nio.file.Path +import kotlin.io.path.createDirectories +import kotlin.io.path.outputStream import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir @@ -7,10 +26,6 @@ import org.pkl.commons.createParentDirectories import org.pkl.commons.toPath import org.pkl.commons.writeString import org.pkl.core.SecurityManagers -import java.net.URI -import java.nio.file.Path -import kotlin.io.path.createDirectories -import kotlin.io.path.outputStream class ModuleKeyFactoriesTest { @Test @@ -78,9 +93,7 @@ class ModuleKeyFactoriesTest { fun `module path - jar files`(@TempDir tempDir: Path) { val jarFile = tempDir.resolve("test.jar") jarFile.outputStream().use { outStream -> - javaClass.getResourceAsStream("test.jar")!!.use { inStream -> - inStream.copyTo(outStream) - } + javaClass.getResourceAsStream("test.jar")!!.use { inStream -> inStream.copyTo(outStream) } } val factory = ModuleKeyFactories.modulePath(ModulePathResolver(listOf(jarFile))) diff --git a/pkl-core/src/test/kotlin/org/pkl/core/module/ModuleKeysTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/module/ModuleKeysTest.kt index 1056cd21..3c709973 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/module/ModuleKeysTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/module/ModuleKeysTest.kt @@ -1,19 +1,34 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.module -import org.pkl.commons.createParentDirectories -import org.pkl.commons.toPath -import org.pkl.commons.writeString -import org.pkl.core.SecurityManagers -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.assertThrows -import org.junit.jupiter.api.io.TempDir import java.io.FileNotFoundException import java.net.MalformedURLException import java.net.URI import java.net.URISyntaxException import java.nio.file.Path import kotlin.io.path.createFile +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows +import org.junit.jupiter.api.io.TempDir +import org.pkl.commons.createParentDirectories +import org.pkl.commons.toPath +import org.pkl.commons.writeString +import org.pkl.core.SecurityManagers class ModuleKeysTest { private val securityManager = SecurityManagers.defaultManager @@ -46,9 +61,7 @@ class ModuleKeysTest { @Test fun `standard library - wrong scheme`() { - assertThrows { - ModuleKeys.standardLibrary(URI("other:base")) - } + assertThrows { ModuleKeys.standardLibrary(URI("other:base")) } } @Test @@ -97,18 +110,18 @@ class ModuleKeysTest { @Test fun `class path - module not found`() { - val key = ModuleKeys.classPath(URI("modulepath:/non/existing"), ModuleKeysTest::class.java.classLoader) + val key = + ModuleKeys.classPath(URI("modulepath:/non/existing"), ModuleKeysTest::class.java.classLoader) - assertThrows { - key.resolve(SecurityManagers.defaultManager) - } + assertThrows { key.resolve(SecurityManagers.defaultManager) } } @Test fun `class path - missing leading slash`() { - val e = assertThrows { - ModuleKeys.classPath(URI("modulepath:foo/bar.pkl"), ModuleKeysTest::class.java.classLoader) - } + val e = + assertThrows { + ModuleKeys.classPath(URI("modulepath:foo/bar.pkl"), ModuleKeysTest::class.java.classLoader) + } assertThat(e).hasMessageContaining("`/`") } @@ -127,10 +140,8 @@ class ModuleKeysTest { val resolvedKey = key.resolve(securityManager) - assertThat(resolvedKey.uri.scheme) - .isEqualTo("file") - assertThat(resolvedKey.loadSource()) - .isEqualTo("age = 40") + assertThat(resolvedKey.uri.scheme).isEqualTo("file") + assertThat(resolvedKey.loadSource()).isEqualTo("age = 40") } @Test @@ -144,61 +155,55 @@ class ModuleKeysTest { fun `module path - module not found`() { val key = ModuleKeys.modulePath(URI("modulepath:/non/existing"), ModulePathResolver(listOf())) - assertThrows { - key.resolve(SecurityManagers.defaultManager) - } + assertThrows { key.resolve(SecurityManagers.defaultManager) } } @Test fun `module path - missing leading slash`() { - val e = assertThrows { - ModuleKeys.modulePath(URI("modulepath:foo/bar.pkl"), ModulePathResolver(listOf())) - } + val e = + assertThrows { + ModuleKeys.modulePath(URI("modulepath:foo/bar.pkl"), ModulePathResolver(listOf())) + } assertThat(e).hasMessageContaining("`/`") } @Test fun `package - no version`() { - val e = assertThrows { - ModuleKeys.pkg(URI("package://localhost:0/birds#/Bird.pkl")) - } + val e = + assertThrows { + ModuleKeys.pkg(URI("package://localhost:0/birds#/Bird.pkl")) + } assertThat(e).hasMessageContaining("A package URI must have its path suffixed by its version") } @Test fun `package - invalid semver`() { - val e = assertThrows { - ModuleKeys.pkg(URI("package://localhost:0/birds@notAVersion#/Bird.pkl")) - } + val e = + assertThrows { + ModuleKeys.pkg(URI("package://localhost:0/birds@notAVersion#/Bird.pkl")) + } assertThat(e).hasMessageContaining("`notAVersion` could not be parsed") } @Test fun `package - missing leading slash`() { - val e = assertThrows { - ModuleKeys.pkg(URI("package:invalid")) - } - assertThat(e).hasMessageContaining("Module URI `package:invalid` is missing a `/` after `package:`") + val e = assertThrows { ModuleKeys.pkg(URI("package:invalid")) } + assertThat(e) + .hasMessageContaining("Module URI `package:invalid` is missing a `/` after `package:`") } @Test fun `package - missing authority`() { - val e = assertThrows { - ModuleKeys.pkg(URI("package:/not/a/valid/path")) - } + val e = assertThrows { ModuleKeys.pkg(URI("package:/not/a/valid/path")) } assertThat(e).hasMessageContaining("Package URIs must have an authority component") - val e2 = assertThrows { - ModuleKeys.pkg(URI("package:///not/a/valid/path")) - } + val e2 = assertThrows { ModuleKeys.pkg(URI("package:///not/a/valid/path")) } assertThat(e2).hasMessageContaining("Package URIs must have an authority component") } @Test fun `package - missing path`() { - val e = assertThrows { - ModuleKeys.pkg(URI("package://example.com")) - } + val e = assertThrows { ModuleKeys.pkg(URI("package://example.com")) } assertThat(e).hasMessageContaining("Package URIs must have a path component") } @@ -234,11 +239,8 @@ class ModuleKeysTest { val uri = URI("repl:foo") val key = ModuleKeys.genericUrl(uri) - val e = assertThrows { - key.resolve(securityManager) - } + val e = assertThrows { key.resolve(securityManager) } - assertThat(e) - .hasMessage("unknown protocol: repl") + assertThat(e).hasMessage("unknown protocol: repl") } } diff --git a/pkl-core/src/test/kotlin/org/pkl/core/module/ModulePathResolverTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/module/ModulePathResolverTest.kt index d31d744a..42cf1657 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/module/ModulePathResolverTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/module/ModulePathResolverTest.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.module import org.assertj.core.api.Assertions.assertThatCode diff --git a/pkl-core/src/test/kotlin/org/pkl/core/module/ResolvedModuleKeysTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/module/ResolvedModuleKeysTest.kt index 91a75378..cda166bb 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/module/ResolvedModuleKeysTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/module/ResolvedModuleKeysTest.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.module import java.net.URI @@ -26,9 +41,7 @@ class ResolvedModuleKeysTest { fun `url()`(@TempDir tempDir: Path) { val path = tempDir.createTempFile().writeString("x = 1") val resolvedUri = URI("test:resolved.uri") - val resolved = ResolvedModuleKeys.url( - module, resolvedUri, path.toUri().toURL() - ) + val resolved = ResolvedModuleKeys.url(module, resolvedUri, path.toUri().toURL()) assertThat(resolved.original).isSameAs(module) assertThat(resolved.uri).isEqualTo(resolvedUri) diff --git a/pkl-core/src/test/kotlin/org/pkl/core/module/ServiceProviderTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/module/ServiceProviderTest.kt index fbc0598d..45e59754 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/module/ServiceProviderTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/module/ServiceProviderTest.kt @@ -1,28 +1,42 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.module +import java.net.URI +import org.assertj.core.api.Assertions +import org.junit.jupiter.api.Test import org.pkl.core.Evaluator import org.pkl.core.ModuleSource import org.pkl.core.PClassInfo import org.pkl.core.PModule -import org.assertj.core.api.Assertions -import org.junit.jupiter.api.Test -import java.net.URI class ServiceProviderTest { @Test fun `load module through service provider`() { - val module = Evaluator - .preconfigured() - .evaluate(ModuleSource.uri(URI("test:foo"))) + val module = Evaluator.preconfigured().evaluate(ModuleSource.uri(URI("test:foo"))) val uri = URI("modulepath:/org/pkl/core/module/testFactoryTest.pkl") - Assertions.assertThat(module).isEqualTo( - PModule( - uri, - "testFactoryTest", - PClassInfo.forModuleClass("testFactoryTest", uri), - mapOf("name" to "Pigeon", "age" to 40L) + Assertions.assertThat(module) + .isEqualTo( + PModule( + uri, + "testFactoryTest", + PClassInfo.forModuleClass("testFactoryTest", uri), + mapOf("name" to "Pigeon", "age" to 40L) + ) ) - ) } } diff --git a/pkl-core/src/test/kotlin/org/pkl/core/module/TestModuleKeyFactory.kt b/pkl-core/src/test/kotlin/org/pkl/core/module/TestModuleKeyFactory.kt index 038a3080..97ea67f1 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/module/TestModuleKeyFactory.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/module/TestModuleKeyFactory.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.module import java.net.URI diff --git a/pkl-core/src/test/kotlin/org/pkl/core/packages/DependencyMetadataTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/packages/DependencyMetadataTest.kt index 4cab438b..a63ad24d 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/packages/DependencyMetadataTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/packages/DependencyMetadataTest.kt @@ -1,33 +1,54 @@ -package org.pkl.core.packages; +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.pkl.core.packages -import org.pkl.core.Version -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test import java.io.ByteArrayOutputStream import java.net.URI import java.nio.charset.StandardCharsets +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test +import org.pkl.core.Version class DependencyMetadataTest { - private val dependencyMetadata = DependencyMetadata( - "my-proj-name", - PackageUri("package://example.com/my-proj-name@0.10.0"), - Version.parse("0.10.0"), - URI("https://example.com/foo/bar@0.5.3.zip"), - Checksums("abc123"), - mapOf( - "foo" to Dependency.RemoteDependency(PackageUri("package://example.com/foo@0.5.3"), Checksums("abc123")), - ), - "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/docs"), - "MIT", - "The MIT License, you know it", - listOf("birdy@bird.com"), - URI("https://example.com/issues"), - "Some package description" - ) + private val dependencyMetadata = + DependencyMetadata( + "my-proj-name", + PackageUri("package://example.com/my-proj-name@0.10.0"), + Version.parse("0.10.0"), + URI("https://example.com/foo/bar@0.5.3.zip"), + Checksums("abc123"), + mapOf( + "foo" to + Dependency.RemoteDependency( + PackageUri("package://example.com/foo@0.5.3"), + Checksums("abc123") + ), + ), + "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/docs"), + "MIT", + "The MIT License, you know it", + listOf("birdy@bird.com"), + URI("https://example.com/issues"), + "Some package description" + ) - private val dependencyMetadataStr = """ + private val dependencyMetadataStr = + """ { "name": "my-proj-name", "packageUri": "package://example.com/my-proj-name@0.10.0", @@ -55,7 +76,8 @@ class DependencyMetadataTest { "issueTracker": "https://example.com/issues", "description": "Some package description" } - """.trimIndent() + """ + .trimIndent() @Test fun parse() { @@ -64,10 +86,11 @@ class DependencyMetadataTest { } @Test - fun writeTo(){ - val str = ByteArrayOutputStream() - .apply { dependencyMetadata.writeTo(this) } - .toString(StandardCharsets.UTF_8) + fun writeTo() { + val str = + ByteArrayOutputStream() + .apply { dependencyMetadata.writeTo(this) } + .toString(StandardCharsets.UTF_8) assertThat(str).isEqualTo(dependencyMetadataStr) } } diff --git a/pkl-core/src/test/kotlin/org/pkl/core/packages/PackageResolversTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/packages/PackageResolversTest.kt index ee28edd4..f4aaa20c 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/packages/PackageResolversTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/packages/PackageResolversTest.kt @@ -1,5 +1,25 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.packages +import java.io.FileNotFoundException +import java.io.IOException +import java.nio.charset.StandardCharsets +import kotlin.io.path.exists +import kotlin.io.path.readBytes import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatCode import org.junit.jupiter.api.AfterAll @@ -11,31 +31,27 @@ import org.pkl.commons.readString import org.pkl.commons.test.FileTestUtils import org.pkl.commons.test.PackageServer import org.pkl.commons.test.listFilesRecursively -import org.pkl.core.http.HttpClient import org.pkl.core.SecurityManagers +import org.pkl.core.http.HttpClient import org.pkl.core.module.PathElement -import java.io.FileNotFoundException -import java.io.IOException -import java.nio.charset.StandardCharsets -import kotlin.io.path.exists -import kotlin.io.path.readBytes class PackageResolversTest { abstract class AbstractPackageResolverTest { abstract val resolver: PackageResolver - private val packageRoot = FileTestUtils.rootProjectDir.resolve("pkl-commons-test/src/main/files/packages") + private val packageRoot = + FileTestUtils.rootProjectDir.resolve("pkl-commons-test/src/main/files/packages") companion object { private val packageServer = PackageServer() - + @JvmStatic @AfterAll fun afterAll() { packageServer.close() } - + val httpClient: HttpClient by lazy { HttpClient.builder() .addCertificates(FileTestUtils.selfSignedCertificate) @@ -46,105 +62,107 @@ class PackageResolversTest { @Test fun `get module bytes`() { - val expectedBirdModule = packageRoot.resolve("birds@0.5.0/package/Bird.pkl").readString(StandardCharsets.UTF_8) + val expectedBirdModule = + packageRoot.resolve("birds@0.5.0/package/Bird.pkl").readString(StandardCharsets.UTF_8) val assetUri = PackageAssetUri("package://localhost:0/birds@0.5.0#/Bird.pkl") - val birdModule = resolver - .getBytes(assetUri, false, null) - .toString(StandardCharsets.UTF_8) + val birdModule = resolver.getBytes(assetUri, false, null).toString(StandardCharsets.UTF_8) assertThat(birdModule).isEqualTo(expectedBirdModule) } @Test fun `get directory`() { val assetUri = PackageAssetUri("package://localhost:0/birds@0.5.0#/") - val err = assertThrows { - resolver - .getBytes(assetUri, false, null) - .toString(StandardCharsets.UTF_8) - } + val err = + assertThrows { + resolver.getBytes(assetUri, false, null).toString(StandardCharsets.UTF_8) + } assertThat(err).hasMessage("Is a directory") } @Test fun `get directory, allowing directory reads`() { val assetUri = PackageAssetUri("package://localhost:0/birds@0.5.0#/") - val bytes = resolver - .getBytes(assetUri, true, null) - .toString(StandardCharsets.UTF_8) - assertThat(bytes).isEqualTo(""" + val bytes = resolver.getBytes(assetUri, true, null).toString(StandardCharsets.UTF_8) + assertThat(bytes) + .isEqualTo( + """ Bird.pkl allFruit.pkl catalog catalog.pkl some - """.trimIndent()) + """ + .trimIndent() + ) } @Test fun `get module bytes resolving path`() { - val expectedBirdModule = packageRoot.resolve("birds@0.5.0/package/Bird.pkl").readString(StandardCharsets.UTF_8) + val expectedBirdModule = + packageRoot.resolve("birds@0.5.0/package/Bird.pkl").readString(StandardCharsets.UTF_8) val assetUri = PackageAssetUri("package://localhost:0/birds@0.5.0#/foo/../Bird.pkl") - val birdModule = resolver - .getBytes(assetUri, false, null) - .toString(StandardCharsets.UTF_8) + val birdModule = resolver.getBytes(assetUri, false, null).toString(StandardCharsets.UTF_8) assertThat(birdModule).isEqualTo(expectedBirdModule) } @Test fun `list path elements at root`() { // cast to set to avoid sort issues - val elements = resolver - .listElements(PackageAssetUri("package://localhost:0/birds@0.5.0#/"), null) - .toSet() - assertThat(elements).isEqualTo( - setOf( - PathElement("some", true), - PathElement("catalog", true), - PathElement("Bird.pkl", false), - PathElement("allFruit.pkl", false), - PathElement("catalog.pkl", false) + val elements = + resolver.listElements(PackageAssetUri("package://localhost:0/birds@0.5.0#/"), null).toSet() + assertThat(elements) + .isEqualTo( + setOf( + PathElement("some", true), + PathElement("catalog", true), + PathElement("Bird.pkl", false), + PathElement("allFruit.pkl", false), + PathElement("catalog.pkl", false) + ) ) - ) } @Test fun `get multiple assets`() { - val bird = resolver.getBytes( - PackageAssetUri("package://localhost:0/birds@0.5.0#/Bird.pkl"), - false, - null - ) - val swallow = resolver.getBytes( - PackageAssetUri("package://localhost:0/birds@0.5.0#/catalog/Swallow.pkl"), - false, - null - ) + val bird = + resolver.getBytes( + PackageAssetUri("package://localhost:0/birds@0.5.0#/Bird.pkl"), + false, + null + ) + val swallow = + resolver.getBytes( + PackageAssetUri("package://localhost:0/birds@0.5.0#/catalog/Swallow.pkl"), + false, + null + ) assertThat(bird).isEqualTo(packageRoot.resolve("birds@0.5.0/package/Bird.pkl").readBytes()) - assertThat(swallow).isEqualTo(packageRoot.resolve("birds@0.5.0/package/catalog/Swallow.pkl").readBytes()) + assertThat(swallow) + .isEqualTo(packageRoot.resolve("birds@0.5.0/package/catalog/Swallow.pkl").readBytes()) } @Test fun `list path elements in nested directory`() { // cast to set to avoid sort issues - val elements = resolver.listElements(PackageAssetUri("package://localhost:0/birds@0.5.0#/catalog/"), null).toSet() - assertThat(elements).isEqualTo( - setOf( - PathElement("Ostritch.pkl", false), - PathElement("Swallow.pkl", false), + val elements = + resolver + .listElements(PackageAssetUri("package://localhost:0/birds@0.5.0#/catalog/"), null) + .toSet() + assertThat(elements) + .isEqualTo( + setOf( + PathElement("Ostritch.pkl", false), + PathElement("Swallow.pkl", false), + ) ) - ) } @Test fun `getBytes() throws FileNotFound if package exists but path does not`() { assertThrows { resolver - .getBytes( - PackageAssetUri("package://localhost:0/birds@0.5.0#/Horse.pkl"), - false, - null - ) + .getBytes(PackageAssetUri("package://localhost:0/birds@0.5.0#/Horse.pkl"), false, null) .toString(StandardCharsets.UTF_8) } } @@ -156,7 +174,8 @@ class PackageResolversTest { .getBytes( PackageAssetUri("package://localhost:0/not-a-package@0.5.0#/Horse.pkl"), false, - null) + null + ) .toString(StandardCharsets.UTF_8) } } @@ -164,26 +183,35 @@ class PackageResolversTest { @Test fun `requires package zip to be an HTTPS URI`() { assertThatCode { - resolver.getBytes( - PackageAssetUri("package://localhost:0/badPackageZipUrl@1.0.0#/Bug.pkl"), - false, - null) - } - .hasMessage("Expected the zip asset for package `package://localhost:0/badPackageZipUrl@1.0.0` to be an HTTPS URI, but got `ftp://wait/a/minute`.") + resolver.getBytes( + PackageAssetUri("package://localhost:0/badPackageZipUrl@1.0.0#/Bug.pkl"), + false, + null + ) + } + .hasMessage( + "Expected the zip asset for package `package://localhost:0/badPackageZipUrl@1.0.0` to be an HTTPS URI, but got `ftp://wait/a/minute`." + ) } @Test fun `throws if package checksum is invalid`() { - val error = assertThrows { - resolver.getBytes( - PackageAssetUri("package://localhost:0/badChecksum@1.0.0#/Bug.pkl"), - false, - null) - } - assertThat(error).hasMessageContaining(""" + val error = + assertThrows { + resolver.getBytes( + PackageAssetUri("package://localhost:0/badChecksum@1.0.0#/Bug.pkl"), + false, + null + ) + } + assertThat(error) + .hasMessageContaining( + """ Computed checksum: "a6bf858cdd1c09da475c2abe50525902580910ee5cc1ff624999170591bf8f69" Expected checksum: "intentionally bogus checksum" - """.trimIndent()) + """ + .trimIndent() + ) } } @@ -205,12 +233,16 @@ class PackageResolversTest { } } - override val resolver: PackageResolver = PackageResolvers.DiskCachedPackageResolver( - SecurityManagers.defaultManager, httpClient, cacheDir) + override val resolver: PackageResolver = + PackageResolvers.DiskCachedPackageResolver( + SecurityManagers.defaultManager, + httpClient, + cacheDir + ) } class InMemoryPackageResolverTest : AbstractPackageResolverTest() { - override val resolver: PackageResolver = PackageResolvers.InMemoryPackageResolver( - SecurityManagers.defaultManager, httpClient) + override val resolver: PackageResolver = + PackageResolvers.InMemoryPackageResolver(SecurityManagers.defaultManager, httpClient) } } diff --git a/pkl-core/src/test/kotlin/org/pkl/core/parser/LexerTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/parser/LexerTest.kt index ab465a21..c8f0807c 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/parser/LexerTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/parser/LexerTest.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.parser import org.antlr.v4.runtime.CommonToken diff --git a/pkl-core/src/test/kotlin/org/pkl/core/parser/MultiLineStringLiteralTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/parser/MultiLineStringLiteralTest.kt index 785902e8..796651e4 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/parser/MultiLineStringLiteralTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/parser/MultiLineStringLiteralTest.kt @@ -1,30 +1,42 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.parser -import org.pkl.core.Evaluator import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test +import org.pkl.core.Evaluator import org.pkl.core.ModuleSource -// tests whitespace handling in multi-line string literals that cannot be reliably tested via snippets +// tests whitespace handling in multi-line string literals that cannot be reliably tested via +// snippets // (e.g. due to editors not displaying and/or automatically removing whitespace) class MultiLineStringLiteralTest { private val evaluator = Evaluator.preconfigured() @Test fun `multi-line strings have unix newlines`() { - val module = evaluator.evaluate( - ModuleSource.text( - "x = \"\"\"\none\rtwo\nthree\r\nfour\n\"\"\"" - ) - ) + val module = + evaluator.evaluate(ModuleSource.text("x = \"\"\"\none\rtwo\nthree\r\nfour\n\"\"\"")) assertThat(module.properties["x"]).isEqualTo("one\ntwo\nthree\nfour") } @Test fun `raw multi-line strings have unix newlines`() { - val module = evaluator.evaluate( - ModuleSource.text("x = #\"\"\"\none\rtwo\nthree\r\nfour\n\"\"\"#") - ) + val module = + evaluator.evaluate(ModuleSource.text("x = #\"\"\"\none\rtwo\nthree\r\nfour\n\"\"\"#")) assertThat(module.properties["x"]).isEqualTo("one\ntwo\nthree\nfour") } } diff --git a/pkl-core/src/test/kotlin/org/pkl/core/parser/ShebangTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/parser/ShebangTest.kt index 8dadb629..64b1a024 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/parser/ShebangTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/parser/ShebangTest.kt @@ -1,8 +1,23 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.parser -import org.pkl.core.Evaluator import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test +import org.pkl.core.Evaluator import org.pkl.core.ModuleSource class ShebangTest { @@ -10,15 +25,17 @@ class ShebangTest { @Test fun `shebang is ignored`() { - val module = evaluator.evaluate( - ModuleSource.text( - """ + val module = + evaluator.evaluate( + ModuleSource.text( + """ #!/usr/local/bin/pkl x = 1 - """.trimIndent() + """ + .trimIndent() + ) ) - ) - assertThat (module.properties["x"]).isEqualTo(1L) + assertThat(module.properties["x"]).isEqualTo(1L) } } diff --git a/pkl-core/src/test/kotlin/org/pkl/core/project/ProjectDependenciesResolverTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/project/ProjectDependenciesResolverTest.kt index db1b682e..fdc0c4ab 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/project/ProjectDependenciesResolverTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/project/ProjectDependenciesResolverTest.kt @@ -1,5 +1,22 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.project +import java.io.ByteArrayOutputStream +import java.nio.charset.StandardCharsets import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.AfterAll import org.junit.jupiter.api.Test @@ -7,23 +24,21 @@ import org.junit.jupiter.api.assertThrows import org.pkl.commons.test.FileTestUtils import org.pkl.commons.test.PackageServer import org.pkl.commons.toPath -import org.pkl.core.http.HttpClient import org.pkl.core.PklException import org.pkl.core.SecurityManagers +import org.pkl.core.http.HttpClient import org.pkl.core.packages.PackageResolver -import java.io.ByteArrayOutputStream -import java.nio.charset.StandardCharsets class ProjectDependenciesResolverTest { companion object { private val packageServer = PackageServer() - + @JvmStatic @AfterAll fun afterAll() { packageServer.close() } - + val httpClient: HttpClient by lazy { HttpClient.builder() .addCertificates(FileTestUtils.selfSignedCertificate) @@ -36,13 +51,17 @@ class ProjectDependenciesResolverTest { fun resolveDependencies() { val project2Path = javaClass.getResource("project2/PklProject")!!.toURI().toPath() val project = Project.loadFromPath(project2Path) - val packageResolver = PackageResolver.getInstance(SecurityManagers.defaultManager, httpClient, null) + val packageResolver = + PackageResolver.getInstance(SecurityManagers.defaultManager, httpClient, null) val deps = ProjectDependenciesResolver(project, packageResolver, System.out.writer()).resolve() - val strDeps = ByteArrayOutputStream() - .apply { deps.writeTo(this) } - .toByteArray() - .toString(StandardCharsets.UTF_8) - assertThat(strDeps).isEqualTo(""" + val strDeps = + ByteArrayOutputStream() + .apply { deps.writeTo(this) } + .toByteArray() + .toString(StandardCharsets.UTF_8) + assertThat(strDeps) + .isEqualTo( + """ { "schemaVersion": 1, "resolvedDependencies": { @@ -67,22 +86,30 @@ class ProjectDependenciesResolverTest { } } } - """.trimIndent()) + """ + .trimIndent() + ) } @Test fun `fails if project declares a package with an incorrect checksum`() { val projectPath = javaClass.getResource("badProjectChecksum/PklProject")!!.toURI().toPath() val project = Project.loadFromPath(projectPath) - val packageResolver = PackageResolver.getInstance(SecurityManagers.defaultManager, httpClient, null) - val e = assertThrows { - ProjectDependenciesResolver(project, packageResolver, System.err.writer()).resolve() - } - assertThat(e).hasMessage(""" + val packageResolver = + PackageResolver.getInstance(SecurityManagers.defaultManager, httpClient, null) + val e = + assertThrows { + ProjectDependenciesResolver(project, packageResolver, System.err.writer()).resolve() + } + assertThat(e) + .hasMessage( + """ Computed checksum did not match declared checksum for dependency `package://localhost:0/birds@0.5.0`. Computed: "${PackageServer.BIRDS_SHA}" Declared: "intentionally bogus value" - """.trimIndent()) + """ + .trimIndent() + ) } } diff --git a/pkl-core/src/test/kotlin/org/pkl/core/project/ProjectDepsTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/project/ProjectDepsTest.kt index 3d44dc50..3a9e4d5a 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/project/ProjectDepsTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/project/ProjectDepsTest.kt @@ -1,16 +1,32 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.project +import java.io.ByteArrayOutputStream +import java.nio.file.Path +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test import org.pkl.core.packages.Checksums import org.pkl.core.packages.Dependency import org.pkl.core.packages.PackageUri import org.pkl.core.util.EconomicMaps -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test -import java.io.ByteArrayOutputStream -import java.nio.file.Path class ProjectDepsTest { - private val projectDepsStr = """ + private val projectDepsStr = + """ { "schemaVersion": 1, "resolvedDependencies": { @@ -28,27 +44,29 @@ class ProjectDepsTest { } } } - """.trimIndent() + """ + .trimIndent() private val projectDeps = let { - val projectDepsMap = EconomicMaps.of( - CanonicalPackageUri.of("package://localhost:0/birds@0"), Dependency.RemoteDependency( - PackageUri.create("package://localhost:0/birds@0.5.0"), - Checksums("abc123") - ), - CanonicalPackageUri.of("package://localhost:0/fruit@1"), Dependency.LocalDependency( - PackageUri.create("package://localhost:0/fruit@1.1.0"), - Path.of("../fruit") + val projectDepsMap = + EconomicMaps.of( + CanonicalPackageUri.of("package://localhost:0/birds@0"), + Dependency.RemoteDependency( + PackageUri.create("package://localhost:0/birds@0.5.0"), + Checksums("abc123") + ), + CanonicalPackageUri.of("package://localhost:0/fruit@1"), + Dependency.LocalDependency( + PackageUri.create("package://localhost:0/fruit@1.1.0"), + Path.of("../fruit") + ) ) - ) ProjectDeps(projectDepsMap) } @Test fun writeTo() { - val str = ByteArrayOutputStream() - .apply { projectDeps.writeTo(this) } - .toString(Charsets.UTF_8) + val str = ByteArrayOutputStream().apply { projectDeps.writeTo(this) }.toString(Charsets.UTF_8) assertThat(str).isEqualTo(projectDepsStr) } diff --git a/pkl-core/src/test/kotlin/org/pkl/core/project/ProjectTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/project/ProjectTest.kt index 8835225d..c24419c2 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/project/ProjectTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/project/ProjectTest.kt @@ -1,5 +1,23 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.project +import java.net.URI +import java.nio.file.Path +import java.util.regex.Pattern import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatCode import org.junit.jupiter.api.Test @@ -8,54 +26,52 @@ import org.pkl.commons.test.FileTestUtils import org.pkl.commons.test.PackageServer import org.pkl.commons.writeString import org.pkl.core.* +import org.pkl.core.evaluatorSettings.PklEvaluatorSettings import org.pkl.core.http.HttpClient import org.pkl.core.packages.PackageUri -import org.pkl.core.evaluatorSettings.PklEvaluatorSettings -import java.net.URI -import java.nio.file.Path -import java.util.regex.Pattern class ProjectTest { @Test fun loadFromPath(@TempDir path: Path) { val projectPath = path.resolve("PklProject") - val expectedPackage = Package( - "hawk", - PackageUri("package://example.com/hawk@0.5.0"), - Version.parse("0.5.0"), - URI("https://example.com/hawk/0.5.0/hawk-0.5.0.zip"), - "Some project about hawks", - listOf("Birdy Bird "), - URI("https://example.com/my/website"), - URI("https://example.com/my/docs"), - URI("https://example.com/my/repo"), - "https://example.com/my/repo/0.5.0%{path}", - "MIT", - """ + val expectedPackage = + Package( + "hawk", + PackageUri("package://example.com/hawk@0.5.0"), + Version.parse("0.5.0"), + URI("https://example.com/hawk/0.5.0/hawk-0.5.0.zip"), + "Some project about hawks", + listOf("Birdy Bird "), + URI("https://example.com/my/website"), + URI("https://example.com/my/docs"), + URI("https://example.com/my/repo"), + "https://example.com/my/repo/0.5.0%{path}", + "MIT", + """ # Some License text This is my license text - """.trimIndent(), - URI("https://example.com/my/issues"), - listOf(Path.of("apiTest1.pkl"), Path.of("apiTest2.pkl")), - listOf("PklProject", "PklProject.deps.json", ".**", "*.exe") - ) - val expectedSettings = PklEvaluatorSettings( - mapOf("two" to "2"), - mapOf("one" to "1"), - listOf("foo:", "bar:").map(Pattern::compile), - listOf("baz:", "biz:").map(Pattern::compile), - false, - path.resolve("cache/"), - listOf( - path.resolve("modulepath1/"), - path.resolve("modulepath2/") - ), - Duration.ofMinutes(5.0), - path, - null - ) - projectPath.writeString(""" + """ + .trimIndent(), + URI("https://example.com/my/issues"), + listOf(Path.of("apiTest1.pkl"), Path.of("apiTest2.pkl")), + listOf("PklProject", "PklProject.deps.json", ".**", "*.exe") + ) + val expectedSettings = + PklEvaluatorSettings( + mapOf("two" to "2"), + mapOf("one" to "1"), + listOf("foo:", "bar:").map(Pattern::compile), + listOf("baz:", "biz:").map(Pattern::compile), + false, + path.resolve("cache/"), + listOf(path.resolve("modulepath1/"), path.resolve("modulepath2/")), + Duration.ofMinutes(5.0), + path, + null + ) + projectPath.writeString( + """ amends "pkl:Project" evaluatorSettings { @@ -114,24 +130,28 @@ class ProjectTest { "test1.pkl" "test2.pkl" } - """.trimIndent()) + """ + .trimIndent() + ) val project = Project.loadFromPath(projectPath) assertThat(project.`package`).isEqualTo(expectedPackage) assertThat(project.evaluatorSettings).isEqualTo(expectedSettings) - assertThat(project.tests).isEqualTo(listOf(path.resolve("test1.pkl"), path.resolve("test2.pkl"))) + assertThat(project.tests) + .isEqualTo(listOf(path.resolve("test1.pkl"), path.resolve("test2.pkl"))) } @Test fun `load wrong type`(@TempDir path: Path) { val projectPath = path.resolve("PklProject") - projectPath.writeString(""" + projectPath.writeString( + """ module com.apple.Foo foo = 1 - """.trimIndent()) - assertThatCode { - Project.loadFromPath(projectPath, SecurityManagers.defaultManager, null) - } + """ + .trimIndent() + ) + assertThatCode { Project.loadFromPath(projectPath, SecurityManagers.defaultManager, null) } .hasMessageContaining("be of type `pkl.Project`, but got type `com.apple.Foo`") } @@ -140,18 +160,20 @@ class ProjectTest { PackageServer().use { server -> val projectDir = Path.of(javaClass.getResource("badProjectChecksum2/")!!.toURI()) val project = Project.loadFromPath(projectDir.resolve("PklProject")) - val httpClient = HttpClient.builder() - .addCertificates(FileTestUtils.selfSignedCertificate) - .setTestPort(server.port) - .build() - val evaluator = EvaluatorBuilder.preconfigured() - .applyFromProject(project) - .setModuleCacheDir(null) - .setHttpClient(httpClient) - .build() - assertThatCode { - evaluator.evaluate(ModuleSource.path(projectDir.resolve("bug.pkl"))) - }.hasMessageStartingWith(""" + val httpClient = + HttpClient.builder() + .addCertificates(FileTestUtils.selfSignedCertificate) + .setTestPort(server.port) + .build() + val evaluator = + EvaluatorBuilder.preconfigured() + .applyFromProject(project) + .setModuleCacheDir(null) + .setHttpClient(httpClient) + .build() + assertThatCode { evaluator.evaluate(ModuleSource.path(projectDir.resolve("bug.pkl"))) } + .hasMessageStartingWith( + """ –– Pkl Error –– Cannot download package `package://localhost:0/fruit@1.0.5` because the computed checksum for package metadata does not match the expected checksum. @@ -161,7 +183,9 @@ class ProjectTest { 1 | import "@fruit/Fruit.pkl" ^^^^^^^^^^^^^^^^^^^^^^^^^ - """.trimIndent()) + """ + .trimIndent() + ) } } } diff --git a/pkl-core/src/test/kotlin/org/pkl/core/resource/ResourceReadersEvaluatorTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/resource/ResourceReadersEvaluatorTest.kt index 83304cc0..469998bc 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/resource/ResourceReadersEvaluatorTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/resource/ResourceReadersEvaluatorTest.kt @@ -1,27 +1,43 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.resource -import org.pkl.core.Evaluator import java.nio.file.Path +import kotlin.io.path.outputStream import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir +import org.pkl.core.Evaluator import org.pkl.core.EvaluatorBuilder import org.pkl.core.ModuleSource import org.pkl.core.module.ModulePathResolver -import kotlin.io.path.outputStream class ResourceReadersEvaluatorTest { @Test fun `class path`() { val evaluator = Evaluator.preconfigured() - val module = evaluator.evaluate( - ModuleSource.text( - """ + val module = + evaluator.evaluate( + ModuleSource.text( + """ res1 = read("modulepath:/org/pkl/core/resource/resource.txt").text """ + ) ) - ) assertThat(module.getProperty("res1")).isEqualTo("content") } @@ -38,18 +54,16 @@ class ResourceReadersEvaluatorTest { ModulePathResolver(listOf(jarFile)).use { resolver -> val reader = ResourceReaders.modulePath(resolver) - val evaluator = EvaluatorBuilder - .preconfigured() - .addResourceReader(reader) - .build() + val evaluator = EvaluatorBuilder.preconfigured().addResourceReader(reader).build() - val module = evaluator.evaluate( - ModuleSource.text( - """ + val module = + evaluator.evaluate( + ModuleSource.text( + """ res1 = read("modulepath:/dir1/resource1.txt").text """ + ) ) - ) assertThat(module.getProperty("res1")).isEqualTo("content\n") } diff --git a/pkl-core/src/test/kotlin/org/pkl/core/resource/ResourceReadersTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/resource/ResourceReadersTest.kt index 04e7902f..34586429 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/resource/ResourceReadersTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/resource/ResourceReadersTest.kt @@ -1,14 +1,29 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.resource +import java.net.URI +import java.net.URISyntaxException +import java.nio.file.Path +import kotlin.io.path.outputStream import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import org.junit.jupiter.api.io.TempDir import org.pkl.core.module.ModulePathResolver -import java.net.URI -import java.net.URISyntaxException -import java.nio.file.Path -import kotlin.io.path.outputStream class ResourceReadersTest { @Test @@ -82,9 +97,7 @@ class ResourceReadersTest { fun `module path - missing leading slash`() { val reader = ResourceReaders.modulePath(ModulePathResolver(listOf())) - assertThrows { - reader.read(URI("modulepath:non/existing")) - } + assertThrows { reader.read(URI("modulepath:non/existing")) } } @Test diff --git a/pkl-core/src/test/kotlin/org/pkl/core/resource/TestResourceReader.kt b/pkl-core/src/test/kotlin/org/pkl/core/resource/TestResourceReader.kt index 90c9adfe..adbd4568 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/resource/TestResourceReader.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/resource/TestResourceReader.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.resource import java.net.URI diff --git a/pkl-core/src/test/kotlin/org/pkl/core/runtime/DefaultModuleResolverTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/runtime/DefaultModuleResolverTest.kt index 184e875d..776a2276 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/runtime/DefaultModuleResolverTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/runtime/DefaultModuleResolverTest.kt @@ -1,38 +1,58 @@ -package org.pkl.core.runtime; +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.pkl.core.runtime + // -//import java.io.IOException; -//import java.net.URI; -//import java.net.URISyntaxException; -//import java.nio.file.Files; -//import java.nio.file.Path; -//import java.util.Arrays; -//import java.util.Collections; +// import java.io.IOException; +// import java.net.URI; +// import java.net.URISyntaxException; +// import java.nio.file.Files; +// import java.nio.file.Path; +// import java.util.Arrays; +// import java.util.Collections; // -//import org.pkl.core.EvalOptions; -//import org.pkl.core.EvalException; -//import org.pkl.core.resolve.ModuleKey; -//import org.pkl.core.resolve.ModuleKeyFactories; -//import org.pkl.core.resolve.ModuleKeys; -//import com.oracle.truffle.api.source.SourceSection; -//import org.junit.Ignore; -//import org.junit.Test; +// import org.pkl.core.EvalOptions; +// import org.pkl.core.EvalException; +// import org.pkl.core.resolve.ModuleKey; +// import org.pkl.core.resolve.ModuleKeyFactories; +// import org.pkl.core.resolve.ModuleKeys; +// import com.oracle.truffle.api.source.SourceSection; +// import org.junit.Ignore; +// import org.junit.Test; // -//import static org.junit.Assert.assertEquals; -//import static org.junit.Assert.assertTrue; +// import static org.junit.Assert.assertEquals; +// import static org.junit.Assert.assertTrue; // -//public class DefaultModuleResolverTest { +// public class DefaultModuleResolverTest { // private final SourceSection sourceSection = VmUtils.unavailableSourceSection(); // private final ModuleResolver resolver = -// new ModuleResolver(ModuleKeyFactories.namedModuleOnClassPath, EvalOptions.namedModuleOnClassPath.getAllowedModules()); +// new ModuleResolver(ModuleKeyFactories.namedModuleOnClassPath, +// EvalOptions.namedModuleOnClassPath.getAllowedModules()); // private final ModuleKey fileUrlModule; // private final ModuleKey httpsUrlModule; // private final ModuleKey literalUrlModule; // // { // try { -// fileUrlModule = ModuleKeys.genericUrl(new URI("file:///path/script.pkl"), ModuleKeys.FULL_TRUST); -// httpsUrlModule = ModuleKeys.genericUrl(new URI("https://some.domain.com/path/script.pkl"), ModuleKeys.FULL_TRUST); -// literalUrlModule = ModuleKeys.synthetic("myLiteralModule", "my literal source code", ModuleKeys.FULL_TRUST); +// fileUrlModule = ModuleKeys.genericUrl(new URI("file:///path/script.pkl"), +// ModuleKeys.FULL_TRUST); +// httpsUrlModule = ModuleKeys.genericUrl(new URI("https://some.domain.com/path/script.pkl"), +// ModuleKeys.FULL_TRUST); +// literalUrlModule = ModuleKeys.synthetic("myLiteralModule", "my literal source code", +// ModuleKeys.FULL_TRUST); // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } @@ -61,7 +81,8 @@ package org.pkl.core.runtime; // // @Test // public void importHttpsUrlFromFileUrl() throws IOException { -// ModuleKey result = resolver.resolve("https://other.domain.com/path2/script2.pkl", fileUrlModule, sourceSection); +// ModuleKey result = resolver.resolve("https://other.domain.com/path2/script2.pkl", +// fileUrlModule, sourceSection); // assertTrue(result instanceof ModuleKey.Url); // assertEquals("https://other.domain.com/path2/script2.pkl", result.toString()); // } @@ -94,7 +115,8 @@ package org.pkl.core.runtime; // // @Test // public void importHttpsUrlFromHttpsUrl() throws IOException { -// ModuleKey result = resolver.resolve("https://other.domain.com/path2/script2.pkl", httpsUrlModule, sourceSection); +// ModuleKey result = resolver.resolve("https://other.domain.com/path2/script2.pkl", +// httpsUrlModule, sourceSection); // assertTrue(result instanceof ModuleKey.Url); // assertEquals("https://other.domain.com/path2/script2.pkl", result.toString()); // } @@ -127,14 +149,16 @@ package org.pkl.core.runtime; // // @Test // public void importFileUrlFromLiteral() throws IOException { -// ModuleKey result = resolver.resolve("file:///import/file.pkl", literalUrlModule, sourceSection); +// ModuleKey result = resolver.resolve("file:///import/file.pkl", literalUrlModule, +// sourceSection); // assertTrue(result instanceof ModuleKey.Url); // assertEquals("file:///import/file.pkl", result.toString()); // } // // @Test // public void importHttpsUrlFromLiteral() throws IOException { -// ModuleKey result = resolver.resolve("https://other.domain.com/path2/script2.pkl", literalUrlModule, sourceSection); +// ModuleKey result = resolver.resolve("https://other.domain.com/path2/script2.pkl", +// literalUrlModule, sourceSection); // assertTrue(result instanceof ModuleKey.Url); // assertEquals("https://other.domain.com/path2/script2.pkl", result.toString()); // } @@ -183,4 +207,4 @@ package org.pkl.core.runtime; // // resolver.resolve("pkl:base", fileUrlModule, sourceSection); // } -//} +// } diff --git a/pkl-core/src/test/kotlin/org/pkl/core/runtime/FileSystemManagerTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/runtime/FileSystemManagerTest.kt index dfeafb4e..3e0c860f 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/runtime/FileSystemManagerTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/runtime/FileSystemManagerTest.kt @@ -1,14 +1,28 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.runtime +import java.net.URI +import java.nio.file.FileSystems import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test -import java.net.URI -import java.nio.file.FileSystems class FileSystemManagerTest { - private val resource = - javaClass.getResource("/org/pkl/core/resource/resource1.jar")!!.toURI() + private val resource = javaClass.getResource("/org/pkl/core/resource/resource1.jar")!!.toURI() private val resourceUri = URI("jar:$resource") @Test diff --git a/pkl-core/src/test/kotlin/org/pkl/core/runtime/IteratorsTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/runtime/IteratorsTest.kt index 998063d0..c46eb013 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/runtime/IteratorsTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/runtime/IteratorsTest.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.runtime import org.assertj.core.api.Assertions.assertThat diff --git a/pkl-core/src/test/kotlin/org/pkl/core/runtime/ModuleKeyTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/runtime/ModuleKeyTest.kt index 77773e82..20db83fd 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/runtime/ModuleKeyTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/runtime/ModuleKeyTest.kt @@ -1,22 +1,38 @@ -package org.pkl.core.runtime; +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.pkl.core.runtime + // -//import java.io.File; -//import java.io.IOException; -//import java.net.URI; -//import java.net.URISyntaxException; +// import java.io.File; +// import java.io.IOException; +// import java.net.URI; +// import java.net.URISyntaxException; // -//import org.pkl.core.resolve.ModuleKey; -//import org.pkl.core.resolve.ModuleKeys; -//import org.junit.Rule; -//import org.junit.Test; -//import org.junit.rules.TemporaryFolder; +// import org.pkl.core.resolve.ModuleKey; +// import org.pkl.core.resolve.ModuleKeys; +// import org.junit.Rule; +// import org.junit.Test; +// import org.junit.rules.TemporaryFolder; // -//import static org.junit.Assert.assertEquals; -//import static org.junit.Assert.assertFalse; -//import static org.junit.Assert.assertTrue; +// import static org.junit.Assert.assertEquals; +// import static org.junit.Assert.assertFalse; +// import static org.junit.Assert.assertTrue; // //// some parts of ModuleKey are tested as part of DefaultModuleResolverTest -//public class ModuleKeyTest { +// public class ModuleKeyTest { // @Rule // public TemporaryFolder folder = new TemporaryFolder(); // @@ -73,4 +89,4 @@ package org.pkl.core.runtime; // assertEquals("literal:name", module.getUri()); // assertFalse(module.isBaseModule()); // } -//} +// } diff --git a/pkl-core/src/test/kotlin/org/pkl/core/runtime/StackTraceRendererTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/runtime/StackTraceRendererTest.kt index 6b4fe99c..a6c140e1 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/runtime/StackTraceRendererTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/runtime/StackTraceRendererTest.kt @@ -1,10 +1,25 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.runtime -import org.pkl.core.* -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.assertThrows import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.AfterAll +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows +import org.pkl.core.* class StackTraceRendererTest { companion object { @@ -20,39 +35,51 @@ class StackTraceRendererTest { @Test fun `stringy self-reference`() { - val message = assertThrows { - evaluator.evaluate( - ModuleSource.text( - """ + val message = + assertThrows { + evaluator.evaluate( + ModuleSource.text( + """ self: String = "Strings; if they were lazy, you could tie the knot on \(self.take(7))" - """.trimIndent()) - ) - }.message!! + """ + .trimIndent() + ) + ) + } + .message!! assertThat(message) .contains("A stack overflow occurred.") - .containsPattern(""" + .containsPattern( + """ ┌─ \d* repetitions of: │ 1 | self: String = "Strings; if they were lazy, you could tie the knot on \\\(self.take\(7\)\)" │ ^^^^ - """.trim()) + """ + .trim() + ) } @Test fun `cyclic property references`() { - val message = assertThrows { - evaluator.evaluate( - ModuleSource.text( - """ + val message = + assertThrows { + evaluator.evaluate( + ModuleSource.text( + """ foo: String = "FOO:" + bar bar: String = "BAR:" + baz baz: String = "BAZ:" + qux qux: String = "QUX:" + foo - """.trimIndent()) + """ + .trimIndent() + ) ) - }.message!! + } + .message!! assertThat(message) .contains("A stack overflow occurred.") - .containsPattern(""" + .containsPattern( + """ ┌─ \d+ repetitions of: │ 4 | qux: String = "QUX:" + foo │ ^^^ @@ -70,13 +97,16 @@ class StackTraceRendererTest { │ ^^^ │ at text#foo (repl:text) └─ - """.trim()) + """ + .trim() + ) } - + @Test @Suppress("RegExpRepeatedSpace") fun `reduce stack overflow from actual Pkl code`() { - val pklCode = """ + val pklCode = + """ function suffix(n: UInt): UInt = if (n == 0) 0 @@ -106,15 +136,15 @@ class StackTraceRendererTest { prefix(n - 1) result = prefix(13) - """.trimIndent() - val message = assertThrows { - evaluator.evaluate(ModuleSource.text(pklCode)) - }.message!! - + """ + .trimIndent() + val message = + assertThrows { evaluator.evaluate(ModuleSource.text(pklCode)) }.message!! + if (message.contains("5 | suffix")) { assertThat(message).containsPattern("repetitions of:\n│ 5 | suffix(n - 1)") } - + assertThat(message) .contains("A stack overflow occurred.") .containsPattern("┌─ \\d+ repetitions of:\n│ \n│ 9 | loop\\(\\)") @@ -159,15 +189,11 @@ class StackTraceRendererTest { add(createFrame("foo", 3)) } val loop = StackTraceRenderer.StackFrameLoop(loopFrames, 1) - val frames = listOf( - createFrame("bar", 1), - createFrame("baz", 2), - loop - ) - val renderedFrames = buildString { - renderer.doRender(frames, null, this, "", true) - } - assertThat(renderedFrames).isEqualTo(""" + val frames = listOf(createFrame("bar", 1), createFrame("baz", 2), loop) + val renderedFrames = buildString { renderer.doRender(frames, null, this, "", true) } + assertThat(renderedFrames) + .isEqualTo( + """ 1 | foo ^ at (file:bar) @@ -188,7 +214,9 @@ class StackTraceRendererTest { ^ at (file:foo) - """.trimIndent()) + """ + .trimIndent() + ) } private fun createFrame(name: String, id: Int): StackFrame { diff --git a/pkl-core/src/test/kotlin/org/pkl/core/runtime/VmClassTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/runtime/VmClassTest.kt index 7a7b702f..d66a680b 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/runtime/VmClassTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/runtime/VmClassTest.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.runtime import org.assertj.core.api.Assertions.assertThat diff --git a/pkl-core/src/test/kotlin/org/pkl/core/runtime/VmDataSizeTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/runtime/VmDataSizeTest.kt index a00d1949..4ce943e2 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/runtime/VmDataSizeTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/runtime/VmDataSizeTest.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.runtime import org.assertj.core.api.Assertions.assertThat diff --git a/pkl-core/src/test/kotlin/org/pkl/core/runtime/VmDurationTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/runtime/VmDurationTest.kt index d5f6fbf5..834e6a17 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/runtime/VmDurationTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/runtime/VmDurationTest.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.runtime import org.assertj.core.api.Assertions.assertThat diff --git a/pkl-core/src/test/kotlin/org/pkl/core/runtime/VmSafeMathTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/runtime/VmSafeMathTest.kt index af5bb41d..3bf95279 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/runtime/VmSafeMathTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/runtime/VmSafeMathTest.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.runtime import org.assertj.core.api.Assertions.assertThat @@ -10,15 +25,12 @@ class VmSafeMathTest { assertThat(VmSafeMath.negate(0)).isEqualTo(0) assertThat(VmSafeMath.negate(1)).isEqualTo(-1) assertThat(VmSafeMath.negate(-1)).isEqualTo(1) - assertThat(VmSafeMath.negate(java.lang.Long.MAX_VALUE)) - .isEqualTo(-java.lang.Long.MAX_VALUE) + assertThat(VmSafeMath.negate(java.lang.Long.MAX_VALUE)).isEqualTo(-java.lang.Long.MAX_VALUE) } @Test fun `negate long - overflow`() { - assertThrows { - VmSafeMath.negate(java.lang.Long.MIN_VALUE) - } + assertThrows { VmSafeMath.negate(java.lang.Long.MIN_VALUE) } } @Test @@ -27,10 +39,8 @@ class VmSafeMathTest { assertThat(VmSafeMath.negate(-1.0)).isEqualTo(1.0) assertThat(VmSafeMath.negate(1.0)).isEqualTo(-1.0) assertThat(VmSafeMath.negate(123.456)).isEqualTo(-123.456) - assertThat(VmSafeMath.negate(-java.lang.Double.MAX_VALUE)) - .isEqualTo(java.lang.Double.MAX_VALUE) - assertThat(VmSafeMath.negate(-java.lang.Double.MIN_VALUE)) - .isEqualTo(java.lang.Double.MIN_VALUE) + assertThat(VmSafeMath.negate(-java.lang.Double.MAX_VALUE)).isEqualTo(java.lang.Double.MAX_VALUE) + assertThat(VmSafeMath.negate(-java.lang.Double.MIN_VALUE)).isEqualTo(java.lang.Double.MIN_VALUE) } @Test @@ -38,31 +48,23 @@ class VmSafeMathTest { assertThat(VmSafeMath.add(0, 0)).isEqualTo(0) assertThat(VmSafeMath.add(1, 2)).isEqualTo(3) assertThat(VmSafeMath.add(1, -2)).isEqualTo(-1) - assertThat(VmSafeMath.add(java.lang.Long.MAX_VALUE - 1, 1)) - .isEqualTo(java.lang.Long.MAX_VALUE) + assertThat(VmSafeMath.add(java.lang.Long.MAX_VALUE - 1, 1)).isEqualTo(java.lang.Long.MAX_VALUE) } @Test fun `add long - overflow #1`() { - assertThrows { - VmSafeMath.add(java.lang.Long.MAX_VALUE, 1) - } + assertThrows { VmSafeMath.add(java.lang.Long.MAX_VALUE, 1) } } @Test fun `add long - overflow #2`() { - assertThrows { - VmSafeMath.add(java.lang.Long.MIN_VALUE, -1) - } + assertThrows { VmSafeMath.add(java.lang.Long.MIN_VALUE, -1) } } @Test fun `add long - overflow #3`() { assertThrows { - VmSafeMath.add( - java.lang.Long.MAX_VALUE / 2, - java.lang.Long.MAX_VALUE / 3 * 2 - ) + VmSafeMath.add(java.lang.Long.MAX_VALUE / 2, java.lang.Long.MAX_VALUE / 3 * 2) } } } diff --git a/pkl-core/src/test/kotlin/org/pkl/core/runtime/VmUtilsTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/runtime/VmUtilsTest.kt index fd30ada6..eabd3378 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/runtime/VmUtilsTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/runtime/VmUtilsTest.kt @@ -1,10 +1,22 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.runtime -import org.pkl.core.SecurityManagers -import org.pkl.core.module.ModuleKeys import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -import java.net.URI class VmUtilsTest { @Test diff --git a/pkl-core/src/test/kotlin/org/pkl/core/runtime/VmValueRendererTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/runtime/VmValueRendererTest.kt index e3b9035e..29be4d79 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/runtime/VmValueRendererTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/runtime/VmValueRendererTest.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.runtime import org.assertj.core.api.Assertions.assertThat diff --git a/pkl-core/src/test/kotlin/org/pkl/core/settings/PklSettingsTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/settings/PklSettingsTest.kt index fc6e9f31..21b5cfa5 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/settings/PklSettingsTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/settings/PklSettingsTest.kt @@ -1,21 +1,33 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.settings +import java.net.URI import java.nio.file.Path import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatCode import org.junit.jupiter.api.Test -import org.junit.jupiter.api.assertThrows import org.junit.jupiter.api.io.TempDir import org.pkl.commons.createParentDirectories import org.pkl.commons.writeString import org.pkl.core.Evaluator import org.pkl.core.ModuleSource import org.pkl.core.PObject -import org.pkl.core.StackFrameTransformers import org.pkl.core.evaluatorSettings.PklEvaluatorSettings -import org.pkl.core.runtime.VmException import org.pkl.core.settings.PklSettings.Editor -import java.net.URI class PklSettingsTest { @Test @@ -26,13 +38,14 @@ class PklSettingsTest { """ amends "pkl:settings" editor = Sublime - """.trimIndent() + """ + .trimIndent() ) val settings = PklSettings.loadFromPklHomeDir(tempDir) assertThat(settings).isEqualTo(PklSettings(Editor.SUBLIME, null)) } - + @Test fun `load user settings with http`(@TempDir tempDir: Path) { val settingsPath = tempDir.resolve("settings.pkl") @@ -49,16 +62,18 @@ class PklSettingsTest { } } } - """.trimIndent() + """ + .trimIndent() ) val settings = PklSettings.loadFromPklHomeDir(tempDir) - val expectedHttp = PklEvaluatorSettings.Http( - PklEvaluatorSettings.Proxy( - URI("http://localhost:8080"), - listOf("example.com", "pkg.pkl-lang.org") + val expectedHttp = + PklEvaluatorSettings.Http( + PklEvaluatorSettings.Proxy( + URI("http://localhost:8080"), + listOf("example.com", "pkg.pkl-lang.org") + ) ) - ) assertThat(settings).isEqualTo(PklSettings(Editor.SYSTEM, expectedHttp)) } @@ -74,16 +89,18 @@ class PklSettingsTest { address = "http://localhost:8080" } } - """.trimIndent() + """ + .trimIndent() ) val settings = PklSettings.loadFromPklHomeDir(tempDir) - val expectedHttp = PklEvaluatorSettings.Http( - PklEvaluatorSettings.Proxy( - URI("http://localhost:8080"), - listOf(), + val expectedHttp = + PklEvaluatorSettings.Http( + PklEvaluatorSettings.Proxy( + URI("http://localhost:8080"), + listOf(), + ) ) - ) assertThat(settings).isEqualTo(PklSettings(Editor.SYSTEM, expectedHttp)) } @@ -94,7 +111,8 @@ class PklSettingsTest { """ amends "pkl:settings" editor = Idea - """.trimIndent() + """ + .trimIndent() ) val settings = PklSettings.load(ModuleSource.path(settingsPath)) @@ -104,9 +122,10 @@ class PklSettingsTest { @Test fun `predefined editors`() { val evaluator = Evaluator.preconfigured() - val module = evaluator.evaluate( - ModuleSource.text( - """ + val module = + evaluator.evaluate( + ModuleSource.text( + """ import "pkl:settings" system = settings.System @@ -115,9 +134,10 @@ class PklSettingsTest { sublime = settings.Sublime atom = settings.Atom vsCode = settings.VsCode - """.trimIndent() + """ + .trimIndent() + ) ) - ) checkEquals(Editor.SYSTEM, module.getProperty("system") as PObject) checkEquals(Editor.IDEA, module.getProperty("idea") as PObject) @@ -131,7 +151,9 @@ class PklSettingsTest { fun `invalid settings file`(@TempDir tempDir: Path) { val settingsFile = tempDir.resolve("settings.pkl").apply { writeString("foo = 1") } assertThatCode { PklSettings.loadFromPklHomeDir(tempDir) } - .hasMessageContaining("Expected `output.value` of module `${settingsFile.toUri()}` to be of type `pkl.settings`, but got type `settings`.") + .hasMessageContaining( + "Expected `output.value` of module `${settingsFile.toUri()}` to be of type `pkl.settings`, but got type `settings`." + ) } private fun checkEquals(expected: Editor, actual: PObject) { diff --git a/pkl-core/src/test/kotlin/org/pkl/core/stdlib/PathConverterSupportTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/stdlib/PathConverterSupportTest.kt index b715cd05..4919ddfd 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/stdlib/PathConverterSupportTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/stdlib/PathConverterSupportTest.kt @@ -1,9 +1,23 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.stdlib -import org.pkl.core.runtime.Identifier import org.junit.jupiter.api.Assertions.assertTrue - import org.junit.jupiter.api.Test +import org.pkl.core.runtime.Identifier class PathConverterSupportTest { @Test @@ -15,14 +29,16 @@ class PathConverterSupportTest { @Test fun `wildcard properties`() { - val pathSpec = listOf(Identifier.get("foo"), PklConverter.WILDCARD_PROPERTY, Identifier.get("baz")) + val pathSpec = + listOf(Identifier.get("foo"), PklConverter.WILDCARD_PROPERTY, Identifier.get("baz")) val pathPartSpec = listOf(Identifier.get("foo"), Identifier.get("bar"), Identifier.get("baz")) assertTrue(PathConverterSupport.pathMatches(pathSpec, pathPartSpec)) } @Test fun `wildcard elements`() { - val pathSpec = listOf(Identifier.get("foo"), PklConverter.WILDCARD_ELEMENT, Identifier.get("baz")) + val pathSpec = + listOf(Identifier.get("foo"), PklConverter.WILDCARD_ELEMENT, Identifier.get("baz")) val pathPartSpec = listOf(Identifier.get("foo"), 0, Identifier.get("baz")) assertTrue(PathConverterSupport.pathMatches(pathSpec, pathPartSpec)) } diff --git a/pkl-core/src/test/kotlin/org/pkl/core/stdlib/PathSpecParserTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/stdlib/PathSpecParserTest.kt index 8a71ed81..5b0b0f83 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/stdlib/PathSpecParserTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/stdlib/PathSpecParserTest.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.stdlib import org.assertj.core.api.Assertions.assertThat @@ -12,14 +27,11 @@ class PathSpecParserTest { @Test fun `parse valid path specs`() { - assertThat(parser.parse("")) - .isEqualTo(arrayOf(TOP_LEVEL_VALUE)) + assertThat(parser.parse("")).isEqualTo(arrayOf(TOP_LEVEL_VALUE)) - assertThat(parser.parse("^")) - .isEqualTo(arrayOf(TOP_LEVEL_VALUE)) + assertThat(parser.parse("^")).isEqualTo(arrayOf(TOP_LEVEL_VALUE)) - assertThat(parser.parse("property")) - .isEqualTo(arrayOf(Identifier.get("property"))) + assertThat(parser.parse("property")).isEqualTo(arrayOf(Identifier.get("property"))) assertThat(parser.parse("^property")) .isEqualTo(arrayOf(Identifier.get("property"), TOP_LEVEL_VALUE)) @@ -28,107 +40,55 @@ class PathSpecParserTest { .isEqualTo(arrayOf(Identifier.get("prop3"), Identifier.get("prop2"), Identifier.get("prop1"))) assertThat(parser.parse("^prop1.prop2.prop3")) - .isEqualTo(arrayOf(Identifier.get("prop3"), Identifier.get("prop2"), Identifier.get("prop1"), TOP_LEVEL_VALUE)) + .isEqualTo( + arrayOf( + Identifier.get("prop3"), + Identifier.get("prop2"), + Identifier.get("prop1"), + TOP_LEVEL_VALUE + ) + ) - assertThat(parser.parse("[key]")) - .isEqualTo(arrayOf("key")) + assertThat(parser.parse("[key]")).isEqualTo(arrayOf("key")) - assertThat(parser.parse("^[key]")) - .isEqualTo(arrayOf("key", TOP_LEVEL_VALUE)) + assertThat(parser.parse("^[key]")).isEqualTo(arrayOf("key", TOP_LEVEL_VALUE)) - assertThat(parser.parse("[key1][key2][key3]")) - .isEqualTo(arrayOf("key3", "key2", "key1")) + assertThat(parser.parse("[key1][key2][key3]")).isEqualTo(arrayOf("key3", "key2", "key1")) assertThat(parser.parse("^[key1][key2][key3]")) .isEqualTo(arrayOf("key3", "key2", "key1", TOP_LEVEL_VALUE)) - assertThat(parser.parse("*")) - .isEqualTo(arrayOf(WILDCARD_PROPERTY)) + assertThat(parser.parse("*")).isEqualTo(arrayOf(WILDCARD_PROPERTY)) - assertThat(parser.parse("^*")) - .isEqualTo(arrayOf(WILDCARD_PROPERTY, TOP_LEVEL_VALUE)) + assertThat(parser.parse("^*")).isEqualTo(arrayOf(WILDCARD_PROPERTY, TOP_LEVEL_VALUE)) - assertThat(parser.parse("[*]")) - .isEqualTo(arrayOf(WILDCARD_ELEMENT)) + assertThat(parser.parse("[*]")).isEqualTo(arrayOf(WILDCARD_ELEMENT)) - assertThat(parser.parse("^[*]")) - .isEqualTo(arrayOf(WILDCARD_ELEMENT, TOP_LEVEL_VALUE)) + assertThat(parser.parse("^[*]")).isEqualTo(arrayOf(WILDCARD_ELEMENT, TOP_LEVEL_VALUE)) assertThat(parser.parse("*.*.*")) - .isEqualTo( - arrayOf( - WILDCARD_PROPERTY, - WILDCARD_PROPERTY, - WILDCARD_PROPERTY - ) - ) + .isEqualTo(arrayOf(WILDCARD_PROPERTY, WILDCARD_PROPERTY, WILDCARD_PROPERTY)) assertThat(parser.parse("^*.*.*")) - .isEqualTo( - arrayOf( - WILDCARD_PROPERTY, - WILDCARD_PROPERTY, - WILDCARD_PROPERTY, - TOP_LEVEL_VALUE - ) - ) + .isEqualTo(arrayOf(WILDCARD_PROPERTY, WILDCARD_PROPERTY, WILDCARD_PROPERTY, TOP_LEVEL_VALUE)) assertThat(parser.parse("[*][*][*]")) - .isEqualTo( - arrayOf( - WILDCARD_ELEMENT, - WILDCARD_ELEMENT, - WILDCARD_ELEMENT - ) - ) + .isEqualTo(arrayOf(WILDCARD_ELEMENT, WILDCARD_ELEMENT, WILDCARD_ELEMENT)) assertThat(parser.parse("^[*][*][*]")) - .isEqualTo( - arrayOf( - WILDCARD_ELEMENT, - WILDCARD_ELEMENT, - WILDCARD_ELEMENT, - TOP_LEVEL_VALUE - ) - ) + .isEqualTo(arrayOf(WILDCARD_ELEMENT, WILDCARD_ELEMENT, WILDCARD_ELEMENT, TOP_LEVEL_VALUE)) assertThat(parser.parse("[*].*[*]")) - .isEqualTo( - arrayOf( - WILDCARD_ELEMENT, - WILDCARD_PROPERTY, - WILDCARD_ELEMENT - ) - ) + .isEqualTo(arrayOf(WILDCARD_ELEMENT, WILDCARD_PROPERTY, WILDCARD_ELEMENT)) assertThat(parser.parse("^[*].*[*]")) - .isEqualTo( - arrayOf( - WILDCARD_ELEMENT, - WILDCARD_PROPERTY, - WILDCARD_ELEMENT, - TOP_LEVEL_VALUE - ) - ) + .isEqualTo(arrayOf(WILDCARD_ELEMENT, WILDCARD_PROPERTY, WILDCARD_ELEMENT, TOP_LEVEL_VALUE)) assertThat(parser.parse("*[*].*")) - .isEqualTo( - arrayOf( - WILDCARD_PROPERTY, - WILDCARD_ELEMENT, - WILDCARD_PROPERTY - ) - ) + .isEqualTo(arrayOf(WILDCARD_PROPERTY, WILDCARD_ELEMENT, WILDCARD_PROPERTY)) assertThat(parser.parse("^*[*].*")) - .isEqualTo( - arrayOf( - WILDCARD_PROPERTY, - WILDCARD_ELEMENT, - WILDCARD_PROPERTY, - TOP_LEVEL_VALUE - ) - ) + .isEqualTo(arrayOf(WILDCARD_PROPERTY, WILDCARD_ELEMENT, WILDCARD_PROPERTY, TOP_LEVEL_VALUE)) assertThat(parser.parse("prop1[key1].*[key2].prop2[*]")) .isEqualTo( @@ -160,60 +120,32 @@ class PathSpecParserTest { // TODO: support quoted identifiers? @Test fun `parse invalid path specs`() { - assertThrows { - parser.parse("^^") - } + assertThrows { parser.parse("^^") } - assertThrows { - parser.parse("property.") - } + assertThrows { parser.parse("property.") } - assertThrows { - parser.parse("property^") - } + assertThrows { parser.parse("property^") } - assertThrows { - parser.parse(".property") - } + assertThrows { parser.parse(".property") } - assertThrows { - parser.parse("prop1..prop2") - } + assertThrows { parser.parse("prop1..prop2") } - assertThrows { - parser.parse("[key") - } + assertThrows { parser.parse("[key") } - assertThrows { - parser.parse("key]") - } + assertThrows { parser.parse("key]") } - assertThrows { - parser.parse("[[key]]") - } + assertThrows { parser.parse("[[key]]") } - assertThrows { - parser.parse("property.[key]") - } + assertThrows { parser.parse("property.[key]") } - assertThrows { - parser.parse("[key1].[key2]") - } + assertThrows { parser.parse("[key1].[key2]") } - assertThrows { - parser.parse("[key1] [key2]") - } + assertThrows { parser.parse("[key1] [key2]") } - assertThrows { - parser.parse("**") - } + assertThrows { parser.parse("**") } - assertThrows { - parser.parse("[**]") - } + assertThrows { parser.parse("[**]") } - assertThrows { - parser.parse("[*") - } + assertThrows { parser.parse("[*") } } } diff --git a/pkl-core/src/test/kotlin/org/pkl/core/stdlib/ReflectModuleTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/stdlib/ReflectModuleTest.kt index 6e76a779..9e0eeeb4 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/stdlib/ReflectModuleTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/stdlib/ReflectModuleTest.kt @@ -1,22 +1,47 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.stdlib -import org.pkl.core.Evaluator import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.ValueSource +import org.pkl.core.Evaluator import org.pkl.core.ModuleSource class ReflectModuleTest { private val evaluator = Evaluator.preconfigured() @ValueSource( - strings = [ - "pkl:base", "pkl:json", "pkl:jsonnet", "pkl:math", "pkl:protobuf", "pkl:reflect", - "pkl:settings", "pkl:shell", "pkl:test", "pkl:xml", "pkl:yaml" - ] + strings = + [ + "pkl:base", + "pkl:json", + "pkl:jsonnet", + "pkl:math", + "pkl:protobuf", + "pkl:reflect", + "pkl:settings", + "pkl:shell", + "pkl:test", + "pkl:xml", + "pkl:yaml" + ] ) @ParameterizedTest(name = "can reflect on {0} module") fun `can reflect on stdlib module`(moduleName: String) { - //language=Pkl + // language=Pkl evaluator.evaluate( ModuleSource.text( """ @@ -26,7 +51,8 @@ class ReflectModuleTest { output { text = reflect.Module(import("$moduleName")).toString() } - """.trimIndent() + """ + .trimIndent() ) ) } diff --git a/pkl-core/src/test/kotlin/org/pkl/core/truffle/LongVsDoubleSpecializationTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/truffle/LongVsDoubleSpecializationTest.kt index 49c82a4c..df506b09 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/truffle/LongVsDoubleSpecializationTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/truffle/LongVsDoubleSpecializationTest.kt @@ -1,8 +1,23 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.truffle -import org.pkl.core.Evaluator import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test +import org.pkl.core.Evaluator import org.pkl.core.ModuleSource // Verifies that (long, long) specialization is chosen for (long, long) inputs @@ -18,84 +33,84 @@ class LongVsDoubleSpecializationTest { @Test fun addition() { - val result = evaluator.evaluate( - ModuleSource.text( - """ + val result = + evaluator.evaluate( + ModuleSource.text(""" x1 = Pair(1.0 + 2.0, 1 + 2).second - """ + """) ) - ) assertThat(result.properties["x1"]).isEqualTo(3L) } @Test fun subtraction() { - val result = evaluator.evaluate( - ModuleSource.text( - """ + val result = + evaluator.evaluate( + ModuleSource.text(""" x1 = Pair(1.0 - 2.0, 1 - 2).second - """ + """) ) - ) assertThat(result.properties["x1"]).isEqualTo(-1L) } @Test fun multiplication() { - val result = evaluator.evaluate( - ModuleSource.text( - """ + val result = + evaluator.evaluate( + ModuleSource.text(""" x1 = Pair(1.0 * 2.0, 1 * 2).second - """ + """) ) - ) assertThat(result.properties["x1"]).isEqualTo(2L) } @Test fun exponentiation() { - val result = evaluator.evaluate( - ModuleSource.text( - """ + val result = + evaluator.evaluate( + ModuleSource.text( + """ import "pkl:math" x1 = Pair(2.0 ** 2.0, 2 ** 2).second """ + ) ) - ) assertThat(result.properties["x1"]).isEqualTo(4L) } @Test fun math_min() { - val result = evaluator.evaluate( - ModuleSource.text( - """ + val result = + evaluator.evaluate( + ModuleSource.text( + """ import "pkl:math" x1 = Pair(math.min(1.0, 2.0), math.min(1, 2)).second """ + ) ) - ) assertThat(result.properties["x1"]).isEqualTo(1L) } @Test fun math_max() { - val result = evaluator.evaluate( - ModuleSource.text( - """ + val result = + evaluator.evaluate( + ModuleSource.text( + """ import "pkl:math" x1 = Pair(math.max(1.0, 2.0), math.max(1, 2)).second """ + ) ) - ) assertThat(result.properties["x1"]).isEqualTo(2L) } diff --git a/pkl-core/src/test/kotlin/org/pkl/core/util/ArrayCharEscaperTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/util/ArrayCharEscaperTest.kt index 9c4cbab7..48104476 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/util/ArrayCharEscaperTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/util/ArrayCharEscaperTest.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.util import org.assertj.core.api.Assertions.assertThat @@ -7,11 +22,12 @@ import org.junit.jupiter.api.assertThrows class ArrayCharEscaperTest { @Test fun `basic usage`() { - val escaper = ArrayCharEscaper.builder() - .withEscape('ä', "ae") - .withEscape('ö', "oe") - .withEscape('ü', "ue") - .build() + val escaper = + ArrayCharEscaper.builder() + .withEscape('ä', "ae") + .withEscape('ö', "oe") + .withEscape('ü', "ue") + .build() assertThat(escaper.escape("")).isEqualTo("") assertThat(escaper.escape("äää")).isEqualTo("aeaeae") @@ -26,10 +42,7 @@ class ArrayCharEscaperTest { @Test fun `enforces size limit`() { assertThrows { - ArrayCharEscaper.builder() - .withEscape('a', "aa") - .withEscape('Ɇ', "ee") - .build() + ArrayCharEscaper.builder().withEscape('a', "aa").withEscape('Ɇ', "ee").build() } } @@ -44,9 +57,7 @@ class ArrayCharEscaperTest { @Test fun `returns original string if no escaping required`() { - val escaper = ArrayCharEscaper.builder() - .withEscape('ä', "ae") - .build() + val escaper = ArrayCharEscaper.builder().withEscape('ä', "ae").build() val fox = "The quick brown fox jumps over the lazy dog." assertThat(escaper.escape(fox)).isSameAs(fox) diff --git a/pkl-core/src/test/kotlin/org/pkl/core/util/ExceptionsTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/util/ExceptionsTest.kt index d9f37eab..feee9e08 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/util/ExceptionsTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/util/ExceptionsTest.kt @@ -1,9 +1,24 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.util -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test import java.io.IOException import java.lang.Error +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test class ExceptionsTest { @Test diff --git a/pkl-core/src/test/kotlin/org/pkl/core/util/GlobResolverTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/util/GlobResolverTest.kt index c943464e..85da5cde 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/util/GlobResolverTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/util/GlobResolverTest.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.util import org.junit.jupiter.api.Assertions.assertFalse @@ -26,77 +41,74 @@ class GlobResolverTest { } @ParameterizedTest - @ValueSource(strings = [ - "foo.pkl", - "bar.pkl", - "baz.pkl", - "buzzy...baz.pkl", - "ted_lasso.min.pkl", - "ted_lasso.pkl.min.pkl" - ]) + @ValueSource( + strings = + [ + "foo.pkl", + "bar.pkl", + "baz.pkl", + "buzzy...baz.pkl", + "ted_lasso.min.pkl", + "ted_lasso.pkl.min.pkl" + ] + ) fun `glob match`(input: String) { val pattern = GlobResolver.toRegexPattern("*.pkl") assertTrue(pattern.matcher(input).matches()) } @ParameterizedTest - @ValueSource(strings = [ - "bar.pcf", - "bar.yml", - "bar.pkl.bcl", - "bar.pklpkl", - "pkl", - // crosses directory boundaries - "/bar/baz.pkl", - "/baz.pkl" - ]) + @ValueSource( + strings = + [ + "bar.pcf", + "bar.yml", + "bar.pkl.bcl", + "bar.pklpkl", + "pkl", + // crosses directory boundaries + "/bar/baz.pkl", + "/baz.pkl" + ] + ) fun `glob non-match`(input: String) { val pattern = GlobResolver.toRegexPattern("*.pkl") assertFalse(pattern.matcher(input).matches()) } @ParameterizedTest - @ValueSource(strings = [ - "/foo.pkl/bar/baz.pkl", - "//fo///ba.pkl", - ".pkl", - "buz.pkl", - "pkl.pkl.pkl.pkl" - ]) + @ValueSource( + strings = ["/foo.pkl/bar/baz.pkl", "//fo///ba.pkl", ".pkl", "buz.pkl", "pkl.pkl.pkl.pkl"] + ) fun `globstar match`(input: String) { val pattern = GlobResolver.toRegexPattern("**.pkl") assertTrue(pattern.matcher(input).matches()) } @ParameterizedTest - @ValueSource(strings = [ - "/foo.pkl/bar/baz.pkl", - "//fo///ba.pkl", - ".pkl", - "buz.pkl", - "pkl.pkl.pkl.pkl" - ]) + @ValueSource( + strings = ["/foo.pkl/bar/baz.pkl", "//fo///ba.pkl", ".pkl", "buz.pkl", "pkl.pkl.pkl.pkl"] + ) fun `globstar non-match`(input: String) { val pattern = GlobResolver.toRegexPattern("**.pkl") assertTrue(pattern.matcher(input).matches()) } @ParameterizedTest - @ValueSource(strings = [ - "/foo.pkl/bar/baz.pkl", - "//fo///ba.pkl", - ]) + @ValueSource( + strings = + [ + "/foo.pkl/bar/baz.pkl", + "//fo///ba.pkl", + ] + ) fun `globstar match 2`(input: String) { val pattern = GlobResolver.toRegexPattern("/**/*.pkl") assertTrue(pattern.matcher(input).matches()) } @ParameterizedTest - @ValueSource(strings = [ - "bar.pkl", - ".pkl", - "/foo.pkl" - ]) + @ValueSource(strings = ["bar.pkl", ".pkl", "/foo.pkl"]) fun `globstar non-match 2`(input: String) { val pattern = GlobResolver.toRegexPattern("/**/*.pkl") assertFalse(pattern.matcher(input).matches()) @@ -135,7 +147,9 @@ class GlobResolverTest { @Test fun `invalid sub-patterns`() { - assertThrows { GlobResolver.toRegexPattern("{foo{bar}}") } + assertThrows { + GlobResolver.toRegexPattern("{foo{bar}}") + } assertThrows { GlobResolver.toRegexPattern("{foo") } // no leading open curly means closing curly is treated verbatim assertDoesNotThrow { GlobResolver.toRegexPattern("foo}") } @@ -164,21 +178,39 @@ class GlobResolverTest { @Test fun `invalid character classes`() { assertThrows { GlobResolver.toRegexPattern("thing[") } - assertThrows { GlobResolver.toRegexPattern("thing[foo/bar]") } - assertThrows { GlobResolver.toRegexPattern("[[=a=]]") } - assertThrows { GlobResolver.toRegexPattern("[[:alnum:]]") } - assertThrows { GlobResolver.toRegexPattern("[[.a-acute.]]") } + assertThrows { + GlobResolver.toRegexPattern("thing[foo/bar]") + } + assertThrows { + GlobResolver.toRegexPattern("[[=a=]]") + } + assertThrows { + GlobResolver.toRegexPattern("[[:alnum:]]") + } + assertThrows { + GlobResolver.toRegexPattern("[[.a-acute.]]") + } // no leading open square bracket means closing square bracket is verbatim assertDoesNotThrow { GlobResolver.toRegexPattern("]") } } @Test fun `invalid extglob`() { - assertThrows { GlobResolver.toRegexPattern("!(foo|bar)") } - assertThrows { GlobResolver.toRegexPattern("+(foo|bar)") } - assertThrows { GlobResolver.toRegexPattern("?(foo|bar)") } - assertThrows { GlobResolver.toRegexPattern("@(foo|bar)") } - assertThrows { GlobResolver.toRegexPattern("*(foo|bar)") } + assertThrows { + GlobResolver.toRegexPattern("!(foo|bar)") + } + assertThrows { + GlobResolver.toRegexPattern("+(foo|bar)") + } + assertThrows { + GlobResolver.toRegexPattern("?(foo|bar)") + } + assertThrows { + GlobResolver.toRegexPattern("@(foo|bar)") + } + assertThrows { + GlobResolver.toRegexPattern("*(foo|bar)") + } } @Test diff --git a/pkl-core/src/test/kotlin/org/pkl/core/util/HttpUtilsTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/util/HttpUtilsTest.kt index 3b84dc2d..626963d7 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/util/HttpUtilsTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/util/HttpUtilsTest.kt @@ -1,12 +1,27 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.util +import java.io.IOException +import java.net.URI import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertDoesNotThrow import org.junit.jupiter.api.assertThrows import org.pkl.commons.test.FakeHttpResponse -import java.io.IOException -import java.net.URI class HttpUtilsTest { @Test @@ -21,32 +36,20 @@ class HttpUtilsTest { assertThat(HttpUtils.isHttpUrl(URI("HtTpS://example.com").toURL())).isTrue assertThat(HttpUtils.isHttpUrl(URI("file://example.com").toURL())).isFalse } - + @Test fun checkHasStatusCode200() { - val response = FakeHttpResponse.withoutBody { - statusCode = 200 - } - assertDoesNotThrow { - HttpUtils.checkHasStatusCode200(response) - } + val response = FakeHttpResponse.withoutBody { statusCode = 200 } + assertDoesNotThrow { HttpUtils.checkHasStatusCode200(response) } - val response2 = FakeHttpResponse.withoutBody { - statusCode = 404 - } - assertThrows { - HttpUtils.checkHasStatusCode200(response2) - } + val response2 = FakeHttpResponse.withoutBody { statusCode = 404 } + assertThrows { HttpUtils.checkHasStatusCode200(response2) } } - + @Test fun setPort() { - assertThrows { - HttpUtils.setPort(URI("https://example.com"), -1) - } - assertThrows { - HttpUtils.setPort(URI("https://example.com"), 65536) - } + assertThrows { HttpUtils.setPort(URI("https://example.com"), -1) } + assertThrows { HttpUtils.setPort(URI("https://example.com"), 65536) } assertThat(HttpUtils.setPort(URI("http://example.com"), 123)) .isEqualTo(URI("http://example.com:123")) assertThat(HttpUtils.setPort(URI("http://example.com:456"), 123)) diff --git a/pkl-core/src/test/kotlin/org/pkl/core/util/IoUtilsTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/util/IoUtilsTest.kt index 8f7034fb..618afe58 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/util/IoUtilsTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/util/IoUtilsTest.kt @@ -1,5 +1,25 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.core.util +import java.io.FileNotFoundException +import java.net.URI +import java.net.URISyntaxException +import java.nio.file.Path +import kotlin.io.path.createFile import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatExceptionOfType import org.junit.jupiter.api.Test @@ -11,12 +31,6 @@ import org.pkl.core.SecurityManager import org.pkl.core.module.ModuleKeyFactories import org.pkl.core.module.ModuleKeys import org.pkl.core.runtime.ModuleResolver -import java.io.FileNotFoundException -import java.net.URI -import java.net.URISyntaxException -import java.net.URL -import java.nio.file.Path -import kotlin.io.path.createFile class IoUtilsTest { object FakeSecurityManager : SecurityManager { @@ -29,35 +43,32 @@ class IoUtilsTest { override fun checkResolveResource(resource: URI) {} } - private val moduleResolver = ModuleResolver( - listOf( - ModuleKeyFactories.pkg, - ModuleKeyFactories.file, - ModuleKeyFactories.standardLibrary, - ModuleKeyFactories.genericUrl + private val moduleResolver = + ModuleResolver( + listOf( + ModuleKeyFactories.pkg, + ModuleKeyFactories.file, + ModuleKeyFactories.standardLibrary, + ModuleKeyFactories.genericUrl + ) ) - ) @Test fun `ensurePathEndsWithSlash() - relative URI`() { val uri = URI("/some/path") - assertThat(IoUtils.ensurePathEndsWithSlash(uri)) - .isEqualTo(URI("/some/path/")) + assertThat(IoUtils.ensurePathEndsWithSlash(uri)).isEqualTo(URI("/some/path/")) val uri2 = URI("/some/path/") - assertThat(IoUtils.ensurePathEndsWithSlash(uri2)) - .isEqualTo(URI("/some/path/")) + assertThat(IoUtils.ensurePathEndsWithSlash(uri2)).isEqualTo(URI("/some/path/")) } @Test fun `ensurePathEndsWithSlash() - absolute URI`() { val uri = URI("https://apple.com/path") - assertThat(IoUtils.ensurePathEndsWithSlash(uri)) - .isEqualTo(URI("https://apple.com/path/")) + assertThat(IoUtils.ensurePathEndsWithSlash(uri)).isEqualTo(URI("https://apple.com/path/")) val uri2 = URI("https://apple.com/path/") - assertThat(IoUtils.ensurePathEndsWithSlash(uri2)) - .isEqualTo(URI("https://apple.com/path/")) + assertThat(IoUtils.ensurePathEndsWithSlash(uri2)).isEqualTo(URI("https://apple.com/path/")) val uri3 = URI("https://user:pwd@apple.com:8080/path?foo=bar#frag") assertThat(IoUtils.ensurePathEndsWithSlash(uri3)) @@ -71,8 +82,7 @@ class IoUtilsTest { @Test fun `ensurePathEndsWithSlash() - opaque URI`() { val uri = URI("foo:some.thing") - assertThat(IoUtils.ensurePathEndsWithSlash(uri)) - .isEqualTo(URI("foo:some.thing")) + assertThat(IoUtils.ensurePathEndsWithSlash(uri)).isEqualTo(URI("foo:some.thing")) } @Test @@ -86,7 +96,7 @@ class IoUtilsTest { val resolved = IoUtils.resolve(URI("file:/foo/bar"), URI("baz")) assertThat(resolved).isEqualTo(URI("file:/foo/baz")) } - + @Test fun `resolving relative URI against triple-slash jar-file URI results in triple-slash jar-file URI`() { val resolved = IoUtils.resolve(URI("jar:file:///some/archive.zip!/foo/bar"), URI("baz")) @@ -98,12 +108,11 @@ class IoUtilsTest { val resolved = IoUtils.resolve(URI("jar:file:/some/archive.zip!/foo/bar"), URI("baz")) assertThat(resolved).isEqualTo(URI("jar:file:/some/archive.zip!/foo/baz")) } - + @Test fun `resolve absolute URI against jar-file URI`() { val uri = URI("jar:file:///some/archive.zip!/foo/bar.pkl") - assertThat(IoUtils.resolve(uri, URI("https://apple.com"))) - .isEqualTo(URI("https://apple.com")) + assertThat(IoUtils.resolve(uri, URI("https://apple.com"))).isEqualTo(URI("https://apple.com")) } @Test @@ -117,150 +126,106 @@ class IoUtilsTest { @Test fun `relativize file URLs`() { - assertThat( - IoUtils.relativize( - URI("file:///foo/bar/baz.pkl"), - URI("file:///foo/bar/baz.pkl") - ) - ).isEqualTo(URI("baz.pkl")) + assertThat(IoUtils.relativize(URI("file:///foo/bar/baz.pkl"), URI("file:///foo/bar/baz.pkl"))) + .isEqualTo(URI("baz.pkl")) - assertThat( - IoUtils.relativize( - URI("file:///foo/bar/baz.pkl"), - URI("file:///foo/bar/qux.pkl") - ) - ).isEqualTo(URI("baz.pkl")) + assertThat(IoUtils.relativize(URI("file:///foo/bar/baz.pkl"), URI("file:///foo/bar/qux.pkl"))) + .isEqualTo(URI("baz.pkl")) - assertThat( - IoUtils.relativize( - URI("file:///foo/bar/baz.pkl"), - URI("file:///foo/bar/") - ) - ).isEqualTo(URI("baz.pkl")) + assertThat(IoUtils.relativize(URI("file:///foo/bar/baz.pkl"), URI("file:///foo/bar/"))) + .isEqualTo(URI("baz.pkl")) - assertThat( - IoUtils.relativize( - URI("file:///foo/bar/baz.pkl"), - URI("file:///foo/bar") - ) - ).isEqualTo(URI("bar/baz.pkl")) + assertThat(IoUtils.relativize(URI("file:///foo/bar/baz.pkl"), URI("file:///foo/bar"))) + .isEqualTo(URI("bar/baz.pkl")) // URI.relativize() returns an absolute URI here - assertThat( - IoUtils.relativize( - URI("file:///foo/bar/baz.pkl"), - URI("file:///foo/qux/") - ) - ).isEqualTo(URI("../bar/baz.pkl")) + assertThat(IoUtils.relativize(URI("file:///foo/bar/baz.pkl"), URI("file:///foo/qux/"))) + .isEqualTo(URI("../bar/baz.pkl")) - assertThat( - IoUtils.relativize( - URI("file:///foo/bar/baz.pkl"), - URI("file:///foo/qux/qux2/") - ) - ).isEqualTo(URI("../../bar/baz.pkl")) + assertThat(IoUtils.relativize(URI("file:///foo/bar/baz.pkl"), URI("file:///foo/qux/qux2/"))) + .isEqualTo(URI("../../bar/baz.pkl")) - assertThat( - IoUtils.relativize( - URI("file:///foo/bar/baz.pkl"), - URI("file:///foo/qux/qux2") - ) - ).isEqualTo(URI("../bar/baz.pkl")) + assertThat(IoUtils.relativize(URI("file:///foo/bar/baz.pkl"), URI("file:///foo/qux/qux2"))) + .isEqualTo(URI("../bar/baz.pkl")) - assertThat( - IoUtils.relativize( - URI("file:///foo/bar/baz.pkl"), - URI("file:///qux/qux2/") - ) - ).isEqualTo(URI("../../foo/bar/baz.pkl")) + assertThat(IoUtils.relativize(URI("file:///foo/bar/baz.pkl"), URI("file:///qux/qux2/"))) + .isEqualTo(URI("../../foo/bar/baz.pkl")) - assertThat( - IoUtils.relativize( - URI("file:///foo/bar/baz.pkl"), - URI("https:///foo/bar/baz.pkl") - ) - ).isEqualTo(URI("file:///foo/bar/baz.pkl")) + assertThat(IoUtils.relativize(URI("file:///foo/bar/baz.pkl"), URI("https:///foo/bar/baz.pkl"))) + .isEqualTo(URI("file:///foo/bar/baz.pkl")) } @Test fun `relativize HTTP URLs`() { // perhaps URI("") would be a more precise result assertThat( - IoUtils.relativize( - URI("https://foo.com/bar/baz.pkl"), - URI("https://foo.com/bar/baz.pkl") + IoUtils.relativize(URI("https://foo.com/bar/baz.pkl"), URI("https://foo.com/bar/baz.pkl")) ) - ).isEqualTo(URI("baz.pkl")) + .isEqualTo(URI("baz.pkl")) assertThat( - IoUtils.relativize( - URI("https://foo.com/bar/baz.pkl"), - URI("https://foo.com/bar/qux.pkl") + IoUtils.relativize(URI("https://foo.com/bar/baz.pkl"), URI("https://foo.com/bar/qux.pkl")) ) - ).isEqualTo(URI("baz.pkl")) + .isEqualTo(URI("baz.pkl")) + + assertThat(IoUtils.relativize(URI("https://foo.com/bar/baz.pkl"), URI("https://foo.com/qux/"))) + .isEqualTo(URI("../bar/baz.pkl")) assertThat( - IoUtils.relativize( - URI("https://foo.com/bar/baz.pkl"), - URI("https://foo.com/qux/") + IoUtils.relativize( + URI("https://foo.com/bar/baz.pkl?query"), + URI("https://foo.com/bar/qux.pkl") + ) ) - ).isEqualTo(URI("../bar/baz.pkl")) + .isEqualTo(URI("baz.pkl?query")) assertThat( - IoUtils.relativize( - URI("https://foo.com/bar/baz.pkl?query"), - URI("https://foo.com/bar/qux.pkl") + IoUtils.relativize( + URI("https://foo.com/bar/baz.pkl#fragment"), + URI("https://foo.com/bar/qux.pkl") + ) ) - ).isEqualTo(URI("baz.pkl?query")) + .isEqualTo(URI("baz.pkl#fragment")) assertThat( - IoUtils.relativize( - URI("https://foo.com/bar/baz.pkl#fragment"), - URI("https://foo.com/bar/qux.pkl") + IoUtils.relativize( + URI("https://foo.com/bar/baz.pkl?query#fragment"), + URI("https://foo.com/bar/qux.pkl") + ) ) - ).isEqualTo(URI("baz.pkl#fragment")) + .isEqualTo(URI("baz.pkl?query#fragment")) assertThat( - IoUtils.relativize( - URI("https://foo.com/bar/baz.pkl?query#fragment"), - URI("https://foo.com/bar/qux.pkl") + IoUtils.relativize( + URI("https://foo.com/bar/baz.pkl?query#fragment"), + URI("https://foo.com/bar/qux.pkl?query2#fragment2") + ) ) - ).isEqualTo(URI("baz.pkl?query#fragment")) + .isEqualTo(URI("baz.pkl?query#fragment")) assertThat( - IoUtils.relativize( - URI("https://foo.com/bar/baz.pkl?query#fragment"), - URI("https://foo.com/bar/qux.pkl?query2#fragment2") + IoUtils.relativize(URI("https://foo.com:80/bar/baz.pkl"), URI("https://foo.com:443/bar/")) ) - ).isEqualTo(URI("baz.pkl?query#fragment")) + .isEqualTo(URI("https://foo.com:80/bar/baz.pkl")) assertThat( - IoUtils.relativize( - URI("https://foo.com:80/bar/baz.pkl"), - URI("https://foo.com:443/bar/") + IoUtils.relativize( + URI("https://foo.com:80/bar/baz.pkl"), + URI("https://bar.com:80/bar/baz.pkl") + ) ) - ).isEqualTo(URI("https://foo.com:80/bar/baz.pkl")) + .isEqualTo(URI("https://foo.com:80/bar/baz.pkl")) assertThat( - IoUtils.relativize( - URI("https://foo.com:80/bar/baz.pkl"), - URI("https://bar.com:80/bar/baz.pkl") + IoUtils.relativize( + URI("https://foo:bar@foo.com:80/bar/baz.pkl"), + URI("https://foo:baz@bar.com:80/bar/baz.pkl") + ) ) - ).isEqualTo(URI("https://foo.com:80/bar/baz.pkl")) + .isEqualTo(URI("https://foo:bar@foo.com:80/bar/baz.pkl")) - assertThat( - IoUtils.relativize( - URI("https://foo:bar@foo.com:80/bar/baz.pkl"), - URI("https://foo:baz@bar.com:80/bar/baz.pkl") - ) - ).isEqualTo(URI("https://foo:bar@foo.com:80/bar/baz.pkl")) - - assertThat( - IoUtils.relativize( - URI("https://foo/bar/baz.pkl"), - URI("file://foo/bar/baz.pkl") - ) - ).isEqualTo(URI("https://foo/bar/baz.pkl")) + assertThat(IoUtils.relativize(URI("https://foo/bar/baz.pkl"), URI("file://foo/bar/baz.pkl"))) + .isEqualTo(URI("https://foo/bar/baz.pkl")) } @Test @@ -304,20 +269,21 @@ class IoUtilsTest { @Test fun inferModuleName() { - val assertions = mapOf( - "file:///foo.pkl" to "foo", - "file:///foo/bar/baz.pkl" to "baz", - "jar:file:///some/archive.zip!/foo.pkl" to "foo", - "jar:file:///some/archive.zip!/foo/bar/baz.pkl" to "baz", - "https://apple.com/foo.pkl" to "foo", - "https://apple.com/foo/bar/baz.pkl" to "baz", - "pkl:foo" to "foo", - "pkl:foo.bar.baz" to "baz", - "modulepath:/foo.pkl" to "foo", - "modulepath:/foo/bar/baz.pkl" to "baz", - "package://example.com/foo/bar@1.0.0#/baz.pkl" to "baz", - "package://example.com/foo/bar@1.0.0#/baz/biz/qux.pkl" to "qux" - ) + val assertions = + mapOf( + "file:///foo.pkl" to "foo", + "file:///foo/bar/baz.pkl" to "baz", + "jar:file:///some/archive.zip!/foo.pkl" to "foo", + "jar:file:///some/archive.zip!/foo/bar/baz.pkl" to "baz", + "https://apple.com/foo.pkl" to "foo", + "https://apple.com/foo/bar/baz.pkl" to "baz", + "pkl:foo" to "foo", + "pkl:foo.bar.baz" to "baz", + "modulepath:/foo.pkl" to "foo", + "modulepath:/foo/bar/baz.pkl" to "baz", + "package://example.com/foo/bar@1.0.0#/baz.pkl" to "baz", + "package://example.com/foo/bar@1.0.0#/baz/biz/qux.pkl" to "qux" + ) for ((uriStr, name) in assertions) { val uri = URI(uriStr) val moduleKey = moduleResolver.resolve(uri) @@ -330,33 +296,32 @@ class IoUtilsTest { assertThat(IoUtils.toUri("file://foo.pkl")).isEqualTo(URI("file://foo.pkl")) assertThat(IoUtils.toUri("foo.pkl")).isEqualTo(URI("foo.pkl")) assertThat(IoUtils.toUri("foo bar.pkl").rawPath).isEqualTo("foo%20bar.pkl") - assertThrows { - IoUtils.toUri("file:foo bar.pkl") - } + assertThrows { IoUtils.toUri("file:foo bar.pkl") } } @Test fun `resolveUri - file hierarchy`(@TempDir tempDir: Path) { val file1 = tempDir.resolve("base1/base2/foo.pkl").createParentDirectories().createFile() - val file2 = tempDir.resolve("base1/base2/dir1/dir2/foo.pkl").createParentDirectories().createFile() + val file2 = + tempDir.resolve("base1/base2/dir1/dir2/foo.pkl").createParentDirectories().createFile() val file3 = tempDir.resolve("base1/dir2/foo.pkl").createParentDirectories().createFile() val uri = file2.toUri() val key = ModuleKeys.file(uri) assertThat(IoUtils.resolve(FakeSecurityManager, key, URI("..."))).isEqualTo(file1.toUri()) - assertThat(IoUtils.resolve(FakeSecurityManager, key, URI(".../foo.pkl"))).isEqualTo(file1.toUri()) - assertThat(IoUtils.resolve(FakeSecurityManager, key, URI(".../base2/foo.pkl"))).isEqualTo(file1.toUri()) - assertThat(IoUtils.resolve(FakeSecurityManager, key, URI(".../base1/base2/foo.pkl"))).isEqualTo(file1.toUri()) - assertThat(IoUtils.resolve(FakeSecurityManager, key, URI(".../dir2/foo.pkl"))).isEqualTo(file3.toUri()) + assertThat(IoUtils.resolve(FakeSecurityManager, key, URI(".../foo.pkl"))) + .isEqualTo(file1.toUri()) + assertThat(IoUtils.resolve(FakeSecurityManager, key, URI(".../base2/foo.pkl"))) + .isEqualTo(file1.toUri()) + assertThat(IoUtils.resolve(FakeSecurityManager, key, URI(".../base1/base2/foo.pkl"))) + .isEqualTo(file1.toUri()) + assertThat(IoUtils.resolve(FakeSecurityManager, key, URI(".../dir2/foo.pkl"))) + .isEqualTo(file3.toUri()) - assertThrows { - IoUtils.resolve(FakeSecurityManager, key, URI(".../")) - } + assertThrows { IoUtils.resolve(FakeSecurityManager, key, URI(".../")) } - assertThrows { - IoUtils.resolve(FakeSecurityManager, key, URI("...abc")) - } + assertThrows { IoUtils.resolve(FakeSecurityManager, key, URI("...abc")) } assertThrows { IoUtils.resolve(FakeSecurityManager, key, URI(".../bar.pkl")) @@ -382,20 +347,32 @@ class IoUtilsTest { assertThat(IoUtils.resolve(FakeSecurityManager, key, URI(".../NamedModuleResolversTest.pkl"))) .isEqualTo(URI("modulepath:/org/pkl/core/module/NamedModuleResolversTest.pkl")) - assertThat(IoUtils.resolve(FakeSecurityManager, key, URI(".../module/NamedModuleResolversTest.pkl"))) + assertThat( + IoUtils.resolve(FakeSecurityManager, key, URI(".../module/NamedModuleResolversTest.pkl")) + ) .isEqualTo(URI("modulepath:/org/pkl/core/module/NamedModuleResolversTest.pkl")) - assertThat(IoUtils.resolve(FakeSecurityManager, key, URI(".../core/module/NamedModuleResolversTest.pkl"))) + assertThat( + IoUtils.resolve( + FakeSecurityManager, + key, + URI(".../core/module/NamedModuleResolversTest.pkl") + ) + ) .isEqualTo(URI("modulepath:/org/pkl/core/module/NamedModuleResolversTest.pkl")) - assertThat(IoUtils.resolve(FakeSecurityManager, key, URI(".../org/pkl/core/module/NamedModuleResolversTest.pkl"))) + assertThat( + IoUtils.resolve( + FakeSecurityManager, + key, + URI(".../org/pkl/core/module/NamedModuleResolversTest.pkl") + ) + ) .isEqualTo(URI("modulepath:/org/pkl/core/module/NamedModuleResolversTest.pkl")) val uri2 = URI("modulepath:/foo/bar/baz.pkl") val key2 = ModuleKeys.classPath(uri2, classLoader) - assertThrows { - IoUtils.resolve(FakeSecurityManager, key2, URI("...")) - } + assertThrows { IoUtils.resolve(FakeSecurityManager, key2, URI("...")) } assertThrows { IoUtils.resolve(FakeSecurityManager, key2, URI(".../other.pkl")) } @@ -403,22 +380,16 @@ class IoUtilsTest { IoUtils.resolve(FakeSecurityManager, key2, URI(".../dir1/dir2/NamedModuleResolversTest.pkl")) } - assertThrows { - IoUtils.resolve(FakeSecurityManager, key2, URI(".../")) - } + assertThrows { IoUtils.resolve(FakeSecurityManager, key2, URI(".../")) } assertThrows { IoUtils.resolve(FakeSecurityManager, key2, URI("...NamedModuleResolversTest.pkl")) } } - + @Test fun `readBytes(URL) does not support HTTP URLs`() { - assertThrows { - IoUtils.readBytes(URI("https://example.com")) - } - assertThrows { - IoUtils.readBytes(URI("http://example.com")) - } + assertThrows { IoUtils.readBytes(URI("https://example.com")) } + assertThrows { IoUtils.readBytes(URI("http://example.com")) } } @Test @@ -426,9 +397,7 @@ class IoUtilsTest { assertThrows { IoUtils.readString(URI("https://example.com").toURL()) } - assertThrows { - IoUtils.readString(URI("http://example.com").toURL()) - } + assertThrows { IoUtils.readString(URI("http://example.com").toURL()) } } @Test diff --git a/pkl-doc/pkl-doc.gradle.kts b/pkl-doc/pkl-doc.gradle.kts index d8a3031b..051b659d 100644 --- a/pkl-doc/pkl-doc.gradle.kts +++ b/pkl-doc/pkl-doc.gradle.kts @@ -1,5 +1,18 @@ -import org.jetbrains.kotlin.gradle.tasks.KotlinCompile - +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ plugins { pklAllProjects pklKotlinLibrary @@ -18,7 +31,8 @@ dependencies { implementation(libs.kotlinxHtml) implementation(libs.kotlinxSerializationJson) { // use our own Kotlin version - // (exclude is supported both for Maven and Gradle metadata, whereas dependency constraints aren't) + // (exclude is supported both for Maven and Gradle metadata, whereas dependency constraints + // aren't) exclude(group = "org.jetbrains.kotlin") } @@ -41,12 +55,6 @@ publishing { } } -tasks.jar { - manifest { - attributes += mapOf("Main-Class" to "org.pkl.doc.Main") - } -} +tasks.jar { manifest { attributes += mapOf("Main-Class" to "org.pkl.doc.Main") } } -htmlValidator { - sources = files("src/test/files/DocGeneratorTest/output") -} +htmlValidator { sources = files("src/test/files/DocGeneratorTest/output") } diff --git a/pkl-executor/pkl-executor.gradle.kts b/pkl-executor/pkl-executor.gradle.kts index a93d7958..e6d10d22 100644 --- a/pkl-executor/pkl-executor.gradle.kts +++ b/pkl-executor/pkl-executor.gradle.kts @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ import java.nio.file.Files import java.nio.file.LinkOption @@ -17,8 +32,7 @@ val pklHistoricalDistributions: Configuration by configurations.creating // (Pkl distributions used by EmbeddedExecutor are isolated via class loaders.) dependencies { pklDistributionCurrent(project(":pkl-config-java", "fatJar")) - @Suppress("UnstableApiUsage") - pklHistoricalDistributions(libs.pklConfigJavaAll025) + @Suppress("UnstableApiUsage") pklHistoricalDistributions(libs.pklConfigJavaAll025) implementation(libs.slf4jApi) @@ -28,67 +42,60 @@ dependencies { } // TODO why is this needed? Without this, we get error: -// `Entry org/pkl/executor/EmbeddedExecutor.java is a duplicate but no duplicate handling strategy has been set.` +// `Entry org/pkl/executor/EmbeddedExecutor.java is a duplicate but no duplicate handling strategy +// has been set.` // However, we do not have multiple of these Java files. -tasks.named("sourcesJar") { - duplicatesStrategy = DuplicatesStrategy.EXCLUDE -} +tasks.named("sourcesJar") { duplicatesStrategy = DuplicatesStrategy.EXCLUDE } publishing { publications { named("library") { pom { url.set("https://github.com/apple/pkl/tree/main/pkl-executor") - description.set(""" + description.set( + """ Library for executing Pkl code in a sandboxed environment. - """.trimIndent()) + """ + .trimIndent() + ) } } } } -sourceSets { - main { - java { - srcDir("src/main/java") - } - } -} +sourceSets { main { java { srcDir("src/main/java") } } } -val prepareHistoricalDistributions by tasks.registering { - val outputDir = layout.buildDirectory.dir("pklHistoricalDistributions") - inputs.files(pklHistoricalDistributions.files()) - outputs.dir(outputDir) - doLast { - val distributionDir = outputDir.get().asFile.toPath() - .also(Files::createDirectories) - for (file in pklHistoricalDistributions.files) { - val target = distributionDir.resolve(file.name) - // Create normal files on Windows, symlink on macOS/linux (need admin priveleges to create - // symlinks on Windows) - if (buildInfo.os.isWindows) { - if (!Files.isRegularFile(target, LinkOption.NOFOLLOW_LINKS)) { - if (Files.exists(target)) { - Files.delete(target) +val prepareHistoricalDistributions by + tasks.registering { + val outputDir = layout.buildDirectory.dir("pklHistoricalDistributions") + inputs.files(pklHistoricalDistributions.files()) + outputs.dir(outputDir) + doLast { + val distributionDir = outputDir.get().asFile.toPath().also(Files::createDirectories) + for (file in pklHistoricalDistributions.files) { + val target = distributionDir.resolve(file.name) + // Create normal files on Windows, symlink on macOS/linux (need admin priveleges to create + // symlinks on Windows) + if (buildInfo.os.isWindows) { + if (!Files.isRegularFile(target, LinkOption.NOFOLLOW_LINKS)) { + if (Files.exists(target)) { + Files.delete(target) + } + Files.copy(file.toPath(), target) } - Files.copy(file.toPath(), target) - } - } else { - if (!Files.isSymbolicLink(target)) { - if (Files.exists(target)) { - Files.delete(target) + } else { + if (!Files.isSymbolicLink(target)) { + if (Files.exists(target)) { + Files.delete(target) + } + Files.createSymbolicLink(target, file.toPath()) } - Files.createSymbolicLink(target, file.toPath()) } } } } -} -val prepareTest by tasks.registering { - dependsOn(pklDistributionCurrent, prepareHistoricalDistributions) -} +val prepareTest by + tasks.registering { dependsOn(pklDistributionCurrent, prepareHistoricalDistributions) } -tasks.test { - dependsOn(prepareTest) -} +tasks.test { dependsOn(prepareTest) } diff --git a/pkl-executor/src/test/kotlin/org/pkl/executor/EmbeddedExecutorTest.kt b/pkl-executor/src/test/kotlin/org/pkl/executor/EmbeddedExecutorTest.kt index 3932a0f8..edb9680c 100644 --- a/pkl-executor/src/test/kotlin/org/pkl/executor/EmbeddedExecutorTest.kt +++ b/pkl-executor/src/test/kotlin/org/pkl/executor/EmbeddedExecutorTest.kt @@ -1,8 +1,28 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.executor +import java.io.File +import java.nio.file.Files +import java.nio.file.Path +import java.time.Duration +import kotlin.io.path.createDirectories +import kotlin.io.path.exists import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.AfterAll -import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import org.junit.jupiter.api.condition.DisabledOnOs @@ -15,17 +35,11 @@ import org.pkl.commons.test.FilteringClassLoader import org.pkl.commons.test.PackageServer import org.pkl.commons.toPath import org.pkl.core.Release -import java.io.File -import java.nio.file.Files -import java.nio.file.Path -import java.time.Duration -import kotlin.io.path.createDirectories -import kotlin.io.path.exists class EmbeddedExecutorTest { /** - * An executor that uses a particular combination of ExecutorSpiOptions version, - * pkl-executor version, and Pkl distribution version. + * An executor that uses a particular combination of ExecutorSpiOptions version, pkl-executor + * version, and Pkl distribution version. */ class TestExecutor( private val executor: Executor, @@ -33,12 +47,11 @@ class EmbeddedExecutorTest { private val name: String ) { fun evaluatePath(modulePath: Path, optionSpec: ExecutorOptions.Builder.() -> Unit): String { - val options = ExecutorOptions.builder() - .apply(optionSpec) - .spiOptionsVersion(spiOptionsVersion) - .build() + val options = + ExecutorOptions.builder().apply(optionSpec).spiOptionsVersion(spiOptionsVersion).build() return executor.evaluatePath(modulePath, options) } + override fun toString(): String = name } @@ -50,19 +63,17 @@ class EmbeddedExecutorTest { // This context has a pkl-executor version that is lower than the distribution version. TestExecutor(executor1_2.value, 1, "SpiOptions1, Executor1, Distribution2"), - TestExecutor(executor2_1.value, 1, "SpiOptions1, Executor2, Distribution1"), TestExecutor(executor2_1.value, 2, "SpiOptions2, Executor2, Distribution1"), - TestExecutor(executor2_2.value, 1, "SpiOptions1, Executor2, Distribution2"), TestExecutor(executor2_2.value, 2, "SpiOptions2, Executor2, Distribution2") ) } - private val currentExecutor: TestExecutor by lazy { - TestExecutor(executor2_2.value, -1, "currentExecutor") + private val currentExecutor: TestExecutor by lazy { + TestExecutor(executor2_2.value, -1, "currentExecutor") } - + // A pkl-executor library that supports ExecutorSpiOptions up to v1 // and a Pkl distribution that supports ExecutorSpiOptions up to v1. private val executor1_1: Lazy = lazy { @@ -86,10 +97,8 @@ class EmbeddedExecutorTest { private val executor2_2: Lazy = lazy { EmbeddedExecutor(listOf(pklDistribution2), pklExecutorClassLoader2) } - - private val allExecutors by lazy { - listOf(executor1_1, executor1_2, executor2_1, executor2_2) - } + + private val allExecutors by lazy { listOf(executor1_1, executor1_2, executor2_1, executor2_2) } // a pkl-executor class loader that supports ExecutorSpiOptions up to v1 private val pklExecutorClassLoader1: ClassLoader by lazy { @@ -102,7 +111,7 @@ class EmbeddedExecutorTest { private val pklExecutorClassLoader2: ClassLoader by lazy { EmbeddedExecutor::class.java.classLoader } - + @AfterAll @JvmStatic fun afterAll() { @@ -114,127 +123,144 @@ class EmbeddedExecutorTest { // a Pkl distribution that supports ExecutorSpiOptions up to v1 private val pklDistribution1: Path by lazy { FileTestUtils.rootProjectDir - .resolve("pkl-executor/build/pklHistoricalDistributions/pkl-config-java-all-0.25.0.jar").apply { - if (!exists()) missingTestFixture() - } + .resolve("pkl-executor/build/pklHistoricalDistributions/pkl-config-java-all-0.25.0.jar") + .apply { if (!exists()) missingTestFixture() } } // a Pkl distribution that supports ExecutorSpiOptions up to v2 private val pklDistribution2: Path by lazy { FileTestUtils.rootProjectDir - .resolve("pkl-config-java/build/libs/pkl-config-java-all-" + - "${Release.current().version().withBuild(null).toString().replaceFirst("dev", "SNAPSHOT")}.jar").apply { - if (!exists()) missingTestFixture() - } + .resolve( + "pkl-config-java/build/libs/pkl-config-java-all-" + + "${Release.current().version().withBuild(null).toString().replaceFirst("dev", "SNAPSHOT")}.jar" + ) + .apply { if (!exists()) missingTestFixture() } } - + private fun missingTestFixture(): Nothing = - throw AssertionError("Missing test fixture. " + - "To fix this problem, run `./gradlew :pkl-executor:prepareTest`.") + throw AssertionError( + "Missing test fixture. " + "To fix this problem, run `./gradlew :pkl-executor:prepareTest`." + ) } @Test fun extractMinPklVersion() { assertThat( - EmbeddedExecutor.extractMinPklVersion( - """ + EmbeddedExecutor.extractMinPklVersion( + """ @ModuleInfo { minPklVersion = "1.2.3" } - """.trimIndent() - ) - ).isEqualTo(Version.parse("1.2.3")) + """ + .trimIndent() + ) + ) + .isEqualTo(Version.parse("1.2.3")) assertThat( - EmbeddedExecutor.extractMinPklVersion( - """ + EmbeddedExecutor.extractMinPklVersion( + """ @ModuleInfo{minPklVersion="1.2.3"} - """.trimIndent() - ) - ).isEqualTo(Version.parse("1.2.3")) + """ + .trimIndent() + ) + ) + .isEqualTo(Version.parse("1.2.3")) assertThat( - EmbeddedExecutor.extractMinPklVersion( - """ + EmbeddedExecutor.extractMinPklVersion( + """ @ModuleInfo { minPklVersion = "1.2.3" } - """.trimIndent() - ) - ).isEqualTo(Version.parse("1.2.3")) + """ + .trimIndent() + ) + ) + .isEqualTo(Version.parse("1.2.3")) assertThat( - EmbeddedExecutor.extractMinPklVersion( - """ + EmbeddedExecutor.extractMinPklVersion( + """ @ModuleInfo { minPklVersion = "1.2.3" } - """.trimIndent() - ) - ).isEqualTo(Version.parse("1.2.3")) + """ + .trimIndent() + ) + ) + .isEqualTo(Version.parse("1.2.3")) assertThat( - EmbeddedExecutor.extractMinPklVersion( - """ + EmbeddedExecutor.extractMinPklVersion( + """ @ModuleInfo { author = "foo@bar.apple.com" minPklVersion = "1.2.3" } - """.trimIndent() - ) - ).isEqualTo(Version.parse("1.2.3")) + """ + .trimIndent() + ) + ) + .isEqualTo(Version.parse("1.2.3")) assertThat( - EmbeddedExecutor.extractMinPklVersion( - """ + EmbeddedExecutor.extractMinPklVersion( + """ @ModuleInfo { minPklVersion = "1.2.3" author = "foo@bar.apple.com" } - """.trimIndent() - ) - ).isEqualTo(Version.parse("1.2.3")) + """ + .trimIndent() + ) + ) + .isEqualTo(Version.parse("1.2.3")) } @Test fun `create embedded executor with non-existing Pkl distribution`() { - val e = assertThrows { + val e = + assertThrows { Executors.embedded(listOf("/non/existing".toPath())) - } + } val sep = File.separatorChar - assertThat(e.message) - .contains("Cannot find Jar file") - .contains("${sep}non${sep}existing") + assertThat(e.message).contains("Cannot find Jar file").contains("${sep}non${sep}existing") } @Test - fun `create embedded executor with invalid Pkl distribution that is not a Jar file`(@TempDir tempDir: Path) { + fun `create embedded executor with invalid Pkl distribution that is not a Jar file`( + @TempDir tempDir: Path + ) { val file = Files.createFile(tempDir.resolve("pkl.jar")) - val e = assertThrows { - Executors.embedded(listOf(file)) - } + val e = assertThrows { Executors.embedded(listOf(file)) } - assertThat(e.message) - .contains("Cannot find service") - .contains("pkl.jar") + assertThat(e.message).contains("Cannot find service").contains("pkl.jar") } @ParameterizedTest @MethodSource("getAllTestExecutors") - fun `evaluate a module that is missing a ModuleInfo annotation`(executor: TestExecutor, @TempDir tempDir: Path) { + fun `evaluate a module that is missing a ModuleInfo annotation`( + executor: TestExecutor, + @TempDir tempDir: Path + ) { val pklFile = tempDir.resolve("test.pkl") - pklFile.toFile().writeText( - """ + pklFile + .toFile() + .writeText( + """ module test x = 1 - """.trimIndent() - ) + """ + .trimIndent() + ) - val e = assertThrows { - executor.evaluatePath(pklFile) { - allowedModules("file:") - allowedResources("prop:") - rootDir(tempDir) + val e = + assertThrows { + executor.evaluatePath(pklFile) { + allowedModules("file:") + allowedResources("prop:") + rootDir(tempDir) + } } - } assertThat(e.message) .contains("Pkl module `test.pkl` does not state which Pkl version it requires.") @@ -242,24 +268,31 @@ class EmbeddedExecutorTest { @ParameterizedTest @MethodSource("getAllTestExecutors") - fun `evaluate a module that requests an incompatible Pkl version`(executor: TestExecutor, @TempDir tempDir: Path) { + fun `evaluate a module that requests an incompatible Pkl version`( + executor: TestExecutor, + @TempDir tempDir: Path + ) { val pklFile = tempDir.resolve("test.pkl") - pklFile.toFile().writeText( - """ + pklFile + .toFile() + .writeText( + """ @ModuleInfo { minPklVersion = "99.99.99" } module test x = 1 - """.trimIndent() - ) + """ + .trimIndent() + ) - val e = assertThrows { - executor.evaluatePath(pklFile) { - allowedModules("file:") - allowedResources("prop:") - rootDir(tempDir) + val e = + assertThrows { + executor.evaluatePath(pklFile) { + allowedModules("file:") + allowedResources("prop:") + rootDir(tempDir) + } } - } assertThat(e.message) .contains("Pkl version `99.99.99` requested by module `test.pkl` is not supported.") @@ -267,94 +300,113 @@ class EmbeddedExecutorTest { @ParameterizedTest @MethodSource("getAllTestExecutors") - fun `evaluate a module that reads environment variables and external properties`(executor: TestExecutor, @TempDir tempDir: Path) { + fun `evaluate a module that reads environment variables and external properties`( + executor: TestExecutor, + @TempDir tempDir: Path + ) { val pklFile = tempDir.resolve("test.pkl") - pklFile.toFile().writeText( - """ + pklFile + .toFile() + .writeText( + """ @ModuleInfo { minPklVersion = "0.11.0" } module test x = read("env:ENV_VAR") y = read("prop:property") - """.trimIndent() - ) + """ + .trimIndent() + ) - val result = executor.evaluatePath(pklFile) { - allowedModules("file:") - // should `prop:pkl.outputFormat` be allowed automatically? - allowedResources("prop:", "env:") - environmentVariables(mapOf("ENV_VAR" to "ENV_VAR")) - externalProperties(mapOf("property" to "property")) - } + val result = + executor.evaluatePath(pklFile) { + allowedModules("file:") + // should `prop:pkl.outputFormat` be allowed automatically? + allowedResources("prop:", "env:") + environmentVariables(mapOf("ENV_VAR" to "ENV_VAR")) + externalProperties(mapOf("property" to "property")) + } - assertThat(result.trim()).isEqualTo( - """ + assertThat(result.trim()) + .isEqualTo(""" x = "ENV_VAR" y = "property" - """.trimIndent().trim() - ) + """.trimIndent().trim()) } @ParameterizedTest @MethodSource("getAllTestExecutors") - fun `evaluate a module that depends on another module`(executor: TestExecutor, @TempDir tempDir: Path) { + fun `evaluate a module that depends on another module`( + executor: TestExecutor, + @TempDir tempDir: Path + ) { val pklFile = tempDir.resolve("test.pkl") - pklFile.toFile().writeText( - """ + pklFile + .toFile() + .writeText( + """ @ModuleInfo { minPklVersion = "0.11.0" } amends "template.pkl" foo { bar = 42 } - """.trimIndent() - ) + """ + .trimIndent() + ) val templateFile = tempDir.resolve("template.pkl") - templateFile.toFile().writeText( - """ + templateFile + .toFile() + .writeText( + """ foo: Foo class Foo { bar: Int } - """.trimIndent() - ) + """ + .trimIndent() + ) - val result = executor.evaluatePath(pklFile) { - allowedModules("file:") - allowedResources("prop:") - } + val result = + executor.evaluatePath(pklFile) { + allowedModules("file:") + allowedResources("prop:") + } - assertThat(result.trim()).isEqualTo( - """ + assertThat(result.trim()) + .isEqualTo(""" foo { bar = 42 } - """.trimIndent().trim() - ) + """.trimIndent().trim()) } @ParameterizedTest @MethodSource("getAllTestExecutors") fun `evaluate a module whose evaluation fails`(executor: TestExecutor, @TempDir tempDir: Path) { val pklFile = tempDir.resolve("test.pkl") - pklFile.toFile().writeText( - """ + pklFile + .toFile() + .writeText( + """ @ModuleInfo { minPklVersion = "0.11.0" } module test foo = throw("ouch") - """.trimIndent() - ) + """ + .trimIndent() + ) - val e = assertThrows { - executor.evaluatePath(pklFile) { - allowedModules("file:") - allowedResources("prop:") - rootDir(tempDir) + val e = + assertThrows { + executor.evaluatePath(pklFile) { + allowedModules("file:") + allowedResources("prop:") + rootDir(tempDir) + } } - } assertThat(e.message) .contains("ouch") @@ -367,62 +419,73 @@ class EmbeddedExecutorTest { @MethodSource("getAllTestExecutors") fun `time out a module`(executor: TestExecutor, @TempDir tempDir: Path) { val pklFile = tempDir.resolve("test.pkl") - pklFile.toFile().writeText( - """ + pklFile + .toFile() + .writeText( + """ @ModuleInfo { minPklVersion = "0.11.0" } module test x = fib(100) function fib(n) = if (n < 2) n else fib(n - 1) + fib(n - 2) - """.trimIndent() - ) + """ + .trimIndent() + ) - val e = assertThrows { - executor.evaluatePath(pklFile) { - allowedModules("file:") - allowedResources("prop:") - rootDir(tempDir) - timeout(Duration.ofSeconds(1)) + val e = + assertThrows { + executor.evaluatePath(pklFile) { + allowedModules("file:") + allowedResources("prop:") + rootDir(tempDir) + timeout(Duration.ofSeconds(1)) + } } - } - assertThat(e.message) - .contains("Evaluation timed out after 1 second(s).") + assertThat(e.message).contains("Evaluation timed out after 1 second(s).") } @Test fun `evaluate a module that loads a package`(@TempDir tempDir: Path) { val cacheDir = tempDir.resolve("cache") val pklFile = tempDir.resolve("test.pkl") - pklFile.toFile().writeText( - """ + pklFile + .toFile() + .writeText( + """ @ModuleInfo { minPklVersion = "0.24.0" } module MyModule import "package://localhost:0/birds@0.5.0#/Bird.pkl" chirpy = new Bird { name = "Chirpy"; favoriteFruit { name = "Orange" } } - """.trimIndent() - ) - val result = PackageServer().use { server -> - currentExecutor.evaluatePath(pklFile) { - allowedModules("file:", "package:", "https:") - allowedResources("prop:", "package:", "https:") - moduleCacheDir(cacheDir) - certificateFiles(FileTestUtils.selfSignedCertificate) - testPort(server.port) + """ + .trimIndent() + ) + val result = + PackageServer().use { server -> + currentExecutor.evaluatePath(pklFile) { + allowedModules("file:", "package:", "https:") + allowedResources("prop:", "package:", "https:") + moduleCacheDir(cacheDir) + certificateFiles(FileTestUtils.selfSignedCertificate) + testPort(server.port) + } } - } - assertThat(result.trim()).isEqualTo(""" + assertThat(result.trim()) + .isEqualTo( + """ chirpy { name = "Chirpy" favoriteFruit { name = "Orange" } } - """.trimIndent()) - + """ + .trimIndent() + ) + // verify that cache was populated assertThat(cacheDir.toFile().list()).isNotEmpty() } @@ -436,15 +499,25 @@ class EmbeddedExecutorTest { PackageServer.populateLegacyCacheDir(cacheDir) val projectDir = tempDir.resolve("project/") projectDir.createDirectories() - projectDir.resolve("PklProject").toFile().writeText(""" + projectDir + .resolve("PklProject") + .toFile() + .writeText( + """ amends "pkl:Project" dependencies { ["birds"] { uri = "package://localhost:0/birds@0.5.0" } } - """.trimIndent()) + """ + .trimIndent() + ) val dollar = '$' - projectDir.resolve("PklProject.deps.json").toFile().writeText(""" + projectDir + .resolve("PklProject.deps.json") + .toFile() + .writeText( + """ { "schemaVersion": 1, "resolvedDependencies": { @@ -464,25 +537,33 @@ class EmbeddedExecutorTest { } } } - """.trimIndent()) + """ + .trimIndent() + ) val pklFile = projectDir.resolve("test.pkl") - pklFile.toFile().writeText( - """ + pklFile + .toFile() + .writeText( + """ @ModuleInfo { minPklVersion = "0.24.0" } module myModule import "@birds/catalog/Swallow.pkl" result = Swallow - """.trimIndent() - ) - val result = executor.evaluatePath(pklFile) { - allowedModules("file:", "package:", "projectpackage:", "https:") - allowedResources("file:", "prop:", "package:", "projectpackage:", "https:") - moduleCacheDir(cacheDir) - projectDir(projectDir) - } - assertThat(result).isEqualTo(""" + """ + .trimIndent() + ) + val result = + executor.evaluatePath(pklFile) { + allowedModules("file:", "package:", "projectpackage:", "https:") + allowedResources("file:", "prop:", "package:", "projectpackage:", "https:") + moduleCacheDir(cacheDir) + projectDir(projectDir) + } + assertThat(result) + .isEqualTo( + """ result { name = "Swallow" favoriteFruit { @@ -490,6 +571,8 @@ class EmbeddedExecutorTest { } } - """.trimIndent()) + """ + .trimIndent() + ) } } diff --git a/pkl-executor/src/test/kotlin/org/pkl/executor/VersionTest.kt b/pkl-executor/src/test/kotlin/org/pkl/executor/VersionTest.kt index 01e9cca2..9f0b3941 100644 --- a/pkl-executor/src/test/kotlin/org/pkl/executor/VersionTest.kt +++ b/pkl-executor/src/test/kotlin/org/pkl/executor/VersionTest.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.executor import org.assertj.core.api.Assertions.assertThat @@ -38,23 +53,16 @@ class VersionTest { @Test fun `parse invalid version`() { - assertThat(Version.parseOrNull("not a version number")) - .isNull() + assertThat(Version.parseOrNull("not a version number")).isNull() - assertThrows { - Version.parse("not a version number") - } + assertThrows { Version.parse("not a version number") } } @Test fun `parse too large version`() { - assertThrows { - Version.parse("not a version number") - } + assertThrows { Version.parse("not a version number") } - assertThrows { - Version.parse("999999999999999.0.0") - } + assertThrows { Version.parse("999999999999999.0.0") } } @Test @@ -67,137 +75,80 @@ class VersionTest { @Test fun withMethods() { - val version = Version.parse("0.0.0") - .withMajor(1) - .withMinor(2) - .withPatch(3) - .withPreRelease("rc.1") - .withBuild("456.789") + val version = + Version.parse("0.0.0") + .withMajor(1) + .withMinor(2) + .withPatch(3) + .withPreRelease("rc.1") + .withBuild("456.789") assertThat(version).isEqualTo(Version.parse("1.2.3-rc.1+456.789")) - val version2 = Version.parse("0.0.0") - .withBuild("456.789") - .withPreRelease("rc.1") - .withPatch(3) - .withMinor(2) - .withMajor(1) + val version2 = + Version.parse("0.0.0") + .withBuild("456.789") + .withPreRelease("rc.1") + .withPatch(3) + .withMinor(2) + .withMajor(1) assertThat(version2).isEqualTo(version) } @Test fun `compareTo()`() { - assertThat( - Version(1, 2, 3, null, null).compareTo( - Version(1, 2, 3, null, null) - ) - ).isEqualTo(0) - assertThat( - Version(1, 2, 3, "SNAPSHOT", null).compareTo( - Version(1, 2, 3, "SNAPSHOT", null) - ) - ).isEqualTo(0) - assertThat( - Version(1, 2, 3, "alpha", null).compareTo( - Version(1, 2, 3, "alpha", null) - ) - ).isEqualTo(0) - assertThat( - Version(1, 2, 3, "alpha", null).compareTo( - Version(1, 2, 3, "alpha", "build123") - ) - ).isEqualTo(0) + assertThat(Version(1, 2, 3, null, null).compareTo(Version(1, 2, 3, null, null))).isEqualTo(0) + assertThat(Version(1, 2, 3, "SNAPSHOT", null).compareTo(Version(1, 2, 3, "SNAPSHOT", null))) + .isEqualTo(0) + assertThat(Version(1, 2, 3, "alpha", null).compareTo(Version(1, 2, 3, "alpha", null))) + .isEqualTo(0) + assertThat(Version(1, 2, 3, "alpha", null).compareTo(Version(1, 2, 3, "alpha", "build123"))) + .isEqualTo(0) - assertThat( - Version(1, 2, 3, null, null).compareTo( - Version(2, 2, 3, null, null) - ) - ).isLessThan(0) - assertThat( - Version(1, 2, 3, null, null).compareTo( - Version(1, 3, 3, null, null) - ) - ).isLessThan(0) - assertThat( - Version(1, 2, 3, null, null).compareTo( - Version(1, 2, 4, null, null) - ) - ).isLessThan(0) + assertThat(Version(1, 2, 3, null, null).compareTo(Version(2, 2, 3, null, null))).isLessThan(0) + assertThat(Version(1, 2, 3, null, null).compareTo(Version(1, 3, 3, null, null))).isLessThan(0) + assertThat(Version(1, 2, 3, null, null).compareTo(Version(1, 2, 4, null, null))).isLessThan(0) - assertThat( - Version(2, 2, 3, null, null).compareTo( - Version(1, 2, 3, null, null) - ) - ).isGreaterThan(0) - assertThat( - Version(1, 3, 3, null, null).compareTo( - Version(1, 2, 3, null, null) - ) - ).isGreaterThan(0) - assertThat( - Version(1, 2, 4, null, null).compareTo( - Version(1, 2, 3, null, null) - ) - ).isGreaterThan(0) + assertThat(Version(2, 2, 3, null, null).compareTo(Version(1, 2, 3, null, null))) + .isGreaterThan(0) + assertThat(Version(1, 3, 3, null, null).compareTo(Version(1, 2, 3, null, null))) + .isGreaterThan(0) + assertThat(Version(1, 2, 4, null, null).compareTo(Version(1, 2, 3, null, null))) + .isGreaterThan(0) - assertThat( - Version(1, 2, 3, "SNAPSHOT", null).compareTo( - Version(1, 2, 3, null, null) - ) - ).isLessThan(0) - assertThat( - Version(1, 2, 3, "alpha", null).compareTo( - Version(1, 2, 3, "beta", null) - ) - ).isLessThan(0) - assertThat( - Version(1, 2, 3, "alpha", "build123").compareTo( - Version(1, 2, 3, "beta", null) - ) - ).isLessThan(0) + assertThat(Version(1, 2, 3, "SNAPSHOT", null).compareTo(Version(1, 2, 3, null, null))) + .isLessThan(0) + assertThat(Version(1, 2, 3, "alpha", null).compareTo(Version(1, 2, 3, "beta", null))) + .isLessThan(0) + assertThat(Version(1, 2, 3, "alpha", "build123").compareTo(Version(1, 2, 3, "beta", null))) + .isLessThan(0) - assertThat( - Version(1, 2, 3, null, null).compareTo( - Version(1, 2, 3, "SNAPSHOT", null) - ) - ).isGreaterThan(0) - assertThat( - Version(1, 2, 3, "beta", null).compareTo( - Version(1, 2, 3, "alpha", "build123") - ) - ).isGreaterThan(0) + assertThat(Version(1, 2, 3, null, null).compareTo(Version(1, 2, 3, "SNAPSHOT", null))) + .isGreaterThan(0) + assertThat(Version(1, 2, 3, "beta", null).compareTo(Version(1, 2, 3, "alpha", "build123"))) + .isGreaterThan(0) } @Test fun `compare version with too large numeric pre-release identifier`() { // error is deferred until compareTo(), but should be good enough assertThrows { - Version(1, 2, 3, "999", null).compareTo( - Version(1, 2, 3, "9999999999999999999", null) - ) + Version(1, 2, 3, "999", null).compareTo(Version(1, 2, 3, "9999999999999999999", null)) } } @Test fun `equals()`() { - assertThat(Version(1, 2, 3, null, null)) - .isEqualTo(Version(1, 2, 3, null, null)) - assertThat(Version(1, 2, 3, "SNAPSHOT", null)) - .isEqualTo(Version(1, 2, 3, "SNAPSHOT", null)) - assertThat(Version(1, 2, 3, "alpha", null)) - .isEqualTo(Version(1, 2, 3, "alpha", null)) - assertThat(Version(1, 2, 3, "beta", "build123")) - .isEqualTo(Version(1, 2, 3, "beta", "build456")) + assertThat(Version(1, 2, 3, null, null)).isEqualTo(Version(1, 2, 3, null, null)) + assertThat(Version(1, 2, 3, "SNAPSHOT", null)).isEqualTo(Version(1, 2, 3, "SNAPSHOT", null)) + assertThat(Version(1, 2, 3, "alpha", null)).isEqualTo(Version(1, 2, 3, "alpha", null)) + assertThat(Version(1, 2, 3, "beta", "build123")).isEqualTo(Version(1, 2, 3, "beta", "build456")) - assertThat(Version(1, 3, 3, null, null)) - .isNotEqualTo(Version(1, 2, 3, null, null)) - assertThat(Version(1, 2, 4, null, null)) - .isNotEqualTo(Version(1, 2, 3, null, null)) - assertThat(Version(1, 2, 3, "SNAPSHOT", null)) - .isNotEqualTo(Version(1, 2, 3, null, null)) - assertThat(Version(1, 2, 3, "beta", null)) - .isNotEqualTo(Version(1, 2, 3, "alpha", null)) + assertThat(Version(1, 3, 3, null, null)).isNotEqualTo(Version(1, 2, 3, null, null)) + assertThat(Version(1, 2, 4, null, null)).isNotEqualTo(Version(1, 2, 3, null, null)) + assertThat(Version(1, 2, 3, "SNAPSHOT", null)).isNotEqualTo(Version(1, 2, 3, null, null)) + assertThat(Version(1, 2, 3, "beta", null)).isNotEqualTo(Version(1, 2, 3, "alpha", null)) } @Test diff --git a/pkl-gradle/pkl-gradle.gradle.kts b/pkl-gradle/pkl-gradle.gradle.kts index c1375a0e..c889146d 100644 --- a/pkl-gradle/pkl-gradle.gradle.kts +++ b/pkl-gradle/pkl-gradle.gradle.kts @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ plugins { pklAllProjects pklJavaLibrary @@ -15,21 +30,19 @@ dependencies { compileOnly(projects.pklTools) // Declare a `runtimeOnly` dependency on `project(":pkl-tools", "fatJar")` - // to ensure that the published plugin - // (and also plugin tests, see the generated `plugin-under-test-metadata.properties`) + // to ensure that the published plugin + // (and also plugin tests, see the generated `plugin-under-test-metadata.properties`) // only depends on the pkl-tools shaded fat JAR. // This avoids dependency version conflicts with other Gradle plugins. // - // Hide this dependency from IntelliJ + // Hide this dependency from IntelliJ // to prevent IntelliJ from reindexing the pkl-tools fat JAR after every build. // (IntelliJ gets everything it needs from the `compileOnly` dependency.) // // To debug shaded code in IntelliJ, temporarily remove the conditional. if (System.getProperty("idea.sync.active") == null) { runtimeOnly(projects.pklTools) { - attributes { - attribute(Bundling.BUNDLING_ATTRIBUTE, objects.named(Bundling.SHADOWED)) - } + attributes { attribute(Bundling.BUNDLING_ATTRIBUTE, objects.named(Bundling.SHADOWED)) } } } diff --git a/pkl-gradle/src/test/kotlin/org/pkl/gradle/AbstractTest.kt b/pkl-gradle/src/test/kotlin/org/pkl/gradle/AbstractTest.kt index 59c3ed12..6343f9ac 100644 --- a/pkl-gradle/src/test/kotlin/org/pkl/gradle/AbstractTest.kt +++ b/pkl-gradle/src/test/kotlin/org/pkl/gradle/AbstractTest.kt @@ -1,34 +1,46 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.gradle -import org.pkl.commons.createParentDirectories -import org.pkl.commons.readString -import org.pkl.commons.writeString +import java.net.URI +import java.nio.file.Path import org.assertj.core.api.Assertions.assertThat import org.gradle.testkit.runner.BuildResult import org.gradle.testkit.runner.GradleRunner import org.gradle.testkit.runner.UnexpectedBuildFailure import org.junit.jupiter.api.io.TempDir -import java.net.URI -import java.nio.file.Path +import org.pkl.commons.createParentDirectories +import org.pkl.commons.readString +import org.pkl.commons.writeString abstract class AbstractTest { private val gradleVersion: String? = System.getProperty("testGradleVersion") private val gradleDistributionUrl: String? = System.getProperty("testGradleDistributionUrl") - @TempDir - protected lateinit var testProjectDir: Path + @TempDir protected lateinit var testProjectDir: Path - protected fun runTask( - taskName: String, - expectFailure: Boolean = false - ): BuildResult { + protected fun runTask(taskName: String, expectFailure: Boolean = false): BuildResult { - val runner = GradleRunner.create() - .withProjectDir(testProjectDir.toFile()) - .withArguments("--stacktrace", "--no-build-cache", taskName) - .withPluginClasspath() - .withDebug(true) + val runner = + GradleRunner.create() + .withProjectDir(testProjectDir.toFile()) + .withArguments("--stacktrace", "--no-build-cache", taskName) + .withPluginClasspath() + .withDebug(true) if (gradleVersion != null) { runner.withGradleVersion(gradleVersion) @@ -45,15 +57,15 @@ abstract class AbstractTest { } protected fun writeFile(fileName: String, contents: String): Path { - return testProjectDir.resolve(fileName) + return testProjectDir + .resolve(fileName) .apply { createParentDirectories() } .writeString(contents.trimIndent()) } protected fun checkFileContents(file: Path, contents: String) { assertThat(file).exists() - assertThat(file.readString().trim()) - .isEqualTo(contents.trim()) + assertThat(file.readString().trim()).isEqualTo(contents.trim()) } protected fun checkTextContains(text: String, vararg contents: String) { diff --git a/pkl-gradle/src/test/kotlin/org/pkl/gradle/EvaluatorsTest.kt b/pkl-gradle/src/test/kotlin/org/pkl/gradle/EvaluatorsTest.kt index ccd58ca4..e13688ac 100644 --- a/pkl-gradle/src/test/kotlin/org/pkl/gradle/EvaluatorsTest.kt +++ b/pkl-gradle/src/test/kotlin/org/pkl/gradle/EvaluatorsTest.kt @@ -1,14 +1,26 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.gradle -import org.assertj.core.api.Assertions -import org.pkl.commons.readString -import org.pkl.commons.readString -import org.pkl.commons.test.PackageServer -import org.pkl.commons.toNormalizedPathString +import java.nio.file.Path import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir -import java.nio.file.Path +import org.pkl.commons.readString +import org.pkl.commons.test.PackageServer class EvaluatorsTest : AbstractTest() { @Test @@ -21,12 +33,14 @@ class EvaluatorsTest : AbstractTest() { val outputFile = testProjectDir.resolve("test.pcf") checkFileContents( - outputFile, """ + outputFile, + """ person { name = "Pigeon" age = 30 } - """.trimIndent() + """ + .trimIndent() ) } @@ -40,11 +54,13 @@ class EvaluatorsTest : AbstractTest() { val outputFile = testProjectDir.resolve("test.yaml") checkFileContents( - outputFile, """ + outputFile, + """ person: name: Pigeon age: 30 - """.trimIndent() + """ + .trimIndent() ) } @@ -58,14 +74,16 @@ class EvaluatorsTest : AbstractTest() { val outputFile = testProjectDir.resolve("test.json") checkFileContents( - outputFile, """ + outputFile, + """ { "person": { "name": "Pigeon", "age": 30 } } - """.trimIndent() + """ + .trimIndent() ) } @@ -79,7 +97,8 @@ class EvaluatorsTest : AbstractTest() { val outputFile = testProjectDir.resolve("test.plist") checkFileContents( - outputFile, """ + outputFile, + """ @@ -93,16 +112,19 @@ class EvaluatorsTest : AbstractTest() { - """.trimIndent() + """ + .trimIndent() ) } @Test fun `set external properties`() { writeBuildFile( - "pcf", """ + "pcf", + """ externalProperties = [prop1: "value1", prop2: "value2"] - """.trimIndent() + """ + .trimIndent() ) writePklFile( @@ -110,18 +132,21 @@ class EvaluatorsTest : AbstractTest() { prop1 = read("prop:prop1") prop2 = read("prop:prop2") other = read?("prop:other") - """.trimIndent() + """ + .trimIndent() ) runTask("evalTest") val outputFile = testProjectDir.resolve("test.pcf") checkFileContents( - outputFile, """ + outputFile, + """ prop1 = "value1" prop2 = "value2" other = null - """.trimIndent() + """ + .trimIndent() ) } @@ -134,27 +159,32 @@ class EvaluatorsTest : AbstractTest() { prop1 = read?("env:USER") prop2 = read?("env:PATH") prop3 = read?("env:JAVA_HOME") - """.trimIndent() + """ + .trimIndent() ) runTask("evalTest") val outputFile = testProjectDir.resolve("test.pcf") checkFileContents( - outputFile, """ + outputFile, + """ prop1 = null prop2 = null prop3 = null - """.trimIndent() + """ + .trimIndent() ) } @Test fun `set environment variables`() { writeBuildFile( - "pcf", """ + "pcf", + """ environmentVariables = [VAR1: "value1", VAR2: "value2"] - """.trimIndent() + """ + .trimIndent() ) writePklFile( @@ -162,25 +192,29 @@ class EvaluatorsTest : AbstractTest() { prop1 = read("env:VAR1") prop2 = read("env:VAR2") other = read?("env:OTHER") - """.trimIndent() + """ + .trimIndent() ) runTask("evalTest") val outputFile = testProjectDir.resolve("test.pcf") checkFileContents( - outputFile, """ + outputFile, + """ prop1 = "value1" prop2 = "value2" other = null - """.trimIndent() + """ + .trimIndent() ) } @Test fun `no source modules`() { writeFile( - "build.gradle", """ + "build.gradle", + """ plugins { id "org.pkl-lang" } @@ -202,7 +236,8 @@ class EvaluatorsTest : AbstractTest() { @Test fun `source module URIs`() { writeFile( - "testDir/test.pkl", """ + "testDir/test.pkl", + """ person { name = "Pigeon" age = 20 + 10 @@ -211,7 +246,8 @@ class EvaluatorsTest : AbstractTest() { ) writeFile( - "build.gradle", """ + "build.gradle", + """ plugins { id "org.pkl-lang" } @@ -233,19 +269,22 @@ class EvaluatorsTest : AbstractTest() { val outputFile = testProjectDir.resolve("test.pcf") checkFileContents( - outputFile, """ + outputFile, + """ person { name = "Pigeon" age = 30 } - """.trimIndent() + """ + .trimIndent() ) } @Test fun `cannot evaluate module located outside evalRootDir`() { writeFile( - "build.gradle", """ + "build.gradle", + """ plugins { id "org.pkl-lang" } @@ -264,17 +303,18 @@ class EvaluatorsTest : AbstractTest() { val result = runTask("evalTest", expectFailure = true) assertThat(result.output).contains("Refusing to load module") - assertThat(result.output).contains("because it does not match any entry in the module allowlist (`--allowed-modules`).") + assertThat(result.output) + .contains( + "because it does not match any entry in the module allowlist (`--allowed-modules`)." + ) } @Test fun `evaluation timeout`() { // Gradle 4.10 doesn't automatically import Duration - writeBuildFile( - "pcf", """ + writeBuildFile("pcf", """ evalTimeout = java.time.Duration.ofMillis(100) - """ - ) + """) writePklFile( """ @@ -291,7 +331,8 @@ class EvaluatorsTest : AbstractTest() { fun `module output separator`() { val outputFile = testProjectDir.resolve("test.pcf") writeFile( - "build.gradle", """ + "build.gradle", + """ plugins { id "org.pkl-lang" } @@ -309,32 +350,34 @@ class EvaluatorsTest : AbstractTest() { """ ) - writeFile( - "test1.pkl", - "foo = 1" - ) - writeFile( - "test2.pkl", - "bar = 2" - ) + writeFile("test1.pkl", "foo = 1") + writeFile("test2.pkl", "bar = 2") runTask("evalTask") - checkFileContents(outputFile, """ + checkFileContents( + outputFile, + """ foo = 1 // hello bar = 2 - """.trimIndent()) + """ + .trimIndent() + ) } - + @Test fun `compliant file URIs`() { writeBuildFile("pcf") - writeFile("test.pkl", """ + writeFile( + "test.pkl", + """ import "pkl:reflect" output { text = reflect.Module(module).uri } - """.trimIndent()) + """ + .trimIndent() + ) runTask("evalTest") @@ -345,9 +388,13 @@ class EvaluatorsTest : AbstractTest() { @Test fun `multiple file output`() { - writeBuildFile("pcf", """ + writeBuildFile( + "pcf", + """ multipleFileOutputDir = layout.projectDirectory.dir("my-output") - """.trimIndent()) + """ + .trimIndent() + ) writeFile( "test.pkl", """ @@ -361,7 +408,8 @@ class EvaluatorsTest : AbstractTest() { } } } - """.trimIndent() + """ + .trimIndent() ) runTask("evalTest") checkFileContents(testProjectDir.resolve("my-output/output-1.txt"), "My output 1") @@ -370,17 +418,22 @@ class EvaluatorsTest : AbstractTest() { @Test fun expression() { - writeBuildFile("yaml", """ + writeBuildFile( + "yaml", + """ expression = "metadata.name" outputFile = layout.projectDirectory.file("output.txt") - """.trimIndent()) + """ + .trimIndent() + ) writeFile( "test.pkl", """ metadata { name = "Uni" } - """.trimIndent() + """ + .trimIndent() ) runTask("evalTest") checkFileContents(testProjectDir.resolve("output.txt"), "Uni") @@ -388,26 +441,33 @@ class EvaluatorsTest : AbstractTest() { @Test fun `explicitly set cache dir`(@TempDir tempDir: Path) { - writeBuildFile("pcf", """ + writeBuildFile( + "pcf", + """ moduleCacheDir = file("${tempDir.toUri()}") - """.trimIndent()) + """ + .trimIndent() + ) writeFile( "test.pkl", """ import "package://localhost:0/birds@0.5.0#/Bird.pkl" res = new Bird { name = "Wally"; favoriteFruit { name = "bananas" } } - """.trimIndent() + """ + .trimIndent() ) PackageServer.populateCacheDir(tempDir) runTask("evalTest") } - + @Test fun `explicitly set project dir`() { writeBuildFile("pcf", "projectDir = file(\"proj1\")", listOf("proj1/foo.pkl")) - - writeFile("proj1/PklProject", """ + + writeFile( + "proj1/PklProject", + """ amends "pkl:Project" dependencies { @@ -420,9 +480,13 @@ class EvaluatorsTest : AbstractTest() { version = "1.0.0" packageZipUrl = "https://localhost:0/\(name)@\(version).zip" } - """.trimIndent()) - - writeFile("proj2/PklProject", """ + """ + .trimIndent() + ) + + writeFile( + "proj2/PklProject", + """ amends "pkl:Project" package { @@ -431,9 +495,13 @@ class EvaluatorsTest : AbstractTest() { version = "1.0.0" packageZipUrl = "https://localhost:0/\(name)@\(version).zip" } - """.trimIndent()) - - writeFile("proj1/PklProject.deps.json", """ + """ + .trimIndent() + ) + + writeFile( + "proj1/PklProject.deps.json", + """ { "schemaVersion": 1, "resolvedDependencies": { @@ -444,38 +512,53 @@ class EvaluatorsTest : AbstractTest() { } } } - """.trimIndent()) - - writeFile("proj2/PklProject.deps.json", """ + """ + .trimIndent() + ) + + writeFile( + "proj2/PklProject.deps.json", + """ { "schemaVersion": 1, "resolvedDependencies": {} } - """.trimIndent()) - - writeFile("proj1/foo.pkl", """ + """ + .trimIndent() + ) + + writeFile( + "proj1/foo.pkl", + """ module proj1.foo bar: String = import("@proj2/baz.pkl").qux - """.trimIndent()) - - writeFile("proj2/baz.pkl", """ + """ + .trimIndent() + ) + + writeFile( + "proj2/baz.pkl", + """ qux: String = "Contents of @proj2/qux" - """.trimIndent()) + """ + .trimIndent() + ) runTask("evalTest") assertThat(testProjectDir.resolve("proj1/foo.pcf")).exists() } private fun writeBuildFile( - // don't use `org.pkl.core.OutputFormat` + // don't use `org.pkl.core.OutputFormat` // because test compile class path doesn't contain pkl-core - outputFormat: String, + outputFormat: String, additionalContents: String = "", sourceModules: List = listOf("test.pkl") ) { writeFile( - "build.gradle", """ + "build.gradle", + """ plugins { id "org.pkl-lang" } diff --git a/pkl-gradle/src/test/kotlin/org/pkl/gradle/JavaCodeGeneratorsTest.kt b/pkl-gradle/src/test/kotlin/org/pkl/gradle/JavaCodeGeneratorsTest.kt index 277d6c24..1a668272 100644 --- a/pkl-gradle/src/test/kotlin/org/pkl/gradle/JavaCodeGeneratorsTest.kt +++ b/pkl-gradle/src/test/kotlin/org/pkl/gradle/JavaCodeGeneratorsTest.kt @@ -1,9 +1,24 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.gradle -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test import kotlin.io.path.listDirectoryEntries import kotlin.io.path.readText +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test class JavaCodeGeneratorsTest : AbstractTest() { @Test @@ -12,7 +27,7 @@ class JavaCodeGeneratorsTest : AbstractTest() { writePklFile() runTask("configClasses") - + val baseDir = testProjectDir.resolve("build/generated/java/foo/bar") val moduleFile = baseDir.resolve("Mod.java") @@ -23,16 +38,18 @@ class JavaCodeGeneratorsTest : AbstractTest() { // shading must not affect generated code assertThat(text).doesNotContain("org.pkl.thirdparty") - + checkTextContains( - text, """ + text, + """ |public final class Mod { | public final @Nonnull Object other; """ ) checkTextContains( - text, """ + text, + """ | public static final class Person { | public final @Nonnull String name; | @@ -41,7 +58,8 @@ class JavaCodeGeneratorsTest : AbstractTest() { ) checkTextContains( - text, """ + text, + """ | public static final class Address { | public final @Nonnull String street; | @@ -54,7 +72,7 @@ class JavaCodeGeneratorsTest : AbstractTest() { fun `compile generated code`() { writeBuildFile() writePklFile() - + runTask("compileJava") val classesDir = testProjectDir.resolve("build/classes/java/main") @@ -65,11 +83,12 @@ class JavaCodeGeneratorsTest : AbstractTest() { assertThat(personClassFile).exists() assertThat(addressClassFile).exists() } - + @Test fun `no source modules`() { writeFile( - "build.gradle", """ + "build.gradle", + """ plugins { id "org.pkl-lang" } @@ -90,7 +109,8 @@ class JavaCodeGeneratorsTest : AbstractTest() { private fun writeBuildFile() { writeFile( - "build.gradle", """ + "build.gradle", + """ plugins { id "java" id "org.pkl-lang" @@ -125,7 +145,8 @@ class JavaCodeGeneratorsTest : AbstractTest() { private fun writePklFile() { writeFile( - "mod.pkl", """ + "mod.pkl", + """ module org.mod class Person { diff --git a/pkl-gradle/src/test/kotlin/org/pkl/gradle/KotlinCodeGeneratorsTest.kt b/pkl-gradle/src/test/kotlin/org/pkl/gradle/KotlinCodeGeneratorsTest.kt index 8ede4c6e..70488c1c 100644 --- a/pkl-gradle/src/test/kotlin/org/pkl/gradle/KotlinCodeGeneratorsTest.kt +++ b/pkl-gradle/src/test/kotlin/org/pkl/gradle/KotlinCodeGeneratorsTest.kt @@ -1,9 +1,24 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.gradle -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test import kotlin.io.path.listDirectoryEntries import kotlin.io.path.readText +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test class KotlinCodeGeneratorsTest : AbstractTest() { @Test @@ -24,16 +39,15 @@ class KotlinCodeGeneratorsTest : AbstractTest() { // shading must not affect generated code assertThat(text).doesNotContain("org.pkl.thirdparty") - checkTextContains( - text, """ + checkTextContains(text, """ |data class Mod( | val other: Any? |) - """ - ) + """) checkTextContains( - text, """ + text, + """ | data class Person( | val name: String, | val addresses: List
@@ -42,7 +56,8 @@ class KotlinCodeGeneratorsTest : AbstractTest() { ) checkTextContains( - text, """ + text, + """ | open class Address( | open val street: String, | open val zip: Long @@ -65,11 +80,12 @@ class KotlinCodeGeneratorsTest : AbstractTest() { assertThat(personClassFile).exists() assertThat(addressClassFile).exists() } - + @Test fun `no source modules`() { writeFile( - "build.gradle", """ + "build.gradle", + """ plugins { id "org.pkl-lang" } @@ -92,7 +108,8 @@ class KotlinCodeGeneratorsTest : AbstractTest() { val kotlinVersion = "1.6.0" writeFile( - "build.gradle", """ + "build.gradle", + """ buildscript { repositories { mavenCentral() @@ -134,10 +151,11 @@ class KotlinCodeGeneratorsTest : AbstractTest() { """ ) } - + private fun writePklFile() { writeFile( - "mod.pkl", """ + "mod.pkl", + """ module org.mod class Person { diff --git a/pkl-gradle/src/test/kotlin/org/pkl/gradle/PkldocGeneratorsTest.kt b/pkl-gradle/src/test/kotlin/org/pkl/gradle/PkldocGeneratorsTest.kt index 500f665d..f619a607 100644 --- a/pkl-gradle/src/test/kotlin/org/pkl/gradle/PkldocGeneratorsTest.kt +++ b/pkl-gradle/src/test/kotlin/org/pkl/gradle/PkldocGeneratorsTest.kt @@ -1,14 +1,30 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.gradle +import kotlin.io.path.readText import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -import kotlin.io.path.readText class PkldocGeneratorsTest : AbstractTest() { @Test fun `generate docs`() { writeFile( - "build.gradle", """ + "build.gradle", + """ plugins { id "org.pkl-lang" } @@ -25,7 +41,8 @@ class PkldocGeneratorsTest : AbstractTest() { """ ) writeFile( - "doc-package-info.pkl", """ + "doc-package-info.pkl", + """ /// A test package. amends "pkl:DocPackageInfo" name = "test" @@ -34,10 +51,12 @@ class PkldocGeneratorsTest : AbstractTest() { authors { "publisher@apple.com" } sourceCode = "sources.apple.com/" issueTracker = "issues.apple.com" - """.trimIndent() + """ + .trimIndent() ) writeFile( - "person.pkl", """ + "person.pkl", + """ module test.person class Person { @@ -51,7 +70,8 @@ class PkldocGeneratorsTest : AbstractTest() { } other = 42 - """.trimIndent() + """ + .trimIndent() ) runTask("pkldoc") @@ -79,7 +99,8 @@ class PkldocGeneratorsTest : AbstractTest() { @Test fun `no source modules`() { writeFile( - "build.gradle", """ + "build.gradle", + """ plugins { id "org.pkl-lang" } @@ -90,7 +111,8 @@ class PkldocGeneratorsTest : AbstractTest() { } } } - """.trimIndent() + """ + .trimIndent() ) val result = runTask("pkldoc", true) diff --git a/pkl-gradle/src/test/kotlin/org/pkl/gradle/ProjectPackageTest.kt b/pkl-gradle/src/test/kotlin/org/pkl/gradle/ProjectPackageTest.kt index 3cc056aa..7ee9ec1a 100644 --- a/pkl-gradle/src/test/kotlin/org/pkl/gradle/ProjectPackageTest.kt +++ b/pkl-gradle/src/test/kotlin/org/pkl/gradle/ProjectPackageTest.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.gradle import org.assertj.core.api.Assertions.assertThat @@ -13,13 +28,14 @@ class ProjectPackageTest : AbstractTest() { assertThat(testProjectDir.resolve("build/generated/pkl/packages/proj1@1.0.0")).exists() } - @Test fun `custom output dir`() { - writeBuildFile( """ + writeBuildFile( + """ outputPath.set(file("thepackages")) skipPublishCheck.set(true) - """) + """ + ) writeProjectContent() runTask("createMyPackages") assertThat(testProjectDir.resolve("thepackages/proj1@1.0.0.zip")).exists() @@ -28,10 +44,13 @@ class ProjectPackageTest : AbstractTest() { @Test fun `junit dir`() { - writeBuildFile(""" + writeBuildFile( + """ junitReportsDir.set(file("test-reports")) skipPublishCheck.set(true) - """.trimIndent()) + """ + .trimIndent() + ) writeProjectContent() runTask("createMyPackages") assertThat(testProjectDir.resolve("test-reports")).isNotEmptyDirectory() @@ -39,7 +58,8 @@ class ProjectPackageTest : AbstractTest() { private fun writeBuildFile(additionalContents: String = "") { writeFile( - "build.gradle", """ + "build.gradle", + """ plugins { id "org.pkl-lang" } @@ -60,7 +80,9 @@ class ProjectPackageTest : AbstractTest() { } private fun writeProjectContent() { - writeFile("proj1/PklProject", """ + writeFile( + "proj1/PklProject", + """ amends "pkl:Project" package { @@ -72,19 +94,31 @@ class ProjectPackageTest : AbstractTest() { "tests.pkl" } } - """.trimIndent()) - writeFile("proj1/PklProject.deps.json", """ + """ + .trimIndent() + ) + writeFile( + "proj1/PklProject.deps.json", + """ { "schemaVersion": 1, "dependencies": {} } - """.trimIndent()) - writeFile("proj1/foo.pkl", """ + """ + .trimIndent() + ) + writeFile( + "proj1/foo.pkl", + """ module proj1.foo bar: String - """.trimIndent()) - writeFile("proj1/tests.pkl", """ + """ + .trimIndent() + ) + writeFile( + "proj1/tests.pkl", + """ amends "pkl:test" facts { @@ -92,7 +126,9 @@ class ProjectPackageTest : AbstractTest() { 1 == 1 } } - """.trimIndent()) + """ + .trimIndent() + ) writeFile("foo.txt", "The contents of foo.txt") } } diff --git a/pkl-gradle/src/test/kotlin/org/pkl/gradle/ProjectResolveTest.kt b/pkl-gradle/src/test/kotlin/org/pkl/gradle/ProjectResolveTest.kt index 0eb58f96..2dfb055b 100644 --- a/pkl-gradle/src/test/kotlin/org/pkl/gradle/ProjectResolveTest.kt +++ b/pkl-gradle/src/test/kotlin/org/pkl/gradle/ProjectResolveTest.kt @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.gradle import org.assertj.core.api.Assertions.assertThat @@ -9,17 +24,22 @@ class ProjectResolveTest : AbstractTest() { writeBuildFile() writeProjectContent() runTask("resolveMyProj") - assertThat(testProjectDir.resolve("proj1/PklProject.deps.json")).hasContent(""" + assertThat(testProjectDir.resolve("proj1/PklProject.deps.json")) + .hasContent( + """ { "schemaVersion": 1, "resolvedDependencies": {} } - """.trimIndent()) + """ + .trimIndent() + ) } private fun writeBuildFile(additionalContents: String = "") { writeFile( - "build.gradle", """ + "build.gradle", + """ plugins { id "org.pkl-lang" } @@ -40,8 +60,12 @@ class ProjectResolveTest : AbstractTest() { } private fun writeProjectContent() { - writeFile("proj1/PklProject", """ + writeFile( + "proj1/PklProject", + """ amends "pkl:Project" - """.trimIndent()) + """ + .trimIndent() + ) } } diff --git a/pkl-gradle/src/test/kotlin/org/pkl/gradle/TestsTest.kt b/pkl-gradle/src/test/kotlin/org/pkl/gradle/TestsTest.kt index 769ec540..b5a77a95 100644 --- a/pkl-gradle/src/test/kotlin/org/pkl/gradle/TestsTest.kt +++ b/pkl-gradle/src/test/kotlin/org/pkl/gradle/TestsTest.kt @@ -1,10 +1,25 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.pkl.gradle -import org.assertj.core.api.Assertions.assertThat -import org.pkl.commons.toNormalizedPathString -import org.junit.jupiter.api.Test import java.nio.file.Path import kotlin.io.path.readText +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test +import org.pkl.commons.toNormalizedPathString class TestsTest : AbstractTest() { @@ -22,12 +37,16 @@ class TestsTest : AbstractTest() { fun `facts fail`() { writeBuildFile() - writePklFile(additionalFacts = """ + writePklFile( + additionalFacts = + """ ["should fail"] { 1 == 3 "foo" == "bar" } - """.trimIndent()) + """ + .trimIndent() + ) val res = runTask("evalTest", expectFailure = true) assertThat(res.output).contains("should fail ❌") @@ -39,15 +58,21 @@ class TestsTest : AbstractTest() { fun error() { writeBuildFile() - writePklFile(additionalFacts = """ + writePklFile( + additionalFacts = + """ ["error"] { throw("exception") } - """.trimIndent()) + """ + .trimIndent() + ) val output = runTask("evalTest", expectFailure = true).output.stripFilesAndLines() - assertThat(output).contains(""" + assertThat(output) + .contains( + """ module test (file:///file, line x) test ❌ Error: @@ -61,7 +86,9 @@ class TestsTest : AbstractTest() { 3 | facts { ^^^^^^^ at test#facts (file:///file, line x) - """.trimIndent()) + """ + .trimIndent() + ) } @Test @@ -73,7 +100,9 @@ class TestsTest : AbstractTest() { val output = runTask("evalTest", expectFailure = true).output.stripFilesAndLines() - assertThat(output.trimStart()).contains(""" + assertThat(output.trimStart()) + .contains( + """ module test (file:///file, line x) sum numbers ✅ divide numbers ✅ @@ -105,12 +134,16 @@ class TestsTest : AbstractTest() { name = "Welma" age = 35 } - """.trimIndent()) + """ + .trimIndent() + ) } @Test fun `overwrite expected examples`() { - writePklFile(additionalExamples = """ + writePklFile( + additionalExamples = + """ ["user 0"] { new { name = "Cool" @@ -127,7 +160,9 @@ class TestsTest : AbstractTest() { age = 35 } } - """.trimIndent()) + """ + .trimIndent() + ) writeFile("test.pkl-expected.pcf", bigTestExpected) writeBuildFile("overwrite = true") @@ -150,7 +185,9 @@ class TestsTest : AbstractTest() { val outputFile = testProjectDir.resolve("build/test.xml") val report = outputFile.readText().stripFilesAndLines() - assertThat(report).isEqualTo(""" + assertThat(report) + .isEqualTo( + """ @@ -190,10 +227,13 @@ class TestsTest : AbstractTest() { ]]> - """.trimIndent()) + """ + .trimIndent() + ) } - private val bigTest = """ + private val bigTest = + """ amends "pkl:test" local function sum(a, b) = a + b @@ -231,9 +271,11 @@ class TestsTest : AbstractTest() { } } } - """.trimIndent() + """ + .trimIndent() - private val bigTestExpected = """ + private val bigTestExpected = + """ examples { ["user 0"] { new { @@ -252,11 +294,13 @@ class TestsTest : AbstractTest() { } } } - """.trimIndent() + """ + .trimIndent() private fun writeBuildFile(additionalContents: String = "") { writeFile( - "build.gradle", """ + "build.gradle", + """ plugins { id "org.pkl-lang" } @@ -277,7 +321,8 @@ class TestsTest : AbstractTest() { private fun writePklFile( additionalFacts: String = "", additionalExamples: String = "", - contents: String = """ + contents: String = + """ amends "pkl:test" facts { diff --git a/pkl-server/pkl-server.gradle.kts b/pkl-server/pkl-server.gradle.kts index b7c32902..5ae810e7 100644 --- a/pkl-server/pkl-server.gradle.kts +++ b/pkl-server/pkl-server.gradle.kts @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ plugins { pklAllProjects pklJavaLibrary @@ -15,10 +30,12 @@ dependencies { } tasks.test { - inputs.dir("src/test/files/SnippetTests/input") + inputs + .dir("src/test/files/SnippetTests/input") .withPropertyName("snippetTestsInput") .withPathSensitivity(PathSensitivity.RELATIVE) - inputs.dir("src/test/files/SnippetTests/output") + inputs + .dir("src/test/files/SnippetTests/output") .withPropertyName("snippetTestsOutput") .withPathSensitivity(PathSensitivity.RELATIVE) exclude("**/NativeServerTest.*") @@ -30,37 +47,44 @@ private fun Test.configureNativeTest() { include("**/NativeServerTest.*") } -val testMacExecutableAarch64 by tasks.registering(Test::class) { - dependsOn(":pkl-cli:macExecutableAarch64") - configureNativeTest() -} +val testMacExecutableAarch64 by + tasks.registering(Test::class) { + dependsOn(":pkl-cli:macExecutableAarch64") + configureNativeTest() + } -val testMacExecutableAmd64 by tasks.registering(Test::class) { - dependsOn(":pkl-cli:macExecutableAmd64") - configureNativeTest() -} +val testMacExecutableAmd64 by + tasks.registering(Test::class) { + dependsOn(":pkl-cli:macExecutableAmd64") + configureNativeTest() + } -val testLinuxExecutableAmd64 by tasks.registering(Test::class) { - dependsOn(":pkl-cli:linuxExecutableAmd64") - configureNativeTest() -} +val testLinuxExecutableAmd64 by + tasks.registering(Test::class) { + dependsOn(":pkl-cli:linuxExecutableAmd64") + configureNativeTest() + } -val testLinuxExecutableAarch64 by tasks.registering(Test::class) { - dependsOn(":pkl-cli:linuxExecutableAarch64") - configureNativeTest() -} +val testLinuxExecutableAarch64 by + tasks.registering(Test::class) { + dependsOn(":pkl-cli:linuxExecutableAarch64") + configureNativeTest() + } -val testAlpineExecutableAmd64 by tasks.registering(Test::class) { - dependsOn(":pkl-cli:alpineExecutableAmd64") - configureNativeTest() -} +val testAlpineExecutableAmd64 by + tasks.registering(Test::class) { + dependsOn(":pkl-cli:alpineExecutableAmd64") + configureNativeTest() + } -val testWindowsExecutableAmd64 by tasks.registering(Test::class) { - dependsOn(":pkl-cli:windowsExecutableAmd64") - configureNativeTest() -} +val testWindowsExecutableAmd64 by + tasks.registering(Test::class) { + dependsOn(":pkl-cli:windowsExecutableAmd64") + configureNativeTest() + } val testNative by tasks.existing + testNative { when { buildInfo.os.isMacOsX -> { diff --git a/pkl-tools/pkl-tools.gradle.kts b/pkl-tools/pkl-tools.gradle.kts index 6abfdfb3..8f6c7e79 100644 --- a/pkl-tools/pkl-tools.gradle.kts +++ b/pkl-tools/pkl-tools.gradle.kts @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ import java.nio.charset.StandardCharsets import java.util.* @@ -11,11 +26,11 @@ val dummy: SourceSet by sourceSets.creating val firstPartySourcesJars by configurations.existing -// Note: pkl-tools cannot (easily) contain pkl-config-kotlin +// Note: pkl-tools cannot (easily) contain pkl-config-kotlin // because pkl-tools ships with a shaded Kotlin stdlib. dependencies { - // Use scope `api` so that other subprojects - // can declare a normal project dependency on this project, + // Use scope `api` so that other subprojects + // can declare a normal project dependency on this project, // which is desirable for IntelliJ integration. // The published fat JAR doesn't declare any dependencies. api(projects.pklCli) @@ -24,7 +39,7 @@ dependencies { api(projects.pklConfigJava) api(projects.pklCore) api(projects.pklDoc) - + // used by `pklFatJar` plugin (ideally this would be inferred automatically) firstPartySourcesJars(project(":pkl-cli", "sourcesJar")) firstPartySourcesJars(project(":pkl-codegen-java", "sourcesJar")) @@ -36,22 +51,17 @@ dependencies { // TODO: need to figure out how to properly generate javadoc here. // For now, we'll include a dummy javadoc jar. -val javadocDummy by tasks.creating(Javadoc::class) { - source = dummy.allJava -} +val javadocDummy by tasks.creating(Javadoc::class) { source = dummy.allJava } -java { - withJavadocJar() -} +java { withJavadocJar() } -val javadocJar by tasks.existing(Jar::class) { - from(javadocDummy.outputs.files) - archiveBaseName.set("pkl-tools-all") -} +val javadocJar by + tasks.existing(Jar::class) { + from(javadocDummy.outputs.files) + archiveBaseName.set("pkl-tools-all") + } -tasks.shadowJar { - archiveBaseName.set("pkl-tools-all") -} +tasks.shadowJar { archiveBaseName.set("pkl-tools-all") } publishing { publications { @@ -59,14 +69,14 @@ publishing { // don't use `-all` suffix because this is the only JAR we publish artifactId = "pkl-tools" // add dummy javadoc jar to publication - artifact(javadocJar.flatMap { it.archiveFile }) { - classifier = "javadoc" - } + artifact(javadocJar.flatMap { it.archiveFile }) { classifier = "javadoc" } pom { url.set("https://github.com/apple/pkl/tree/main/pkl-tools") - description.set("Fat Jar containing pkl-cli, pkl-codegen-java, " + - "pkl-codegen-kotlin, pkl-config-java, pkl-core, pkl-doc, " + - "and their shaded third-party dependencies.") + description.set( + "Fat Jar containing pkl-cli, pkl-codegen-java, " + + "pkl-codegen-kotlin, pkl-config-java, pkl-core, pkl-doc, " + + "and their shaded third-party dependencies." + ) name.set(artifactId) // keep in sync with pklPublishLibrary licenses { @@ -104,8 +114,10 @@ publishing { signing { // provided as env vars `ORG_GRADLE_PROJECT_signingKey` and `ORG_GRADLE_PROJECT_signingPassword` // in CI. - val signingKey = (findProperty("signingKey") as String?) - ?.let { Base64.getDecoder().decode(it).toString(StandardCharsets.US_ASCII) } + val signingKey = + (findProperty("signingKey") as String?)?.let { + Base64.getDecoder().decode(it).toString(StandardCharsets.US_ASCII) + } val signingPassword = findProperty("signingPassword") as String? if (signingKey != null && signingPassword != null) { useInMemoryPgpKeys(signingKey, signingPassword) diff --git a/settings.gradle.kts b/settings.gradle.kts index 521a2785..9b9e91ff 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1,22 +1,52 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ rootProject.name = "pkl" include("bench") + include("docs") + include("stdlib") include("pkl-cli") + include("pkl-codegen-java") + include("pkl-codegen-kotlin") + include("pkl-commons") + include("pkl-commons-cli") + include("pkl-commons-test") + include("pkl-config-java") + include("pkl-config-kotlin") + include("pkl-core") + include("pkl-doc") + include("pkl-gradle") + include("pkl-executor") + include("pkl-tools") + include("pkl-server") pluginManagement { @@ -26,20 +56,17 @@ pluginManagement { } } -@Suppress("UnstableApiUsage") -dependencyResolutionManagement { - repositories { - mavenCentral() - } -} +@Suppress("UnstableApiUsage") dependencyResolutionManagement { repositories { mavenCentral() } } val javaVersion = JavaVersion.current() + require(javaVersion.isCompatibleWith(JavaVersion.VERSION_17)) { "Project requires Java 17 or higher, but found ${javaVersion.majorVersion}." } -if (gradle.startParameter.taskNames.contains("updateDependencyLocks") || - gradle.startParameter.taskNames.contains("uDL") +if ( + gradle.startParameter.taskNames.contains("updateDependencyLocks") || + gradle.startParameter.taskNames.contains("uDL") ) { gradle.startParameter.isWriteDependencyLocks = true } diff --git a/stdlib/stdlib.gradle.kts b/stdlib/stdlib.gradle.kts index 4f0159ce..0f660d93 100644 --- a/stdlib/stdlib.gradle.kts +++ b/stdlib/stdlib.gradle.kts @@ -1,3 +1,18 @@ +/** + * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ plugins { pklAllProjects base @@ -9,18 +24,18 @@ plugins { // create and publish a self-contained stdlib archive // purpose is to provide non-jvm tools/projects with a versioned stdlib -val stdlibZip by tasks.registering(Zip::class) { - destinationDirectory.set(layout.buildDirectory.dir("libs")) - archiveBaseName.set("pkl-stdlib") - archiveVersion.set(project.version as String) - into("org/pkl/stdlib") { - from(projectDir) - include("*.pkl") +val stdlibZip by + tasks.registering(Zip::class) { + destinationDirectory.set(layout.buildDirectory.dir("libs")) + archiveBaseName.set("pkl-stdlib") + archiveVersion.set(project.version as String) + into("org/pkl/stdlib") { + from(projectDir) + include("*.pkl") + } } -} -tasks.assemble { - dependsOn(stdlibZip) -} + +tasks.assemble { dependsOn(stdlibZip) } publishing { publications { @@ -35,13 +50,14 @@ publishing { } } -signing { - sign(publishing.publications["stdlib"]) -} +signing { sign(publishing.publications["stdlib"]) } spotless { format("pkl") { target("*.pkl") - licenseHeaderFile(rootProject.file("buildSrc/src/main/resources/license-header.line-comment.txt"), "/// ") + licenseHeaderFile( + rootProject.file("buildSrc/src/main/resources/license-header.line-comment.txt"), + "/// " + ) } }