From 48f9a9b982da245d494b5e90b917eeaed2e03f53 Mon Sep 17 00:00:00 2001 From: Adam <897017+aSemy@users.noreply.github.com> Date: Thu, 1 Oct 2026 12:50:05 +0200 Subject: [PATCH 1/3] Add `dev-publish-common`, for shared code - `DevPublishMetadata` - constants for the metadata file. - `DevPublishInternalApi` - shared between the plugin and test-utils. (test-utils will be created in the next commit) --- build.gradle.kts | 1 + .../conventions/kotlin-jvm-library.gradle.kts | 60 +++++++++++++++++++ .../api/dev-publish-common.api | 3 + modules/dev-publish-common/build.gradle.kts | 31 ++++++++++ .../internal/DevPublishInternalApi.kt | 0 .../internal/DevPublishMetadata.kt | 16 +++++ .../api/dev-publish-plugin.api | 3 - modules/dev-publish-plugin/build.gradle.kts | 7 ++- settings.gradle.kts | 1 + 9 files changed, 117 insertions(+), 5 deletions(-) create mode 100644 buildSrc/src/main/kotlin/buildsrc/conventions/kotlin-jvm-library.gradle.kts create mode 100644 modules/dev-publish-common/api/dev-publish-common.api create mode 100644 modules/dev-publish-common/build.gradle.kts rename modules/{dev-publish-plugin/src/main/kotlin => dev-publish-common/src/main/kotlin/dev/adamko/gradle/dev_publish}/internal/DevPublishInternalApi.kt (100%) create mode 100644 modules/dev-publish-common/src/main/kotlin/dev/adamko/gradle/dev_publish/internal/DevPublishMetadata.kt diff --git a/build.gradle.kts b/build.gradle.kts index 8706bee..7cee82b 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -15,6 +15,7 @@ val mavenPublishing = extensions.create(MavenPublishingSettings.EXTENSION_NAME, project) dependencies { + nmcpAggregation(projects.modules.devPublishCommon) nmcpAggregation(projects.modules.devPublishPlugin) } diff --git a/buildSrc/src/main/kotlin/buildsrc/conventions/kotlin-jvm-library.gradle.kts b/buildSrc/src/main/kotlin/buildsrc/conventions/kotlin-jvm-library.gradle.kts new file mode 100644 index 0000000..90726fc --- /dev/null +++ b/buildSrc/src/main/kotlin/buildsrc/conventions/kotlin-jvm-library.gradle.kts @@ -0,0 +1,60 @@ +package buildsrc.conventions + +import org.gradle.api.attributes.Bundling.BUNDLING_ATTRIBUTE +import org.gradle.api.attributes.Category.CATEGORY_ATTRIBUTE +import org.gradle.api.attributes.DocsType.DOCS_TYPE_ATTRIBUTE +import org.gradle.api.attributes.Usage.USAGE_ATTRIBUTE +import org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi +import org.jetbrains.kotlin.gradle.dsl.abi.ExperimentalAbiValidation +import provideDelegate +import registering + +plugins { + id("buildsrc.conventions.base") + id("buildsrc.conventions.java-base") + id("org.jetbrains.kotlin.jvm") + id("buildsrc.conventions.maven-publishing") +} + +kotlin { + jvmToolchain(17) + @OptIn(ExperimentalAbiValidation::class) + abiValidation {} + compilerOptions { + optIn.addAll( + "kotlin.io.path.ExperimentalPathApi", + ) + } +} + +val javadocJar by tasks.registering(Jar::class) { + archiveClassifier.set("javadoc") + from(tasks.named("createJavadocJarReadme")) +} + +val javadocElements by configurations.consumable { + attributes { + attribute(USAGE_ATTRIBUTE, objects.named(Usage.JAVA_RUNTIME)) + attribute(CATEGORY_ATTRIBUTE, objects.named(Category.DOCUMENTATION)) + attribute(BUNDLING_ATTRIBUTE, objects.named(Bundling.EXTERNAL)) + attribute(DOCS_TYPE_ATTRIBUTE, objects.named(DocsType.JAVADOC)) + } + outgoing.artifact(javadocJar) +} + +kotlin { + @OptIn(ExperimentalKotlinGradlePluginApi::class) + publishing.adhocSoftwareComponent { + addVariantsFromConfiguration(javadocElements) { + mapToOptional() + } + } +} + +publishing { + publications { + register("mavenJava") { + from(components["java"]) + } + } +} diff --git a/modules/dev-publish-common/api/dev-publish-common.api b/modules/dev-publish-common/api/dev-publish-common.api new file mode 100644 index 0000000..e7a6e58 --- /dev/null +++ b/modules/dev-publish-common/api/dev-publish-common.api @@ -0,0 +1,3 @@ +public abstract interface annotation class dev/adamko/gradle/dev_publish/internal/DevPublishInternalApi : java/lang/annotation/Annotation { +} + diff --git a/modules/dev-publish-common/build.gradle.kts b/modules/dev-publish-common/build.gradle.kts new file mode 100644 index 0000000..eeaa857 --- /dev/null +++ b/modules/dev-publish-common/build.gradle.kts @@ -0,0 +1,31 @@ +@file:Suppress("UnstableApiUsage") + +import org.jetbrains.kotlin.gradle.dsl.abi.ExperimentalAbiValidation + +plugins { + buildsrc.conventions.`kotlin-jvm-library` +} + +description = "Common code shared between DevPublish libraries." + +publishing { + repositories { + maven(isolated.rootProject.projectDirectory.dir("build/test-maven-repo")) { + name = "TestMavenRepo" + } + } +} + +kotlin { + compilerOptions { + optIn.addAll( + "dev.adamko.gradle.dev_publish.internal.DevPublishInternalApi", + ) + } + @OptIn(ExperimentalAbiValidation::class) + abiValidation { + filters { + exclude { annotatedWith.add("dev.adamko.gradle.dev_publish.internal.DevPublishInternalApi") } + } + } +} diff --git a/modules/dev-publish-plugin/src/main/kotlin/internal/DevPublishInternalApi.kt b/modules/dev-publish-common/src/main/kotlin/dev/adamko/gradle/dev_publish/internal/DevPublishInternalApi.kt similarity index 100% rename from modules/dev-publish-plugin/src/main/kotlin/internal/DevPublishInternalApi.kt rename to modules/dev-publish-common/src/main/kotlin/dev/adamko/gradle/dev_publish/internal/DevPublishInternalApi.kt diff --git a/modules/dev-publish-common/src/main/kotlin/dev/adamko/gradle/dev_publish/internal/DevPublishMetadata.kt b/modules/dev-publish-common/src/main/kotlin/dev/adamko/gradle/dev_publish/internal/DevPublishMetadata.kt new file mode 100644 index 0000000..cb9baa5 --- /dev/null +++ b/modules/dev-publish-common/src/main/kotlin/dev/adamko/gradle/dev_publish/internal/DevPublishMetadata.kt @@ -0,0 +1,16 @@ +package dev.adamko.gradle.dev_publish.internal + +/** + * The metadata file that the DevPublish Gradle plugin writes, and `dev-publish-utils` reads back + * inside a test JVM. + */ +@DevPublishInternalApi +object DevPublishMetadata { + + /** + * File containing the relative path to the dev-maven repo. + * + * The path is relative to the _parent directory_ of the metadata file. + */ + const val REPO_LOCATION_FILE_NAME = "dev.publish.metadata.repo-location.txt" +} diff --git a/modules/dev-publish-plugin/api/dev-publish-plugin.api b/modules/dev-publish-plugin/api/dev-publish-plugin.api index d811b5f..5acb30d 100644 --- a/modules/dev-publish-plugin/api/dev-publish-plugin.api +++ b/modules/dev-publish-plugin/api/dev-publish-plugin.api @@ -25,9 +25,6 @@ public abstract class dev/adamko/gradle/dev_publish/data/PublicationData : org/g public fun getName ()Ljava/lang/String; } -public abstract interface annotation class dev/adamko/gradle/dev_publish/internal/DevPublishInternalApi : java/lang/annotation/Annotation { -} - public abstract class dev/adamko/gradle/dev_publish/tasks/BaseDevPublishTask : org/gradle/api/DefaultTask { public static final field Companion Ldev/adamko/gradle/dev_publish/tasks/BaseDevPublishTask$Companion; public static final field TASK_GROUP Ljava/lang/String; diff --git a/modules/dev-publish-plugin/build.gradle.kts b/modules/dev-publish-plugin/build.gradle.kts index 05f6caa..c1c78b3 100644 --- a/modules/dev-publish-plugin/build.gradle.kts +++ b/modules/dev-publish-plugin/build.gradle.kts @@ -10,6 +10,8 @@ plugins { } dependencies { + implementation(projects.modules.devPublishCommon) + testFixturesApi(gradleTestKit()) testFixturesApi(platform(libs.kotest.bom)) testFixturesApi(libs.kotest.runnerJUnit5) @@ -62,7 +64,7 @@ gradlePlugin { } } -val testMavenRepoDir: Provider = layout.buildDirectory.dir("test-maven-repo") +val testMavenRepoDir: Directory = isolated.rootProject.projectDirectory.dir("build/test-maven-repo") val projectTestTempDir: Provider = layout.buildDirectory.dir("project-tests") publishing { @@ -77,6 +79,7 @@ skipTestFixturesPublications() tasks.withType().configureEach { dependsOn("publishAllPublicationsToTestMavenRepoRepository") - systemProperty("testMavenRepoDir", testMavenRepoDir.get().asFile.invariantSeparatorsPath) + dependsOn(":modules:dev-publish-common:publishAllPublicationsToTestMavenRepoRepository") + systemProperty("testMavenRepoDir", testMavenRepoDir.asFile.invariantSeparatorsPath) systemProperty("projectTestTempDir", projectTestTempDir.get().asFile.invariantSeparatorsPath) } diff --git a/settings.gradle.kts b/settings.gradle.kts index 4b73352..ecdf71b 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -20,5 +20,6 @@ enableFeaturePreview("TYPESAFE_PROJECT_ACCESSORS") enableFeaturePreview("STABLE_CONFIGURATION_CACHE") include( + ":modules:dev-publish-common", ":modules:dev-publish-plugin", ) From 4a8f1b04a6e81bd68d17353adfd07bca7fecad9b Mon Sep 17 00:00:00 2001 From: Adam <897017+aSemy@users.noreply.github.com> Date: Thu, 1 Oct 2026 12:51:57 +0200 Subject: [PATCH 2/3] Add `dev-publish-utils`, for reading the dev repo from a test JVM A utility library for users of DevPublish. It finds the dev Maven repository from the test runtime classpath, and generates the `repositories {}` and `pluginManagement {}` blocks a test project needs, in either the Kotlin or the Groovy DSL. Nothing wires it up yet: the plugin will use it when the `devPublish.dependency()` util is added in the next commit. --- build.gradle.kts | 1 + modules/dev-publish-plugin/build.gradle.kts | 2 + .../api/dev-publish-utils.api | 33 +++ modules/dev-publish-utils/build.gradle.kts | 21 ++ .../gradle/dev_publish/DevPublishTestKit.kt | 251 +++++++++++++++++ .../src/test/kotlin/DevPublishTestKitTest.kt | 259 ++++++++++++++++++ settings.gradle.kts | 1 + 7 files changed, 568 insertions(+) create mode 100644 modules/dev-publish-utils/api/dev-publish-utils.api create mode 100644 modules/dev-publish-utils/build.gradle.kts create mode 100644 modules/dev-publish-utils/src/main/kotlin/dev/adamko/gradle/dev_publish/DevPublishTestKit.kt create mode 100644 modules/dev-publish-utils/src/test/kotlin/DevPublishTestKitTest.kt diff --git a/build.gradle.kts b/build.gradle.kts index 7cee82b..bd8834d 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -17,6 +17,7 @@ val mavenPublishing = dependencies { nmcpAggregation(projects.modules.devPublishCommon) nmcpAggregation(projects.modules.devPublishPlugin) + nmcpAggregation(projects.modules.devPublishUtils) } nmcpAggregation { diff --git a/modules/dev-publish-plugin/build.gradle.kts b/modules/dev-publish-plugin/build.gradle.kts index c1c78b3..3da45ea 100644 --- a/modules/dev-publish-plugin/build.gradle.kts +++ b/modules/dev-publish-plugin/build.gradle.kts @@ -12,6 +12,8 @@ plugins { dependencies { implementation(projects.modules.devPublishCommon) + testFixturesImplementation(projects.modules.devPublishCommon) + testFixturesApi(gradleTestKit()) testFixturesApi(platform(libs.kotest.bom)) testFixturesApi(libs.kotest.runnerJUnit5) diff --git a/modules/dev-publish-utils/api/dev-publish-utils.api b/modules/dev-publish-utils/api/dev-publish-utils.api new file mode 100644 index 0000000..69fd7cd --- /dev/null +++ b/modules/dev-publish-utils/api/dev-publish-utils.api @@ -0,0 +1,33 @@ +public final class dev/adamko/gradle/dev_publish/DevPublishTestKit { + public static final fun devMavenRepo ()Ljava/nio/file/Path; + public static final fun devPublishDependencyResolutionManagement ()Ljava/lang/String; + public static final fun devPublishDependencyResolutionManagement (Ljava/nio/file/Path;)Ljava/lang/String; + public static final fun devPublishDependencyResolutionManagement (Ljava/nio/file/Path;Z)Ljava/lang/String; + public static final fun devPublishDependencyResolutionManagement (Ljava/nio/file/Path;ZLdev/adamko/gradle/dev_publish/ScriptDsl;)Ljava/lang/String; + public static synthetic fun devPublishDependencyResolutionManagement$default (Ljava/nio/file/Path;ZLdev/adamko/gradle/dev_publish/ScriptDsl;ILjava/lang/Object;)Ljava/lang/String; + public static final fun devPublishPluginManagement ()Ljava/lang/String; + public static final fun devPublishPluginManagement (Ljava/nio/file/Path;)Ljava/lang/String; + public static final fun devPublishPluginManagement (Ljava/nio/file/Path;Z)Ljava/lang/String; + public static final fun devPublishPluginManagement (Ljava/nio/file/Path;ZZ)Ljava/lang/String; + public static final fun devPublishPluginManagement (Ljava/nio/file/Path;ZZLdev/adamko/gradle/dev_publish/ScriptDsl;)Ljava/lang/String; + public static synthetic fun devPublishPluginManagement$default (Ljava/nio/file/Path;ZZLdev/adamko/gradle/dev_publish/ScriptDsl;ILjava/lang/Object;)Ljava/lang/String; + public static final fun devPublishRepository ()Ljava/lang/String; + public static final fun devPublishRepository (Ljava/nio/file/Path;)Ljava/lang/String; + public static final fun devPublishRepository (Ljava/nio/file/Path;Ldev/adamko/gradle/dev_publish/ScriptDsl;)Ljava/lang/String; + public static synthetic fun devPublishRepository$default (Ljava/nio/file/Path;Ldev/adamko/gradle/dev_publish/ScriptDsl;ILjava/lang/Object;)Ljava/lang/String; + public static final fun devPublishSettings ()Ljava/lang/String; + public static final fun devPublishSettings (Ljava/lang/String;)Ljava/lang/String; + public static final fun devPublishSettings (Ljava/lang/String;Ljava/nio/file/Path;)Ljava/lang/String; + public static final fun devPublishSettings (Ljava/lang/String;Ljava/nio/file/Path;Ldev/adamko/gradle/dev_publish/ScriptDsl;)Ljava/lang/String; + public static synthetic fun devPublishSettings$default (Ljava/lang/String;Ljava/nio/file/Path;Ldev/adamko/gradle/dev_publish/ScriptDsl;ILjava/lang/Object;)Ljava/lang/String; +} + +public abstract class dev/adamko/gradle/dev_publish/ScriptDsl { + public static final field Companion Ldev/adamko/gradle/dev_publish/ScriptDsl$Companion; + public static final field Groovy Ldev/adamko/gradle/dev_publish/ScriptDsl; + public static final field Kotlin Ldev/adamko/gradle/dev_publish/ScriptDsl; +} + +public final class dev/adamko/gradle/dev_publish/ScriptDsl$Companion { +} + diff --git a/modules/dev-publish-utils/build.gradle.kts b/modules/dev-publish-utils/build.gradle.kts new file mode 100644 index 0000000..a80666c --- /dev/null +++ b/modules/dev-publish-utils/build.gradle.kts @@ -0,0 +1,21 @@ +plugins { + buildsrc.conventions.`kotlin-jvm-library` +} + +description = "Helpers for reading the DevPublish dev Maven repository from a test JVM." + +dependencies { + implementation(projects.modules.devPublishCommon) + + testImplementation(platform(libs.kotest.bom)) + testImplementation(libs.kotest.runnerJUnit5) + testImplementation(libs.kotest.assertionsCore) +} + +kotlin { + compilerOptions { + optIn.addAll( + "dev.adamko.gradle.dev_publish.internal.DevPublishInternalApi", + ) + } +} diff --git a/modules/dev-publish-utils/src/main/kotlin/dev/adamko/gradle/dev_publish/DevPublishTestKit.kt b/modules/dev-publish-utils/src/main/kotlin/dev/adamko/gradle/dev_publish/DevPublishTestKit.kt new file mode 100644 index 0000000..1e0cc67 --- /dev/null +++ b/modules/dev-publish-utils/src/main/kotlin/dev/adamko/gradle/dev_publish/DevPublishTestKit.kt @@ -0,0 +1,251 @@ +@file:JvmName("DevPublishTestKit") + +package dev.adamko.gradle.dev_publish + +import dev.adamko.gradle.dev_publish.internal.DevPublishMetadata.REPO_LOCATION_FILE_NAME +import java.io.BufferedReader +import java.nio.file.Path +import kotlin.io.path.* +import kotlin.text.Charsets.UTF_8 + +/** Name of the repository declared in the generated scripts. */ +private const val REPO_NAME = "DevMavenRepo" + +/** Script language of the generated scripts. */ +sealed class ScriptDsl { + companion object { + @JvmField + val Kotlin: ScriptDsl = KotlinInternal + @JvmField + val Groovy: ScriptDsl = GroovyInternal + } + + internal data object KotlinInternal : ScriptDsl() + internal data object GroovyInternal : ScriptDsl() +} + +/** + * The location of the dev Maven repository. + * + * Declare `dependencies { implementation(devPublish.dependency()) }` in the build script, and this + * reads the location from the metadata file that declaration puts on the runtime classpath. + */ +fun devMavenRepo(): Path { + return when (val fromClasspath = devMavenRepoFromClasspath()) { + is DevRepoFromClasspathResult.DevMavenRepo -> fromClasspath.path + is DevRepoFromClasspathResult.Failure -> error( + "The dev Maven repository could not be located. " + fromClasspath.message + ) + } +} + +/** + * Read the dev Maven repository location from the metadata file that + * `dependencies { implementation(devPublish.dependency()) }` puts on the runtime classpath. + * + * Must also discover the location of the metadata file on the runtime classpath, + * because the dev-maven repo is a relative path relative to the metadata file. + */ +private fun devMavenRepoFromClasspath(): DevRepoFromClasspathResult { + val resourcePath = "/$REPO_LOCATION_FILE_NAME" + + val addTheDependency = + "Add it to this test's runtime classpath with " + + "`dependencies { implementation(devPublish.dependency()) }`." + + val devPublishRelativeLocation = + {}::class.java.getResourceAsStream(resourcePath) + ?.bufferedReader(UTF_8) + ?.use(BufferedReader::readText) + ?: return DevRepoFromClasspathResult.Failure( + "getResourceAsStream could not find $resourcePath in the runtime classpath. $addTheDependency" + ) + + val devPublishActualLocation = + {}::class.java.getResource(resourcePath) + ?: return DevRepoFromClasspathResult.Failure( + "getResource could not find $resourcePath in the runtime classpath. $addTheDependency" + ) + + if (devPublishActualLocation.protocol != "file") + return DevRepoFromClasspathResult.Failure( + "The dev Maven repository metadata was found at $devPublishActualLocation, which is not a file on disk, " + + "so the recorded location '$devPublishRelativeLocation' cannot be resolved against it. " + + "DevPublish expects the metadata to be a directory on the runtime classpath." + ) + + val metadataDir = devPublishActualLocation.toURI().toPath().parent + + val devMavenRepo = metadataDir + .resolve(devPublishRelativeLocation) + .normalize() + + // the recorded path is relative, so a stale or misconfigured one resolves to a plausible-looking + // directory that simply is not there - report that here, not later as a missing artifact + if (!devMavenRepo.exists()) { + return DevRepoFromClasspathResult.Failure( + "The location was recorded as '$devPublishRelativeLocation', relative to " + + "${metadataDir.invariantSeparatorsPathString}, but nothing exists at " + + "${devMavenRepo.invariantSeparatorsPathString}. " + + "Run the `updateDevRepo` task to create it." + ) + } + + return DevRepoFromClasspathResult.DevMavenRepo(devMavenRepo) +} + +private sealed interface DevRepoFromClasspathResult { + @JvmInline + value class DevMavenRepo(val path: Path) : DevRepoFromClasspathResult + @JvmInline + value class Failure(val message: String) : DevRepoFromClasspathResult +} + +/** + * An `exclusiveContent { }` block for the dev Maven repository, to be placed inside a + * `repositories { }` block. + * + * The groups are derived from the publications actually present in [devMavenRepo], so a Gradle + * plugin's Plugin Marker Artifact and its implementation are both covered without either having to + * be named. + */ +@JvmOverloads +fun devPublishRepository( + devMavenRepo: Path = devMavenRepo(), + scriptDsl: ScriptDsl = ScriptDsl.Kotlin, +): String { + val groups = publishedGroups(devMavenRepo) + + if (groups.isEmpty()) { + error( + "No publications found in the dev Maven repository " + + "${devMavenRepo.invariantSeparatorsPathString}. " + + "Did the test task depend on `updateDevRepo`? " + + "Declaring `implementation(devPublish.dependency())` wires that up." + ) + } + + val repoUrl = devMavenRepo.invariantSeparatorsPathString.asQuotedString(scriptDsl) + val repoName = REPO_NAME.asQuotedString(scriptDsl) + + return buildString { + appendLine("exclusiveContent {") + appendLine(" forRepository {") + when (scriptDsl) { + ScriptDsl.KotlinInternal -> { + appendLine(" maven(file($repoUrl)) {") + appendLine(" name = $repoName") + } + + ScriptDsl.GroovyInternal -> { + appendLine(" maven {") + appendLine(" url = file($repoUrl)") + appendLine(" name = $repoName") + } + } + appendLine(" }") + appendLine(" }") + appendLine(" filter {") + groups.sorted().forEach { group -> + appendLine(" includeGroup(${group.asQuotedString(scriptDsl)})") + } + appendLine(" }") + append("}") + appendLine() + } +} + +/** + * A complete `pluginManagement { }` block, so that the build under test can apply plugins published + * to the dev Maven repository by plugin id and version. + */ +@JvmOverloads +fun devPublishPluginManagement( + devMavenRepo: Path = devMavenRepo(), + gradlePluginPortal: Boolean = true, + mavenCentral: Boolean = true, + scriptDsl: ScriptDsl = ScriptDsl.Kotlin, +): String = buildString { + appendLine("pluginManagement {") + appendLine(" repositories {") + appendLine(devPublishRepository(devMavenRepo, scriptDsl).trim().prependIndent(" ")) + if (gradlePluginPortal) appendLine(" gradlePluginPortal()") + if (mavenCentral) appendLine(" mavenCentral()") + appendLine(" }") + append("}") + appendLine() +} + +/** + * A complete `dependencyResolutionManagement { }` block, so that the build under test can resolve + * ordinary dependencies published to the dev Maven repository. + */ +@JvmOverloads +fun devPublishDependencyResolutionManagement( + devMavenRepo: Path = devMavenRepo(), + mavenCentral: Boolean = true, + scriptDsl: ScriptDsl = ScriptDsl.Kotlin, +): String = buildString { + appendLine("dependencyResolutionManagement {") + appendLine(" repositories {") + appendLine(devPublishRepository(devMavenRepo, scriptDsl).trim().prependIndent(" ")) + if (mavenCentral) appendLine(" mavenCentral()") + appendLine(" }") + append("}") + appendLine() +} + +/** + * A complete settings script for a build under test: both + * [devPublishPluginManagement] and [devPublishDependencyResolutionManagement], and optionally + * `rootProject.name`. + * + * ``` + * projectDir.resolve("settings.gradle.kts") + * .writeText(devPublishSettings(rootProjectName = "my-test-project")) + * ``` + */ +@JvmOverloads +fun devPublishSettings( + rootProjectName: String? = null, + devMavenRepo: Path = devMavenRepo(), + scriptDsl: ScriptDsl = ScriptDsl.Kotlin, +): String = buildString { + appendLine(devPublishPluginManagement(devMavenRepo, scriptDsl = scriptDsl)) + appendLine() + appendLine(devPublishDependencyResolutionManagement(devMavenRepo, scriptDsl = scriptDsl)) + if (rootProjectName != null) { + appendLine() + append("rootProject.name = ${rootProjectName.asQuotedString(scriptDsl)}") + } +} + +/** + * Every Maven group with a publication in [devMavenRepo]. + * + * A Maven repository is laid out as `///`, so the + * group of each `.pom` is its path with the last three segments removed. + */ +private fun publishedGroups(devMavenRepo: Path): Set = + devMavenRepo + .walk() + .filter { it.isRegularFile() && it.extension == "pom" } + .mapNotNull { pom -> + val segments = pom.relativeTo(devMavenRepo).map(Path::name) + // , , , + if (segments.size < 4) { + null + } else { + segments.dropLast(3).joinToString(".") + } + } + .toSortedSet() + +/** Quote the string as a string literal, escaped for [ScriptDsl]. */ +private fun String.asQuotedString(dsl: ScriptDsl): String { + val escaped = replace("""\""", """\\""") + return when (dsl) { + ScriptDsl.KotlinInternal -> """"${escaped.replace("\"", """\"""").replace("$", $$"${'$'}")}"""" + ScriptDsl.GroovyInternal -> "'${escaped.replace("'", """\'""")}'" + } +} diff --git a/modules/dev-publish-utils/src/test/kotlin/DevPublishTestKitTest.kt b/modules/dev-publish-utils/src/test/kotlin/DevPublishTestKitTest.kt new file mode 100644 index 0000000..5ac44f4 --- /dev/null +++ b/modules/dev-publish-utils/src/test/kotlin/DevPublishTestKitTest.kt @@ -0,0 +1,259 @@ +package dev.adamko.gradle.dev_publish + +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.core.spec.style.FunSpec +import io.kotest.engine.spec.tempdir +import io.kotest.matchers.shouldBe +import io.kotest.matchers.string.shouldContain +import io.kotest.matchers.string.shouldEndWith +import io.kotest.matchers.string.shouldNotContain +import java.io.File +import java.nio.file.Path +import kotlin.io.path.invariantSeparatorsPathString + +class DevPublishTestKitTest : FunSpec({ + + /** Creates a Maven-layout repository containing the given `group:artifact:version` coordinates. */ + fun devMavenRepo(vararg coordinates: String, dir: File = tempdir()): Path = + dir.also { repo -> + coordinates.forEach { gav -> + val (group, artifact, version) = gav.split(":") + repo.resolve("${group.replace('.', '/')}/$artifact/$version") + .apply { mkdirs() } + .resolve("$artifact-$version.pom") + .writeText("") + } + }.toPath() + + /** + * The groups the generated `exclusiveContent` block includes, in the order it writes them. + * + * Read back from the generated code, because deriving the groups is an implementation detail - + * what callers depend on is the filter that ends up in their settings script. + */ + fun includedGroups(devMavenRepo: Path): List = + devPublishRepository(devMavenRepo) + .lines() + .map { it.trim() } + .filter { it.startsWith("includeGroup(") } + .map { it.substringAfter("includeGroup(\"").substringBefore("\")") } + + context("deriving the published groups") { + + test("expect the group of a plain library") { + includedGroups(devMavenRepo("com.example:lib-core:1.0.0")) shouldBe listOf("com.example") + } + + test("expect BOTH the plugin marker group and the implementation group") { + val repo = devMavenRepo( + "com.example.greeting:com.example.greeting.gradle.plugin:1.0.0", + "com.example:greeting-plugin:1.0.0", + ) + + includedGroups(repo) shouldBe listOf("com.example", "com.example.greeting") + } + + test("expect groups to be sorted, so the generated script is stable") { + val repo = devMavenRepo( + "zeta.example:z:1.0.0", + "alpha.example:a:1.0.0", + "mid.example:m:1.0.0", + ) + + includedGroups(repo) shouldBe listOf("alpha.example", "mid.example", "zeta.example") + } + + test("expect each group only once, however many artifacts it has") { + val repo = devMavenRepo( + "com.example:one:1.0.0", + "com.example:two:1.0.0", + "com.example:two:2.0.0", + ) + + includedGroups(repo) shouldBe listOf("com.example") + } + + // an empty repo produces no block at all - covered by "a directed error when the repo has no + // publications" in the next context + } + + context("generating the repository block") { + + test("expect an includeGroup for every published group") { + val repo = devMavenRepo( + "com.example.greeting:com.example.greeting.gradle.plugin:1.0.0", + "com.example:greeting-plugin:1.0.0", + ) + + devPublishRepository(repo) shouldBe /*language=kotlin*/ """ + |exclusiveContent { + | forRepository { + | maven(file("${repo.invariantSeparatorsPathString}")) { + | name = "DevMavenRepo" + | } + | } + | filter { + | includeGroup("com.example") + | includeGroup("com.example.greeting") + | } + |} + |""".trimMargin() + } + + test("expect a directed error when the repo has no publications") { + // the failure a user hits when the test task does not depend on `updateDevRepo` + val error = shouldThrow { + devPublishRepository(tempdir().toPath()) + } + + error.message shouldContain "No publications found" + error.message shouldContain "updateDevRepo" + error.message shouldContain "implementation(devPublish.dependency())" + } + } + + context("generating settings blocks") { + val repo = devMavenRepo("com.example:lib:1.0.0") + + test("expect pluginManagement to nest the repository and the fallbacks") { + devPublishPluginManagement(repo) shouldBe /*language=kotlin*/ """ + |pluginManagement { + | repositories { + | exclusiveContent { + | forRepository { + | maven(file("${repo.invariantSeparatorsPathString}")) { + | name = "DevMavenRepo" + | } + | } + | filter { + | includeGroup("com.example") + | } + | } + | gradlePluginPortal() + | mavenCentral() + | } + |} + |""".trimMargin() + } + + test("expect fallback repositories to be optional") { + val block = devPublishPluginManagement(repo, gradlePluginPortal = false, mavenCentral = false) + + block shouldContain "exclusiveContent {" + block shouldNotContain "gradlePluginPortal()" + block shouldNotContain "mavenCentral()" + } + + test("expect dependencyResolutionManagement to wrap the same repository") { + devPublishDependencyResolutionManagement(repo) shouldBe /*language=kotlin*/ """ + |dependencyResolutionManagement { + | repositories { + | exclusiveContent { + | forRepository { + | maven(file("${repo.invariantSeparatorsPathString}")) { + | name = "DevMavenRepo" + | } + | } + | filter { + | includeGroup("com.example") + | } + | } + | mavenCentral() + | } + |} + |""".trimMargin() + } + + test("expect a whole settings file, with the root project name last") { + val settings = devPublishSettings(rootProjectName = "consumer", devMavenRepo = repo) + + settings shouldContain "pluginManagement {" + settings shouldContain "dependencyResolutionManagement {" + settings.trim() shouldEndWith """rootProject.name = "consumer"""" + } + + test("expect the root project name to be optional") { + devPublishSettings(rootProjectName = null, devMavenRepo = repo) shouldNotContain "rootProject.name" + } + } + + context("generating Groovy scripts") { + val repo = devMavenRepo("com.example:lib:1.0.0") + + test("expect a url assignment, because Groovy has no maven(url) { } overload") { + devPublishRepository(repo, ScriptDsl.Groovy) shouldBe /*language=groovy*/ """ + |exclusiveContent { + | forRepository { + | maven { + | url = file('${repo.invariantSeparatorsPathString}') + | name = 'DevMavenRepo' + | } + | } + | filter { + | includeGroup('com.example') + | } + |} + |""".trimMargin() + } + + test("expect the settings blocks to nest the Groovy repository") { + val settings = devPublishSettings("consumer", repo, ScriptDsl.Groovy) + + settings shouldContain "pluginManagement {" + settings shouldContain "url = file('" + settings shouldNotContain "maven(file(" + settings.trim() shouldEndWith "rootProject.name = 'consumer'" + } + } + + // TODO are these test worthwhile keeping, or is DevMavenRepoDependencyTest enough? +// context("locating the repo from the classpath metadata") { +// +// /** Lays out a classpath root holding the metadata file, and returns its URL. */ +// fun metadataUrl(dir: File, recordedPath: String): URL { +// val metadata = dir.toPath().resolve(DevPublishMetadata.METADATA_FILE_PATH) +// DevPublishMetadata.write(metadata, recordedPath, devMavenRepoChecksum = "abc123") +// return URLClassLoader(arrayOf(dir.toURI().toURL())) +// .getResource(DevPublishMetadata.METADATA_FILE_PATH)!! +// } +// +// test("expect the recorded path resolves against the classpath root, not the metadata file") { +// val dir = tempdir() +// val repo = dir.resolve("maven-dev").apply { mkdirs() } +// +// devMavenRepoFrom(metadataUrl(dir, "maven-dev")) shouldBe repo.toPath() +// } +// +// test("expect a path that climbs out of the classpath root resolves too") { +// val dir = tempdir() +// val repo = dir.parentFile.resolve("maven-dev").apply { mkdirs() } +// +// devMavenRepoFrom(metadataUrl(dir, "../maven-dev")) shouldBe repo.toPath() +// } +// +// test("expect a repo that does not exist is reported, rather than returned") { +// val dir = tempdir() +// +// val error = shouldThrow { +// devMavenRepoFrom(metadataUrl(dir, "nowhere")) +// } +// +// error.message shouldContain "was recorded as 'nowhere'" +// } +// } + + context("escaping the repo path") { + + test("expect a quote to be escaped for Groovy") { + val repo = devMavenRepo("com.example:lib:1.0.0", dir = tempdir().resolve("it's").apply { mkdirs() }) + + devPublishRepository(repo, ScriptDsl.Groovy) shouldContain """/it\'s')""" + } + + test("expect a dollar to be escaped for Kotlin") { + val repo = devMavenRepo("com.example:lib:1.0.0", dir = tempdir().resolve("costs\$5").apply { mkdirs() }) + + devPublishRepository(repo) shouldContain $$"""/costs${'$'}5")""" + } + } +}) diff --git a/settings.gradle.kts b/settings.gradle.kts index ecdf71b..658080b 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -22,4 +22,5 @@ enableFeaturePreview("STABLE_CONFIGURATION_CACHE") include( ":modules:dev-publish-common", ":modules:dev-publish-plugin", + ":modules:dev-publish-utils", ) From a1e9186c674a4b8ac292808bf88cdfaf47ea54d9 Mon Sep 17 00:00:00 2001 From: Adam <897017+aSemy@users.noreply.github.com> Date: Thu, 1 Oct 2026 19:11:03 +0200 Subject: [PATCH 3/3] Declare the dev repo with `devPublish.dependency()` Tests get the dev Maven repository by declaring a dependency on `devPublish.dependency()`. example: ``` dependencies { testImplementation(devPublish.dependency()) } ``` The dependency wires the `updateDevRepo` task dependency, adds `dev-publish-utils`, and puts a metadata file on the test runtime classpath with a relative path to the dev-repo location. --- .../api/dev-publish-plugin.api | 1 + modules/dev-publish-plugin/build.gradle.kts | 32 +++ .../src/main/kotlin/DevPublishPlugin.kt | 97 ++++++++- .../main/kotlin/DevPublishPluginExtension.kt | 39 ++++ .../src/main/kotlin/data/DevPubAttributes.kt | 10 +- .../data/DevPubConfigurationsContainer.kt | 26 +++ .../kotlin/tasks/DevPublishTasksContainer.kt | 17 ++ .../tasks/GenerateDevPublishMetadataTask.kt | 75 +++++++ .../src/main/kotlin/utils/gradleUtils.kt | 18 +- .../src/test/kotlin/ApiPropagationTest.kt | 1 - .../test/kotlin/DevMavenRepoDependencyTest.kt | 117 +++++++++++ .../DevPublishCapabilityNotationTest.kt | 53 +++++ .../src/test/kotlin/JavaConsumerTest.kt | 195 ++++++++++++++++++ .../src/test/kotlin/JvmTestSuiteTest.kt | 131 ++++++++++++ .../testFixtures/kotlin/GradleTestKitUtils.kt | 61 +++--- modules/dev-publish-utils/build.gradle.kts | 8 + 16 files changed, 848 insertions(+), 33 deletions(-) create mode 100644 modules/dev-publish-plugin/src/main/kotlin/tasks/GenerateDevPublishMetadataTask.kt create mode 100644 modules/dev-publish-plugin/src/test/kotlin/DevMavenRepoDependencyTest.kt create mode 100644 modules/dev-publish-plugin/src/test/kotlin/DevPublishCapabilityNotationTest.kt create mode 100644 modules/dev-publish-plugin/src/test/kotlin/JavaConsumerTest.kt create mode 100644 modules/dev-publish-plugin/src/test/kotlin/JvmTestSuiteTest.kt diff --git a/modules/dev-publish-plugin/api/dev-publish-plugin.api b/modules/dev-publish-plugin/api/dev-publish-plugin.api index 5acb30d..84f4f66 100644 --- a/modules/dev-publish-plugin/api/dev-publish-plugin.api +++ b/modules/dev-publish-plugin/api/dev-publish-plugin.api @@ -15,6 +15,7 @@ public final class dev/adamko/gradle/dev_publish/DevPublishPlugin$Companion { } public abstract class dev/adamko/gradle/dev_publish/DevPublishPluginExtension { + public final fun dependency ()Lorg/gradle/api/provider/Provider; public abstract fun getDevMavenRepo ()Lorg/gradle/api/file/DirectoryProperty; } diff --git a/modules/dev-publish-plugin/build.gradle.kts b/modules/dev-publish-plugin/build.gradle.kts index 3da45ea..01033b3 100644 --- a/modules/dev-publish-plugin/build.gradle.kts +++ b/modules/dev-publish-plugin/build.gradle.kts @@ -1,7 +1,10 @@ @file:Suppress("UnstableApiUsage") import buildsrc.utils.skipTestFixturesPublications +import kotlin.io.path.createDirectories +import kotlin.io.path.writeText import org.gradle.plugin.compatibility.compatibility +import org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi import org.jetbrains.kotlin.gradle.dsl.abi.ExperimentalAbiValidation plugins { @@ -82,6 +85,35 @@ skipTestFixturesPublications() tasks.withType().configureEach { dependsOn("publishAllPublicationsToTestMavenRepoRepository") dependsOn(":modules:dev-publish-common:publishAllPublicationsToTestMavenRepoRepository") + dependsOn(":modules:dev-publish-utils:publishAllPublicationsToTestMavenRepoRepository") systemProperty("testMavenRepoDir", testMavenRepoDir.asFile.invariantSeparatorsPath) systemProperty("projectTestTempDir", projectTestTempDir.get().asFile.invariantSeparatorsPath) } + +val generateDevPublishVersionKt by tasks.registering { + val outputDir = temporaryDir.toPath() + outputs.dir(outputDir) + + val projectVersion = provider { project.version.toString() } + inputs.property("version", projectVersion) + doLast { + outputDir + .resolve("dev/adamko/gradle/dev_publish/internal") + .createDirectories() + .resolve("DevPublishVersion.kt") + .writeText( + """ + |// Do not edit: generated by $path + |package dev.adamko.gradle.dev_publish.internal + | + |/** The current version of the DevPublish plugin. */ + |internal const val DevPublishVersion = "${projectVersion.get()}" + |""".trimMargin() + ) + } +} + +kotlin.sourceSets.main { + @OptIn(ExperimentalKotlinGradlePluginApi::class) + generatedKotlin.srcDir(generateDevPublishVersionKt) +} diff --git a/modules/dev-publish-plugin/src/main/kotlin/DevPublishPlugin.kt b/modules/dev-publish-plugin/src/main/kotlin/DevPublishPlugin.kt index 82c20bc..c15dc64 100644 --- a/modules/dev-publish-plugin/src/main/kotlin/DevPublishPlugin.kt +++ b/modules/dev-publish-plugin/src/main/kotlin/DevPublishPlugin.kt @@ -4,6 +4,7 @@ import dev.adamko.gradle.dev_publish.data.DevPubAttributes import dev.adamko.gradle.dev_publish.data.DevPubConfigurationsContainer import dev.adamko.gradle.dev_publish.data.PublicationData import dev.adamko.gradle.dev_publish.internal.DevPublishInternalApi +import dev.adamko.gradle.dev_publish.internal.DevPublishVersion import dev.adamko.gradle.dev_publish.internal.checksums.CreatePublicationChecksum.Companion.createPublicationChecksum import dev.adamko.gradle.dev_publish.internal.checksums.LoadPublicationChecksum.Companion.loadPublicationChecksum import dev.adamko.gradle.dev_publish.internal.checksums.checksumsToDebugString @@ -14,6 +15,8 @@ import dev.adamko.gradle.dev_publish.utils.* import javax.inject.Inject import org.gradle.api.Plugin import org.gradle.api.Project +import org.gradle.api.artifacts.Dependency +import org.gradle.api.artifacts.ProjectDependency import org.gradle.api.file.FileCollection import org.gradle.api.file.FileSystemOperations import org.gradle.api.file.ProjectLayout @@ -53,7 +56,9 @@ constructor( ) : Plugin { override fun apply(project: Project) { - val devPubExtension = project.extensions.createDevPublishExtension() + val devPublishDependency = createDevPublishDependency(project) + + val devPubExtension = project.extensions.createDevPublishExtension(devPublishDependency) val devPubService = project.gradle.sharedServices.registerDevPubService(project.path) @@ -85,6 +90,13 @@ constructor( } } + configureDevMavenRepoMetadata( + project = project, + devPubExtension = devPubExtension, + devPubTasks = devPubTasks, + devPubConfigurations = devPubConfigurations, + ) + configureMavenPublishingPlugin( project = project, devPubExtension = devPubExtension, @@ -103,15 +115,19 @@ constructor( } } - private fun ExtensionContainer.createDevPublishExtension(): DevPublishPluginExtension { + private fun ExtensionContainer.createDevPublishExtension( + devPublishDependency: Provider, + ): DevPublishPluginExtension { return create(DEV_PUB__EXTENSION_NAME).apply { devMavenRepo.convention(layout.buildDirectory.dir(DEV_PUB__MAVEN_REPO_DIR)) val tmpDir = layout.buildDirectory.dir("tmp/.$DEV_PUB__MAVEN_REPO_DIR/") + devMavenRepoMetadataDir.convention(tmpDir.map { it.dir("metadata") }) stagingDevMavenRepo.convention(tmpDir.map { it.dir("staging") }) checksumsStore.convention(tmpDir.map { it.dir("checksum-store") }) publicationsStore.convention(tmpDir.map { it.dir("publications-store") }) + dependency.convention(devPublishDependency) } } @@ -126,6 +142,32 @@ constructor( maxParallelUsages.set(1) } + /** + * Expose the generated metadata file, and `dev-publish-utils`, through a consumable + * Configuration, so [DevPublishPluginExtension.dependency] wires up a test source set on its own. + */ + private fun configureDevMavenRepoMetadata( + project: Project, + devPubExtension: DevPublishPluginExtension, + devPubTasks: DevPublishTasksContainer, + devPubConfigurations: DevPubConfigurationsContainer, + ) { + devPubConfigurations.devPublishElements.configure { + outgoing { + artifact(devPubExtension.devMavenRepoMetadataDir) { + builtBy(devPubTasks.generateDevPublishMetadata) + } + // Distinguishes this from `runtimeElements`. + // Without this, the TargetJvmVersion attribute is required, and it's impossible to guess the required value. + capability( + devPublishCapabilityNotation(project.groupProvider, project.name).map { notation -> + "$notation:$DevPublishVersion" + } + ) + } + } + } + /** React to [MavenPublishPlugin], and configure the appropriate DevPublish tasks. */ private fun configureMavenPublishingPlugin( project: Project, @@ -307,6 +349,20 @@ constructor( const val DEV_PUB__MAVEN_REPO_DIR = "maven-dev" + /** Name of the consumable Configuration behind [DevPublishPluginExtension.dependency]. */ + internal const val DEV_PUB__ELEMENTS_CONFIGURATION = "devPublishElements" + + /** Group of the capability that identifies [DEV_PUB__ELEMENTS_CONFIGURATION]. */ + internal const val DEV_PUB__CAPABILITY_GROUP = "dev.adamko.dev-publish" + + /** Coordinates of the helper library that [DevPublishPluginExtension.dependency] brings in. */ + internal const val DEV_PUB__UTILS_GROUP = "dev.adamko.gradle" + + /** @see DEV_PUB__UTILS_GROUP */ + internal const val DEV_PUB__UTILS_MODULE = "dev-publish-utils" + + internal const val DEV_PUB__UTILS_CONFIGURATION = "devPublishUtils" + const val DEV_PUB__PUBLICATION_DEPENDENCIES = "devPublication" const val DEV_PUB__PUBLICATION_API_DEPENDENCIES = "devPublicationApi" const val DEV_PUB__PUBLICATION_INCOMING = "devPublicationResolvableElements" @@ -314,6 +370,43 @@ constructor( private val logger = Logging.getLogger(DevPublishService::class.java) + /** + * The [ProjectDependency] handed to users as [DevPublishPluginExtension.dependency]. + * + * Targets [DEV_PUB__ELEMENTS_CONFIGURATION] of this same project, selected by capability + * because `runtimeElements` matches the same attributes and would otherwise be ambiguous. + */ + private fun createDevPublishDependency(project: Project): Provider { + return devPublishCapabilityNotation(group = project.groupProvider, name = project.name).map { capability -> + createProjectDependency(project).apply { + capabilities { + requireCapability(capability) + } + because("the DevPublish dev Maven repository, and the dev-publish-utils library that reads it") + } + } + } + + /** + * Coordinates of the capability that distinguishes [DEV_PUB__ELEMENTS_CONFIGURATION] from the + * project's other variants. + * + * Derived from the project's own coordinates, which are already required to be unique. + */ + internal fun devPublishCapabilityNotation(group: Provider, name: String): Provider = + group.map { group -> + buildString { + append(DEV_PUB__CAPABILITY_GROUP) + if (group.isNotEmpty()) { + append(".") + append(group) + } + append(":") + append(name) + append("-dev-publish") + } + } + private fun MavenPublication.getGenerateModuleMetadataTaskName(): String = "generateMetadataFileFor${name.uppercaseFirstChar()}Publication" } diff --git a/modules/dev-publish-plugin/src/main/kotlin/DevPublishPluginExtension.kt b/modules/dev-publish-plugin/src/main/kotlin/DevPublishPluginExtension.kt index 8e32f7d..d586f86 100644 --- a/modules/dev-publish-plugin/src/main/kotlin/DevPublishPluginExtension.kt +++ b/modules/dev-publish-plugin/src/main/kotlin/DevPublishPluginExtension.kt @@ -1,7 +1,10 @@ package dev.adamko.gradle.dev_publish import dev.adamko.gradle.dev_publish.internal.DevPublishInternalApi +import org.gradle.api.artifacts.Dependency import org.gradle.api.file.DirectoryProperty +import org.gradle.api.provider.Property +import org.gradle.api.provider.Provider /** * Settings for controlling the behaviour of [DevPublishPlugin] and its tasks. @@ -9,15 +12,51 @@ import org.gradle.api.file.DirectoryProperty abstract class DevPublishPluginExtension @DevPublishInternalApi constructor() { + /** + * Declare this to make a source set depend on dev publishing. + * + * ```kotlin + * dependencies { + * testImplementation(devPublish.dependency()) + * } + * // or inside a JvmTestSuite + * testing.suites { + * register("functionalTest") { + * dependencies { + * implementation(devPublish.dependency()) + * } + * } + * } + * ``` + * + * Declaring it runs `updateDevRepo` before the tests, puts the [devMavenRepo] location on their + * runtime classpath, and adds `dev-publish-utils` for reading it. + */ + fun dependency(): Provider = dependency + + internal abstract val dependency: Property + /** * Location of the file-based test Maven repository. * * The repository is specific per subproject and should not be referenced by other subprojects. * * This property should be passed into tests and provided as a Maven repository. + * The simplest way to do that is to declare [dependency]. + * + * Default: `build/maven-dev` + * + * @see dependency */ abstract val devMavenRepo: DirectoryProperty + /** + * Directory holding the generated metadata file that records the [devMavenRepo] location. + * + * This value is intended for internal use and should not typically be configured in build scripts. + */ + @DevPublishInternalApi + abstract val devMavenRepoMetadataDir: DirectoryProperty /** * Location of temporary Maven repository, that will be used to populate [devMavenRepo]. * diff --git a/modules/dev-publish-plugin/src/main/kotlin/data/DevPubAttributes.kt b/modules/dev-publish-plugin/src/main/kotlin/data/DevPubAttributes.kt index d313f12..adb46e7 100644 --- a/modules/dev-publish-plugin/src/main/kotlin/data/DevPubAttributes.kt +++ b/modules/dev-publish-plugin/src/main/kotlin/data/DevPubAttributes.kt @@ -18,17 +18,23 @@ import org.gradle.kotlin.dsl.named class DevPubAttributes( objects: ObjectFactory, ) { - /** Indicates a [Configuration] contains a Maven Repository */ + /** Indicates a [Configuration] contains a Maven repository. */ val devPublishUsage: Usage = objects.named("dev-publish") - /** Indicates a [Configuration] contains a Maven Repository */ + /** @see devPublishUsage */ val devPublishCategory: Category = objects.named("dev-publish") val mavenRepositoryType = "maven-repository" + val mavenRepositoryChecksumsType = "maven-repository-checksums" @DevPublishInternalApi companion object { val DevPublishTypeAttribute: Attribute = Attribute("dev.adamko.gradle.dev_publish.type") + /** + * Indicates a [Configuration] contains the generated file recording the dev Maven repository + * location, and the library that reads it. + */ + const val DEV_REPO_METADATA_KEY = "dev-maven-repo-metadata" } } diff --git a/modules/dev-publish-plugin/src/main/kotlin/data/DevPubConfigurationsContainer.kt b/modules/dev-publish-plugin/src/main/kotlin/data/DevPubConfigurationsContainer.kt index 2285130..14a96bd 100644 --- a/modules/dev-publish-plugin/src/main/kotlin/data/DevPubConfigurationsContainer.kt +++ b/modules/dev-publish-plugin/src/main/kotlin/data/DevPubConfigurationsContainer.kt @@ -2,12 +2,17 @@ package dev.adamko.gradle.dev_publish.data +import dev.adamko.gradle.dev_publish.DevPublishPlugin.Companion.DEV_PUB__ELEMENTS_CONFIGURATION import dev.adamko.gradle.dev_publish.DevPublishPlugin.Companion.DEV_PUB__PUBLICATION_API_DEPENDENCIES import dev.adamko.gradle.dev_publish.DevPublishPlugin.Companion.DEV_PUB__PUBLICATION_DEPENDENCIES import dev.adamko.gradle.dev_publish.DevPublishPlugin.Companion.DEV_PUB__PUBLICATION_INCOMING import dev.adamko.gradle.dev_publish.DevPublishPlugin.Companion.DEV_PUB__PUBLICATION_OUTGOING +import dev.adamko.gradle.dev_publish.DevPublishPlugin.Companion.DEV_PUB__UTILS_CONFIGURATION +import dev.adamko.gradle.dev_publish.DevPublishPlugin.Companion.DEV_PUB__UTILS_GROUP +import dev.adamko.gradle.dev_publish.DevPublishPlugin.Companion.DEV_PUB__UTILS_MODULE import dev.adamko.gradle.dev_publish.data.DevPubAttributes.Companion.DevPublishTypeAttribute import dev.adamko.gradle.dev_publish.internal.DevPublishInternalApi +import dev.adamko.gradle.dev_publish.internal.DevPublishVersion import dev.adamko.gradle.dev_publish.utils.extendsFrom_ import org.gradle.api.NamedDomainObjectProvider import org.gradle.api.artifacts.* @@ -19,6 +24,7 @@ import org.gradle.api.attributes.Usage.USAGE_ATTRIBUTE /** * Utility class that contains all [Configuration]s used by [dev.adamko.gradle.dev_publish.DevPublishPlugin]. */ +@Suppress("UnstableApiUsage") @DevPublishInternalApi class DevPubConfigurationsContainer( private val devPubAttributes: DevPubAttributes, @@ -65,6 +71,26 @@ class DevPubConfigurationsContainer( attribute(DevPublishTypeAttribute, devPubAttributes.mavenRepositoryType) } + val devPublishUtils: NamedDomainObjectProvider = + configurations.dependencyScope(DEV_PUB__UTILS_CONFIGURATION) { + description = "Declares the DevPublish helper library, for reading the dev Maven repo." + defaultDependencies { + add(dependencies.create("$DEV_PUB__UTILS_GROUP:$DEV_PUB__UTILS_MODULE:$DevPublishVersion")) + } + } + + val devPublishElements: NamedDomainObjectProvider = + configurations.consumable(DEV_PUB__ELEMENTS_CONFIGURATION) { + description = "The dev Maven repository location, and the library that reads it." + + extendsFrom_(devPublishUtils) + + attributes { + // An attribute is required to trigger 'variant aware matching'. + attribute(DevPublishTypeAttribute, DevPubAttributes.DEV_REPO_METADATA_KEY) + } + } + @DevPublishInternalApi companion object } diff --git a/modules/dev-publish-plugin/src/main/kotlin/tasks/DevPublishTasksContainer.kt b/modules/dev-publish-plugin/src/main/kotlin/tasks/DevPublishTasksContainer.kt index d65040c..d72a8ef 100644 --- a/modules/dev-publish-plugin/src/main/kotlin/tasks/DevPublishTasksContainer.kt +++ b/modules/dev-publish-plugin/src/main/kotlin/tasks/DevPublishTasksContainer.kt @@ -27,6 +27,10 @@ class DevPublishTasksContainer( val updateDevRepo: TaskProvider = tasks.registerUpdateDevRepoTask() + /** Writes the dev repo location into a file, for putting on a test runtime classpath. */ + val generateDevPublishMetadata: TaskProvider = + tasks.registerGenerateDevPublishMetadataTask() + private fun TaskContainer.registerPublishAllToDevRepoTask(): TaskProvider = register(PUBLISH_ALL_TO_DEV_REPO_TASK_NAME) { description = "Publishes all Maven publications to the dev Maven repository. " + @@ -53,6 +57,18 @@ class DevPublishTasksContainer( tempDir.convention(objects.directoryProperty().fileValue(temporaryDir)) } + private fun TaskContainer.registerGenerateDevPublishMetadataTask(): TaskProvider = + register(GENERATE_DEV_PUBLISH_METADATA_TASK_NAME) { + description = "Writes the dev Maven repository location into a properties file, " + + "so it can be read from a test runtime classpath. " + + "This is an internal task that should not typically be manually referenced or called." + + outputDirectory.convention(devPubExtension.devMavenRepoMetadataDir) + devMavenRepo.convention(updateDevRepo.flatMap { it.devRepo }) + @Suppress("UnstableApiUsage") + rootProjectDir.convention(project.isolated.rootProject.projectDirectory) + } + private fun TaskContainer.registerUpdateDevRepoTask(): TaskProvider = register(UPDATE_DEV_REPO_TASK_NAME) { description = "Updates the dev-repo" @@ -69,6 +85,7 @@ class DevPublishTasksContainer( companion object { const val PUBLISH_ALL_TO_DEV_REPO_TASK_NAME = "publishAllToDevRepo" const val UPDATE_DEV_REPO_TASK_NAME = "updateDevRepo" + const val GENERATE_DEV_PUBLISH_METADATA_TASK_NAME = "generateDevPublishMetadata" const val GENERATE_PUBLICATION_CHECKSUM_TASK = "generatePublicationHashTask" } } diff --git a/modules/dev-publish-plugin/src/main/kotlin/tasks/GenerateDevPublishMetadataTask.kt b/modules/dev-publish-plugin/src/main/kotlin/tasks/GenerateDevPublishMetadataTask.kt new file mode 100644 index 0000000..cabc2c2 --- /dev/null +++ b/modules/dev-publish-plugin/src/main/kotlin/tasks/GenerateDevPublishMetadataTask.kt @@ -0,0 +1,75 @@ +@file:Suppress("UnstableApiUsage") + +package dev.adamko.gradle.dev_publish.tasks + +import dev.adamko.gradle.dev_publish.internal.DevPublishInternalApi +import dev.adamko.gradle.dev_publish.internal.DevPublishMetadata.REPO_LOCATION_FILE_NAME +import javax.inject.Inject +import kotlin.io.path.createDirectories +import kotlin.io.path.deleteRecursively +import kotlin.io.path.writeText +import org.gradle.api.file.ConfigurableFileCollection +import org.gradle.api.file.DirectoryProperty +import org.gradle.api.provider.Provider +import org.gradle.api.tasks.* +import org.gradle.api.tasks.PathSensitivity.RELATIVE +import org.gradle.work.DisableCachingByDefault + +/** + * Writes the location of the dev Maven repository into a properties file, so it can be put on a + * test runtime classpath and read back by `devMavenRepo()` in `dev-publish-utils`. + * + * @see dev.adamko.gradle.dev_publish.internal.DevPublishMetadata.REPO_LOCATION_FILE_NAME + */ +@DisableCachingByDefault(because = "Not worth caching") +@DevPublishInternalApi +abstract class GenerateDevPublishMetadataTask +@Inject +@DevPublishInternalApi +constructor() : BaseDevPublishTask() { + + @get:OutputDirectory + abstract val outputDirectory: DirectoryProperty + + /** @see dev.adamko.gradle.dev_publish.DevPublishPluginExtension.devMavenRepo */ + @get:Internal + abstract val devMavenRepo: DirectoryProperty + + @get:Internal + abstract val rootProjectDir: DirectoryProperty + + /** + * Directories containing checksum files for the dev Maven repository. + * + * Used to produce a checksum file for up-to-date check purposes. + */ + @get:InputFiles + @get:PathSensitive(RELATIVE) + @get:IgnoreEmptyDirectories + @DevPublishInternalApi + abstract val devMavenRepoChecksumDirs: ConfigurableFileCollection + + /** Location of the dev Maven repository, relative to [outputDirectory]. */ + @get:Input + val devMavenRepoRelativeToMetadataDir: Provider + get() = devMavenRepo.zip(outputDirectory.locationOnly) { devMavenRepo, metadataDir -> + val baseDir = metadataDir.asFile.resolve(REPO_LOCATION_FILE_NAME).normalize().parentFile + val repoDir = devMavenRepo.asFile + val relative = repoDir.relativeToOrNull(baseDir) + ?: error("devMavenRepo is not relative to metadataDir: $devMavenRepo, $metadataDir") + relative.invariantSeparatorsPath + } + + @TaskAction + @DevPublishInternalApi + protected fun generate() { + val outputDir = outputDirectory.get().asFile.toPath() + + // delete output dir first, to clear any stale files + outputDir.deleteRecursively() + outputDir.createDirectories() + + outputDir.resolve(REPO_LOCATION_FILE_NAME) + .writeText(devMavenRepoRelativeToMetadataDir.get()) + } +} diff --git a/modules/dev-publish-plugin/src/main/kotlin/utils/gradleUtils.kt b/modules/dev-publish-plugin/src/main/kotlin/utils/gradleUtils.kt index a77046b..58b6cf9 100644 --- a/modules/dev-publish-plugin/src/main/kotlin/utils/gradleUtils.kt +++ b/modules/dev-publish-plugin/src/main/kotlin/utils/gradleUtils.kt @@ -3,8 +3,10 @@ package dev.adamko.gradle.dev_publish.utils import java.io.File import org.gradle.api.Action import org.gradle.api.DefaultTask +import org.gradle.api.Project import org.gradle.api.Task import org.gradle.api.artifacts.Configuration +import org.gradle.api.artifacts.ProjectDependency import org.gradle.api.attributes.Attribute import org.gradle.api.attributes.AttributeContainer import org.gradle.api.file.Directory @@ -82,7 +84,6 @@ internal inline fun T.doFirst_( } } - /** Calls [Task.doLast], but smart-casts the task. */ @Suppress("FunctionName") internal inline fun T.doLast_( @@ -104,3 +105,18 @@ internal fun Configuration.extendsFrom_(configuration: Provider= "9.5.0") { + project.dependencies.project() + } else { + project.dependencies.create(project) as? ProjectDependency + ?: error("Failed to create project dependency for project ${project.path}. Current Gradle version: $CurrentGradleVersion") + } +} + +internal val Project.groupProvider: Provider + get() = providers.provider { group.toString() } diff --git a/modules/dev-publish-plugin/src/test/kotlin/ApiPropagationTest.kt b/modules/dev-publish-plugin/src/test/kotlin/ApiPropagationTest.kt index 30c8f44..8141fa4 100644 --- a/modules/dev-publish-plugin/src/test/kotlin/ApiPropagationTest.kt +++ b/modules/dev-publish-plugin/src/test/kotlin/ApiPropagationTest.kt @@ -23,7 +23,6 @@ class ApiPropagationTest : FunSpec({ output shouldContain "SUCCESSFUL" } } - test("api dependencies are propagated") { project.runner.withArguments( ":project-aggregate:updateDevRepo", diff --git a/modules/dev-publish-plugin/src/test/kotlin/DevMavenRepoDependencyTest.kt b/modules/dev-publish-plugin/src/test/kotlin/DevMavenRepoDependencyTest.kt new file mode 100644 index 0000000..0a9523d --- /dev/null +++ b/modules/dev-publish-plugin/src/test/kotlin/DevMavenRepoDependencyTest.kt @@ -0,0 +1,117 @@ +package dev.adamko.gradle.dev_publish + +import dev.adamko.gradle.dev_publish.test_utils.* +import io.kotest.assertions.assertSoftly +import io.kotest.core.spec.style.FunSpec +import io.kotest.core.test.TestScope +import io.kotest.matchers.shouldBe +import io.kotest.matchers.string.shouldContain +import io.kotest.matchers.string.shouldNotContain +import kotlin.io.path.readText +import org.gradle.testkit.runner.TaskOutcome.* + +class DevMavenRepoDependencyTest : FunSpec({ + + context("a project that only declares devPublish.dependency") { + val project = project() + + test("expect the tests run, and updateDevRepo runs for them") { + project.runner + .withArguments( + ":test", + ) + .forwardOutput() + .build { + output shouldContain "SUCCESSFUL" + + shouldHaveTaskWithAnyOutcome(":test", SUCCESS, FROM_CACHE, UP_TO_DATE) + + shouldHaveRunTask(":updateDevRepo") + shouldHaveRunTask(":generateDevPublishMetadata") + } + } + + test("expect the path is relative") { + project.runner.withArguments(":generateDevPublishMetadata").forwardOutput().build { + val repoLocation = project.projectDir + .resolve("build/tmp/.maven-dev/metadata/dev.publish.metadata.repo-location.txt") + .readText() + .trim() + + assertSoftly { + repoLocation shouldBe "../../../maven-dev" + repoLocation shouldNotContain project.projectDir.toString() + repoLocation shouldNotContain ":\\" + } + } + } + } +}) { + + companion object { + + private fun TestScope.project(): GradleProjectTest = + gradleKtsProjectTest( + projectName = "dev-maven-repo-dependency", + testProjectPath = testCase.descriptor.slashSeparatedPath(), + ) { + + buildGradleKts = """ + |plugins { + | kotlin("jvm") version embeddedKotlinVersion + | `maven-publish` + | id("dev.adamko.dev-publish") version "+" + |} + | + |group = "foo.project" + |version = "0.0.1" + | + |publishing { + | publications { + | create("mavenJava") { + | from(components["java"]) + | } + | } + |} + | + |dependencies { + | testImplementation(devPublish.dependency()) + | testImplementation(kotlin("test")) + |} + | + |tasks.test { + | useJUnitPlatform() + |} + |""".trimMargin() + + createKotlinFile( + "src/main/kotlin/FooClass.kt", + """ + |class FooClass { + | fun name(): String = "FooClass" + |} + |""".trimMargin() + ) + + createKotlinFile( + "src/test/kotlin/DevMavenRepoDependencyTest.kt", + $$""" + |import dev.adamko.gradle.dev_publish.devMavenRepo + |import kotlin.io.path.exists + |import kotlin.test.Test + |import kotlin.test.assertTrue + | + |class DevMavenRepoDependencyTest { + | + | @Test + | fun canAccessDevMavenRepo() { + | val repo = devMavenRepo() + | val jar = repo.resolve("foo/project/dev-maven-repo-dependency/0.0.1/dev-maven-repo-dependency-0.0.1.jar") + | assertTrue(jar.exists(), "expected this project's own publication at $jar") + | } + |} + |""".trimMargin() + ) + } + } +} diff --git a/modules/dev-publish-plugin/src/test/kotlin/DevPublishCapabilityNotationTest.kt b/modules/dev-publish-plugin/src/test/kotlin/DevPublishCapabilityNotationTest.kt new file mode 100644 index 0000000..2200055 --- /dev/null +++ b/modules/dev-publish-plugin/src/test/kotlin/DevPublishCapabilityNotationTest.kt @@ -0,0 +1,53 @@ +package dev.adamko.gradle.dev_publish + +import dev.adamko.gradle.dev_publish.DevPublishPlugin.Companion.devPublishCapabilityNotation +import dev.adamko.gradle.dev_publish.utils.groupProvider +import io.kotest.core.spec.style.FunSpec +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe +import org.gradle.api.Project +import org.gradle.testfixtures.ProjectBuilder + +class DevPublishCapabilityNotationTest : FunSpec({ + + test("expect the group is appended to the DevPublish group") { + project(name = "lib", group = "com.example").notation() shouldBe + "dev.adamko.dev-publish.com.example:lib-dev-publish" + } + + test("expect a project without a group is still valid coordinates") { + project(name = "my-build", group = "").notation() shouldBe + "dev.adamko.dev-publish:my-build-dev-publish" + } + + test("expect the group is read lazily, after the build script sets it") { + val project = project(name = "lib", group = "x.y.z") + val notation = devPublishCapabilityNotation(project.groupProvider, project.name) + + project.group = "com.example" + + notation.orNull shouldBe "dev.adamko.dev-publish.com.example:lib-dev-publish" + } + + test("expect projects differing only by group do not collide") { + val bazANotation = project(name = "baz", group = "com.example.a").notation() + val bazBNotation = project(name = "baz", group = "com.example.b").notation() + bazANotation shouldNotBe bazBNotation + } + + test("expect projects differing only by name do not collide") { + val fooNotation = project(name = "foo", group = "com.example").notation() + val barNotation = project(name = "bar", group = "com.example").notation() + fooNotation shouldNotBe barNotation + } +}) + + +private fun project(name: String, group: String): Project = + ProjectBuilder.builder() + .withName(name) + .build() + .also { it.group = group } + +private fun Project.notation(): String = + devPublishCapabilityNotation(groupProvider, name).get() diff --git a/modules/dev-publish-plugin/src/test/kotlin/JavaConsumerTest.kt b/modules/dev-publish-plugin/src/test/kotlin/JavaConsumerTest.kt new file mode 100644 index 0000000..4f1d5e4 --- /dev/null +++ b/modules/dev-publish-plugin/src/test/kotlin/JavaConsumerTest.kt @@ -0,0 +1,195 @@ +package dev.adamko.gradle.dev_publish + +import dev.adamko.gradle.dev_publish.internal.DevPublishVersion +import dev.adamko.gradle.dev_publish.test_utils.* +import io.kotest.core.spec.style.FunSpec +import io.kotest.core.test.TestScope +import io.kotest.matchers.shouldBe +import kotlin.io.path.Path +import kotlin.io.path.pathString +import kotlin.text.Regex.Companion.escape +import org.gradle.testkit.runner.TaskOutcome.* + +/** + * Verify that a Java-only project can use `devPublish.dependency()` and `dev-publish-utils`. + */ +class JavaConsumerTest : FunSpec({ + + context("a Java-only project that declares devPublish.dependency") { + val project = project() + + test("expect the tests run, and the Kotlin helpers work from Java") { + project.runner + .withArguments( + ":test", + ) + .forwardOutput() + .build { + shouldHaveTaskWithAnyOutcome(":test", SUCCESS, FROM_CACHE, UP_TO_DATE) + shouldHaveRunTask(":updateDevRepo") + } + } + + test("expect dev-publish-utils resolves as a real module, on the runtime classpath") { + project.runner + .withArguments( + ":dependencyInsight", + "--configuration", "testRuntimeClasspath", + "--dependency", "dev-publish-utils", + "--quiet", + ) + .build { + + val dependencyInsightReport = + output + .normalizeVersion() + .substringBefore("(*) - Indicates repeated occurrences") + .lines() + // Drop `org.gradle.status`. Gradle derives it from the dev-publish-plugin version, so it's not stable. + .filterNot { "| org.gradle.status" in it } + // Drop JVM version - it can change per machine. + .filterNot { "| org.gradle.jvm.version" in it } + .joinToString("\n") + .trim() + + dependencyInsightReport shouldBe """ + |dev.adamko.gradle:dev-publish-utils:{version} + | Variant runtimeElements: + | | Attribute Name | Provided | Requested | + | |------------------------------------|--------------|--------------| + | | org.jetbrains.kotlin.platform.type | jvm | | + | | org.gradle.category | library | library | + | | org.gradle.dependency.bundling | external | external | + | | org.gradle.jvm.environment | standard-jvm | standard-jvm | + | | org.gradle.libraryelements | jar | jar | + | | org.gradle.usage | java-runtime | java-runtime | + | + |dev.adamko.gradle:dev-publish-utils:{version} + |\--- root project 'java-consumer' + | \--- root project 'java-consumer' (*) + """.trimMargin() + } + } + + test("expect devPublishElements carries a project-specific capability") { + project.runner + .withArguments( + ":outgoingVariants", + "--variant", "devPublishElements", + "--quiet", + ) + .build { + output.trim().normalizeVersion() shouldBe """ + |-------------------------------------------------- + |Variant devPublishElements + |-------------------------------------------------- + |The dev Maven repository location, and the library that reads it. + | + |Capabilities + | - dev.adamko.dev-publish.foo.project:java-consumer-dev-publish:{version} + |Attributes + | - dev.adamko.gradle.dev_publish.type = dev-maven-repo-metadata + |Artifacts + | - ${Path("build/tmp/.maven-dev/metadata").pathString} + """.trimMargin() + } + } + } +}) { + + companion object { + + private fun TestScope.project(): GradleProjectTest = + gradleKtsProjectTest( + projectName = "java-consumer", + testProjectPath = testCase.descriptor.slashSeparatedPath(), + ) { + + buildGradleKts = """ + |plugins { + | `java-library` + | `maven-publish` + | id("dev.adamko.dev-publish") version "+" + |} + | + |group = "foo.project" + |version = "0.0.1" + | + |publishing { + | publications { + | create("mavenJava") { + | from(components["java"]) + | } + | } + |} + | + |dependencies { + | testImplementation(devPublish.dependency()) + | testImplementation("org.junit.jupiter:junit-jupiter:5.12.2") + | testRuntimeOnly("org.junit.platform:junit-platform-launcher") + |} + | + |tasks.test { + | useJUnitPlatform() + |} + |""".trimMargin() + + createJavaFile( + "src/main/java/com/example/Main.java", + """ + |package com.example; + | + |public class Main { + | public static String hello() { + | return "hello"; + | } + |} + |""".trimMargin() + ) + + createJavaFile( + "src/test/java/com/example/JavaConsumerTest.java", + """ + |package com.example; + | + |import static org.junit.jupiter.api.Assertions.assertTrue; + | + |import dev.adamko.gradle.dev_publish.DevPublishTestKit; + |import java.nio.file.Files; + |import java.nio.file.Path; + |import org.junit.jupiter.api.Test; + | + |class JavaConsumerTest { + | + | @Test + | void devMavenRepoIsCallableFromJava() { + | Path repo = DevPublishTestKit.devMavenRepo(); + | + | Path jar = repo.resolve("foo/project/java-consumer/0.0.1/java-consumer-0.0.1.jar"); + | assertTrue(Files.exists(jar), "expected this project's own publication at " + jar); + | } + | + | @Test + | void settingsHelpersAreCallableFromJava() { + | String settings = DevPublishTestKit.devPublishSettings("consumer"); + | + | assertTrue(settings.contains("pluginManagement"), settings); + | } + |} + |""".trimMargin() + ) + } + + private val devPublishVersionRegex = Regex( + """(?<=[:\-]dev-publish(?:-utils)?:)${escape(DevPublishVersion)}\S*""" + ) + + /** + * Replace versions of dev-publish dependencies with `{version}`, for stable test assertions. + */ + private fun String.normalizeVersion(): String = + lines().joinToString("\n") { line -> + line.replace(devPublishVersionRegex, "{version}") + } + } +} diff --git a/modules/dev-publish-plugin/src/test/kotlin/JvmTestSuiteTest.kt b/modules/dev-publish-plugin/src/test/kotlin/JvmTestSuiteTest.kt new file mode 100644 index 0000000..376ecfa --- /dev/null +++ b/modules/dev-publish-plugin/src/test/kotlin/JvmTestSuiteTest.kt @@ -0,0 +1,131 @@ +package dev.adamko.gradle.dev_publish + +import dev.adamko.gradle.dev_publish.test_utils.* +import io.kotest.core.spec.style.FunSpec +import io.kotest.core.test.TestScope +import io.kotest.matchers.string.shouldContain +import org.gradle.testkit.runner.TaskOutcome.* + +class JvmTestSuiteTest : FunSpec({ + + context("a project with two jvm-test-suite suites") { + val project = project() + + test("expect both suites run, and updateDevRepo runs for them") { + project.runner + .withArguments( + ":functionalTest", + ":integrationTest", + ) + .forwardOutput() + .build { + output shouldContain "SUCCESSFUL" + + shouldHaveTaskWithAnyOutcome(":functionalTest", SUCCESS, FROM_CACHE, UP_TO_DATE) + shouldHaveTaskWithAnyOutcome(":integrationTest", SUCCESS, FROM_CACHE, UP_TO_DATE) + + // the dependency edge has to be attached to the suite tasks, not only to `test` + shouldHaveRunTask(":updateDevRepo") + shouldNotHaveRunTask(":test") + } + } + + test("expect the default test task does not trigger updateDevRepo") { + project.runner + .withArguments( + ":test", + ) + .forwardOutput() + .build { + output shouldContain "SUCCESSFUL" + + shouldHaveRunTask(":test") + + shouldNotHaveRunTask(":updateDevRepo") + shouldNotHaveRunTask(":functionalTest") + shouldNotHaveRunTask(":integrationTest") + } + } + } +}) { + + companion object { + + private fun TestScope.project(): GradleProjectTest = + gradleKtsProjectTest( + projectName = "jvm-test-suite-project", + testProjectPath = testCase.descriptor.slashSeparatedPath(), + ) { + + buildGradleKts = """ + |plugins { + | `java-library` + | `jvm-test-suite` + | `maven-publish` + | id("dev.adamko.dev-publish") version "+" + |} + | + |group = "foo.project" + |version = "0.0.1" + | + |publishing { + | publications { + | create("mavenJava") { + | from(components["java"]) + | } + | } + |} + | + |testing.suites { + | register("functionalTest") { + | useJUnitJupiter() + | dependencies { + | implementation(devPublish.dependency()) + | } + | } + | register("integrationTest") { + | useJUnitJupiter() + | dependencies { + | implementation(devPublish.dependency()) + | } + | } + |} + |""".trimMargin() + + createFile( + "src/main/java/FooClass.java", + """ + |public class FooClass { + | public String name() { return "FooClass"; } + |} + |""".trimMargin() + ) + + listOf("functionalTest", "integrationTest").forEach { suite -> + createFile( + "src/$suite/java/DevMavenRepoTest.java", + """ + |import static org.junit.jupiter.api.Assertions.assertTrue; + | + |import dev.adamko.gradle.dev_publish.DevPublishTestKit; + |import java.nio.file.Files; + |import java.nio.file.Path; + |import org.junit.jupiter.api.Test; + | + |class DevMavenRepoTest { + | + | @Test + | void devMavenRepoIsAvailableToThisSuite() { + | // fails if the metadata never reached the $suite runtime classpath + | Path repo = DevPublishTestKit.devMavenRepo(); + | + | Path jar = repo.resolve("foo/project/jvm-test-suite-project/0.0.1/jvm-test-suite-project-0.0.1.jar"); + | assertTrue(Files.exists(jar), "expected this project's own publication at " + jar); + | } + |} + |""".trimMargin() + ) + } + } + } +} diff --git a/modules/dev-publish-plugin/src/testFixtures/kotlin/GradleTestKitUtils.kt b/modules/dev-publish-plugin/src/testFixtures/kotlin/GradleTestKitUtils.kt index c8bfc5b..d4d2560 100644 --- a/modules/dev-publish-plugin/src/testFixtures/kotlin/GradleTestKitUtils.kt +++ b/modules/dev-publish-plugin/src/testFixtures/kotlin/GradleTestKitUtils.kt @@ -45,31 +45,37 @@ class GradleProjectTest( .invariantSeparatorsPath val settingRepositories: String - get() = """ - |pluginManagement { - | repositories { - | exclusiveContent { - | forRepository { - | maven(file("$testMavenRepoPathString")) { - | name = "MavenDevRepo" - | } - | } - | filter { - | includeGroup("dev.adamko.dev-publish") - | includeGroup("dev.adamko.gradle") - | } - | } - | mavenCentral() - | gradlePluginPortal() - | } - |} - | - |dependencyResolutionManagement { - | repositories { - | mavenCentral() - | } - |} - """.trimMargin() + get() { + val devMavenRepo = """ + |exclusiveContent { + | forRepository { + | maven(file("$testMavenRepoPathString")) { + | name = "MavenDevRepo" + | } + | } + | filter { + | includeGroup("dev.adamko.dev-publish") + | includeGroup("dev.adamko.gradle") + | } + |} + |""".trimMargin().prependIndent(" ") + return """ + |pluginManagement { + | repositories { + |${devMavenRepo} + | mavenCentral() + | gradlePluginPortal() + | } + |} + | + |dependencyResolutionManagement { + | repositories { + |${devMavenRepo} + | mavenCentral() + | } + |} + """.trimMargin() + } val projectTestTempDir: Path by systemProperty(Paths::get) @@ -179,7 +185,6 @@ fun ProjectDirectoryScope.createFile(filePath: String, contents: String): File = } -@ProjectDirectoryDsl fun ProjectDirectoryScope.dir( path: String, block: ProjectDirectoryScope.() -> Unit = {}, @@ -187,7 +192,6 @@ fun ProjectDirectoryScope.dir( ProjectDirectoryScopeImpl(projectDir.resolve(path)).apply(block) -@ProjectDirectoryDsl fun ProjectDirectoryScope.file( path: String ): Path = projectDir.resolve(path) @@ -214,3 +218,6 @@ fun ProjectDirectoryScope.createKotlinFile(filePath: String, @Language("kotlin") fun ProjectDirectoryScope.createKtsFile(filePath: String, @Language("kts") contents: String) = createFile(filePath, contents) + +fun ProjectDirectoryScope.createJavaFile(filePath: String, @Language("java") contents: String) = + createFile(filePath, contents) diff --git a/modules/dev-publish-utils/build.gradle.kts b/modules/dev-publish-utils/build.gradle.kts index a80666c..76f673c 100644 --- a/modules/dev-publish-utils/build.gradle.kts +++ b/modules/dev-publish-utils/build.gradle.kts @@ -4,6 +4,14 @@ plugins { description = "Helpers for reading the DevPublish dev Maven repository from a test JVM." +publishing { + repositories { + maven(isolated.rootProject.projectDirectory.dir("build/test-maven-repo")) { + name = "TestMavenRepo" + } + } +} + dependencies { implementation(projects.modules.devPublishCommon)