User: kyle wood Date: 23 Nov 26 05:28 Revision: e0069be60d2f270af6ea985afd8f533ef1d0a42e Summary: Improve error handling around creator downloads TeamCity URL: http://ci.mcdev.io:80/viewModification.html?tab=vcsModificationFiles&modId=10821&personal=false Index: buildSrc/src/main/kotlin/mcdev-core.gradle.kts =================================================================== --- buildSrc/src/main/kotlin/mcdev-core.gradle.kts (revision 37f735141f4e949bcceb52111e97c58496353e55) +++ buildSrc/src/main/kotlin/mcdev-core.gradle.kts (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -69,7 +69,7 @@ languageVersion = KotlinVersion.KOTLIN_2_2 apiVersion = KotlinVersion.KOTLIN_2_2 jvmDefault = JvmDefaultMode.NO_COMPATIBILITY - freeCompilerArgs = listOf("-Xjdk-release=21") + freeCompilerArgs = listOf("-Xjdk-release=21", "-Xallow-contracts-on-more-functions") optIn.add("kotlin.contracts.ExperimentalContracts") } } Index: src/main/kotlin/creator/ParchmentVersion.kt =================================================================== --- src/main/kotlin/creator/ParchmentVersion.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) +++ src/main/kotlin/creator/ParchmentVersion.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -21,6 +21,7 @@ package com.demonwav.mcdev.creator import com.demonwav.mcdev.util.SemanticVersion +import com.demonwav.mcdev.util.fetchOrNull import com.intellij.openapi.diagnostic.logger import com.intellij.util.io.HttpRequests @@ -33,48 +34,52 @@ companion object { private val LOGGER = logger() - suspend fun downloadData(limit: Int = 50): List { + private const val BASE_URL = "https://maven.parchmentmc.org/org/parchmentmc/data/" + + /** + * Returns up to [limit] Parchment versions, newest Minecraft version first, or null after logging a warning if + * none could be downloaded. A Minecraft version whose versions fail to download is left out with a warning. + */ + suspend fun downloadData(limit: Int = 50): List? { val versions = mutableListOf() - val mcVersions = collectSupportedMcVersions() ?: return emptyList() + val mcVersions = collectSupportedMcVersions() ?: return null for (mcVersion in mcVersions) { - val url = "https://maven.parchmentmc.org/org/parchmentmc/data/parchment-$mcVersion/maven-metadata.xml" + val url = "${BASE_URL}parchment-$mcVersion/maven-metadata.xml" + val found = fetchOrNull(LOGGER, url) { - try { + try { - collectMavenVersions(url) - .mapTo(versions) { ParchmentVersion(mcVersion, it) } - if (versions.size > limit) { - return versions.subList(0, limit) + fetchMavenVersions(url) + } catch (e: HttpRequests.HttpStatusException) { + // Some listed Minecraft versions have no Parchment release + if (e.statusCode != 404) { + throw e - } + } - } catch (e: Exception) { - if (e !is HttpRequests.HttpStatusException) { - LOGGER.error("Failed to retrieve Parchment version data from $url", e) + null } + } ?: continue + found.mapTo(versions) { ParchmentVersion(mcVersion, it) } + if (versions.size >= limit) { + return versions.subList(0, limit) } } + if (versions.isEmpty()) { + LOGGER.warn("No Parchment versions found at $BASE_URL") + return null + } return versions } private suspend fun collectSupportedMcVersions(): List? { - try { - val baseUrl = "https://maven.parchmentmc.org/org/parchmentmc/data/" - val scrapeArtifactoryDirectoryListing = scrapeArtifactoryDirectoryListing(baseUrl) - return scrapeArtifactoryDirectoryListing - .asReversed() + val listing = scrapeArtifactoryDirectoryListing(BASE_URL) ?: return null + return listing - .asSequence() - .filter { it.startsWith("parchment-") } - .mapNotNull { - val mcVersion = it.removePrefix("parchment-").removeSuffix("/") - SemanticVersion.tryParse(mcVersion) - } + .asSequence() + .filter { it.startsWith("parchment-") } + .mapNotNull { + val mcVersion = it.removePrefix("parchment-").removeSuffix("/") + SemanticVersion.tryParse(mcVersion) + } + .sortedDescending() - .toList() + .toList() - } catch (e: Exception) { - if (e is HttpRequests.HttpStatusException) { - return null - } + } - LOGGER.error("Failed to list supported Parchment Minecraft versions", e) - } + } - - return null - } +} - } -} Index: src/main/kotlin/creator/custom/derivation/ExtractVersionMajorMinorPropertyDerivation.kt =================================================================== --- src/main/kotlin/creator/custom/derivation/ExtractVersionMajorMinorPropertyDerivation.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) +++ src/main/kotlin/creator/custom/derivation/ExtractVersionMajorMinorPropertyDerivation.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -35,10 +35,9 @@ } val (part1, part2) = from.parts - if (part1 is SemanticVersion.Companion.VersionPart.ReleasePart && - part2 is SemanticVersion.Companion.VersionPart.ReleasePart - ) { - return SemanticVersion(listOf(part1, part2)) + if (part1.isReleasePart && (part2.isReleasePart || part2.isPreReleasePart)) { + val releasePart2 = if (part2.isPreReleasePart) part2.asReleasePart() else part2 + return SemanticVersion(listOf(part1, releasePart2)) } return SemanticVersion(emptyList()) Index: src/main/kotlin/creator/custom/derivation/FetchPaperDependencyVersionForMcVersion.kt =================================================================== --- src/main/kotlin/creator/custom/derivation/FetchPaperDependencyVersionForMcVersion.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) +++ src/main/kotlin/creator/custom/derivation/FetchPaperDependencyVersionForMcVersion.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -32,7 +32,7 @@ override fun derive(parentValues: List): Any { val version = parentValues[0] as SemanticVersion if (version < MinecraftVersions.MC26_1) { - return "${version}-R0.1-SNAPSHOT"; + return "${version}-R0.1-SNAPSHOT" } val isMaven = (parentValues[1] as String) == "Maven" Index: src/main/kotlin/creator/custom/types/ArchitecturyVersionsCreatorProperty.kt =================================================================== --- src/main/kotlin/creator/custom/types/ArchitecturyVersionsCreatorProperty.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) +++ src/main/kotlin/creator/custom/types/ArchitecturyVersionsCreatorProperty.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -35,6 +35,8 @@ import com.demonwav.mcdev.platform.neoforge.version.NeoForgeVersion import com.demonwav.mcdev.util.SemanticVersion import com.demonwav.mcdev.util.asyncIO +import com.demonwav.mcdev.util.noVersionsFound +import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.observable.properties.GraphProperty import com.intellij.openapi.observable.util.not import com.intellij.openapi.observable.util.transform @@ -44,7 +46,6 @@ import com.intellij.ui.dsl.builder.bindItem import com.intellij.ui.dsl.builder.bindSelected import com.intellij.util.application -import com.intellij.util.ui.AsyncProcessIcon import javax.swing.DefaultComboBoxModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.awaitAll @@ -72,7 +73,7 @@ ) private val defaultValue = createDefaultValue(descriptor.default) - private val loadingVersionsProperty = graph.property(true) + internal val downloadStatus = VersionDownloadStatus(graph) override val graphProperty: GraphProperty = graph.property(defaultValue) var model: ArchitecturyVersionsModel by graphProperty @@ -162,9 +163,8 @@ override fun buildUi(panel: Panel) { panel.row("") { - cell(AsyncProcessIcon("ArchitecturyVersions download")) - label(MCDevBundle("creator.ui.versions_download.label")) - }.visibleIf(loadingVersionsProperty) + downloadStatus(downloadStatus, "ArchitecturyVersions download", loadingLabel = true) + }.visibleIf(downloadStatus.loading) panel.row(MCDevBundle("creator.ui.mc_version.label")) { comboBox(mcVersionModel) @@ -173,7 +173,7 @@ .validationOnApply(BuiltinValidations.nonEmptyVersion) .also { ComboboxSpeedSearch.installOn(it.component) } }.enabled(descriptor.editable != false) - .visibleIf(!loadingVersionsProperty) + .visibleIf(!downloadStatus.loading) panel.row(MCDevBundle("creator.ui.architectury.forge_version.label")) { comboBox(forgeVersionsModel) @@ -182,7 +182,7 @@ .also { ComboboxSpeedSearch.installOn(it.component) } .component }.enabled(descriptor.editable != false) - .visibleIf(!loadingVersionsProperty) + .visibleIf(!downloadStatus.loading) panel.row(MCDevBundle("creator.ui.architectury.neoforge_version.label")) { comboBox(nfVersionsModel) @@ -191,7 +191,7 @@ .also { ComboboxSpeedSearch.installOn(it.component) } .component }.enabled(descriptor.editable != false) - .visibleIf(!loadingVersionsProperty) + .visibleIf(!downloadStatus.loading) // // panel.row("Loom Version:") { @@ -209,7 +209,7 @@ .validationOnApply(BuiltinValidations.nonEmptyVersion) .also { ComboboxSpeedSearch.installOn(it.component) } }.enabled(descriptor.editable != false) - .visibleIf(!loadingVersionsProperty) + .visibleIf(!downloadStatus.loading) // Official mappings forced currently, yarn mappings are not handled yet // panel.row("Yarn Version:") { @@ -241,7 +241,7 @@ label(MCDevBundle("creator.ui.warn.no_fabricapi_to_mc_match")) .visibleIf(fabricApiHasMatchingGameVersion.not()) .component.foreground = JBColor.YELLOW - }.visibleIf(!loadingVersionsProperty) + }.visibleIf(!downloadStatus.loading) panel.row(MCDevBundle("creator.ui.architectury.api_version.label")) { comboBox(architecturyApiVersionModel) @@ -257,7 +257,7 @@ .visibleIf(architecturyApiHasMatchingGameVersion.not()) .component.foreground = JBColor.YELLOW }.enabled(descriptor.editable != false) - .visibleIf(!loadingVersionsProperty) + .visibleIf(!downloadStatus.loading) } override fun setupProperty(reporter: TemplateValidationReporter) { @@ -278,7 +278,12 @@ updateArchitecturyApiVersions() } - downloadVersions(context) { + downloadVersions(context) { failure -> + if (failure != null) { + downloadStatus.failed(failure) + return@downloadVersions + } + val fabricVersions = fabricVersions if (fabricVersions != null) { loaderVersionModel.removeAllElements() @@ -291,7 +296,7 @@ loomVersionModel.removeAllElements() loomVersionModel.addAll(loomVersions) val defaultValue = loomVersions.find { - it.parts.any { p -> p is SemanticVersion.Companion.VersionPart.PreReleasePart } + it.parts.any { p -> p.isPreReleasePart } } ?: loomVersions.firstOrNull() ?: emptyVersion loomVersionProperty.set(defaultValue) @@ -299,7 +304,7 @@ updateMcVersionsList() - loadingVersionsProperty.set(false) + downloadStatus.succeeded() } } @@ -314,7 +319,7 @@ val selectedMcVersion = when { mcVersionProperty.get() in mcVersions -> mcVersionProperty.get() defaultValue.minecraft in mcVersions -> defaultValue.minecraft - else -> mcVersions.first() + else -> mcVersions.firstOrNull() ?: emptyVersion } mcVersionProperty.set(selectedMcVersion) } @@ -336,7 +341,7 @@ } } - val availableForgeVersions = forgeVersions!!.getForgeVersions(mcVersion) + val availableForgeVersions = forgeVersions?.getForgeVersions(mcVersion).orEmpty() .take(descriptor.limit ?: 50) forgeVersionsModel.removeAllElements() forgeVersionsModel.addAll(availableForgeVersions) @@ -360,7 +365,7 @@ } } - val availableNeoForgeVersions = neoForgeVersions!!.getNeoForgeVersions(mcVersion) + val availableNeoForgeVersions = neoForgeVersions?.getNeoForgeVersions(mcVersion).orEmpty() .take(descriptor.limit ?: 50) nfVersionsModel.removeAllElements() nfVersionsModel.addAll(availableNeoForgeVersions) @@ -422,17 +427,34 @@ } companion object { - private var hasDownloadedVersions = false + private val LOGGER = logger() + private const val LOOM_URL = + "https://maven.architectury.dev/dev/architectury/architectury-loom/maven-metadata.xml" + // Each part is kept once downloaded, so a later creator only downloads the parts that failed + @Volatile private var forgeVersions: ForgeVersion? = null + + @Volatile private var neoForgeVersions: NeoForgeVersion? = null + + @Volatile private var fabricVersions: FabricVersions? = null + + @Volatile private var loomVersions: List? = null + + @Volatile private var fabricApiVersions: FabricApiVersions? = null + + @Volatile private var architecturyVersions: ArchitecturyVersion? = null + private val hasAllVersions: Boolean + get() = forgeVersions != null && neoForgeVersions != null && fabricVersions != null && + loomVersions != null && fabricApiVersions != null && architecturyVersions != null + internal fun clearCache() { - hasDownloadedVersions = false forgeVersions = null neoForgeVersions = null fabricVersions = null @@ -441,39 +463,64 @@ architecturyVersions = null } - private fun downloadVersions(context: CreatorContext, completeCallback: () -> Unit) { - if (hasDownloadedVersions) { - completeCallback() + private fun downloadVersions( + context: CreatorContext, + completeCallback: (failure: VersionPartFailure?) -> Unit, + ) { + if (hasAllVersions) { + completeCallback(null) return } val scope = context.childScope("ArchitecturyVersionsCreatorProperty") scope.launch(Dispatchers.Default) { - awaitAll( - asyncIO { ForgeVersion.downloadData().also { forgeVersions = it } }, - asyncIO { NeoForgeVersion.downloadData().also { neoForgeVersions = it } }, - asyncIO { FabricVersions.downloadData().also { fabricVersions = it } }, + val failure = awaitAll( asyncIO { - collectMavenVersions( - "https://maven.architectury.dev/dev/architectury/architectury-loom/maven-metadata.xml" - ).also { - loomVersions = it - .mapNotNull(SemanticVersion::tryParse) - .sortedDescending() + downloadPart("Forge", forgeVersions, { forgeVersions = it }) { ForgeVersion.downloadData() } + }, + asyncIO { + downloadPart("NeoForge", neoForgeVersions, { neoForgeVersions = it }) { + NeoForgeVersion.downloadData() } }, - asyncIO { FabricApiVersions.downloadData().also { fabricApiVersions = it } }, - asyncIO { ArchitecturyVersion.downloadData().also { architecturyVersions = it } }, - ) + asyncIO { + downloadPart("Fabric", fabricVersions, { fabricVersions = it }) { + FabricVersions.downloadData() + } + }, + asyncIO { + downloadPart("Architectury Loom", loomVersions, { loomVersions = it }) { + downloadLoomVersions() + } + }, + asyncIO { + downloadPart("Fabric API", fabricApiVersions, { fabricApiVersions = it }) { + FabricApiVersions.downloadData() + } + }, + asyncIO { + downloadPart("Architectury API", architecturyVersions, { architecturyVersions = it }) { + ArchitecturyVersion.downloadData() + } + }, + ).firstNotNullOfOrNull { it } - hasDownloadedVersions = true - withContext(context.uiContext) { - completeCallback() + completeCallback(failure) } } } + + private suspend fun downloadLoomVersions(): Result> { + val versions = collectMavenVersions(LOOM_URL).getOrElse { return Result.failure(it) } + .mapNotNull(SemanticVersion::tryParse) + .sortedDescending() + if (versions.isEmpty()) { + return noVersionsFound(LOGGER, "Architectury Loom", LOOM_URL) - } + } + return Result.success(versions) + } + } class Factory : CreatorPropertyFactory { Index: src/main/kotlin/creator/custom/types/FabricGameVersionCreatorProperty.kt =================================================================== --- src/main/kotlin/creator/custom/types/FabricGameVersionCreatorProperty.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) +++ src/main/kotlin/creator/custom/types/FabricGameVersionCreatorProperty.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -20,7 +20,6 @@ package com.demonwav.mcdev.creator.custom.types -import com.demonwav.mcdev.asset.MCDevBundle import com.demonwav.mcdev.creator.custom.BuiltinValidations import com.demonwav.mcdev.creator.custom.CreatorContext import com.demonwav.mcdev.creator.custom.TemplatePropertyDescriptor @@ -31,7 +30,6 @@ import com.intellij.ui.ComboboxSpeedSearch import com.intellij.ui.dsl.builder.Panel import com.intellij.ui.dsl.builder.bindItem -import com.intellij.util.ui.AsyncProcessIcon import javax.swing.DefaultComboBoxModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch @@ -49,7 +47,7 @@ context: CreatorContext ) : SemanticVersionCreatorProperty(descriptor, context) { - private val loadingVersionsProperty = graph.property(true) + internal val downloadStatus = VersionDownloadStatus(graph) private val versionsModel = DefaultComboBoxModel() override fun buildUi(panel: Panel) { @@ -61,10 +59,7 @@ .enabled(descriptor.editable != false) .also { ComboboxSpeedSearch.installOn(it.component) } - cell(AsyncProcessIcon(makeStorageKey("progress"))) - .visibleIf(loadingVersionsProperty) - label(MCDevBundle("creator.ui.versions_download.label")) - .visibleIf(loadingVersionsProperty) + downloadStatus(downloadStatus, makeStorageKey("progress"), loadingLabel = true) }.propertyVisibility() } @@ -73,8 +68,12 @@ val scope = context.childScope("FabricGameVersionCreatorProperty") scope.launch(Dispatchers.Default) { - val versions = getGameVersions() + val result = getGameVersions() withContext(context.uiContext) { + val versions = result.getOrElse { + downloadStatus.failed(it) + return@withContext + } versionsModel.removeAllElements() versionsModel.addAll(versions.all) if (graphProperty.get() !in versions.all) { @@ -83,23 +82,23 @@ // Clearing the model also cleared its selection, which won't be restored by the binding if the // property kept its (remembered) value versionsModel.selectedItem = graphProperty.get() - loadingVersionsProperty.set(false) + downloadStatus.succeeded() } } } companion object { + @Volatile private var gameVersions: GameVersions? = null internal fun clearCache() { gameVersions = null } - private suspend fun getGameVersions(): GameVersions { - gameVersions?.let { return it } + private suspend fun getGameVersions(): Result { + gameVersions?.let { return Result.success(it) } - val fabricVersions = FabricVersions.downloadData() - ?: return GameVersions(emptyList(), null) + val fabricVersions = FabricVersions.downloadData().getOrElse { return Result.failure(it) } val stableVersions = fabricVersions.game.asSequence() .filter { it.stable } .mapNotNull { SemanticVersion.tryParse(it.version) } @@ -112,8 +111,9 @@ val latestSnapshot = fabricVersions.game.firstOrNull() ?.takeUnless { it.stable } ?.let { SemanticVersion.tryParse(it.version) } - return GameVersions(listOfNotNull(latestSnapshot) + stableVersions, stableVersions.firstOrNull()) - .also { gameVersions = it } + val versions = GameVersions(listOfNotNull(latestSnapshot) + stableVersions, stableVersions.firstOrNull()) + gameVersions = versions + return Result.success(versions) } } Index: src/main/kotlin/creator/custom/types/FabricVersionsCreatorProperty.kt =================================================================== --- src/main/kotlin/creator/custom/types/FabricVersionsCreatorProperty.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) +++ src/main/kotlin/creator/custom/types/FabricVersionsCreatorProperty.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -32,6 +32,8 @@ import com.demonwav.mcdev.util.MinecraftVersions import com.demonwav.mcdev.util.SemanticVersion import com.demonwav.mcdev.util.asyncIO +import com.demonwav.mcdev.util.noVersionsFound +import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.observable.properties.GraphProperty import com.intellij.openapi.observable.util.and import com.intellij.openapi.observable.util.bindBooleanStorage @@ -43,7 +45,6 @@ import com.intellij.ui.dsl.builder.Panel import com.intellij.ui.dsl.builder.bindItem import com.intellij.ui.dsl.builder.bindSelected -import com.intellij.util.ui.AsyncProcessIcon import javax.swing.DefaultComboBoxModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.awaitAll @@ -67,7 +68,7 @@ ) private val defaultValue = createDefaultValue(descriptor.default) - private val loadingVersionsProperty = graph.property(true) + internal val downloadStatus = VersionDownloadStatus(graph) override val graphProperty: GraphProperty = graph.property(defaultValue) var model: FabricVersionsModel by graphProperty @@ -136,9 +137,8 @@ override fun buildUi(panel: Panel) { panel.row("") { - cell(AsyncProcessIcon("FabricVersions download")) - label(MCDevBundle("creator.ui.versions_download.label")) - }.visibleIf(loadingVersionsProperty) + downloadStatus(downloadStatus, "FabricVersions download", loadingLabel = true) + }.visibleIf(downloadStatus.loading) panel.row(MCDevBundle("creator.ui.mc_version.label")) { comboBox(mcVersionModel) @@ -151,7 +151,7 @@ checkBox(MCDevBundle("creator.ui.show_snapshots.label")) .bindSelected(showMcSnapshotsProperty) }.enabled(descriptor.editable != false) - .visibleIf(!loadingVersionsProperty) + .visibleIf(!downloadStatus.loading) panel.row(MCDevBundle("creator.ui.loom_version.label")) { comboBox(loomVersionModel) @@ -160,7 +160,7 @@ .validationOnApply(BuiltinValidations.nonEmptyVersion) .also { ComboboxSpeedSearch.installOn(it.component) } }.enabled(descriptor.editable != false) - .visibleIf(!loadingVersionsProperty) + .visibleIf(!downloadStatus.loading) panel.row(MCDevBundle("creator.ui.loader_version.label")) { comboBox(loaderVersionModel) @@ -169,7 +169,7 @@ .validationOnApply(BuiltinValidations.nonEmptyVersion) .also { ComboboxSpeedSearch.installOn(it.component) } }.enabled(descriptor.editable != false) - .visibleIf(!loadingVersionsProperty) + .visibleIf(!downloadStatus.loading) panel.row(MCDevBundle("creator.ui.yarn_version.label")) { comboBox(yarnVersionModel) @@ -186,7 +186,7 @@ .visibleIf(yarnHasMatchingGameVersion.not()) .component.foreground = JBColor.YELLOW }.enabled(descriptor.editable != false) - .visibleIf(!loadingVersionsProperty and usesMappingsProperty) + .visibleIf(!downloadStatus.loading and usesMappingsProperty) panel.row(MCDevBundle("creator.ui.fabricapi_version.label")) { comboBox(fabricApiVersionModel) @@ -202,7 +202,7 @@ .visibleIf(fabricApiHasMatchingGameVersion.not()) .component.foreground = JBColor.YELLOW }.enabled(descriptor.editable != false) - .visibleIf(!loadingVersionsProperty) + .visibleIf(!downloadStatus.loading) } override fun setupProperty(reporter: TemplateValidationReporter) { @@ -221,7 +221,12 @@ updateFabricApiVersions() } - downloadVersion(context) { + downloadVersions(context) { failure -> + if (failure != null) { + downloadStatus.failed(failure) + return@downloadVersions + } + val fabricVersions = fabricVersions if (fabricVersions != null) { loaderVersionModel.removeAllElements() @@ -242,7 +247,7 @@ loomVersionProperty.set(defaultValue) } - loadingVersionsProperty.set(false) + downloadStatus.succeeded() } } @@ -302,47 +307,68 @@ } companion object { - private var hasDownloadedVersions = false + private val LOGGER = logger() + private const val LOOM_URL = "https://maven.fabricmc.net/net/fabricmc/fabric-loom/maven-metadata.xml" + // Each part is kept once downloaded, so a later creator only downloads the parts that failed + @Volatile private var fabricVersions: FabricVersions? = null + + @Volatile private var loomVersions: List? = null + + @Volatile private var fabricApiVersions: FabricApiVersions? = null + private val hasAllVersions: Boolean + get() = fabricVersions != null && loomVersions != null && fabricApiVersions != null + internal fun clearCache() { - hasDownloadedVersions = false fabricVersions = null loomVersions = null fabricApiVersions = null } - private fun downloadVersion(context: CreatorContext, uiCallback: () -> Unit) { - if (hasDownloadedVersions) { - uiCallback() + private fun downloadVersions(context: CreatorContext, uiCallback: (failure: VersionPartFailure?) -> Unit) { + if (hasAllVersions) { + uiCallback(null) return } val scope = context.childScope("FabricVersionsCreatorProperty") scope.launch(Dispatchers.Default) { - awaitAll( - asyncIO { FabricVersions.downloadData().also { fabricVersions = it } }, + val failure = awaitAll( asyncIO { - collectMavenVersions( - "https://maven.fabricmc.net/net/fabricmc/fabric-loom/maven-metadata.xml" - ).mapNotNull(SemanticVersion::tryParse) - .sortedDescending() - .also { loomVersions = it } + downloadPart("Fabric", fabricVersions, { fabricVersions = it }) { + FabricVersions.downloadData() + } }, - asyncIO { FabricApiVersions.downloadData().also { fabricApiVersions = it } }, - ) + asyncIO { + downloadPart("Fabric Loom", loomVersions, { loomVersions = it }) { downloadLoomVersions() } + }, + asyncIO { + downloadPart("Fabric API", fabricApiVersions, { fabricApiVersions = it }) { + FabricApiVersions.downloadData() + } + }, + ).firstNotNullOfOrNull { it } - hasDownloadedVersions = true - withContext(context.uiContext) { - uiCallback() + uiCallback(failure) } } } + + private suspend fun downloadLoomVersions(): Result> { + val versions = collectMavenVersions(LOOM_URL).getOrElse { return Result.failure(it) } + .mapNotNull(SemanticVersion::tryParse) + .sortedDescending() + if (versions.isEmpty()) { + return noVersionsFound(LOGGER, "Fabric Loom", LOOM_URL) - } + } + return Result.success(versions) + } + } class Factory : CreatorPropertyFactory { Index: src/main/kotlin/creator/custom/types/ForgeVersionsCreatorProperty.kt =================================================================== --- src/main/kotlin/creator/custom/types/ForgeVersionsCreatorProperty.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) +++ src/main/kotlin/creator/custom/types/ForgeVersionsCreatorProperty.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -36,7 +36,6 @@ import com.intellij.ui.dsl.builder.Panel import com.intellij.ui.dsl.builder.RightGap import com.intellij.ui.dsl.builder.bindItem -import com.intellij.util.ui.AsyncProcessIcon import javax.swing.DefaultComboBoxModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch @@ -51,7 +50,7 @@ private val defaultValue = createDefaultValue(descriptor.default) - private val loadingVersionsProperty = graph.property(true) + internal val downloadStatus = VersionDownloadStatus(graph) override val graphProperty: GraphProperty = graph.property(defaultValue) var versions: ForgeVersions by graphProperty @@ -89,9 +88,8 @@ override fun buildUi(panel: Panel) { panel.row("") { - cell(AsyncProcessIcon("ForgeVersions download")) - label(MCDevBundle("creator.ui.versions_download.label")) - }.visibleIf(loadingVersionsProperty) + downloadStatus(downloadStatus, "ForgeVersions download", loadingLabel = true) + }.visibleIf(downloadStatus.loading) panel.row(MCDevBundle("creator.ui.mc_version.label")) { comboBox(mcVersionsModel) @@ -107,7 +105,7 @@ .validationOnApply(BuiltinValidations.nonEmptyVersion) .also { ComboboxSpeedSearch.installOn(it.component) } }.enabled(descriptor.editable != false) - .visibleIf(!loadingVersionsProperty) + .visibleIf(!downloadStatus.loading) } override fun setupProperty(reporter: TemplateValidationReporter) { @@ -119,7 +117,7 @@ } previousMcVersion = mcVersion - val availableForgeVersions = forgeVersion!!.getForgeVersions(mcVersion) + val availableForgeVersions = forgeVersion?.getForgeVersions(mcVersion).orEmpty() .take(descriptor.limit ?: 50) forgeVersionsModel.removeAllElements() forgeVersionsModel.addAll(availableForgeVersions) @@ -148,12 +146,15 @@ } } - downloadVersions(context) { + downloadVersions(context) { failure -> + if (failure == null) { - reloadMinecraftVersions() + reloadMinecraftVersions() - - loadingVersionsProperty.set(false) + downloadStatus.succeeded() + } else { + downloadStatus.failed(failure) - } - } + } + } + } private fun reloadMinecraftVersions() { val forgeVersions = forgeVersion @@ -176,35 +177,32 @@ val selectedMcVersion = when { mcVersionProperty.get() in mcVersions -> mcVersionProperty.get() defaultValue.minecraft in mcVersions -> defaultValue.minecraft - else -> mcVersions.first() + else -> mcVersions.firstOrNull() ?: emptyVersion } mcVersionProperty.set(selectedMcVersion) } companion object { - private var hasDownloadedVersions = false - + @Volatile private var forgeVersion: ForgeVersion? = null internal fun clearCache() { - hasDownloadedVersions = false forgeVersion = null } - private fun downloadVersions(context: CreatorContext, uiCallback: () -> Unit) { - if (hasDownloadedVersions) { - uiCallback() + private fun downloadVersions(context: CreatorContext, uiCallback: (failure: Throwable?) -> Unit) { + if (forgeVersion != null) { + uiCallback(null) return } val scope = context.childScope("ForgeVersionsCreatorProperty") scope.launch(Dispatchers.IO) { - forgeVersion = ForgeVersion.downloadData() + val downloaded = ForgeVersion.downloadData() + downloaded.onSuccess { forgeVersion = it } - hasDownloadedVersions = true - withContext(context.uiContext) { - uiCallback() + uiCallback(downloaded.exceptionOrNull()) } } } Index: src/main/kotlin/creator/custom/types/GradlePluginSelectorCreatorProperty.kt =================================================================== --- src/main/kotlin/creator/custom/types/GradlePluginSelectorCreatorProperty.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) +++ src/main/kotlin/creator/custom/types/GradlePluginSelectorCreatorProperty.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -31,18 +31,17 @@ import com.demonwav.mcdev.creator.custom.types.GradlePluginSelectorCreatorProperty.Holder import com.demonwav.mcdev.util.SemanticVersion import com.demonwav.mcdev.util.getOrLogException +import com.demonwav.mcdev.util.noVersionsFound import com.demonwav.mcdev.util.toBooleanLenient +import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.diagnostic.thisLogger import com.intellij.openapi.observable.properties.GraphProperty import com.intellij.openapi.observable.util.transform import com.intellij.ui.ComboboxSpeedSearch -import com.intellij.ui.JBColor import com.intellij.ui.dsl.builder.Panel import com.intellij.ui.dsl.builder.RightGap import com.intellij.ui.dsl.builder.bindItem import com.intellij.ui.dsl.builder.bindSelected -import com.intellij.ui.dsl.builder.bindText -import com.intellij.util.ui.AsyncProcessIcon import java.util.concurrent.ConcurrentHashMap import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch @@ -52,8 +51,7 @@ descriptor: TemplatePropertyDescriptor, context: CreatorContext ) : CreatorProperty(descriptor, context, Holder::class.java) { - private val loadingVersionsProperty = graph.property(true) - private val loadingVersionsStatusProperty = graph.property("") + internal val downloadStatus = VersionDownloadStatus(graph) private val defaultValue = createDefaultValue(descriptor.default) @@ -108,11 +106,7 @@ combobox.comment(descriptor.translate(warning)) } - cell(AsyncProcessIcon(makeStorageKey("progress"))) - .visibleIf(loadingVersionsProperty) - label("").applyToComponent { foreground = JBColor.RED } - .bindText(loadingVersionsStatusProperty) - .visibleIf(loadingVersionsProperty) + downloadStatus(downloadStatus, makeStorageKey("progress")) versionsModel.afterChange { versions -> combobox.component.removeAllItems() @@ -171,16 +165,14 @@ descriptor.limit ?: 50 ) { result -> result.onSuccess { versions -> - val set = versions.toSet() - versionsModel.set(set) - loadingVersionsProperty.set(false) - }.onFailure { exception -> - loadingVersionsStatusProperty.set(exception.message ?: exception.javaClass.simpleName) + versionsModel.set(versions.toSet()) + downloadStatus.succeeded() + }.onFailure(downloadStatus::failed) - } - } + } + } - } companion object { + private val LOGGER = logger() private val versionsCache = ConcurrentHashMap>() @@ -210,19 +202,19 @@ scope.launch(Dispatchers.Default) { val result = withContext(Dispatchers.IO) { val headers = CreatorCredentials.findMavenRepoAuthHeaders(url) - runCatching { collectMavenVersions(url, headers) } + collectMavenVersions(url, headers) }.map { result -> - val versions = result.asSequence() + result.asSequence() .filter(rawVersionFilter) .mapNotNull(SemanticVersion::tryParse) .filter(versionFilter) .sortedDescending() .take(limit) .toList() - - versionsCache[cacheKey] = versions - versions + }.let { result -> + if (result.getOrNull()?.isEmpty() == true) noVersionsFound(LOGGER, "matching", url) else result } + result.onSuccess { versionsCache[cacheKey] = it } withContext(context.uiContext) { uiCallback(result) Index: src/main/kotlin/creator/custom/types/MavenArtifactVersionCreatorProperty.kt =================================================================== --- src/main/kotlin/creator/custom/types/MavenArtifactVersionCreatorProperty.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) +++ src/main/kotlin/creator/custom/types/MavenArtifactVersionCreatorProperty.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -29,14 +29,13 @@ import com.demonwav.mcdev.creator.custom.TemplateValidationReporter import com.demonwav.mcdev.util.SemanticVersion import com.demonwav.mcdev.util.getOrLogException +import com.demonwav.mcdev.util.noVersionsFound +import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.diagnostic.thisLogger import com.intellij.openapi.observable.properties.GraphProperty import com.intellij.ui.ComboboxSpeedSearch -import com.intellij.ui.JBColor import com.intellij.ui.dsl.builder.Panel import com.intellij.ui.dsl.builder.bindItem -import com.intellij.ui.dsl.builder.bindText -import com.intellij.util.ui.AsyncProcessIcon import java.util.concurrent.ConcurrentHashMap import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch @@ -53,8 +52,7 @@ override val graphProperty: GraphProperty = graph.property(SemanticVersion(emptyList())) private val versionsProperty = graph.property>(emptySet()) - private val loadingVersionsProperty = graph.property(true) - private val loadingVersionsStatusProperty = graph.property("") + internal val downloadStatus = VersionDownloadStatus(graph) override fun buildUi(panel: Panel) { panel.row(descriptor.translatedLabel) { @@ -63,11 +61,7 @@ .enabled(descriptor.editable != false) .also { ComboboxSpeedSearch.installOn(it.component) } - cell(AsyncProcessIcon(makeStorageKey("progress"))) - .visibleIf(loadingVersionsProperty) - label("").applyToComponent { foreground = JBColor.RED } - .bindText(loadingVersionsStatusProperty) - .visibleIf(loadingVersionsProperty) + downloadStatus(downloadStatus, makeStorageKey("progress")) versionsProperty.afterChange { versions -> combobox.component.removeAllItems() @@ -126,14 +120,13 @@ ) { result -> result.onSuccess { versions -> versionsProperty.set(versions.toSet()) - loadingVersionsProperty.set(false) - }.onFailure { exception -> - loadingVersionsStatusProperty.set(exception.message ?: exception.javaClass.simpleName) + downloadStatus.succeeded() + }.onFailure(downloadStatus::failed) - } - } + } + } - } companion object { + private val LOGGER = logger() private val versionsCache = ConcurrentHashMap>() @@ -163,19 +156,19 @@ scope.launch(Dispatchers.Default) { val result = withContext(Dispatchers.IO) { val headers = CreatorCredentials.findMavenRepoAuthHeaders(url) - runCatching { collectMavenVersions(url, headers) } + collectMavenVersions(url, headers) }.map { result -> - val versions = result.asSequence() + result.asSequence() .filter(rawVersionFilter) .mapNotNull(SemanticVersion::tryParse) .filter(versionFilter) .sortedDescending() .take(limit) .toList() - - versionsCache[cacheKey] = versions - versions + }.let { result -> + if (result.getOrNull()?.isEmpty() == true) noVersionsFound(LOGGER, "matching", url) else result } + result.onSuccess { versionsCache[cacheKey] = it } withContext(context.uiContext) { uiCallback(result) Index: src/main/kotlin/creator/custom/types/NeoForgeVersionsCreatorProperty.kt =================================================================== --- src/main/kotlin/creator/custom/types/NeoForgeVersionsCreatorProperty.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) +++ src/main/kotlin/creator/custom/types/NeoForgeVersionsCreatorProperty.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -29,7 +29,7 @@ import com.demonwav.mcdev.creator.custom.model.NeoForgeVersions import com.demonwav.mcdev.platform.neoforge.version.NeoForgeVersion import com.demonwav.mcdev.platform.neoforge.version.NeoGradleVersion -import com.demonwav.mcdev.platform.neoforge.version.platform.neoforge.version.NeoModDevVersion +import com.demonwav.mcdev.platform.neoforge.version.NeoModDevVersion import com.demonwav.mcdev.util.SemanticVersion import com.demonwav.mcdev.util.asyncIO import com.intellij.openapi.observable.properties.GraphProperty @@ -39,7 +39,6 @@ import com.intellij.ui.dsl.builder.Panel import com.intellij.ui.dsl.builder.RightGap import com.intellij.ui.dsl.builder.bindItem -import com.intellij.util.ui.AsyncProcessIcon import javax.swing.DefaultComboBoxModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.awaitAll @@ -55,7 +54,7 @@ private val defaultValue = createDefaultValue(descriptor.default) - private val loadingVersionsProperty = graph.property(true) + internal val downloadStatus = VersionDownloadStatus(graph) override val graphProperty: GraphProperty = graph.property(defaultValue) var versions: NeoForgeVersions by graphProperty @@ -95,9 +94,8 @@ override fun buildUi(panel: Panel) { panel.row("") { - cell(AsyncProcessIcon("NeoForgeVersions download")) - label(MCDevBundle("creator.ui.versions_download.label")) - }.visibleIf(loadingVersionsProperty) + downloadStatus(downloadStatus, "NeoForgeVersions download", loadingLabel = true) + }.visibleIf(downloadStatus.loading) panel.row(MCDevBundle("creator.ui.mc_version.label")) { comboBox(mcVersionsModel) @@ -113,7 +111,7 @@ .validationOnApply(BuiltinValidations.nonEmptyVersion) .also { ComboboxSpeedSearch.installOn(it.component) } }.enabled(descriptor.editable != false) - .visibleIf(!loadingVersionsProperty) + .visibleIf(!downloadStatus.loading) } override fun setupProperty(reporter: TemplateValidationReporter) { @@ -125,7 +123,7 @@ } previousMcVersion = mcVersion - val availableNfVersions = nfVersion!!.getNeoForgeVersions(mcVersion) + val availableNfVersions = nfVersion?.getNeoForgeVersions(mcVersion).orEmpty() .take(descriptor.limit ?: 50) nfVersionsModel.removeAllElements() nfVersionsModel.addAll(availableNfVersions) @@ -133,72 +131,77 @@ } val mcVersionFilter = descriptor.parameters?.get("mcVersionFilter") as? String - downloadVersion(context, mcVersionFilter) { - val mcVersions = mcVersions ?: return@downloadVersion + downloadVersions(context) { failure -> + if (failure != null) { + downloadStatus.failed(failure) + return@downloadVersions + } + val mcVersions = nfVersion?.sortedMcVersions.orEmpty().filter { version -> + mcVersionFilter == null || + TemplateEvaluator.condition(mapOf("MC_VERSION" to version), mcVersionFilter).getOrDefault(true) + } + mcVersionsModel.removeAllElements() mcVersionsModel.addAll(mcVersions) val selectedMcVersion = when { mcVersionProperty.get() in mcVersions -> mcVersionProperty.get() defaultValue.minecraft in mcVersions -> defaultValue.minecraft - else -> mcVersions.first() + else -> mcVersions.firstOrNull() ?: emptyVersion } mcVersionProperty.set(selectedMcVersion) ngVersionProperty.set(ngVersion?.versions?.firstOrNull() ?: emptyVersion) mdVersionProperty.set(mdVersion?.versions?.firstOrNull() ?: emptyVersion) - loadingVersionsProperty.set(false) + downloadStatus.succeeded() } } companion object { - private var hasDownloadedVersions = false - + // Each part is kept once downloaded, so a later creator only downloads the parts that failed + @Volatile private var nfVersion: NeoForgeVersion? = null + + @Volatile private var ngVersion: NeoGradleVersion? = null + + @Volatile private var mdVersion: NeoModDevVersion? = null - private var mcVersions: List? = null + private val hasAllVersions: Boolean + get() = nfVersion != null && ngVersion != null && mdVersion != null + internal fun clearCache() { - hasDownloadedVersions = false nfVersion = null ngVersion = null mdVersion = null - mcVersions = null } - private fun downloadVersion(context: CreatorContext, mcVersionFilter: String?, uiCallback: () -> Unit) { - if (hasDownloadedVersions) { - uiCallback() + private fun downloadVersions(context: CreatorContext, uiCallback: (failure: VersionPartFailure?) -> Unit) { + if (hasAllVersions) { + uiCallback(null) return } val scope = context.childScope("NeoForgeVersionsCreatorProperty") scope.launch(Dispatchers.Default) { - awaitAll( - asyncIO { NeoForgeVersion.downloadData().also { nfVersion = it } }, - asyncIO { NeoGradleVersion.downloadData().also { ngVersion = it } }, - asyncIO { NeoModDevVersion.downloadData().also { mdVersion = it } }, - ) + val failure = awaitAll( + asyncIO { + downloadPart("NeoForge", nfVersion, { nfVersion = it }) { NeoForgeVersion.downloadData() } + }, + asyncIO { + downloadPart("NeoGradle", ngVersion, { ngVersion = it }) { NeoGradleVersion.downloadData() } + }, + asyncIO { + downloadPart("ModDevGradle", mdVersion, { mdVersion = it }) { NeoModDevVersion.downloadData() } + }, + ).firstNotNullOfOrNull { it } - mcVersions = nfVersion?.sortedMcVersions?.let { mcVersion -> - if (mcVersionFilter != null) { - mcVersion.filter { version -> - val conditionProps = mapOf("MC_VERSION" to version) - TemplateEvaluator.condition(conditionProps, mcVersionFilter).getOrDefault(true) - } - } else { - mcVersion - } - } - - hasDownloadedVersions = true - withContext(context.uiContext) { - uiCallback() + uiCallback(failure) } } } Index: src/main/kotlin/creator/custom/types/PaperVersionCreatorProperty.kt =================================================================== --- src/main/kotlin/creator/custom/types/PaperVersionCreatorProperty.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) +++ src/main/kotlin/creator/custom/types/PaperVersionCreatorProperty.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -24,18 +24,18 @@ import com.demonwav.mcdev.creator.custom.TemplatePropertyDescriptor import com.demonwav.mcdev.creator.custom.TemplateValidationReporter import com.demonwav.mcdev.update.PluginUtil +import com.demonwav.mcdev.util.McdevHttp import com.demonwav.mcdev.util.MinecraftVersions import com.demonwav.mcdev.util.SemanticVersion -import com.demonwav.mcdev.util.McdevHttp +import com.demonwav.mcdev.util.fetchOrNull +import com.intellij.openapi.diagnostic.logger import com.intellij.ui.ComboboxSpeedSearch -import com.intellij.ui.JBColor import com.intellij.ui.dsl.builder.Panel import com.intellij.ui.dsl.builder.bindItem -import com.intellij.ui.dsl.builder.bindText -import com.intellij.util.io.HttpRequests -import com.intellij.util.ui.AsyncProcessIcon +import java.io.IOException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext import kotlinx.serialization.json.Json import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonObject @@ -47,49 +47,56 @@ ) : SemanticVersionCreatorProperty(descriptor, context) { companion object { + private val LOGGER = logger() + private const val URL = "https://fill.papermc.io/v3/projects/paper" + + @Volatile private var paperVersions: List? = null internal fun clearCache() { paperVersions = null } - suspend fun getPaperVersions(): List { + /** + * Returns the Paper release versions from 1.18.2 on, newest first, or null after logging a warning if the + * download fails or finds none. + */ + suspend fun getPaperVersions(): List? { paperVersions?.let { return it } - val body = try { - McdevHttp.get("https://fill.papermc.io/v3/projects/paper") { + val versions = fetchOrNull(LOGGER, URL) { + val body = McdevHttp.get(URL) { userAgent("minecraft-dev/${PluginUtil.pluginVersion} (https://github.com/minecraft-dev/MinecraftDev)") }.suspend().connect { readString() } - } catch (_: HttpRequests.HttpStatusException) { - null + parse(body) + } ?: return null + if (versions.isEmpty()) { + LOGGER.warn("No Paper versions found at $URL") + return null } - if (body != null) { - val element = Json.parseToJsonElement(body) - val result = element.jsonObject["versions"]?.jsonObject?.values - ?.asSequence() - ?.flatMap { it.jsonArray } - ?.map { it.jsonPrimitive.content } - ?.mapNotNull { SemanticVersion.tryParse(it) } - // only release versions - ?.filter { ver -> ver.parts.all { it is SemanticVersion.Companion.VersionPart.ReleasePart } } - // nothing lower than 1.18.2 should be selectable - ?.filter { it >= MinecraftVersions.MC1_18_2 } - ?.toList() - ?.sortedDescending() - if (result != null) { - paperVersions = result - return result + paperVersions = versions + return versions - } + } - } - return emptyList() + private fun parse(body: String): List { + val groups = Json.parseToJsonElement(body).jsonObject["versions"]?.jsonObject + ?: throw IOException("Unexpected Paper version data") + return groups.values.asSequence() + .flatMap { it.jsonArray } + .map { it.jsonPrimitive.content } + .mapNotNull { SemanticVersion.tryParse(it) } + // only release versions + .filter { ver -> ver.parts.all { it.isReleasePart } } + // nothing lower than 1.18.2 should be selectable + .filter { it >= MinecraftVersions.MC1_18_2 } + .sortedDescending() + .toList() } } + internal val downloadStatus = VersionDownloadStatus(graph) private val versionsProperty = graph.property>(emptySet()) - private val loadingVersionsProperty = graph.property(true) - private val loadingVersionsStatusProperty = graph.property("") override fun buildUi(panel: Panel) { panel.row(descriptor.translatedLabel) { @@ -98,11 +105,7 @@ .enabled(descriptor.editable != false) .also { ComboboxSpeedSearch.installOn(it.component) } - cell(AsyncProcessIcon(makeStorageKey("progress"))) - .visibleIf(loadingVersionsProperty) - label("").applyToComponent { foreground = JBColor.RED } - .bindText(loadingVersionsStatusProperty) - .visibleIf(loadingVersionsProperty) + downloadStatus(downloadStatus, makeStorageKey("progress")) versionsProperty.afterChange { versions -> combobox.component.removeAllItems() @@ -118,10 +121,16 @@ val scope = context.childScope("PaperVersionCreatorProperty") scope.launch(Dispatchers.Default) { val result = getPaperVersions() + withContext(context.uiContext) { + if (result == null) { + downloadStatus.failed() + } else { - versionsProperty.set(result.toSet()) + versionsProperty.set(result.toSet()) - loadingVersionsProperty.set(false) + downloadStatus.succeeded() - } - } + } + } + } + } class Factory : CreatorPropertyFactory { override fun create( Index: src/main/kotlin/creator/custom/types/ParchmentCreatorProperty.kt =================================================================== --- src/main/kotlin/creator/custom/types/ParchmentCreatorProperty.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) +++ src/main/kotlin/creator/custom/types/ParchmentCreatorProperty.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -54,6 +54,8 @@ private var availableParchmentVersions: List = emptyList() + internal val downloadStatus = VersionDownloadStatus(graph) + private val useParchmentProperty = graphProperty.transform({ it.use }, { versions.copy(use = it) }) private val versionProperty = graphProperty.transform({ it.version }, { versions.copy(version = it) }) private val versionsModel = DefaultComboBoxModel() @@ -93,36 +95,42 @@ } override fun buildUi(panel: Panel) { + val editable = descriptor.editable != false + val parchmentEnabled = useParchmentProperty.transform { it && editable } + panel.row(descriptor.translatedLabel) { @Suppress("DialogTitleCapitalization") checkBox(MCDevBundle("creator.ui.parchment.use.label")) .bindSelected(useParchmentProperty) + .enabled(editable) comboBox(mcVersionsModel) .bindItem(mcVersionProperty) - .enabledIf(useParchmentProperty) + .enabledIf(parchmentEnabled) .validationOnInput(BuiltinValidations.nonEmptyVersion) .validationOnApply(BuiltinValidations.nonEmptyVersion) .also { ComboboxSpeedSearch.installOn(it.component) } comboBox(versionsModel) .bindItem(versionProperty) - .enabledIf(useParchmentProperty) + .enabledIf(parchmentEnabled) .validationOnInput(BuiltinValidations.nonEmptyVersion) .validationOnApply(BuiltinValidations.nonEmptyVersion) .also { ComboboxSpeedSearch.installOn(it.component) } - }.enabled(descriptor.editable != false) + downloadStatus(downloadStatus, makeStorageKey("progress")) + } + panel.row(MCDevBundle("creator.ui.parchment.include.label")) { checkBox(MCDevBundle("creator.ui.parchment.include.older_mc_versions")) .bindSelected(includeOlderMcVersionsProperty) - .enabledIf(useParchmentProperty) + .enabledIf(parchmentEnabled) checkBox(MCDevBundle("creator.ui.parchment.include.snapshots")) .bindSelected(includeSnapshotsProperty) - .enabledIf(useParchmentProperty) - }.enabled(descriptor.editable != false) + .enabledIf(parchmentEnabled) - } + } + } override fun setupProperty(reporter: TemplateValidationReporter) { super.setupProperty(reporter) @@ -168,10 +176,15 @@ refreshVersionsLists() } - downloadVersions(context) { + downloadVersions(context) { success -> + if (success) { - refreshVersionsLists() + refreshVersionsLists() + downloadStatus.succeeded() + } else { + downloadStatus.failed() - } - } + } + } + } private fun refreshVersionsLists(updateMcVersions: Boolean = true, forceLatestVersions: Boolean = false) { val includeOlderMcVersions = includeOlderMcVersionsProperty.get() || forceLatestVersions @@ -244,7 +257,7 @@ // Ensures we get no trailing .0 for the first major version (1.21.0 -> 1.21) // This is required because otherwise those versions won't be properly compared against Parchment's val normalizedVersion = version.parts.dropLastWhile { part -> - part is SemanticVersion.Companion.VersionPart.ReleasePart && part.version == 0 + part.isReleasePart && part.version == 0 } return SemanticVersion(normalizedVersion) @@ -252,30 +265,28 @@ companion object { - private var hasDownloadedVersions = false - + @Volatile private var allParchmentVersions: List? = null internal fun clearCache() { - hasDownloadedVersions = false allParchmentVersions = null } - private fun downloadVersions(context: CreatorContext, uiCallback: () -> Unit) { - if (hasDownloadedVersions) { - uiCallback() + private fun downloadVersions(context: CreatorContext, uiCallback: (success: Boolean) -> Unit) { + if (allParchmentVersions != null) { + uiCallback(true) return } val scope = context.childScope("ParchmentCreatorProperty") scope.launch(Dispatchers.IO) { - allParchmentVersions = ParchmentVersion.downloadData() - .sortedByDescending(ParchmentVersion::parchmentVersion) + val downloaded = ParchmentVersion.downloadData() + if (downloaded != null) { + allParchmentVersions = downloaded + } - hasDownloadedVersions = true - withContext(context.uiContext) { - uiCallback() + uiCallback(downloaded != null) } } } Index: src/main/kotlin/creator/custom/types/VersionDownloadStatus.kt =================================================================== --- src/main/kotlin/creator/custom/types/VersionDownloadStatus.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) +++ src/main/kotlin/creator/custom/types/VersionDownloadStatus.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -0,0 +1,132 @@ +/* + * Minecraft Development for IntelliJ + * + * https://mcdev.io/ + * + * Copyright (C) 2026 minecraft-dev + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published + * by the Free Software Foundation, version 3.0 only. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.demonwav.mcdev.creator.custom.types + +import com.demonwav.mcdev.asset.MCDevBundle +import com.demonwav.mcdev.util.NoVersionsFoundException +import com.intellij.openapi.observable.properties.GraphProperty +import com.intellij.openapi.observable.properties.ObservableProperty +import com.intellij.openapi.observable.properties.PropertyGraph +import com.intellij.openapi.observable.util.and +import com.intellij.openapi.observable.util.not +import com.intellij.openapi.observable.util.transform +import com.intellij.ui.JBColor +import com.intellij.ui.dsl.builder.Row +import com.intellij.ui.dsl.builder.bindText +import com.intellij.util.ui.AsyncProcessIcon + +/** + * Tracks a version property's download, for display with [downloadStatus]. + */ +class VersionDownloadStatus(graph: PropertyGraph) { + + /** + * True until the versions are downloaded. Stays true after a failure. + */ + val loading: GraphProperty = graph.property(true) + + /** + * The message shown for a failed download, or empty if it hasn't failed. + */ + val failure: GraphProperty = graph.property("") + + val failed: ObservableProperty = failure.transform { it.isNotEmpty() } + + fun succeeded() { + failure.set("") + loading.set(false) + } + + fun failed(message: String = MCDevBundle("creator.ui.versions_download.failed")) { + failure.set(message) + } + + /** + * Shows a failure message that includes the message of [cause]. + */ + fun failed(cause: Throwable) { + failed( + if (cause is NoVersionsFoundException) { + MCDevBundle("creator.ui.versions_download.none_found") + } else { + MCDevBundle("creator.ui.versions_download.failed_cause", describe(cause)) + } + ) + } + + /** + * Shows a failure message that names the part that failed and includes the message of its cause. + */ + fun failed(failure: VersionPartFailure) { + val (part, cause) = failure + failed( + if (cause is NoVersionsFoundException) { + MCDevBundle("creator.ui.versions_download.none_found_part", part) + } else { + MCDevBundle("creator.ui.versions_download.failed_part", part, describe(cause)) + } + ) + } + + private fun describe(cause: Throwable): String = cause.message ?: cause.javaClass.simpleName +} + +/** + * A failed part of a property that downloads several sets of versions. [part] names the versions in the UI. + */ +data class VersionPartFailure(val part: String, val cause: Throwable) + +/** + * Downloads one part of a multi-part property unless [cached] is already set, passing a successful result to [store]. + * Returns the failure, or null if the part is available. + */ +internal inline fun downloadPart( + part: String, + cached: T?, + store: (T) -> Unit, + download: () -> Result, +): VersionPartFailure? { + if (cached != null) { + return null + } + return download().fold( + onSuccess = { + store(it) + null + }, + onFailure = { VersionPartFailure(part, it) }, + ) +} + +/** + * Adds a spinner to this row while [status] is loading, and the failure message once it fails. With [loadingLabel], + * a "Downloading versions" label shows next to the spinner. + */ +fun Row.downloadStatus(status: VersionDownloadStatus, iconKey: String, loadingLabel: Boolean = false) { + val inProgress = status.loading and !status.failed + cell(AsyncProcessIcon(iconKey)).visibleIf(inProgress) + if (loadingLabel) { + label(MCDevBundle("creator.ui.versions_download.label")).visibleIf(inProgress) + } + label("").applyToComponent { foreground = JBColor.RED } + .bindText(status.failure) + .visibleIf(status.failed) +} Index: src/main/kotlin/creator/maven-repo-utils.kt =================================================================== --- src/main/kotlin/creator/maven-repo-utils.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) +++ src/main/kotlin/creator/maven-repo-utils.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -21,77 +21,71 @@ package com.demonwav.mcdev.creator import com.demonwav.mcdev.util.McdevHttp +import com.demonwav.mcdev.util.fetchCatching +import com.demonwav.mcdev.util.fetchOrNull +import com.demonwav.mcdev.util.loggerForTopLevel import java.io.IOException +import java.io.InputStream import java.util.function.Predicate import javax.xml.stream.XMLInputFactory -import javax.xml.stream.events.XMLEvent +import javax.xml.stream.XMLStreamConstants +import javax.xml.stream.XMLStreamException -@Throws(IOException::class) +private val LOGGER = loggerForTopLevel() + +/** + * Returns the versions in the Maven metadata at [url] that match [filter], or a failure after logging a warning if + * the download or parse fails. + */ suspend fun collectMavenVersions( url: String, headers: Map = emptyMap(), filter: Predicate = Predicate { true } -): List = McdevHttp.get(url, headers).suspend().connect { - val result = mutableListOf() - inputStream.use { stream -> - val inputFactory = XMLInputFactory.newInstance() +): Result> = fetchCatching(LOGGER, url) { fetchMavenVersions(url, headers, filter) } - @Suppress("UNCHECKED_CAST") - val reader = inputFactory.createXMLEventReader(stream) as Iterator - for (event in reader) { - if (!event.isStartElement) { - continue +/** + * Like [collectMavenVersions], but throws on failure. + */ +@Throws(IOException::class, XMLStreamException::class) +internal suspend fun fetchMavenVersions( + url: String, + headers: Map = emptyMap(), + filter: Predicate = Predicate { true } +): List = McdevHttp.get(url, headers).suspend().connect { + inputStream.use { stream -> readElementTexts(stream, "version").filter(filter::test) } - } +} - val start = event.asStartElement() - val name = start.name.localPart - if (name != "version") { - continue - } - val versionEvent = reader.next() - if (!versionEvent.isCharacters) { - continue - } +/** + * Returns the entries of the directory listing at [url], or null after logging a warning if the download or parse + * fails. Directories end with `/`. + */ +suspend fun scrapeArtifactoryDirectoryListing(url: String): List? = + fetchOrNull(LOGGER, url) { fetchArtifactoryDirectoryListing(url) } - val version = versionEvent.asCharacters().data - if (filter.test(version)) { - result += version +/** + * Like [scrapeArtifactoryDirectoryListing], but throws on failure. + */ +@Throws(IOException::class, XMLStreamException::class) +internal suspend fun fetchArtifactoryDirectoryListing(url: String): List = McdevHttp.get(url).suspend().connect { + inputStream.use { stream -> readElementTexts(stream, "a").filter { it != "../" } } - } +} - } - } - result -} - -@Throws(IOException::class) -suspend fun scrapeArtifactoryDirectoryListing(url: String): List = McdevHttp.get(url).suspend().connect { +private fun readElementTexts(stream: InputStream, element: String): List { + val factory = XMLInputFactory.newInstance() + factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false) + val reader = factory.createXMLStreamReader(stream) + try { - val result = mutableListOf() + val result = mutableListOf() - inputStream.use { stream -> - val inputFactory = XMLInputFactory.newInstance() - - @Suppress("UNCHECKED_CAST") - val reader = inputFactory.createXMLEventReader(stream) as Iterator - for (event in reader) { - if (!event.isStartElement) { - continue + while (reader.hasNext()) { + if (reader.next() == XMLStreamConstants.START_ELEMENT && reader.localName == element) { + val text = reader.elementText.trim() + if (text.isNotEmpty()) { + result += text - } + } - val start = event.asStartElement() - val name = start.name.localPart - if (name != "a") { - continue } - - val childPathEvent = reader.next() - if (!childPathEvent.isCharacters) { - continue - } + } - - val childPath = childPathEvent.asCharacters().data - if (childPath != "../") { - result += childPath + return result + } finally { + reader.close() - } - } + } +} - } - - result -} Index: src/main/kotlin/platform/architectury/ArchitecturyVersion.kt =================================================================== --- src/main/kotlin/platform/architectury/ArchitecturyVersion.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) +++ src/main/kotlin/platform/architectury/ArchitecturyVersion.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -20,11 +20,14 @@ package com.demonwav.mcdev.platform.architectury -import com.demonwav.mcdev.util.SemanticVersion -import com.demonwav.mcdev.util.fromJson import com.demonwav.mcdev.util.McdevHttp +import com.demonwav.mcdev.util.SemanticVersion +import com.demonwav.mcdev.util.fetchCatching +import com.demonwav.mcdev.util.noVersionsFound import com.google.gson.Gson import com.google.gson.annotations.SerializedName +import com.intellij.openapi.diagnostic.logger +import java.io.IOException class ArchitecturyVersion private constructor( val versions: Map>, @@ -42,36 +45,45 @@ ) companion object { + private val LOGGER = logger() + private const val URL = "https://api.modrinth.com/v2/project/architectury-api/version" - suspend fun downloadData(): ArchitecturyVersion? { - try { - val url = "https://api.modrinth.com/v2/project/architectury-api/version" - val response = McdevHttp.getString(url) + /** + * Returns the Architectury API versions by Minecraft version, or a failure after logging a warning if the + * download fails or finds none. + */ + suspend fun downloadData(): Result { + val versions = fetchCatching(LOGGER, URL) { parse(McdevHttp.getString(URL)) } + .getOrElse { return Result.failure(it) } + if (versions.versions.isEmpty()) { + return noVersionsFound(LOGGER, "Architectury API", URL) + } + return Result.success(versions) + } - val data = Gson().fromJson>(response) + private fun parse(response: String): ArchitecturyVersion { + // Gson gives null for an empty body + val data: Array = Gson().fromJson(response, Array::class.java) + ?: throw IOException("Unexpected Architectury API version data") - val apiVersionMap = HashMap>() + val apiVersionMap = HashMap>() - for (version in data) { - val apiVersion = SemanticVersion.parse(version.versionNumber.substringBeforeLast('+')) + for (version in data) { + val apiVersion = SemanticVersion.parse(version.versionNumber.substringBeforeLast('+')) - for (gameVersion in version.gameVersions) { - val parsed = SemanticVersion.tryParse(gameVersion) ?: continue - val set = apiVersionMap.computeIfAbsent(parsed) { HashSet() } - set += apiVersion - } - } + for (gameVersion in version.gameVersions) { + val parsed = SemanticVersion.tryParse(gameVersion) ?: continue + val set = apiVersionMap.computeIfAbsent(parsed) { HashSet() } + set += apiVersion + } + } - val apiVersionMapList = HashMap>() - for ((mcVersion, archList) in apiVersionMap.entries) { - apiVersionMapList[mcVersion] = archList.sortedDescending() - } + val apiVersionMapList = HashMap>() + for ((mcVersion, archList) in apiVersionMap.entries) { + apiVersionMapList[mcVersion] = archList.sortedDescending() + } - return ArchitecturyVersion(apiVersionMapList) + return ArchitecturyVersion(apiVersionMapList) - } catch (e: Exception) { - e.printStackTrace() - return null - } - } - } + } + } +} -} Index: src/main/kotlin/platform/fabric/util/FabricApiVersions.kt =================================================================== --- src/main/kotlin/platform/fabric/util/FabricApiVersions.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) +++ src/main/kotlin/platform/fabric/util/FabricApiVersions.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -20,10 +20,11 @@ package com.demonwav.mcdev.platform.fabric.util -import com.demonwav.mcdev.util.SemanticVersion import com.demonwav.mcdev.util.McdevHttp +import com.demonwav.mcdev.util.SemanticVersion +import com.demonwav.mcdev.util.fetchCatching +import com.demonwav.mcdev.util.noVersionsFound import com.google.gson.JsonParser -import com.google.gson.JsonSyntaxException import com.intellij.openapi.diagnostic.logger import java.io.IOException @@ -33,45 +34,46 @@ class Version(val gameVersions: List, val version: SemanticVersion) companion object { - suspend fun downloadData(): FabricApiVersions? { - try { - val url = "https://api.modrinth.com/v2/project/P7dR8mSH/version" - val text = McdevHttp.getString(url) + private const val URL = "https://api.modrinth.com/v2/project/P7dR8mSH/version" + /** + * Returns the Fabric API versions, or a failure after logging a warning if the download fails or finds none. + */ + suspend fun downloadData(): Result { + val versions = fetchCatching(LOGGER, URL) { + parse(McdevHttp.getString(URL)) ?: throw IOException("Unexpected Fabric API version data") + }.getOrElse { return Result.failure(it) } + if (versions.versions.isEmpty()) { + return noVersionsFound(LOGGER, "Fabric API", URL) + } + return Result.success(versions) + } + + private fun parse(text: String): FabricApiVersions? { - val versions = mutableListOf() - val json = JsonParser.parseString(text)?.asJsonArray ?: return null - versionLoop@ - for (ver in json) { - val version = ver?.asJsonObject ?: return null - val files = version["files"]?.asJsonArray ?: return null - for (file in files) { - val fileObj = file?.asJsonObject ?: return null - val filename = fileObj["filename"]?.asString ?: return null - if (!filename.startsWith("fabric-api-")) { - continue@versionLoop - } - } - val versionNumber = version["version_number"]?.asString?.let(SemanticVersion::tryParse) - ?: return null - val gameVersions = version["game_versions"]?.asJsonArray ?: return null - val gameVersionsList = mutableListOf() - for (gameVer in gameVersions) { - val gameVersion = gameVer?.asString ?: return null - gameVersionsList += gameVersion - } - versions += Version(gameVersionsList, versionNumber) - } - return FabricApiVersions(versions) + val versions = mutableListOf() + val json = JsonParser.parseString(text)?.asJsonArray ?: return null + versionLoop@ + for (ver in json) { + val version = ver?.asJsonObject ?: return null + val files = version["files"]?.asJsonArray ?: return null + for (file in files) { + val fileObj = file?.asJsonObject ?: return null + val filename = fileObj["filename"]?.asString ?: return null + if (!filename.startsWith("fabric-api-")) { + continue@versionLoop + } + } + val versionNumber = version["version_number"]?.asString?.let(SemanticVersion::tryParse) + ?: return null + val gameVersions = version["game_versions"]?.asJsonArray ?: return null + val gameVersionsList = mutableListOf() + for (gameVer in gameVersions) { + val gameVersion = gameVer?.asString ?: return null + gameVersionsList += gameVersion + } + versions += Version(gameVersionsList, versionNumber) + } + return FabricApiVersions(versions) - } catch (e: IOException) { - LOGGER.error(e) - } catch (e: JsonSyntaxException) { - LOGGER.error(e) - } catch (e: IllegalStateException) { - LOGGER.error(e) - } catch (e: UnsupportedOperationException) { - LOGGER.error(e) - } + } - return null - } - } + } +} -} Index: src/main/kotlin/platform/fabric/util/FabricVersions.kt =================================================================== --- src/main/kotlin/platform/fabric/util/FabricVersions.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) +++ src/main/kotlin/platform/fabric/util/FabricVersions.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -21,10 +21,11 @@ package com.demonwav.mcdev.platform.fabric.util import com.demonwav.mcdev.creator.custom.model.TemplateApi -import com.demonwav.mcdev.util.SemanticVersion import com.demonwav.mcdev.util.McdevHttp +import com.demonwav.mcdev.util.SemanticVersion +import com.demonwav.mcdev.util.fetchCatching +import com.demonwav.mcdev.util.noVersionsFound import com.google.gson.JsonParser -import com.google.gson.JsonSyntaxException import com.intellij.openapi.diagnostic.logger import java.io.IOException @@ -41,50 +42,52 @@ } companion object { - suspend fun downloadData(): FabricVersions? { - try { - val url = "https://meta.fabricmc.net/v2/versions" - val text = McdevHttp.getString(url) + private const val URL = "https://meta.fabricmc.net/v2/versions" + /** + * Returns the Fabric game, Yarn and loader versions, or a failure after logging a warning if the download + * fails or finds no game versions. + */ + suspend fun downloadData(): Result { + val versions = fetchCatching(LOGGER, URL) { + parse(McdevHttp.getString(URL)) ?: throw IOException("Unexpected Fabric version data") + }.getOrElse { return Result.failure(it) } + if (versions.game.isEmpty()) { + return noVersionsFound(LOGGER, "Fabric game", URL) + } + return Result.success(versions) + } + + private fun parse(text: String): FabricVersions? { - val gameList = mutableListOf() - val mappingsList = mutableListOf() - val loaderList = mutableListOf() - val json = JsonParser.parseString(text)?.asJsonObject ?: return null + val gameList = mutableListOf() + val mappingsList = mutableListOf() + val loaderList = mutableListOf() + val json = JsonParser.parseString(text)?.asJsonObject ?: return null - val game = json["game"]?.asJsonArray ?: return null - for (version in game) { - val versionObj = version?.asJsonObject ?: return null - val gameVer = versionObj["version"]?.asString ?: return null - val stable = versionObj["stable"]?.asBoolean ?: return null - gameList += Game(gameVer, stable) - } + val game = json["game"]?.asJsonArray ?: return null + for (version in game) { + val versionObj = version?.asJsonObject ?: return null + val gameVer = versionObj["version"]?.asString ?: return null + val stable = versionObj["stable"]?.asBoolean ?: return null + gameList += Game(gameVer, stable) + } - val mappings = json["mappings"]?.asJsonArray ?: return null - for (mapping in mappings) { - val mappingObj = mapping?.asJsonObject ?: return null - val gameVersion = mappingObj["gameVersion"]?.asString ?: return null - val version = mappingObj["version"]?.asString ?: return null - val build = mappingObj["build"]?.asInt ?: return null - mappingsList += Mappings(gameVersion, YarnVersion(version, build)) - } + val mappings = json["mappings"]?.asJsonArray ?: return null + for (mapping in mappings) { + val mappingObj = mapping?.asJsonObject ?: return null + val gameVersion = mappingObj["gameVersion"]?.asString ?: return null + val version = mappingObj["version"]?.asString ?: return null + val build = mappingObj["build"]?.asInt ?: return null + mappingsList += Mappings(gameVersion, YarnVersion(version, build)) + } - val loaders = json["loader"]?.asJsonArray ?: return null - for (loader in loaders) { - val loaderObj = loader?.asJsonObject ?: return null - val version = loaderObj["version"]?.asString?.let(SemanticVersion::tryParse) ?: return null - loaderList += version - } - return FabricVersions(gameList, mappingsList, loaderList) + val loaders = json["loader"]?.asJsonArray ?: return null + for (loader in loaders) { + val loaderObj = loader?.asJsonObject ?: return null + val version = loaderObj["version"]?.asString?.let(SemanticVersion::tryParse) ?: return null + loaderList += version + } + return FabricVersions(gameList, mappingsList, loaderList) - } catch (e: IOException) { - LOGGER.error(e) - } catch (e: JsonSyntaxException) { - LOGGER.error(e) - } catch (e: IllegalStateException) { - LOGGER.error(e) - } catch (e: UnsupportedOperationException) { - LOGGER.error(e) - } + } - return null - } - } + } +} -} Index: src/main/kotlin/platform/forge/version/ForgeVersion.kt =================================================================== --- src/main/kotlin/platform/forge/version/ForgeVersion.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) +++ src/main/kotlin/platform/forge/version/ForgeVersion.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -3,7 +3,7 @@ * * https://mcdev.io/ * - * Copyright (C) 2025 minecraft-dev + * Copyright (C) 2026 minecraft-dev * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published @@ -22,9 +22,9 @@ import com.demonwav.mcdev.creator.collectMavenVersions import com.demonwav.mcdev.util.SemanticVersion +import com.demonwav.mcdev.util.noVersionsFound import com.demonwav.mcdev.util.sortVersions import com.intellij.openapi.diagnostic.logger -import java.io.IOException class ForgeVersion private constructor(val versions: List) { @@ -62,15 +62,17 @@ companion object { private val LOGGER = logger() - suspend fun downloadData(): ForgeVersion? { - try { + /** + * Returns every Forge version, or a failure after logging a warning if the download fails or finds none. + */ + suspend fun downloadData(): Result { - val url = "https://files.minecraftforge.net/maven/net/minecraftforge/forge/maven-metadata.xml" - val versions = collectMavenVersions(url) { version -> version.indexOf('-') != -1 } + val url = "https://files.minecraftforge.net/maven/net/minecraftforge/forge/maven-metadata.xml" + val versions = collectMavenVersions(url) { version -> version.indexOf('-') != -1 } - return ForgeVersion(versions) - } catch (e: IOException) { - LOGGER.error("Failed to retrieve Forge version data", e) + .getOrElse { return Result.failure(it) } + if (versions.isEmpty()) { + return noVersionsFound(LOGGER, "Forge", url) } - return null + return Result.success(ForgeVersion(versions)) } } } Index: src/main/kotlin/platform/neoforge/version/NeoForgeVersion.kt =================================================================== --- src/main/kotlin/platform/neoforge/version/NeoForgeVersion.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) +++ src/main/kotlin/platform/neoforge/version/NeoForgeVersion.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -22,8 +22,8 @@ import com.demonwav.mcdev.creator.collectMavenVersions import com.demonwav.mcdev.util.SemanticVersion +import com.demonwav.mcdev.util.noVersionsFound import com.intellij.openapi.diagnostic.logger -import java.io.IOException class NeoForgeVersion private constructor(val versions: List) { @@ -68,15 +68,16 @@ } } - suspend fun downloadData(): NeoForgeVersion? { - try { + /** + * Returns the NeoForge versions, or a failure after logging a warning if the download fails or finds none. + */ + suspend fun downloadData(): Result { - val url = "https://maven.neoforged.net/releases/net/neoforged/neoforge/maven-metadata.xml" + val url = "https://maven.neoforged.net/releases/net/neoforged/neoforge/maven-metadata.xml" - val versions = collectMavenVersions(url) - return NeoForgeVersion(versions) - } catch (e: IOException) { - LOGGER.error("Failed to retrieve NeoForge version data", e) + val versions = collectMavenVersions(url).getOrElse { return Result.failure(it) } + if (versions.isEmpty()) { + return noVersionsFound(LOGGER, "NeoForge", url) } - return null + return Result.success(NeoForgeVersion(versions)) } } } Index: src/main/kotlin/platform/neoforge/version/NeoGradleVersion.kt =================================================================== --- src/main/kotlin/platform/neoforge/version/NeoGradleVersion.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) +++ src/main/kotlin/platform/neoforge/version/NeoGradleVersion.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -3,7 +3,7 @@ * * https://mcdev.io/ * - * Copyright (C) 2025 minecraft-dev + * Copyright (C) 2026 minecraft-dev * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published @@ -22,28 +22,28 @@ import com.demonwav.mcdev.creator.collectMavenVersions import com.demonwav.mcdev.util.SemanticVersion +import com.demonwav.mcdev.util.noVersionsFound import com.intellij.openapi.diagnostic.logger -import java.io.IOException class NeoGradleVersion private constructor(val versions: List) { companion object { private val LOGGER = logger() - suspend fun downloadData(): NeoGradleVersion? { - try { + /** + * Returns the NeoGradle versions, or a failure after logging a warning if the download fails or finds none. + */ + suspend fun downloadData(): Result { - val url = "https://maven.neoforged.net/releases/net/neoforged/gradle/userdev/maven-metadata.xml" + val url = "https://maven.neoforged.net/releases/net/neoforged/gradle/userdev/maven-metadata.xml" - val versions = collectMavenVersions(url) - .asSequence() + val versions = collectMavenVersions(url).getOrElse { return Result.failure(it) }.asSequence() - .mapNotNull(SemanticVersion.Companion::tryParse) - .sortedDescending() - .take(50) - .toList() + .mapNotNull(SemanticVersion.Companion::tryParse) + .sortedDescending() + .take(50) + .toList() - return NeoGradleVersion(versions) - } catch (e: IOException) { - LOGGER.error("Failed to retrieve NeoForge version data", e) + if (versions.isEmpty()) { + return noVersionsFound(LOGGER, "NeoGradle", url) } - return null + return Result.success(NeoGradleVersion(versions)) } } } Index: src/main/kotlin/platform/neoforge/version/NeoModDevVersion.kt =================================================================== --- src/main/kotlin/platform/neoforge/version/NeoModDevVersion.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) +++ src/main/kotlin/platform/neoforge/version/NeoModDevVersion.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -0,0 +1,50 @@ +/* + * Minecraft Development for IntelliJ + * + * https://mcdev.io/ + * + * Copyright (C) 2026 minecraft-dev + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published + * by the Free Software Foundation, version 3.0 only. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.demonwav.mcdev.platform.neoforge.version + +import com.demonwav.mcdev.creator.collectMavenVersions +import com.demonwav.mcdev.util.SemanticVersion +import com.demonwav.mcdev.util.noVersionsFound +import com.intellij.openapi.diagnostic.logger + +class NeoModDevVersion private constructor(val versions: List) { + + companion object { + private val LOGGER = logger() + + /** + * Returns the ModDevGradle versions, or a failure after logging a warning if the download fails or finds none. + */ + suspend fun downloadData(): Result { + val url = "https://maven.neoforged.net/releases/net/neoforged/moddev" + + "/net.neoforged.moddev.gradle.plugin/maven-metadata.xml" + val versions = collectMavenVersions(url).getOrElse { return Result.failure(it) }.asSequence() + .mapNotNull(SemanticVersion.Companion::tryParse) + .sortedDescending() + .take(50) + .toList() + if (versions.isEmpty()) { + return noVersionsFound(LOGGER, "ModDevGradle", url) + } + return Result.success(NeoModDevVersion(versions)) + } + } +} Index: src/main/kotlin/platform/neoforge/version/platform/neoforge/version/NeoModDevVersion.kt =================================================================== --- src/main/kotlin/platform/neoforge/version/platform/neoforge/version/NeoModDevVersion.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) +++ src/main/kotlin/platform/neoforge/version/platform/neoforge/version/NeoModDevVersion.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) @@ -1,50 +0,0 @@ -/* - * Minecraft Development for IntelliJ - * - * https://mcdev.io/ - * - * Copyright (C) 2025 minecraft-dev - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published - * by the Free Software Foundation, version 3.0 only. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package com.demonwav.mcdev.platform.neoforge.version.platform.neoforge.version - -import com.demonwav.mcdev.creator.collectMavenVersions -import com.demonwav.mcdev.util.SemanticVersion -import com.intellij.openapi.diagnostic.logger -import java.io.IOException - -class NeoModDevVersion private constructor(val versions: List) { - - companion object { - private val LOGGER = logger() - - suspend fun downloadData(): NeoModDevVersion? { - try { - val url = "https://maven.neoforged.net/releases/net/neoforged/moddev" + - "/net.neoforged.moddev.gradle.plugin/maven-metadata.xml" - val versions = collectMavenVersions(url) - .asSequence() - .mapNotNull(SemanticVersion.Companion::tryParse) - .sortedDescending() - .take(50) - .toList() - return NeoModDevVersion(versions) - } catch (e: IOException) { - LOGGER.error("Failed to retrieve NeoForged ModDev version data", e) - } - return null - } - } -} Index: src/main/kotlin/util/McdevHttp.kt =================================================================== --- src/main/kotlin/util/McdevHttp.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) +++ src/main/kotlin/util/McdevHttp.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -21,10 +21,14 @@ package com.demonwav.mcdev.util import com.demonwav.mcdev.update.PluginUtil +import com.intellij.openapi.diagnostic.ControlFlowException +import com.intellij.openapi.diagnostic.Logger import com.intellij.util.io.HttpRequests import com.intellij.util.io.RequestBuilder +import java.io.IOException import java.net.URI import java.net.URISyntaxException +import java.util.concurrent.CancellationException import kotlin.collections.iterator import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext @@ -129,3 +133,39 @@ } } } + +/** + * Runs a download in [block] and returns its result. Any failure is logged to [logger] as a warning, naming [what] was + * being downloaded, and gives null. Cancellation always propagates. + */ +inline fun fetchOrNull(logger: Logger, what: String, block: () -> T?): T? = + fetchCatching(logger, what, block).getOrNull() + +/** + * Like [fetchOrNull], but a failure is returned as a failed [Result] so callers can show its cause. + */ +inline fun fetchCatching(logger: Logger, what: String, block: () -> T): Result { + return try { + Result.success(block()) + } catch (e: Exception) { + if (e is CancellationException || e is ControlFlowException) { + throw e + } + logger.warn("Failed to download $what", e) + Result.failure(e) + } +} + +/** + * A download that succeeded but found no versions. + */ +class NoVersionsFoundException(message: String) : IOException(message) + +/** + * Logs a warning to [logger] and returns a [NoVersionsFoundException] failure for the [what] versions at [url]. + */ +fun noVersionsFound(logger: Logger, what: String, url: String): Result { + val e = NoVersionsFoundException("No $what versions found at $url") + logger.warn(e.message) + return Result.failure(e) +} Index: src/main/kotlin/util/MinecraftVersions.kt =================================================================== --- src/main/kotlin/util/MinecraftVersions.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) +++ src/main/kotlin/util/MinecraftVersions.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -73,9 +73,10 @@ */ fun nextMajorVersion(minecraftVersion: SemanticVersion): String { val first = minecraftVersion.parts.getOrNull(0)?.versionString ?: "1" - val mcNext = when (val part = minecraftVersion.parts.getOrNull(1)) { - is SemanticVersion.Companion.VersionPart.ReleasePart -> (part.version + 1).toString() - null -> "?" + val part = minecraftVersion.parts.getOrNull(1) + val mcNext = when { + part == null -> "?" + part.isReleasePart -> (part.version + 1).toString() else -> part.versionString } return "$first.$mcNext" Index: src/main/kotlin/util/SemanticVersion.kt =================================================================== --- src/main/kotlin/util/SemanticVersion.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) +++ src/main/kotlin/util/SemanticVersion.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -3,7 +3,7 @@ * * https://mcdev.io/ * - * Copyright (C) 2025 minecraft-dev + * Copyright (C) 2026 minecraft-dev * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published @@ -25,6 +25,7 @@ import com.demonwav.mcdev.util.SemanticVersion.Companion.VersionPart.ReleasePart import com.demonwav.mcdev.util.SemanticVersion.Companion.VersionPart.TextPart import java.net.URLDecoder +import kotlin.contracts.contract /** * Represents a comparable and generalised "semantic version". @@ -101,7 +102,7 @@ fun tryParse(value: String): SemanticVersion? { return try { parse(value) - } catch (e: IllegalArgumentException) { + } catch (_: IllegalArgumentException) { null } } @@ -197,6 +198,28 @@ sealed class VersionPart : Comparable { abstract val versionString: String + val isReleasePart: Boolean + get() { + contract { + returns(true) implies (this@VersionPart is ReleasePart) + } + return this is ReleasePart + } + val isTextPart: Boolean + get() { + contract { + returns(true) implies (this@VersionPart is TextPart) + } + return this is TextPart + } + val isPreReleasePart: Boolean + get() { + contract { + returns(true) implies (this@VersionPart is PreReleasePart) + } + return this is PreReleasePart + } + data class ReleasePart(val version: Int, override val versionString: String) : VersionPart() { override fun compareTo(other: VersionPart) = when (other) { @@ -237,6 +260,10 @@ override val versionString: String, ) : VersionPart() { + fun asReleasePart(): ReleasePart { + return ReleasePart(version, version.toString()) + } + override fun compareTo(other: VersionPart): Int = when (other) { is ReleasePart -> if (version != other.version) version - other.version else -1 Index: src/main/resources/messages/MinecraftDevelopmentBundle.properties =================================================================== --- src/main/resources/messages/MinecraftDevelopmentBundle.properties (revision 37f735141f4e949bcceb52111e97c58496353e55) +++ src/main/resources/messages/MinecraftDevelopmentBundle.properties (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -139,6 +139,11 @@ creator.ui.spongeapi_version.label=Sponge Version\: creator.ui.velocity_version.label=Velocity Version\: creator.ui.versions_download.label=Downloading versions... +creator.ui.versions_download.failed=Failed to download versions +creator.ui.versions_download.failed_cause=Failed to download versions: {0} +creator.ui.versions_download.none_found=No versions found +creator.ui.versions_download.failed_part=Failed to download {0} versions: {1} +creator.ui.versions_download.none_found_part=No {0} versions found creator.ui.use_version_catalog.label=Use Gradle version catalog\: creator.ui.include_plugin_bootstrap.label=Include plugin bootstrap file\: creator.ui.include_plugin_loader.label=Include plugin loader file\: Index: src/test/kotlin/creator/VersionDownloadFailureTest.kt =================================================================== --- src/test/kotlin/creator/VersionDownloadFailureTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) +++ src/test/kotlin/creator/VersionDownloadFailureTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -0,0 +1,302 @@ +/* + * Minecraft Development for IntelliJ + * + * https://mcdev.io/ + * + * Copyright (C) 2026 minecraft-dev + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published + * by the Free Software Foundation, version 3.0 only. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.demonwav.mcdev.creator + +import com.demonwav.mcdev.asset.MCDevBundle +import com.demonwav.mcdev.creator.custom.CreatorTemplateProcessor +import com.demonwav.mcdev.creator.custom.TemplateDescriptor +import com.demonwav.mcdev.creator.custom.TemplateService +import com.demonwav.mcdev.creator.custom.TemplateValidationReporterImpl +import com.demonwav.mcdev.creator.custom.model.ForgeVersions +import com.demonwav.mcdev.creator.custom.model.NeoForgeVersions +import com.demonwav.mcdev.creator.custom.types.ArchitecturyVersionsCreatorProperty +import com.demonwav.mcdev.creator.custom.types.FabricGameVersionCreatorProperty +import com.demonwav.mcdev.creator.custom.types.FabricVersionsCreatorProperty +import com.demonwav.mcdev.creator.custom.types.ForgeVersionsCreatorProperty +import com.demonwav.mcdev.creator.custom.types.GradlePluginSelectorCreatorProperty +import com.demonwav.mcdev.creator.custom.types.MavenArtifactVersionCreatorProperty +import com.demonwav.mcdev.creator.custom.types.NeoForgeVersionsCreatorProperty +import com.demonwav.mcdev.creator.custom.types.PaperVersionCreatorProperty +import com.demonwav.mcdev.creator.custom.types.ParchmentCreatorProperty +import com.demonwav.mcdev.creator.custom.types.VersionDownloadStatus +import com.demonwav.mcdev.framework.LogCapture +import com.demonwav.mcdev.framework.http.HttpMockExtension +import com.demonwav.mcdev.framework.http.HttpMockServer.Companion.mockUrl +import com.demonwav.mcdev.util.SemanticVersion +import com.github.tomakehurst.wiremock.client.WireMock.get +import com.github.tomakehurst.wiremock.client.WireMock.serverError +import com.intellij.ide.util.projectWizard.WizardContext +import com.intellij.openapi.application.ModalityState +import com.intellij.openapi.observable.properties.PropertyGraph +import kotlin.time.Duration.Companion.seconds +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.RegisterExtension + +@DisplayName("Version Download Failure Tests") +class VersionDownloadFailureTest : CreatorTemplateProcessorTestBase() { + + @JvmField + @RegisterExtension + val http = HttpMockExtension() + + private lateinit var log: LogCapture + + private val forgeUrl = "https://files.minecraftforge.net/maven/net/minecraftforge/forge/maven-metadata.xml" + private val neoForgeUrl = "https://maven.neoforged.net/releases/net/neoforged/neoforge/maven-metadata.xml" + private val modDevUrl = + "https://maven.neoforged.net/releases/net/neoforged/moddev/net.neoforged.moddev.gradle.plugin/maven-metadata.xml" + private val fabricMetaUrl = "https://meta.fabricmc.net/v2/versions" + private val fabricLoomUrl = "https://maven.fabricmc.net/net/fabricmc/fabric-loom/maven-metadata.xml" + private val architecturyApiUrl = "https://api.modrinth.com/v2/project/architectury-api/version" + private val parchmentUrl = "https://maven.parchmentmc.org/org/parchmentmc/data/" + private val paperUrl = "https://fill.papermc.io/v3/projects/paper" + private val gremlinUrl = "https://plugins.gradle.org/m2/xyz/jpenilla/gremlin-gradle/maven-metadata.xml" + + private val failureMessage = MCDevBundle("creator.ui.versions_download.failed") + private val serverError = "Request failed with status code 500" + private val serverErrorMessage = MCDevBundle("creator.ui.versions_download.failed_cause", serverError) + private val noneFoundMessage = MCDevBundle("creator.ui.versions_download.none_found") + private val noMatchParameters = """{"sourceUrl": "$gremlinUrl", "rawVersionFilter": "false"}""" + + private fun partFailedMessage(part: String) = + MCDevBundle("creator.ui.versions_download.failed_part", part, serverError) + + @BeforeEach + override fun setUp() { + super.setUp() + log = LogCapture() + } + + @AfterEach + override fun tearDown() { + try { + log.close() + log.assertNoErrors() + } finally { + super.tearDown() + } + } + + private fun test(block: suspend () -> Unit) = runBlocking { withTimeout(30.seconds) { block() } } + + private fun template(type: String, parameters: String = "{}") = """ + { + "version": ${TemplateDescriptor.LATEST_FORMAT_VERSION}, + "properties": [ + { + "name": "VERSIONS", + "type": "$type", + "parameters": $parameters + } + ] + } + """.trimIndent() + + private fun fail(vararg urls: String) { + for (url in urls) { + http.server.stubFor(get(mockUrl(url)).willReturn(serverError())) + } + } + + private fun restore(vararg urls: String) { + for (url in urls) { + http.server.stubFor(get(mockUrl(url)).willReturn(http.server.fixture(url))) + } + } + + private fun newProcessor(): CreatorTemplateProcessor { + val graph = PropertyGraph() + val context = WizardContext(null, fixture.testRootDisposable) + context.overrideModalityState(ModalityState.nonModal()) + val session = TemplateService.instance.openSession("Second creator", fixture.testRootDisposable) + return CreatorTemplateProcessor(graph, context, session, TestExternalTemplatePropertyProvider(graph)) + .apply { initBuiltinProperties() } + } + + private suspend fun setUpAndWait(template: String, processor: CreatorTemplateProcessor = this.processor) { + val reporter = TemplateValidationReporterImpl() + processor.setupTemplate(TestLoadedTemplate(template), reporter) + assertFalse(reporter.hasErrors, "Template errors: ${reporter.items}") + processor.context.session.awaitIdle() + } + + private fun status(processor: CreatorTemplateProcessor = this.processor): VersionDownloadStatus { + return when (val property = processor.context.properties["VERSIONS"]) { + is ArchitecturyVersionsCreatorProperty -> property.downloadStatus + is FabricGameVersionCreatorProperty -> property.downloadStatus + is FabricVersionsCreatorProperty -> property.downloadStatus + is ForgeVersionsCreatorProperty -> property.downloadStatus + is GradlePluginSelectorCreatorProperty -> property.downloadStatus + is MavenArtifactVersionCreatorProperty -> property.downloadStatus + is NeoForgeVersionsCreatorProperty -> property.downloadStatus + is PaperVersionCreatorProperty -> property.downloadStatus + is ParchmentCreatorProperty -> property.downloadStatus + else -> throw AssertionError("No download status for $property") + } + } + + private fun assertFailed( + processor: CreatorTemplateProcessor = this.processor, + message: String = failureMessage, + ) { + assertEquals(message, status(processor).failure.get()) + assertTrue(log.warnings.isNotEmpty(), "The failure should be logged as a warning") + log.assertNoErrors() + } + + private fun assertSucceeded(processor: CreatorTemplateProcessor = this.processor) { + assertEquals("", status(processor).failure.get()) + assertFalse(status(processor).loading.get()) + } + + private fun assertFailsWith( + type: String, + vararg urls: String, + parameters: String = "{}", + message: String = failureMessage, + ) = test { + fail(*urls) + setUpAndWait(template(type, parameters)) + assertFailed(message = message) + } + + private fun assertFindsNone(type: String) = test { + setUpAndWait(template(type, noMatchParameters)) + assertFailed(message = noneFoundMessage) + } + + @Test + @DisplayName("Forge versions show a failure") + fun forge() = assertFailsWith("forge_versions", forgeUrl, message = serverErrorMessage) + + @Test + @DisplayName("NeoForge versions show a failure when one part fails") + fun neoForge() = assertFailsWith("neoforge_versions", modDevUrl, message = partFailedMessage("ModDevGradle")) + + @Test + @DisplayName("Fabric versions show a failure when one part fails") + fun fabric() = assertFailsWith("fabric_versions", fabricLoomUrl, message = partFailedMessage("Fabric Loom")) + + @Test + @DisplayName("Fabric game versions show a failure") + fun fabricGame() = assertFailsWith("fabric_game_version", fabricMetaUrl, message = serverErrorMessage) + + @Test + @DisplayName("Architectury versions show a failure when one part fails") + fun architectury() = assertFailsWith( + "architectury_versions", + architecturyApiUrl, + message = partFailedMessage("Architectury API"), + ) + + @Test + @DisplayName("Parchment versions show a failure") + fun parchment() = assertFailsWith("parchment", parchmentUrl) + + @Test + @DisplayName("Paper versions show a failure") + fun paper() = assertFailsWith("paper_versions", paperUrl) + + @Test + @DisplayName("Maven artifact versions show a failure") + fun mavenArtifact() = assertFailsWith( + "maven_artifact_version", + gremlinUrl, + parameters = """{"sourceUrl": "$gremlinUrl"}""", + message = serverErrorMessage, + ) + + @Test + @DisplayName("Gradle plugin versions show a failure") + fun gradlePlugin() = assertFailsWith( + "gradle_plugin", + gremlinUrl, + parameters = """{"sourceUrl": "$gremlinUrl"}""", + message = serverErrorMessage, + ) + + @Test + @DisplayName("Maven artifact versions show a failure when no version matches the filters") + fun mavenArtifactNoneFound() = assertFindsNone("maven_artifact_version") + + @Test + @DisplayName("Gradle plugin versions show a failure when no version matches the filters") + fun gradlePluginNoneFound() = assertFindsNone("gradle_plugin") + + @Test + @DisplayName("A later creator downloads versions again when none matched the filters") + fun retryNoneFound() = test { + val template = template("maven_artifact_version", noMatchParameters) + setUpAndWait(template) + assertFailed(message = noneFoundMessage) + + val retry = newProcessor() + setUpAndWait(template, retry) + assertFailed(retry, noneFoundMessage) + assertEquals(2, http.server.requestsTo(gremlinUrl).size) + } + + @Test + @DisplayName("A later creator downloads versions again after a failure") + fun retry() = test { + val template = template("forge_versions") + fail(forgeUrl) + setUpAndWait(template) + assertFailed(message = serverErrorMessage) + + restore(forgeUrl) + val retry = newProcessor() + setUpAndWait(template, retry) + assertSucceeded(retry) + assertEquals( + ForgeVersions(SemanticVersion.parse("26.3"), SemanticVersion.parse("66.1.8")), + retry.context.property("VERSIONS").get(), + ) + assertEquals(2, http.server.requestsTo(forgeUrl).size) + } + + @Test + @DisplayName("A later creator downloads only the parts that failed") + fun retryPart() = test { + val template = template("neoforge_versions") + fail(modDevUrl) + setUpAndWait(template) + assertFailed(message = partFailedMessage("ModDevGradle")) + + restore(modDevUrl) + val retry = newProcessor() + setUpAndWait(template, retry) + assertSucceeded(retry) + val versions = checkNotNull(retry.context.property("VERSIONS").get()) + assertEquals(SemanticVersion.parse("26.3"), versions.minecraft) + assertEquals(SemanticVersion.parse("2.0.148"), versions.moddev) + assertEquals(1, http.server.requestsTo(neoForgeUrl).size) + assertEquals(2, http.server.requestsTo(modDevUrl).size) + } +} Index: src/test/kotlin/creator/derivation/ExtractPaperApiVersionPropertyDerivationTest.kt =================================================================== --- src/test/kotlin/creator/derivation/ExtractPaperApiVersionPropertyDerivationTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) +++ src/test/kotlin/creator/derivation/ExtractPaperApiVersionPropertyDerivationTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -0,0 +1,48 @@ +/* + * Minecraft Development for IntelliJ + * + * https://mcdev.io/ + * + * Copyright (C) 2026 minecraft-dev + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published + * by the Free Software Foundation, version 3.0 only. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.demonwav.mcdev.creator.derivation + +import com.demonwav.mcdev.creator.custom.derivation.ExtractPaperApiVersionPropertyDerivation +import com.demonwav.mcdev.util.SemanticVersion +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test + +@DisplayName("Extract Paper API Version Derivation Tests") +class ExtractPaperApiVersionPropertyDerivationTest { + + @Test + @DisplayName("Versions from 1.20.5 on are kept whole, and older ones are cut to major and minor") + fun extracts() { + val cases = mapOf( + "1.18.2" to "1.18", + "1.20.4" to "1.20", + "1.20.5" to "1.20.5", + "1.21.11" to "1.21.11", + "26.1" to "26.1", + "26.1.2" to "26.1.2", + ) + for ((version, expected) in cases) { + val result = ExtractPaperApiVersionPropertyDerivation().derive(listOf(SemanticVersion.parse(version))) + assertEquals(SemanticVersion.parse(expected), result, version) + } + } +} Index: src/test/kotlin/creator/derivation/ExtractVersionMajorMinorPropertyDerivationTest.kt =================================================================== --- src/test/kotlin/creator/derivation/ExtractVersionMajorMinorPropertyDerivationTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) +++ src/test/kotlin/creator/derivation/ExtractVersionMajorMinorPropertyDerivationTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -0,0 +1,51 @@ +/* + * Minecraft Development for IntelliJ + * + * https://mcdev.io/ + * + * Copyright (C) 2026 minecraft-dev + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published + * by the Free Software Foundation, version 3.0 only. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.demonwav.mcdev.creator.derivation + +import com.demonwav.mcdev.creator.custom.derivation.ExtractVersionMajorMinorPropertyDerivation +import com.demonwav.mcdev.util.SemanticVersion +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test + +@DisplayName("Extract Version Major Minor Derivation Tests") +class ExtractVersionMajorMinorPropertyDerivationTest { + + @Test + @DisplayName("The major and minor versions are kept, without a pre-release suffix, or none for a single part") + fun extracts() { + val cases = mapOf( + "1.21.11" to "1.21", + "1.21" to "1.21", + "1.21.5-pre1" to "1.21", + "26.1.2" to "26.1", + "1.21-pre1" to "1.21", + "26.1-snapshot-1" to "26.1", + "26.1-rc-2" to "26.1", + "1" to "", + "24w39a" to "", + ) + for ((version, expected) in cases) { + val result = ExtractVersionMajorMinorPropertyDerivation().derive(listOf(SemanticVersion.parse(version))) + assertEquals(expected, result.toString(), version) + } + } +} Index: src/test/kotlin/creator/derivation/FetchPaperDependencyVersionForMcVersionTest.kt =================================================================== --- src/test/kotlin/creator/derivation/FetchPaperDependencyVersionForMcVersionTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) +++ src/test/kotlin/creator/derivation/FetchPaperDependencyVersionForMcVersionTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -0,0 +1,51 @@ +/* + * Minecraft Development for IntelliJ + * + * https://mcdev.io/ + * + * Copyright (C) 2026 minecraft-dev + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published + * by the Free Software Foundation, version 3.0 only. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.demonwav.mcdev.creator.derivation + +import com.demonwav.mcdev.creator.custom.derivation.FetchPaperDependencyVersionForMcVersion +import com.demonwav.mcdev.util.SemanticVersion +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test + +@DisplayName("Fetch Paper Dependency Version Derivation Tests") +class FetchPaperDependencyVersionForMcVersionTest { + + private fun derive(mcVersion: String, buildSystem: String) = + FetchPaperDependencyVersionForMcVersion().derive(listOf(SemanticVersion.parse(mcVersion), buildSystem)) + + @Test + @DisplayName("Versions before 26.1 use the R0.1 snapshot for every build system") + fun beforeYearVersions() { + assertEquals("1.20.4-R0.1-SNAPSHOT", derive("1.20.4", "Gradle")) + assertEquals("1.21.11-R0.1-SNAPSHOT", derive("1.21.11", "Gradle")) + assertEquals("1.21.11-R0.1-SNAPSHOT", derive("1.21.11", "Maven")) + } + + @Test + @DisplayName("Versions from 26.1 on use the latest build, in each build system's range syntax") + fun yearVersions() { + assertEquals("26.1.build.+", derive("26.1", "Gradle")) + assertEquals("[26.1.build,)", derive("26.1", "Maven")) + assertEquals("26.1.2.build.+", derive("26.1.2", "Gradle")) + assertEquals("[26.1.2.build,)", derive("26.1.2", "Maven")) + } +} Index: src/test/kotlin/creator/derivation/RecommendJavaVersionForMcVersionPropertyDerivationTest.kt =================================================================== --- src/test/kotlin/creator/derivation/RecommendJavaVersionForMcVersionPropertyDerivationTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) +++ src/test/kotlin/creator/derivation/RecommendJavaVersionForMcVersionPropertyDerivationTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -0,0 +1,68 @@ +/* + * Minecraft Development for IntelliJ + * + * https://mcdev.io/ + * + * Copyright (C) 2026 minecraft-dev + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published + * by the Free Software Foundation, version 3.0 only. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.demonwav.mcdev.creator.derivation + +import com.demonwav.mcdev.creator.custom.derivation.RecommendJavaVersionForMcVersionPropertyDerivation +import com.demonwav.mcdev.creator.custom.model.ForgeVersions +import com.demonwav.mcdev.util.SemanticVersion +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test + +@DisplayName("Recommend Java Version Derivation Tests") +class RecommendJavaVersionForMcVersionPropertyDerivationTest { + + private val derivation = RecommendJavaVersionForMcVersionPropertyDerivation(17) + + @Test + @DisplayName("Each Minecraft version recommends the Java version it requires") + fun recommends() { + val cases = mapOf( + "1.12.2" to 8, + "1.16.5" to 8, + "1.17" to 16, + "1.17.1" to 16, + "1.18" to 17, + "1.20.4" to 17, + "1.20.5" to 21, + "1.21.11" to 21, + "26.1" to 25, + "26.3" to 25, + ) + for ((mcVersion, java) in cases) { + assertEquals(java, derivation.derive(listOf(SemanticVersion.parse(mcVersion))), "Minecraft $mcVersion") + } + } + + @Test + @DisplayName("Values with a Minecraft version are supported") + fun hasMinecraftVersion() { + val forge = ForgeVersions(SemanticVersion.parse("1.20.1"), SemanticVersion.parse("47.1.0")) + assertEquals(17, derivation.derive(listOf(forge))) + } + + @Test + @DisplayName("Other values give the default") + fun default() { + assertEquals(17, derivation.derive(listOf("1.21"))) + assertEquals(17, derivation.derive(listOf(null))) + } +} Index: src/test/kotlin/creator/derivation/ReplacePropertyDerivationTest.kt =================================================================== --- src/test/kotlin/creator/derivation/ReplacePropertyDerivationTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) +++ src/test/kotlin/creator/derivation/ReplacePropertyDerivationTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -0,0 +1,60 @@ +/* + * Minecraft Development for IntelliJ + * + * https://mcdev.io/ + * + * Copyright (C) 2026 minecraft-dev + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published + * by the Free Software Foundation, version 3.0 only. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.demonwav.mcdev.creator.derivation + +import com.demonwav.mcdev.creator.custom.derivation.ReplacePropertyDerivation +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test + +@DisplayName("Replace Derivation Tests") +class ReplacePropertyDerivationTest { + + private fun replace(value: Any?, maxLength: Int? = null, lowercase: Boolean = false) = + ReplacePropertyDerivation(Regex("[^a-zA-Z0-9_]+"), "_", maxLength, lowercase).derive(listOf(value)) + + @Test + @DisplayName("Matches are replaced") + fun replaces() { + assertEquals("My_Cool_Mod_", replace("My Cool-Mod!")) + } + + @Test + @DisplayName("The value can be lowercased before replacing") + fun lowercase() { + assertEquals("my_cool_mod", replace("My Cool Mod", lowercase = true)) + } + + @Test + @DisplayName("The result is cut to the maximum length") + fun maxLength() { + assertEquals("My_Co", replace("My Cool Mod", maxLength = 5)) + assertEquals("My", replace("My", maxLength = 5)) + } + + @Test + @DisplayName("A value that isn't a string gives null") + fun notString() { + assertNull(replace(42)) + assertNull(replace(null)) + } +} Index: src/test/kotlin/creator/derivation/SelectPropertyDerivationTest.kt =================================================================== --- src/test/kotlin/creator/derivation/SelectPropertyDerivationTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) +++ src/test/kotlin/creator/derivation/SelectPropertyDerivationTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -0,0 +1,60 @@ +/* + * Minecraft Development for IntelliJ + * + * https://mcdev.io/ + * + * Copyright (C) 2026 minecraft-dev + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published + * by the Free Software Foundation, version 3.0 only. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.demonwav.mcdev.creator.derivation + +import com.demonwav.mcdev.creator.custom.PropertyDerivationSelect +import com.demonwav.mcdev.creator.custom.derivation.SelectPropertyDerivation +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test + +@DisplayName("Select Derivation Tests") +class SelectPropertyDerivationTest { + + private val options = listOf( + PropertyDerivationSelect($$"$BUILD_SYSTEM == 'gradle' && $USE_KOTLIN", "build.gradle.kts"), + PropertyDerivationSelect($$"$BUILD_SYSTEM == 'gradle'", "build.gradle"), + PropertyDerivationSelect($$"$BUILD_SYSTEM == 'maven'", "pom.xml"), + ) + + private val derivation = SelectPropertyDerivation(listOf("BUILD_SYSTEM", "USE_KOTLIN"), options, "none") + + @Test + @DisplayName("The first option whose condition holds is selected") + fun firstMatch() { + assertEquals("build.gradle.kts", derivation.derive(listOf("gradle", true))) + assertEquals("build.gradle", derivation.derive(listOf("gradle", false))) + assertEquals("pom.xml", derivation.derive(listOf("maven", true))) + } + + @Test + @DisplayName("The default is selected when no condition holds") + fun default() { + assertEquals("none", derivation.derive(listOf("ant", false))) + } + + @Test + @DisplayName("Conditions can use the base properties without parents") + fun noParents() { + val options = listOf(PropertyDerivationSelect($$"$semver.parse('1.21') > $mcver.MC1_20", "new")) + assertEquals("new", SelectPropertyDerivation(null, options, "old").derive(emptyList())) + } +} Index: src/test/kotlin/creator/derivation/SuggestClassNamePropertyDerivationTest.kt =================================================================== --- src/test/kotlin/creator/derivation/SuggestClassNamePropertyDerivationTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) +++ src/test/kotlin/creator/derivation/SuggestClassNamePropertyDerivationTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -0,0 +1,49 @@ +/* + * Minecraft Development for IntelliJ + * + * https://mcdev.io/ + * + * Copyright (C) 2026 minecraft-dev + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published + * by the Free Software Foundation, version 3.0 only. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.demonwav.mcdev.creator.derivation + +import com.demonwav.mcdev.creator.custom.derivation.SuggestClassNamePropertyDerivation +import com.demonwav.mcdev.creator.custom.model.BuildSystemCoordinates +import com.demonwav.mcdev.creator.custom.model.ClassFqn +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test + +@DisplayName("Suggest Class Name Derivation Tests") +class SuggestClassNamePropertyDerivationTest { + + private val coords = BuildSystemCoordinates("com.example", "mod", "1.0") + + private fun suggest(name: String) = SuggestClassNamePropertyDerivation().derive(listOf(coords, name)) + + @Test + @DisplayName("The class is named after the project, in a package under the group") + fun suggests() { + assertEquals(ClassFqn("com.example.myMod.MyMod"), suggest("MyMod")) + } + + @Test + @DisplayName("Characters that can't be in a Java identifier split the name into capitalized words") + fun sanitizes() { + assertEquals(ClassFqn("com.example.myCoolMod.MyCoolMod"), suggest("my cool-mod!")) + assertEquals(ClassFqn("com.example.my_mod.My_mod"), suggest("my_mod")) + } +} Index: src/test/kotlin/creator/fetcher/ArchitecturyVersionTest.kt =================================================================== --- src/test/kotlin/creator/fetcher/ArchitecturyVersionTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) +++ src/test/kotlin/creator/fetcher/ArchitecturyVersionTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -0,0 +1,104 @@ +/* + * Minecraft Development for IntelliJ + * + * https://mcdev.io/ + * + * Copyright (C) 2026 minecraft-dev + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published + * by the Free Software Foundation, version 3.0 only. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.demonwav.mcdev.creator.fetcher + +import com.demonwav.mcdev.platform.architectury.ArchitecturyVersion +import com.demonwav.mcdev.util.SemanticVersion +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test + +@DisplayName("Architectury API Version Fetcher Tests") +class ArchitecturyVersionTest : FetcherTestBase() { + + private val url = "https://api.modrinth.com/v2/project/architectury-api/version" + + private fun v(version: String) = SemanticVersion.parse(version) + + @Test + @DisplayName("Versions are grouped by Minecraft version, newest first, without the loader suffix") + fun recorded() { + val architectury = fetch { ArchitecturyVersion.downloadData() }.getOrThrow() + assertEquals(33, architectury.versions.size) + assertEquals(listOf(v("22.0.5")), architectury.getArchitecturyVersions(v("26.3"))) + assertEquals(listOf(v("20.1.17"), v("20.0.4")), architectury.getArchitecturyVersions(v("26.1.2"))) + assertEquals(listOf(v("13.0.12")), architectury.getArchitecturyVersions(v("1.21"))) + assertEquals(emptyList(), architectury.getArchitecturyVersions(v("1.12.2"))) + assertNothingLogged() + } + + @Test + @DisplayName("Unparseable game versions are skipped") + fun unparseableGameVersion() { + stubBody(url, """[{"version_number": "13.0.1+fabric", "game_versions": ["not a version", "1.21"]}]""") + val architectury = fetch { ArchitecturyVersion.downloadData() }.getOrThrow() + assertEquals(mapOf(v("1.21") to listOf(v("13.0.1"))), architectury.versions) + } + + @Test + @DisplayName("No versions finds none") + fun empty() { + stubBody(url, "[]") + assertFindsNone { ArchitecturyVersion.downloadData() } + } + + @Test + @DisplayName("An empty body fails quietly") + fun emptyBody() { + stubBody(url, "") + assertFailsQuietly { ArchitecturyVersion.downloadData() } + } + + @Test + @DisplayName("An unparseable version number fails quietly") + fun unparseableVersion() { + stubBody(url, """[{"version_number": "not a version", "game_versions": ["1.21"]}]""") + assertFailsQuietly { ArchitecturyVersion.downloadData() } + } + + @Test + @DisplayName("A missing field fails quietly") + fun missingField() { + stubBody(url, """[{"version_number": "13.0.1+fabric"}]""") + assertFailsQuietly { ArchitecturyVersion.downloadData() } + } + + @Test + @DisplayName("JSON of the wrong shape fails quietly") + fun wrongShape() { + stubBody(url, "{}") + assertFailsQuietly { ArchitecturyVersion.downloadData() } + } + + @Test + @DisplayName("Malformed JSON fails quietly") + fun malformed() { + stubBody(url, MALFORMED_JSON) + assertFailsQuietly { ArchitecturyVersion.downloadData() } + } + + @Test + @DisplayName("An HTTP error fails quietly") + fun httpError() { + stubServerError(url) + assertFailsQuietly { ArchitecturyVersion.downloadData() } + } +} Index: src/test/kotlin/creator/fetcher/CollectMavenVersionsTest.kt =================================================================== --- src/test/kotlin/creator/fetcher/CollectMavenVersionsTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) +++ src/test/kotlin/creator/fetcher/CollectMavenVersionsTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -0,0 +1,126 @@ +/* + * Minecraft Development for IntelliJ + * + * https://mcdev.io/ + * + * Copyright (C) 2026 minecraft-dev + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published + * by the Free Software Foundation, version 3.0 only. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.demonwav.mcdev.creator.fetcher + +import com.demonwav.mcdev.creator.collectMavenVersions +import com.github.tomakehurst.wiremock.client.WireMock.aResponse +import com.github.tomakehurst.wiremock.client.WireMock.ok +import com.github.tomakehurst.wiremock.http.Fault +import kotlin.time.Duration.Companion.milliseconds +import kotlinx.coroutines.TimeoutCancellationException +import kotlinx.coroutines.withTimeout +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows + +@DisplayName("Maven Metadata Fetcher Tests") +class CollectMavenVersionsTest : FetcherTestBase() { + + private val url = "https://maven.fabricmc.net/net/fabricmc/fabric-loom/maven-metadata.xml" + + @Test + @DisplayName("Versions are read from recorded metadata in file order") + fun recorded() { + val versions = fetch { collectMavenVersions(url) }.getOrThrow() + assertEquals(101, versions.size) + assertEquals("1.20.0-alpha.31", versions.last()) + assertTrue("1.19.4" in versions) + assertNothingLogged() + } + + @Test + @DisplayName("The filter drops versions") + fun filter() { + val versions = fetch { collectMavenVersions(url) { !it.contains('-') } }.getOrThrow() + assertTrue(versions.isNotEmpty()) + assertTrue(versions.none { it.contains('-') }) { versions.toString() } + } + + @Test + @DisplayName("Headers are sent with the request") + fun headers() { + fetch { collectMavenVersions(url, mapOf("Authorization" to "Bearer token")) } + assertEquals("Bearer token", http.server.requestsTo(url).single().getHeader("Authorization")) + } + + @Test + @DisplayName("Whitespace around versions is trimmed and empty versions are skipped") + fun whitespace() { + stubBody(url, mavenMetadata(" 1.0 ", "", "\n2.0\n")) + assertEquals(listOf("1.0", "2.0"), fetch { collectMavenVersions(url) }.getOrThrow()) + assertNothingLogged() + } + + @Test + @DisplayName("Metadata with no versions gives an empty list") + fun empty() { + stubBody(url, "") + assertEquals(emptyList(), fetch { collectMavenVersions(url) }.getOrThrow()) + assertNothingLogged() + } + + @Test + @DisplayName("An empty body fails quietly") + fun emptyBody() { + stubBody(url, "") + assertFailsQuietly { collectMavenVersions(url) } + } + + @Test + @DisplayName("Malformed XML fails quietly") + fun malformed() { + stubBody(url, MALFORMED_XML) + assertFailsQuietly { collectMavenVersions(url) } + } + + @Test + @DisplayName("An HTML error page fails quietly") + fun htmlPage() { + stubBody(url, "

Bad gateway

") + assertFailsQuietly { collectMavenVersions(url) } + } + + @Test + @DisplayName("An HTTP error fails quietly") + fun httpError() { + stubServerError(url) + assertFailsQuietly { collectMavenVersions(url) } + } + + @Test + @DisplayName("A dropped connection fails quietly") + fun droppedConnection() { + stub(url, aResponse().withFault(Fault.CONNECTION_RESET_BY_PEER)) + assertFailsQuietly { collectMavenVersions(url) } + } + + @Test + @DisplayName("Cancellation propagates instead of being logged") + fun cancellation() { + stub(url, ok(mavenMetadata("1.0")).withFixedDelay(50)) + assertThrows { + fetch { withTimeout(5.milliseconds) { collectMavenVersions(url) } } + } + assertNothingLogged() + } +} Index: src/test/kotlin/creator/fetcher/FabricApiVersionsTest.kt =================================================================== --- src/test/kotlin/creator/fetcher/FabricApiVersionsTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) +++ src/test/kotlin/creator/fetcher/FabricApiVersionsTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -0,0 +1,102 @@ +/* + * Minecraft Development for IntelliJ + * + * https://mcdev.io/ + * + * Copyright (C) 2026 minecraft-dev + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published + * by the Free Software Foundation, version 3.0 only. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.demonwav.mcdev.creator.fetcher + +import com.demonwav.mcdev.platform.fabric.util.FabricApiVersions +import com.demonwav.mcdev.util.SemanticVersion +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test + +@DisplayName("Fabric API Version Fetcher Tests") +class FabricApiVersionsTest : FetcherTestBase() { + + private val url = "https://api.modrinth.com/v2/project/P7dR8mSH/version" + + private fun version(number: String, gameVersion: String, filename: String = "fabric-api-$number.jar") = + """{"version_number": "$number", "game_versions": ["$gameVersion"], "files": [{"filename": "$filename"}]}""" + + @Test + @DisplayName("Versions are read from recorded data") + fun recorded() { + val versions = fetch { FabricApiVersions.downloadData() }.getOrThrow().versions + assertEquals(49, versions.size) + assertEquals(SemanticVersion.parse("0.166.2+26.4"), versions[0].version) + assertEquals(listOf("26.4-snapshot-8"), versions[0].gameVersions) + assertEquals(SemanticVersion.parse("0.166.2+26.3"), versions[1].version) + assertEquals(listOf("26.3"), versions[1].gameVersions) + assertNothingLogged() + } + + @Test + @DisplayName("Versions with files other than the Fabric API jar are skipped") + fun otherFiles() { + stubBody( + url, + "[" + version("0.100.0+1.21", "1.21", "fabric-api-deprecated.jar") + "," + + version("0.99.0+1.21", "1.21", "something-else.jar") + "]", + ) + val versions = fetch { FabricApiVersions.downloadData() }.getOrThrow().versions + assertEquals(listOf(SemanticVersion.parse("0.100.0+1.21")), versions.map { it.version }) + } + + @Test + @DisplayName("No versions finds none") + fun empty() { + stubBody(url, "[]") + assertFindsNone { FabricApiVersions.downloadData() } + } + + @Test + @DisplayName("Only skipped versions finds none") + fun onlySkipped() { + stubBody(url, "[" + version("0.99.0+1.21", "1.21", "something-else.jar") + "]") + assertFindsNone { FabricApiVersions.downloadData() } + } + + @Test + @DisplayName("A missing field fails quietly") + fun missingField() { + stubBody(url, """[{"version_number": "0.100.0+1.21", "files": []}]""") + assertFailsQuietly { FabricApiVersions.downloadData() } + } + + @Test + @DisplayName("JSON of the wrong shape fails quietly") + fun wrongShape() { + stubBody(url, "{}") + assertFailsQuietly { FabricApiVersions.downloadData() } + } + + @Test + @DisplayName("Malformed JSON fails quietly") + fun malformed() { + stubBody(url, MALFORMED_JSON) + assertFailsQuietly { FabricApiVersions.downloadData() } + } + + @Test + @DisplayName("An HTTP error fails quietly") + fun httpError() { + stubServerError(url) + assertFailsQuietly { FabricApiVersions.downloadData() } + } +} Index: src/test/kotlin/creator/fetcher/FabricVersionsTest.kt =================================================================== --- src/test/kotlin/creator/fetcher/FabricVersionsTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) +++ src/test/kotlin/creator/fetcher/FabricVersionsTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -0,0 +1,93 @@ +/* + * Minecraft Development for IntelliJ + * + * https://mcdev.io/ + * + * Copyright (C) 2026 minecraft-dev + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published + * by the Free Software Foundation, version 3.0 only. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.demonwav.mcdev.creator.fetcher + +import com.demonwav.mcdev.platform.fabric.util.FabricVersions +import com.demonwav.mcdev.util.SemanticVersion +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test + +@DisplayName("Fabric Version Fetcher Tests") +class FabricVersionsTest : FetcherTestBase() { + + private val url = "https://meta.fabricmc.net/v2/versions" + + @Test + @DisplayName("Game, Yarn and loader versions are read from recorded data") + fun recorded() { + val versions = fetch { FabricVersions.downloadData() }.getOrThrow() + assertEquals(58, versions.game.size) + assertEquals("26.4-snapshot-8", versions.game.first().version) + assertFalse(versions.game.first().stable) + assertEquals(77, versions.mappings.size) + val mapping = versions.mappings.first() + assertEquals("1.21.11", mapping.gameVersion) + assertEquals("1.21.11+build.6", mapping.version.name) + assertEquals(6, mapping.version.build) + assertEquals(10, versions.loader.size) + assertEquals(SemanticVersion.parse("0.20.1"), versions.loader.first()) + assertNothingLogged() + } + + @Test + @DisplayName("No game versions finds none") + fun noGameVersions() { + stubBody(url, """{"game": [], "mappings": [], "loader": []}""") + assertFindsNone { FabricVersions.downloadData() } + } + + @Test + @DisplayName("A missing section fails quietly") + fun missingSection() { + stubBody(url, """{"game": [{"version": "1.21", "stable": true}], "loader": []}""") + assertFailsQuietly { FabricVersions.downloadData() } + } + + @Test + @DisplayName("A missing field fails quietly") + fun missingField() { + stubBody(url, """{"game": [{"version": "1.21"}], "mappings": [], "loader": []}""") + assertFailsQuietly { FabricVersions.downloadData() } + } + + @Test + @DisplayName("JSON of the wrong shape fails quietly") + fun wrongShape() { + stubBody(url, "[]") + assertFailsQuietly { FabricVersions.downloadData() } + } + + @Test + @DisplayName("Malformed JSON fails quietly") + fun malformed() { + stubBody(url, MALFORMED_JSON) + assertFailsQuietly { FabricVersions.downloadData() } + } + + @Test + @DisplayName("An HTTP error fails quietly") + fun httpError() { + stubServerError(url) + assertFailsQuietly { FabricVersions.downloadData() } + } +} Index: src/test/kotlin/creator/fetcher/FetchCatchingTest.kt =================================================================== --- src/test/kotlin/creator/fetcher/FetchCatchingTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) +++ src/test/kotlin/creator/fetcher/FetchCatchingTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -0,0 +1,87 @@ +/* + * Minecraft Development for IntelliJ + * + * https://mcdev.io/ + * + * Copyright (C) 2026 minecraft-dev + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published + * by the Free Software Foundation, version 3.0 only. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.demonwav.mcdev.creator.fetcher + +import com.demonwav.mcdev.util.fetchCatching +import com.demonwav.mcdev.util.fetchOrNull +import com.intellij.openapi.diagnostic.logger +import com.intellij.openapi.progress.ProcessCanceledException +import java.io.IOException +import java.util.concurrent.CancellationException +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertSame +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows + +@DisplayName("fetchCatching and fetchOrNull Tests") +class FetchCatchingTest : FetcherTestBase() { + + private val logger = logger() + + @Test + @DisplayName("A successful fetch returns its result without logging") + fun success() { + assertEquals("ok", fetchOrNull(logger, "test") { "ok" }) + assertNothingLogged() + } + + @Test + @DisplayName("A failed fetch gives null and a warning") + fun failure() { + assertFailsQuietly { fetchOrNull(logger, "test") { throw IOException("boom") } } + } + + @Test + @DisplayName("A runtime exception gives null and a warning") + fun runtimeFailure() { + assertFailsQuietly { fetchOrNull(logger, "test") { throw IllegalStateException("boom") } } + } + + @Test + @DisplayName("Coroutine cancellation propagates") + fun cancellation() { + assertThrows { fetchOrNull(logger, "test") { throw CancellationException() } } + assertNothingLogged() + } + + @Test + @DisplayName("Progress cancellation propagates") + fun processCanceled() { + assertThrows { fetchOrNull(logger, "test") { throw ProcessCanceledException() } } + assertNothingLogged() + } + + @Test + @DisplayName("A failed catching fetch keeps its cause and logs a warning") + fun catchingFailure() { + val cause = IOException("boom") + assertFailsQuietly { fetchCatching(logger, "test") { throw cause } } + assertSame(cause, fetchCatching(logger, "test") { throw cause }.exceptionOrNull()) + } + + @Test + @DisplayName("Coroutine cancellation propagates from a catching fetch") + fun catchingCancellation() { + assertThrows { fetchCatching(logger, "test") { throw CancellationException() } } + assertNothingLogged() + } +} Index: src/test/kotlin/creator/fetcher/FetcherTestBase.kt =================================================================== --- src/test/kotlin/creator/fetcher/FetcherTestBase.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) +++ src/test/kotlin/creator/fetcher/FetcherTestBase.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -0,0 +1,132 @@ +/* + * Minecraft Development for IntelliJ + * + * https://mcdev.io/ + * + * Copyright (C) 2026 minecraft-dev + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published + * by the Free Software Foundation, version 3.0 only. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.demonwav.mcdev.creator.fetcher + +import com.demonwav.mcdev.framework.LogCapture +import com.demonwav.mcdev.framework.http.HttpMockExtension +import com.demonwav.mcdev.framework.http.HttpMockServer.Companion.mockUrl +import com.demonwav.mcdev.util.NoVersionsFoundException +import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder +import com.github.tomakehurst.wiremock.client.WireMock.get +import com.github.tomakehurst.wiremock.client.WireMock.notFound +import com.github.tomakehurst.wiremock.client.WireMock.ok +import com.github.tomakehurst.wiremock.client.WireMock.serverError +import com.intellij.testFramework.fixtures.BareTestFixture +import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory +import kotlin.time.Duration.Companion.seconds +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertInstanceOf +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.extension.RegisterExtension + +/** + * Runs fetchers against the recorded fixtures, capturing what they log. Every test fails if a fetcher logs an error. + */ +abstract class FetcherTestBase { + + @JvmField + @RegisterExtension + val http = HttpMockExtension() + + // The plugin's user agent reads the plugin version, which needs the IDE application + private lateinit var fixture: BareTestFixture + lateinit var log: LogCapture + + @BeforeEach + fun setUpFetcherTest() { + fixture = IdeaTestFixtureFactory.getFixtureFactory().createBareFixture() + fixture.setUp() + log = LogCapture() + } + + @AfterEach + fun tearDownFetcherTest() { + try { + log.close() + log.assertNoErrors() + } finally { + fixture.tearDown() + } + } + + fun fetch(block: suspend () -> T): T = runBlocking { withTimeout(30.seconds) { block() } } + + fun stub(url: String, response: ResponseDefinitionBuilder) { + http.server.stubFor(get(mockUrl(url)).willReturn(response)) + } + + fun stubBody(url: String, body: String) = stub(url, ok(body)) + + fun stubServerError(url: String) = stub(url, serverError()) + + fun stubNotFound(url: String) = stub(url, notFound()) + + fun mavenMetadata(vararg versions: String): String { + val tags = versions.joinToString("") { "$it" } + return "$tags" + } + + /** + * Asserts that [fetcher] returns null or a failure other than finding no versions, and logs a warning without an + * error. + */ + fun assertFailsQuietly(fetcher: suspend () -> Any?) { + val result = fetch(fetcher) + assertTrue( + result == null || (result is Result<*> && result.isFailure), + "The fetcher should give null or a failure, but gave $result", + ) + assertFalse( + result is Result<*> && result.exceptionOrNull() is NoVersionsFoundException, + "The fetcher should fail, not find no versions", + ) + assertTrue(log.warnings.isNotEmpty(), "The failure should be logged as a warning") + log.assertNoErrors() + } + + /** + * Asserts that [fetcher] reports finding no versions and logs a warning without an error. + */ + fun assertFindsNone(fetcher: suspend () -> Result<*>) { + val failure = fetch(fetcher).exceptionOrNull() + assertInstanceOf(NoVersionsFoundException::class.java, failure, "The fetcher should find no versions") + assertTrue(log.warnings.isNotEmpty(), "Finding no versions should be logged as a warning") + log.assertNoErrors() + } + + /** + * Asserts that nothing was logged as a warning or an error. + */ + fun assertNothingLogged() { + assertEquals(emptyList(), log.warnings) + log.assertNoErrors() + } + + companion object { + const val MALFORMED_XML = "1.0" + const val MALFORMED_JSON = "{\"versions\": [1, 2" + } +} Index: src/test/kotlin/creator/fetcher/ForgeVersionTest.kt =================================================================== --- src/test/kotlin/creator/fetcher/ForgeVersionTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) +++ src/test/kotlin/creator/fetcher/ForgeVersionTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -0,0 +1,104 @@ +/* + * Minecraft Development for IntelliJ + * + * https://mcdev.io/ + * + * Copyright (C) 2026 minecraft-dev + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published + * by the Free Software Foundation, version 3.0 only. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.demonwav.mcdev.creator.fetcher + +import com.demonwav.mcdev.creator.custom.model.ForgeVersions +import com.demonwav.mcdev.platform.forge.version.ForgeVersion +import com.demonwav.mcdev.util.SemanticVersion +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test + +@DisplayName("Forge Version Fetcher Tests") +class ForgeVersionTest : FetcherTestBase() { + + private val url = "https://files.minecraftforge.net/maven/net/minecraftforge/forge/maven-metadata.xml" + + private fun v(version: String) = SemanticVersion.parse(version) + + @Test + @DisplayName("Minecraft versions without a \"1.\" prefix are listed, and their next version keeps the prefix") + fun noOnePrefix() { + val forge = fetch { ForgeVersion.downloadData() }.getOrThrow() + val mcVersions = forge.sortedMcVersions + assertEquals(listOf(v("26.3"), v("26.2"), v("26.1.2"), v("26.1.1"), v("26.1")), mcVersions.take(5)) + assertEquals(listOf(v("62.0.9"), v("62.0.8"), v("62.0.5")), forge.getForgeVersions(v("26.1"))) + + assertEquals("26.2", ForgeVersions(v("26.1"), v("62.0.9")).minecraftNext) + assertEquals("26.2", ForgeVersions(v("26.1.2"), v("64.1.6")).minecraftNext) + assertEquals("1.21", ForgeVersions(v("1.20.4"), v("49.0.1")).minecraftNext) + assertNothingLogged() + } + + @Test + @DisplayName("Versions are read from recorded metadata") + fun recorded() { + val forge = fetch { ForgeVersion.downloadData() }.getOrThrow() + assertEquals(233, forge.versions.size) + assertEquals(v("66.1.8"), forge.getForgeVersions(v("26.3")).first()) + assertTrue(v("1.20.1") in forge.sortedMcVersions) + assertNothingLogged() + } + + @Test + @DisplayName("Forge versions for a Minecraft version are newest first and capped at 50") + fun forgeVersionOrder() { + val versions = (1..60).map { "1.20.1-47.1.$it" } + "1.20-46.0.1" + stubBody(url, mavenMetadata(*versions.toTypedArray())) + val forge = fetch { ForgeVersion.downloadData() }.getOrThrow() + val forgeVersions = forge.getForgeVersions(v("1.20.1")) + assertEquals(50, forgeVersions.size) + assertEquals(v("47.1.60"), forgeVersions.first()) + assertEquals(listOf(v("46.0.1")), forge.getForgeVersions(v("1.20"))) + } + + @Test + @DisplayName("Versions without a Minecraft version are skipped") + fun noMcVersion() { + stubBody(url, mavenMetadata("47.1.0", "1.20.1-47.1.0")) + val forge = fetch { ForgeVersion.downloadData() }.getOrThrow() + assertEquals(listOf("1.20.1-47.1.0"), forge.versions) + assertEquals(listOf(v("1.20.1")), forge.sortedMcVersions) + } + + @Test + @DisplayName("Metadata with no versions finds none") + fun empty() { + stubBody(url, mavenMetadata()) + assertFindsNone { ForgeVersion.downloadData() } + } + + // Before every failure was caught, an XMLStreamException escaped the fetcher + @Test + @DisplayName("Malformed XML fails quietly") + fun malformed() { + stubBody(url, MALFORMED_XML) + assertFailsQuietly { ForgeVersion.downloadData() } + } + + @Test + @DisplayName("An HTTP error fails quietly") + fun httpError() { + stubServerError(url) + assertFailsQuietly { ForgeVersion.downloadData() } + } +} Index: src/test/kotlin/creator/fetcher/NeoForgeVersionTest.kt =================================================================== --- src/test/kotlin/creator/fetcher/NeoForgeVersionTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) +++ src/test/kotlin/creator/fetcher/NeoForgeVersionTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -0,0 +1,85 @@ +/* + * Minecraft Development for IntelliJ + * + * https://mcdev.io/ + * + * Copyright (C) 2026 minecraft-dev + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published + * by the Free Software Foundation, version 3.0 only. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.demonwav.mcdev.creator.fetcher + +import com.demonwav.mcdev.platform.neoforge.version.NeoForgeVersion +import com.demonwav.mcdev.util.SemanticVersion +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test + +@DisplayName("NeoForge Version Fetcher Tests") +class NeoForgeVersionTest : FetcherTestBase() { + + private val url = "https://maven.neoforged.net/releases/net/neoforged/neoforge/maven-metadata.xml" + + private fun v(version: String) = SemanticVersion.parse(version) + + @Test + @DisplayName("Versions are grouped by Minecraft version, newest first") + fun recorded() { + val neoForge = fetch { NeoForgeVersion.downloadData() }.getOrThrow() + assertEquals(62, neoForge.versions.size) + assertEquals(listOf(v("26.3"), v("26.2"), v("26.1.2"), v("1.21.11")), neoForge.sortedMcVersions.take(4)) + assertEquals( + listOf(v("26.3.0.103"), v("26.3.0.102"), v("26.3.0.101")), + neoForge.getNeoForgeVersions(v("26.3")), + ) + assertEquals(listOf(v("21.1.266"), v("21.1.265"), v("21.1.264")), neoForge.getNeoForgeVersions(v("1.21.1"))) + assertEquals(listOf(v("21.0.167"), v("21.0.166"), v("21.0.165")), neoForge.getNeoForgeVersions(v("1.21"))) + assertNothingLogged() + } + + @Test + @DisplayName("Minecraft versions are derived from both NeoForge version schemes") + fun minecraftVersion() { + assertEquals("1.21.1", NeoForgeVersion.getMinecraftVersion("21.1.77")) + assertEquals("1.21", NeoForgeVersion.getMinecraftVersion("21.0.167")) + assertEquals("1.20.2", NeoForgeVersion.getMinecraftVersion("20.2.91")) + assertEquals("26.1", NeoForgeVersion.getMinecraftVersion("26.1.0.19-beta")) + assertEquals("26.1.1", NeoForgeVersion.getMinecraftVersion("26.1.1.6-beta")) + assertEquals("26.1.2", NeoForgeVersion.getMinecraftVersion("26.1.2.124")) + assertNull(NeoForgeVersion.getMinecraftVersion("26.1.19")) + assertNull(NeoForgeVersion.getMinecraftVersion("snapshot.1")) + } + + @Test + @DisplayName("Metadata with no versions finds none") + fun empty() { + stubBody(url, mavenMetadata()) + assertFindsNone { NeoForgeVersion.downloadData() } + } + + @Test + @DisplayName("Malformed XML fails quietly") + fun malformed() { + stubBody(url, MALFORMED_XML) + assertFailsQuietly { NeoForgeVersion.downloadData() } + } + + @Test + @DisplayName("An HTTP error fails quietly") + fun httpError() { + stubServerError(url) + assertFailsQuietly { NeoForgeVersion.downloadData() } + } +} Index: src/test/kotlin/creator/fetcher/NeoGradleVersionTest.kt =================================================================== --- src/test/kotlin/creator/fetcher/NeoGradleVersionTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) +++ src/test/kotlin/creator/fetcher/NeoGradleVersionTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -0,0 +1,81 @@ +/* + * Minecraft Development for IntelliJ + * + * https://mcdev.io/ + * + * Copyright (C) 2026 minecraft-dev + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published + * by the Free Software Foundation, version 3.0 only. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.demonwav.mcdev.creator.fetcher + +import com.demonwav.mcdev.platform.neoforge.version.NeoGradleVersion +import com.demonwav.mcdev.util.SemanticVersion +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test + +@DisplayName("NeoGradle Version Fetcher Tests") +class NeoGradleVersionTest : FetcherTestBase() { + + private val url = "https://maven.neoforged.net/releases/net/neoforged/gradle/userdev/maven-metadata.xml" + + @Test + @DisplayName("Versions are read from recorded metadata, newest first") + fun recorded() { + val versions = fetch { NeoGradleVersion.downloadData() }.getOrThrow().versions + assertEquals(6, versions.size) + assertEquals(SemanticVersion.parse("7.1.39"), versions.first()) + assertEquals(versions.sortedDescending(), versions) + assertNothingLogged() + } + + @Test + @DisplayName("Unparseable versions are skipped and at most 50 are kept") + fun filtered() { + val versions = (1..60).map { "1.0.$it" } + "not a version" + stubBody(url, mavenMetadata(*versions.toTypedArray())) + val result = fetch { NeoGradleVersion.downloadData() }.getOrThrow().versions + assertEquals(50, result.size) + assertEquals(SemanticVersion.parse("1.0.60"), result.first()) + } + + @Test + @DisplayName("Metadata with only unparseable versions finds none") + fun noParseableVersions() { + stubBody(url, mavenMetadata("not a version")) + assertFindsNone { NeoGradleVersion.downloadData() } + } + + @Test + @DisplayName("Metadata with no versions finds none") + fun empty() { + stubBody(url, mavenMetadata()) + assertFindsNone { NeoGradleVersion.downloadData() } + } + + @Test + @DisplayName("Malformed XML fails quietly") + fun malformed() { + stubBody(url, MALFORMED_XML) + assertFailsQuietly { NeoGradleVersion.downloadData() } + } + + @Test + @DisplayName("An HTTP error fails quietly") + fun httpError() { + stubServerError(url) + assertFailsQuietly { NeoGradleVersion.downloadData() } + } +} Index: src/test/kotlin/creator/fetcher/NeoModDevVersionTest.kt =================================================================== --- src/test/kotlin/creator/fetcher/NeoModDevVersionTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) +++ src/test/kotlin/creator/fetcher/NeoModDevVersionTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -0,0 +1,81 @@ +/* + * Minecraft Development for IntelliJ + * + * https://mcdev.io/ + * + * Copyright (C) 2026 minecraft-dev + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published + * by the Free Software Foundation, version 3.0 only. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.demonwav.mcdev.creator.fetcher + +import com.demonwav.mcdev.platform.neoforge.version.NeoModDevVersion +import com.demonwav.mcdev.util.SemanticVersion +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test + +@DisplayName("ModDevGradle Version Fetcher Tests") +class NeoModDevVersionTest : FetcherTestBase() { + + private val url = "https://maven.neoforged.net/releases/net/neoforged/moddev/net.neoforged.moddev.gradle.plugin/maven-metadata.xml" + + @Test + @DisplayName("Versions are read from recorded metadata, newest first") + fun recorded() { + val versions = fetch { NeoModDevVersion.downloadData() }.getOrThrow().versions + assertEquals(9, versions.size) + assertEquals(SemanticVersion.parse("2.0.148"), versions.first()) + assertEquals(versions.sortedDescending(), versions) + assertNothingLogged() + } + + @Test + @DisplayName("Unparseable versions are skipped and at most 50 are kept") + fun filtered() { + val versions = (1..60).map { "1.0.$it" } + "not a version" + stubBody(url, mavenMetadata(*versions.toTypedArray())) + val result = fetch { NeoModDevVersion.downloadData() }.getOrThrow().versions + assertEquals(50, result.size) + assertEquals(SemanticVersion.parse("1.0.60"), result.first()) + } + + @Test + @DisplayName("Metadata with only unparseable versions finds none") + fun noParseableVersions() { + stubBody(url, mavenMetadata("not a version")) + assertFindsNone { NeoModDevVersion.downloadData() } + } + + @Test + @DisplayName("Metadata with no versions finds none") + fun empty() { + stubBody(url, mavenMetadata()) + assertFindsNone { NeoModDevVersion.downloadData() } + } + + @Test + @DisplayName("Malformed XML fails quietly") + fun malformed() { + stubBody(url, MALFORMED_XML) + assertFailsQuietly { NeoModDevVersion.downloadData() } + } + + @Test + @DisplayName("An HTTP error fails quietly") + fun httpError() { + stubServerError(url) + assertFailsQuietly { NeoModDevVersion.downloadData() } + } +} Index: src/test/kotlin/creator/fetcher/PaperVersionsTest.kt =================================================================== --- src/test/kotlin/creator/fetcher/PaperVersionsTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) +++ src/test/kotlin/creator/fetcher/PaperVersionsTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -0,0 +1,114 @@ +/* + * Minecraft Development for IntelliJ + * + * https://mcdev.io/ + * + * Copyright (C) 2026 minecraft-dev + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published + * by the Free Software Foundation, version 3.0 only. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.demonwav.mcdev.creator.fetcher + +import com.demonwav.mcdev.creator.custom.types.PaperVersionCreatorProperty +import com.demonwav.mcdev.util.SemanticVersion +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test + +@DisplayName("Paper Version Fetcher Tests") +class PaperVersionsTest : FetcherTestBase() { + + private val url = "https://fill.papermc.io/v3/projects/paper" + + private fun v(version: String) = SemanticVersion.parse(version) + + @BeforeEach + fun clearPaperCache() { + PaperVersionCreatorProperty.clearCache() + } + + @Test + @DisplayName("Release versions from 1.18.2 on are listed newest first, including 26.x") + fun recorded() { + val versions = fetch { PaperVersionCreatorProperty.getPaperVersions() }!! + assertEquals(27, versions.size) + assertEquals(listOf(v("26.3"), v("26.2"), v("26.1.2"), v("26.1.1"), v("1.21.11")), versions.take(5)) + assertEquals(v("1.18.2"), versions.last()) + assertNothingLogged() + } + + @Test + @DisplayName("Pre-releases, release candidates and unparseable versions are left out") + fun releasesOnly() { + stubBody( + url, + """{"versions": {"26.1": ["26.1.1", "26.1-rc-2", "nonsense version"], "1.21": ["1.21.11-pre5", "1.21.11"]}}""", + ) + val versions = fetch { PaperVersionCreatorProperty.getPaperVersions() }!! + assertEquals(listOf(v("26.1.1"), v("1.21.11")), versions) + } + + @Test + @DisplayName("Successful results are cached") + fun cached() { + fetch { PaperVersionCreatorProperty.getPaperVersions() }!! + fetch { PaperVersionCreatorProperty.getPaperVersions() }!! + assertEquals(1, http.server.requestsTo(url).size) + } + + @Test + @DisplayName("Failures aren't cached") + fun failureNotCached() { + stubServerError(url) + assertFailsQuietly { PaperVersionCreatorProperty.getPaperVersions() } + stub(url, http.server.fixture(url)) + assertEquals(27, fetch { PaperVersionCreatorProperty.getPaperVersions() }!!.size) + } + + @Test + @DisplayName("Only versions older than 1.18.2 fails quietly") + fun onlyOldVersions() { + stubBody(url, """{"versions": {"1.18": ["1.18.1", "1.18"]}}""") + assertFailsQuietly { PaperVersionCreatorProperty.getPaperVersions() } + } + + @Test + @DisplayName("No versions fails quietly") + fun empty() { + stubBody(url, """{"versions": {}}""") + assertFailsQuietly { PaperVersionCreatorProperty.getPaperVersions() } + } + + @Test + @DisplayName("A missing versions object fails quietly") + fun missingVersions() { + stubBody(url, """{"project": {"id": "paper"}}""") + assertFailsQuietly { PaperVersionCreatorProperty.getPaperVersions() } + } + + @Test + @DisplayName("Malformed JSON fails quietly") + fun malformed() { + stubBody(url, MALFORMED_JSON) + assertFailsQuietly { PaperVersionCreatorProperty.getPaperVersions() } + } + + @Test + @DisplayName("An HTTP error fails quietly") + fun httpError() { + stubServerError(url) + assertFailsQuietly { PaperVersionCreatorProperty.getPaperVersions() } + } +} Index: src/test/kotlin/creator/fetcher/ParchmentVersionTest.kt =================================================================== --- src/test/kotlin/creator/fetcher/ParchmentVersionTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) +++ src/test/kotlin/creator/fetcher/ParchmentVersionTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -0,0 +1,132 @@ +/* + * Minecraft Development for IntelliJ + * + * https://mcdev.io/ + * + * Copyright (C) 2026 minecraft-dev + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published + * by the Free Software Foundation, version 3.0 only. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.demonwav.mcdev.creator.fetcher + +import com.demonwav.mcdev.creator.ParchmentVersion +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test + +@DisplayName("Parchment Version Fetcher Tests") +class ParchmentVersionTest : FetcherTestBase() { + + private val baseUrl = "https://maven.parchmentmc.org/org/parchmentmc/data/" + + private fun metadataUrl(mcVersion: String) = "${baseUrl}parchment-$mcVersion/maven-metadata.xml" + + private fun listing(vararg entries: String): String { + val links = entries.joinToString("\n") { "$it" } + return "
../\n$links
" + } + + @Test + @DisplayName("Versions are read from recorded data, newest Minecraft version first") + fun recorded() { + val versions = fetch { ParchmentVersion.downloadData() }!! + assertEquals(50, versions.size) + assertEquals( + listOf("1.21.11 - BLEEDING-SNAPSHOT", "1.21.11 - 2025.12.20", "1.21.11 - 2025.12.21-nightly-SNAPSHOT"), + versions.take(3).map { it.toString() }, + ) + assertEquals("1.21.10 - BLEEDING-SNAPSHOT", versions[3].toString()) + assertNothingLogged() + } + + @Test + @DisplayName("Downloading stops once the limit is reached") + fun limit() { + val versions = fetch { ParchmentVersion.downloadData(limit = 4) }!! + assertEquals(4, versions.size) + assertEquals(1, http.server.requestsTo(metadataUrl("1.21.10")).size) + assertEquals(0, http.server.requestsTo(metadataUrl("1.21.9")).size) + } + + @Test + @DisplayName("Minecraft versions without a release are skipped silently") + fun notFound() { + stubNotFound(metadataUrl("1.21.11")) + val versions = fetch { ParchmentVersion.downloadData() }!! + assertEquals("1.21.10 - BLEEDING-SNAPSHOT", versions.first().toString()) + assertNothingLogged() + } + + @Test + @DisplayName("A Minecraft version that fails to download is skipped with a warning") + fun partialFailure() { + stubServerError(metadataUrl("1.21.11")) + val versions = fetch { ParchmentVersion.downloadData() }!! + assertEquals("1.21.10 - BLEEDING-SNAPSHOT", versions.first().toString()) + assertTrue(log.warnings.isNotEmpty()) + } + + @Test + @DisplayName("Malformed metadata for a Minecraft version is skipped with a warning") + fun partialMalformed() { + stubBody(metadataUrl("1.21.11"), MALFORMED_XML) + val versions = fetch { ParchmentVersion.downloadData() }!! + assertEquals("1.21.10 - BLEEDING-SNAPSHOT", versions.first().toString()) + assertTrue(log.warnings.isNotEmpty()) + } + + @Test + @DisplayName("Entries that aren't Parchment versions are ignored") + fun otherEntries() { + stubBody(baseUrl, listing("blackstone/", "parchment-1.21.11/", "parchment-not.a.version/")) + val versions = fetch { ParchmentVersion.downloadData() }!! + assertEquals( + listOf("1.21.11 - BLEEDING-SNAPSHOT", "1.21.11 - 2025.12.20", "1.21.11 - 2025.12.21-nightly-SNAPSHOT"), + versions.map { it.toString() }, + ) + assertNothingLogged() + } + + @Test + @DisplayName("No Minecraft version with a release fails quietly") + fun noReleases() { + stubBody(baseUrl, listing("parchment-1.21.11/")) + stubNotFound(metadataUrl("1.21.11")) + assertFailsQuietly { ParchmentVersion.downloadData() } + } + + @Test + @DisplayName("Every Minecraft version failing to download fails quietly") + fun allFail() { + stubBody(baseUrl, listing("parchment-1.21.10/", "parchment-1.21.11/")) + stubServerError(metadataUrl("1.21.10")) + stubServerError(metadataUrl("1.21.11")) + assertFailsQuietly { ParchmentVersion.downloadData() } + } + + @Test + @DisplayName("An empty listing fails quietly") + fun emptyListing() { + stubBody(baseUrl, listing()) + assertFailsQuietly { ParchmentVersion.downloadData() } + } + + @Test + @DisplayName("A listing that fails to download fails quietly") + fun listingFailure() { + stubServerError(baseUrl) + assertFailsQuietly { ParchmentVersion.downloadData() } + } +} Index: src/test/kotlin/creator/fetcher/ScrapeArtifactoryDirectoryListingTest.kt =================================================================== --- src/test/kotlin/creator/fetcher/ScrapeArtifactoryDirectoryListingTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) +++ src/test/kotlin/creator/fetcher/ScrapeArtifactoryDirectoryListingTest.kt (revision e0069be60d2f270af6ea985afd8f533ef1d0a42e) @@ -0,0 +1,73 @@ +/* + * Minecraft Development for IntelliJ + * + * https://mcdev.io/ + * + * Copyright (C) 2026 minecraft-dev + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published + * by the Free Software Foundation, version 3.0 only. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.demonwav.mcdev.creator.fetcher + +import com.demonwav.mcdev.creator.scrapeArtifactoryDirectoryListing +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test + +@DisplayName("Artifactory Directory Listing Fetcher Tests") +class ScrapeArtifactoryDirectoryListingTest : FetcherTestBase() { + + private val url = "https://maven.parchmentmc.org/org/parchmentmc/data/" + + @Test + @DisplayName("Entries are read from the recorded listing, without the parent directory") + fun recorded() { + val entries = fetch { scrapeArtifactoryDirectoryListing(url) }!! + assertEquals(27, entries.size) + assertEquals("blackstone/", entries.first()) + assertEquals("parchment-1.21.9/", entries.last()) + assertFalse("../" in entries) + assertNothingLogged() + } + + @Test + @DisplayName("A listing with no entries gives an empty list") + fun empty() { + stubBody(url, "
../
") + assertEquals(emptyList(), fetch { scrapeArtifactoryDirectoryListing(url) }) + assertNothingLogged() + } + + @Test + @DisplayName("Malformed HTML fails quietly") + fun malformed() { + stubBody(url, "
x/
") + assertFailsQuietly { scrapeArtifactoryDirectoryListing(url) } + } + + @Test + @DisplayName("An HTTP error fails quietly") + fun httpError() { + stubServerError(url) + assertFailsQuietly { scrapeArtifactoryDirectoryListing(url) } + } + + @Test + @DisplayName("A missing listing fails quietly") + fun notFound() { + stubNotFound(url) + assertFailsQuietly { scrapeArtifactoryDirectoryListing(url) } + } +}