User: kyle wood Date: 17 Nov 26 04:06 Revision: 37f735141f4e949bcceb52111e97c58496353e55 Summary: Add test infrastructure for project creator tests Creator properties can now be cleared in between tests, and define a better model for managing the coroutine scope and jobs during project creation. TeamCity URL: http://ci.mcdev.io:80/viewModification.html?tab=vcsModificationFiles&modId=10813&personal=false Index: src/main/kotlin/creator/creator-utils.kt =================================================================== --- src/main/kotlin/creator/creator-utils.kt (revision 108d68f45ff493303afa9be9187a60d6384c1f0e) +++ src/main/kotlin/creator/creator-utils.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) @@ -25,14 +25,20 @@ import com.intellij.openapi.application.ModalityState import com.intellij.openapi.diagnostic.thisLogger import com.intellij.openapi.progress.ProgressManager +import com.intellij.openapi.util.Key import javax.swing.JComponent +import org.jetbrains.annotations.TestOnly +private val MODALITY_STATE_OVERRIDE = Key.create("mcdev.creator.modalityStateOverride") + val WizardContext.contentPanel: JComponent? get() = this.getUserData(AbstractWizard.KEY)?.contentPanel val WizardContext.modalityState: ModalityState get() { ProgressManager.checkCanceled() + getUserData(MODALITY_STATE_OVERRIDE)?.let { return it } + val contentPanel = contentPanel if (contentPanel == null) { thisLogger().error("Wizard content panel is null, using default modality state") @@ -41,3 +47,12 @@ return ModalityState.stateForComponent(contentPanel) } + +/** + * Makes the creator use [state] for this wizard instead of the wizard dialog's modality state, so the creator can run + * without a dialog. + */ +@TestOnly +fun WizardContext.overrideModalityState(state: ModalityState) { + putUserData(MODALITY_STATE_OVERRIDE, state) +} Index: src/main/kotlin/creator/custom/CreatorCaches.kt =================================================================== --- src/main/kotlin/creator/custom/CreatorCaches.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) +++ src/main/kotlin/creator/custom/CreatorCaches.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) @@ -0,0 +1,65 @@ +/* + * 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 + +import com.demonwav.mcdev.creator.custom.providers.RemoteTemplateProvider +import com.demonwav.mcdev.creator.custom.providers.TemplateProvider +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.intellij.openapi.util.io.NioFiles +import com.intellij.openapi.vfs.VfsUtil +import org.jetbrains.annotations.TestOnly + +object CreatorCaches { + + /** + * Forgets everything the creator downloaded during this JVM's lifetime, so the next creator downloads versions and + * template repos again, as it would after an IDE restart. Deletes the downloaded template repos from disk too. + */ + @TestOnly + fun clear() { + ArchitecturyVersionsCreatorProperty.clearCache() + FabricGameVersionCreatorProperty.clearCache() + FabricVersionsCreatorProperty.clearCache() + ForgeVersionsCreatorProperty.clearCache() + GradlePluginSelectorCreatorProperty.clearCache() + MavenArtifactVersionCreatorProperty.clearCache() + NeoForgeVersionsCreatorProperty.clearCache() + PaperVersionCreatorProperty.clearCache() + ParchmentCreatorProperty.clearCache() + + for (key in TemplateProvider.getAllKeys()) { + (TemplateProvider.get(key) as? RemoteTemplateProvider)?.clearCache() + } + + val templatesDir = RemoteTemplateProvider.RemoteTemplateRepo.templatesBaseDir + NioFiles.deleteRecursively(templatesDir) + // Drop the VFS's view of the deleted zips, so a new zip with the same name isn't read from stale data + VfsUtil.markDirtyAndRefresh(false, true, true, templatesDir.toFile()) + } +} Index: src/main/kotlin/creator/custom/CreatorContext.kt =================================================================== --- src/main/kotlin/creator/custom/CreatorContext.kt (revision 108d68f45ff493303afa9be9187a60d6384c1f0e) +++ src/main/kotlin/creator/custom/CreatorContext.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) @@ -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 @@ -27,7 +27,6 @@ import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.asContextElement import com.intellij.openapi.observable.properties.PropertyGraph -import com.intellij.platform.util.coroutines.childScope import kotlin.coroutines.CoroutineContext import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers @@ -36,8 +35,14 @@ val graph: PropertyGraph, val properties: Map>, val wizardContext: WizardContext, - val scope: CoroutineScope + val session: CreatorSession, ) { + /** + * The main creator scope, canceled when the creator is closed. + */ + val scope: CoroutineScope + get() = session.scope + val modalityState: ModalityState get() = wizardContext.modalityState @@ -53,7 +58,7 @@ /** * A general purpose scope dependent of the main creator scope, cancelled when the creator is closed. */ - fun childScope(name: String): CoroutineScope = scope.childScope(name) + fun childScope(name: String): CoroutineScope = session.childScope(name) @Suppress("UNCHECKED_CAST") fun property(name: String): CreatorProperty = properties[name] as CreatorProperty Index: src/main/kotlin/creator/custom/CreatorSession.kt =================================================================== --- src/main/kotlin/creator/custom/CreatorSession.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) +++ src/main/kotlin/creator/custom/CreatorSession.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) @@ -0,0 +1,96 @@ +/* + * 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 + +import com.intellij.platform.util.coroutines.childScope +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.cancel +import kotlinx.coroutines.job +import kotlinx.coroutines.joinAll + +/** + * The coroutine scopes of one open creator. Callers can check whether the creator still has background work running, + * such as version downloads, through [isIdle] and [awaitIdle]. + * + * Get one from [TemplateService.openSession]. + */ +class CreatorSession internal constructor(val name: String, parentScope: CoroutineScope) { + + /** + * The creator's main scope. Cancelled when the creator closes. + */ + val scope: CoroutineScope = parentScope.childScope(name) + + // Guarded by itself. A new scope joins its parent before it's added here, and without the lock a concurrent + // check would see it as running work that never finishes. + private val scopeJobs: MutableSet = hashSetOf(scope.coroutineContext.job) + + /** + * A scope under [scope] whose work counts towards [isIdle]. + */ + fun childScope(name: String): CoroutineScope { + synchronized(scopeJobs) { + val child = scope.childScope(name) + scopeJobs += child.coroutineContext.job + return child + } + } + + /** + * True if no coroutine launched in this session's scopes is still running. + */ + val isIdle: Boolean + get() = runningJobs().isEmpty() + + /** + * Suspends until [isIdle] is true, including work launched while waiting. Never returns if called from a coroutine + * running in this session. + */ + suspend fun awaitIdle() { + while (true) { + val running = runningJobs() + if (running.isEmpty()) { + return + } + running.joinAll() + } + } + + internal fun cancel() { + scope.cancel("The creator got disposed") + } + + private fun runningJobs(): List = synchronized(scopeJobs) { + buildList { collectRunningJobs(scope.coroutineContext.job, this) } + } + + // Scope jobs never complete on their own, so look through them at the work launched in them + private fun collectRunningJobs(parent: Job, into: MutableList) { + for (child in parent.children) { + if (child in scopeJobs) { + collectRunningJobs(child, into) + } else if (!child.isCompleted) { + into += child + } + } + } +} Index: src/main/kotlin/creator/custom/CreatorTemplateProcessor.kt =================================================================== --- src/main/kotlin/creator/custom/CreatorTemplateProcessor.kt (revision 108d68f45ff493303afa9be9187a60d6384c1f0e) +++ src/main/kotlin/creator/custom/CreatorTemplateProcessor.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) @@ -57,8 +57,6 @@ import java.util.function.Consumer import kotlin.io.path.createDirectories import kotlin.io.path.writeText -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.launch interface ExternalTemplatePropertyProvider { @@ -73,7 +71,7 @@ class CreatorTemplateProcessor( propertyGraph: PropertyGraph, wizardContext: WizardContext, - scope: CoroutineScope, + session: CreatorSession, private val externalPropertyProvider: ExternalTemplatePropertyProvider, ) { @@ -81,7 +79,7 @@ private set private var properties: MutableMap> = mutableMapOf() - var context: CreatorContext = CreatorContext(propertyGraph, properties, wizardContext, scope) + var context: CreatorContext = CreatorContext(propertyGraph, properties, wizardContext, session) fun initBuiltinProperties() { val projectNameProperty = externalPropertyProvider.projectNameProperty @@ -256,7 +254,7 @@ if (context.wizardContext.isCreatingNewProject) { TemplateService.instance.registerFinalizerAction(project, finalizeAction) } else { - context.scope.launch { finalizeAction() } + TemplateService.instance.launchFinalizer(project, context.scope, finalizeAction) } } Index: src/main/kotlin/creator/custom/CustomPlatformStep.kt =================================================================== --- src/main/kotlin/creator/custom/CustomPlatformStep.kt (revision 108d68f45ff493303afa9be9187a60d6384c1f0e) +++ src/main/kotlin/creator/custom/CustomPlatformStep.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) @@ -39,7 +39,6 @@ import com.intellij.openapi.observable.properties.GraphProperty import com.intellij.openapi.observable.util.transform import com.intellij.openapi.project.Project -import com.intellij.openapi.util.Disposer import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.ui.JBColor import com.intellij.ui.dsl.builder.AlignX @@ -66,8 +65,8 @@ parent: NewProjectWizardStep, ) : AbstractNewProjectWizardStep(parent) { - val creatorScope = TemplateService.instance.scope("MinecraftDev Creator") - val creatorUiScope = TemplateService.instance.scope("MinecraftDev Creator UI") + val session = TemplateService.instance.openSession("MinecraftDev Creator", context.disposable) + val creatorUiScope = session.childScope("MinecraftDev Creator UI") val templateRepos = MinecraftSettings.instance.creatorTemplateRepos val templateRepoProperty = propertyGraph.property( @@ -109,15 +108,8 @@ get() = data.getUserData(GitNewProjectWizardData.KEY)?.git == true } private val templateProcessor = - CreatorTemplateProcessor(propertyGraph, context, creatorScope, externalPropertyProvider) + CreatorTemplateProcessor(propertyGraph, context, session, externalPropertyProvider) - init { - Disposer.register(context.disposable) { - creatorScope.cancel("The creator got disposed") - creatorUiScope.cancel("The creator got disposed") - } - } - override fun setupUI(builder: Panel) { lateinit var templatePropertyPlaceholder: Placeholder @@ -300,7 +292,7 @@ template.descriptor.version, TemplateDescriptor.SUPPORTED_FORMAT_VERSIONS.joinToString(", "), ) - return true; + return true } return false } Index: src/main/kotlin/creator/custom/TemplateService.kt =================================================================== --- src/main/kotlin/creator/custom/TemplateService.kt (revision 108d68f45ff493303afa9be9187a60d6384c1f0e) +++ src/main/kotlin/creator/custom/TemplateService.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) @@ -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 @@ -20,35 +20,128 @@ package com.demonwav.mcdev.creator.custom +import com.intellij.openapi.Disposable import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.thisLogger import com.intellij.openapi.project.Project import com.intellij.openapi.startup.ProjectActivity -import com.intellij.platform.util.coroutines.childScope +import com.intellij.openapi.util.Disposer import com.intellij.util.application +import java.util.concurrent.CopyOnWriteArrayList import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.getAndUpdate +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch @Service class TemplateService(private val scope: CoroutineScope) { - private val pendingActions: MutableMap Unit> = mutableMapOf() + private val sessions = CopyOnWriteArrayList() + private val finalizers = MutableStateFlow>(emptyMap()) + + /** + * The sessions of every creator currently open, oldest first. + */ + val activeSessions: List + get() = sessions.toList() + + /** + * Starts a session for a new creator. It's canceled and leaves [activeSessions] when [parentDisposable] is + * disposed. + */ + fun openSession(name: String, parentDisposable: Disposable): CreatorSession { + val session = CreatorSession(name, scope) + sessions += session + Disposer.register(parentDisposable) { + sessions -= session + session.cancel() + } + return session + } + + /** + * Holds [action] until [executeFinalizer] is called for [project], which happens when the project opens. Only one + * action can wait per project, later ones are dropped with an error. + */ fun registerFinalizerAction(project: Project, action: suspend () -> Unit) { - if (pendingActions.containsKey(project.name)) { - thisLogger().error("More than one finalizer action registered for project $project") - return + val key = project.locationHash + var registered = false + finalizers.update { all -> + val current = all[key] ?: ProjectFinalizers() + registered = current.pending == null + if (registered) all + (key to current.copy(pending = action)) else all } - pendingActions[project.locationHash] = action + if (!registered) { + thisLogger().error("More than one finalizer action registered for project $project") - } + } + } + /** + * Runs the action registered for [project], if there is one, and returns once it finishes. + */ suspend fun executeFinalizer(project: Project) { - pendingActions.remove(project.locationHash)?.invoke() + val key = project.locationHash + // Count the action as running before it stops being pending, so isFinalizing never misses it + val before = finalizers.getAndUpdate { all -> + val current = all[key] + if (current?.pending == null) all else all + (key to ProjectFinalizers(running = current.running + 1)) - } + } + val action = before[key]?.pending ?: return - fun scope(name: String): CoroutineScope = scope.childScope(name) + try { + action() + } finally { + finishedRunning(key) + } + } + /** + * Runs [action] in [scope] right away, tracked by [isFinalizing] and [awaitFinalizers] like a registered action. + */ + fun launchFinalizer(project: Project, scope: CoroutineScope, action: suspend () -> Unit): Job { + val key = project.locationHash + finalizers.update { all -> + val current = all[key] ?: ProjectFinalizers() + all + (key to current.copy(running = current.running + 1)) + } + + // Counts down even if the scope is cancelled before the action starts + return scope.launch { action() }.apply { invokeOnCompletion { finishedRunning(key) } } + } + + /** + * True while a finalize action for [project] is waiting for the project to open or still running. + */ + fun isFinalizing(project: Project): Boolean = finalizers.value[project.locationHash] != null + + /** + * Suspends until [isFinalizing] is false for [project]. An action waiting for the project to open keeps this + * suspended until [executeFinalizer] runs it. + */ + suspend fun awaitFinalizers(project: Project) { + val key = project.locationHash + finalizers.first { key !in it } + } + + private fun finishedRunning(key: String) { + finalizers.update { all -> + val current = all[key] ?: return@update all + val updated = current.copy(running = current.running - 1) + if (updated.isDone) all - key else all + (key to updated) + } + } + + private data class ProjectFinalizers(val pending: (suspend () -> Unit)? = null, val running: Int = 0) { + val isDone: Boolean + get() = pending == null && running <= 0 + } + companion object { val instance: TemplateService Index: src/main/kotlin/creator/custom/providers/BuiltinTemplateProvider.kt =================================================================== --- src/main/kotlin/creator/custom/providers/BuiltinTemplateProvider.kt (revision 108d68f45ff493303afa9be9187a60d6384c1f0e) +++ src/main/kotlin/creator/custom/providers/BuiltinTemplateProvider.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) @@ -55,6 +55,11 @@ } } + override fun clearCache() { + super.clearCache() + repoUpdated = false + } + override suspend fun loadTemplates( context: WizardContext, repo: MinecraftSettings.TemplateRepo Index: src/main/kotlin/creator/custom/providers/RemoteTemplateProvider.kt =================================================================== --- src/main/kotlin/creator/custom/providers/RemoteTemplateProvider.kt (revision 108d68f45ff493303afa9be9187a60d6384c1f0e) +++ src/main/kotlin/creator/custom/providers/RemoteTemplateProvider.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) @@ -66,7 +66,7 @@ open class RemoteTemplateProvider : TemplateProvider { - private var updatedTemplates = mutableSetOf() + private val updatedTemplates = mutableSetOf() override val label: String = MCDevBundle("template.provider.remote.label") @@ -87,6 +87,13 @@ } } + /** + * Makes the next [init] update every repo again. + */ + internal open fun clearCache() { + updatedTemplates.clear() + } + protected suspend fun doUpdateRepo( indicator: ProgressIndicator, repoName: String, Index: src/main/kotlin/creator/custom/types/ArchitecturyVersionsCreatorProperty.kt =================================================================== --- src/main/kotlin/creator/custom/types/ArchitecturyVersionsCreatorProperty.kt (revision 108d68f45ff493303afa9be9187a60d6384c1f0e) +++ src/main/kotlin/creator/custom/types/ArchitecturyVersionsCreatorProperty.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) @@ -431,6 +431,16 @@ private var fabricApiVersions: FabricApiVersions? = null private var architecturyVersions: ArchitecturyVersion? = null + internal fun clearCache() { + hasDownloadedVersions = false + forgeVersions = null + neoForgeVersions = null + fabricVersions = null + loomVersions = null + fabricApiVersions = null + architecturyVersions = null + } + private fun downloadVersions(context: CreatorContext, completeCallback: () -> Unit) { if (hasDownloadedVersions) { completeCallback() Index: src/main/kotlin/creator/custom/types/FabricGameVersionCreatorProperty.kt =================================================================== --- src/main/kotlin/creator/custom/types/FabricGameVersionCreatorProperty.kt (revision 108d68f45ff493303afa9be9187a60d6384c1f0e) +++ src/main/kotlin/creator/custom/types/FabricGameVersionCreatorProperty.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) @@ -91,6 +91,10 @@ companion object { private var gameVersions: GameVersions? = null + internal fun clearCache() { + gameVersions = null + } + private suspend fun getGameVersions(): GameVersions { gameVersions?.let { return it } Index: src/main/kotlin/creator/custom/types/FabricVersionsCreatorProperty.kt =================================================================== --- src/main/kotlin/creator/custom/types/FabricVersionsCreatorProperty.kt (revision 108d68f45ff493303afa9be9187a60d6384c1f0e) +++ src/main/kotlin/creator/custom/types/FabricVersionsCreatorProperty.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) @@ -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 @@ -308,6 +308,13 @@ private var loomVersions: List? = null private var fabricApiVersions: FabricApiVersions? = null + internal fun clearCache() { + hasDownloadedVersions = false + fabricVersions = null + loomVersions = null + fabricApiVersions = null + } + private fun downloadVersion(context: CreatorContext, uiCallback: () -> Unit) { if (hasDownloadedVersions) { uiCallback() Index: src/main/kotlin/creator/custom/types/ForgeVersionsCreatorProperty.kt =================================================================== --- src/main/kotlin/creator/custom/types/ForgeVersionsCreatorProperty.kt (revision 108d68f45ff493303afa9be9187a60d6384c1f0e) +++ src/main/kotlin/creator/custom/types/ForgeVersionsCreatorProperty.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) @@ -186,6 +186,11 @@ private var forgeVersion: ForgeVersion? = null + internal fun clearCache() { + hasDownloadedVersions = false + forgeVersion = null + } + private fun downloadVersions(context: CreatorContext, uiCallback: () -> Unit) { if (hasDownloadedVersions) { uiCallback() Index: src/main/kotlin/creator/custom/types/GradlePluginSelectorCreatorProperty.kt =================================================================== --- src/main/kotlin/creator/custom/types/GradlePluginSelectorCreatorProperty.kt (revision 108d68f45ff493303afa9be9187a60d6384c1f0e) +++ src/main/kotlin/creator/custom/types/GradlePluginSelectorCreatorProperty.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) @@ -182,8 +182,12 @@ companion object { - private var versionsCache = ConcurrentHashMap>() + private val versionsCache = ConcurrentHashMap>() + internal fun clearCache() { + versionsCache.clear() + } + fun downloadVersions( context: CreatorContext, key: String, Index: src/main/kotlin/creator/custom/types/MavenArtifactVersionCreatorProperty.kt =================================================================== --- src/main/kotlin/creator/custom/types/MavenArtifactVersionCreatorProperty.kt (revision 108d68f45ff493303afa9be9187a60d6384c1f0e) +++ src/main/kotlin/creator/custom/types/MavenArtifactVersionCreatorProperty.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) @@ -135,8 +135,12 @@ companion object { - private var versionsCache = ConcurrentHashMap>() + private val versionsCache = ConcurrentHashMap>() + internal fun clearCache() { + versionsCache.clear() + } + private fun downloadVersions( context: CreatorContext, key: String, Index: src/main/kotlin/creator/custom/types/NeoForgeVersionsCreatorProperty.kt =================================================================== --- src/main/kotlin/creator/custom/types/NeoForgeVersionsCreatorProperty.kt (revision 108d68f45ff493303afa9be9187a60d6384c1f0e) +++ src/main/kotlin/creator/custom/types/NeoForgeVersionsCreatorProperty.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) @@ -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 @@ -162,6 +162,14 @@ private var mdVersion: NeoModDevVersion? = null private var mcVersions: List? = 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() Index: src/main/kotlin/creator/custom/types/PaperVersionCreatorProperty.kt =================================================================== --- src/main/kotlin/creator/custom/types/PaperVersionCreatorProperty.kt (revision 108d68f45ff493303afa9be9187a60d6384c1f0e) +++ src/main/kotlin/creator/custom/types/PaperVersionCreatorProperty.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) @@ -49,6 +49,10 @@ companion object { private var paperVersions: List? = null + internal fun clearCache() { + paperVersions = null + } + suspend fun getPaperVersions(): List { paperVersions?.let { return it } Index: src/main/kotlin/creator/custom/types/ParchmentCreatorProperty.kt =================================================================== --- src/main/kotlin/creator/custom/types/ParchmentCreatorProperty.kt (revision 108d68f45ff493303afa9be9187a60d6384c1f0e) +++ src/main/kotlin/creator/custom/types/ParchmentCreatorProperty.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) @@ -256,6 +256,11 @@ private var allParchmentVersions: List? = null + internal fun clearCache() { + hasDownloadedVersions = false + allParchmentVersions = null + } + private fun downloadVersions(context: CreatorContext, uiCallback: () -> Unit) { if (hasDownloadedVersions) { uiCallback() Index: src/test/kotlin/creator/CreatorCachesTest.kt =================================================================== --- src/test/kotlin/creator/CreatorCachesTest.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) +++ src/test/kotlin/creator/CreatorCachesTest.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) @@ -0,0 +1,120 @@ +/* + * 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.MinecraftSettings +import com.demonwav.mcdev.creator.custom.CreatorCaches +import com.demonwav.mcdev.creator.custom.providers.RemoteTemplateProvider.RemoteAuthType +import com.demonwav.mcdev.creator.custom.providers.RemoteTemplateProvider.RemoteTemplateRepo +import com.demonwav.mcdev.creator.custom.providers.TemplateProvider +import com.demonwav.mcdev.framework.http.HttpMockExtension +import com.intellij.openapi.progress.EmptyProgressIndicator +import com.intellij.testFramework.fixtures.BareTestFixture +import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory +import java.nio.file.Files +import kotlin.io.path.exists +import kotlin.io.path.isRegularFile +import kotlinx.coroutines.runBlocking +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("Creator Caches Tests") +class CreatorCachesTest { + + @JvmField + @RegisterExtension + val http = HttpMockExtension() + + private lateinit var fixture: BareTestFixture + + private val builtinZipUrl = "https://github.com/minecraft-dev/templates/archive/refs/heads/v4.zip" + + @BeforeEach + fun setUp() { + fixture = IdeaTestFixtureFactory.getFixtureFactory().createBareFixture() + fixture.setUp() + CreatorCaches.clear() + } + + @AfterEach + fun tearDown() { + try { + CreatorCaches.clear() + } finally { + fixture.tearDown() + } + } + + private fun savedZips(): List { + val dir = RemoteTemplateRepo.templatesBaseDir + if (!dir.exists()) { + return emptyList() + } + return Files.list(dir).use { files -> + files.filter { it.isRegularFile() }.map { it.fileName.toString() }.toList() + } + } + + private fun init(providerKey: String, repo: MinecraftSettings.TemplateRepo) = runBlocking { + TemplateProvider.get(providerKey)!!.init(EmptyProgressIndicator(), listOf(repo)) + } + + @Test + @DisplayName("The builtin provider updates again after a reset, and the saved zip is deleted") + fun builtinProvider() { + val repo = MinecraftSettings.TemplateRepo.makeBuiltinRepo() + + init("builtin", repo) + init("builtin", repo) + assertEquals(1, http.server.requestsTo(builtinZipUrl).size, "The second init should reuse the update") + assertTrue(savedZips().isNotEmpty()) + + CreatorCaches.clear() + assertEquals(emptyList(), savedZips()) + + init("builtin", repo) + assertEquals(2, http.server.requestsTo(builtinZipUrl).size) + } + + @Test + @DisplayName("The remote provider updates again after a reset, and the saved zip is deleted") + fun remoteProvider() { + val data = RemoteTemplateRepo(builtinZipUrl, true, "", RemoteAuthType.NONE, "").serialize() + val repo = MinecraftSettings.TemplateRepo("Cache test", "remote", data) + + init("remote", repo) + init("remote", repo) + assertEquals(1, http.server.requestsTo(builtinZipUrl).size, "The second init should reuse the update") + assertEquals(listOf("Cache test.zip"), savedZips()) + + CreatorCaches.clear() + assertFalse(RemoteTemplateRepo.getDestinationZip("Cache test").exists()) + + init("remote", repo) + assertEquals(2, http.server.requestsTo(builtinZipUrl).size) + } +} Index: src/test/kotlin/creator/CreatorLoadingTest.kt =================================================================== --- src/test/kotlin/creator/CreatorLoadingTest.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) +++ src/test/kotlin/creator/CreatorLoadingTest.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) @@ -0,0 +1,181 @@ +/* + * 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.MinecraftSettings +import com.demonwav.mcdev.creator.custom.CreatorCaches +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.providers.LoadedTemplate +import com.demonwav.mcdev.creator.custom.providers.TemplateProvider +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.ok +import com.intellij.ide.util.projectWizard.WizardContext +import com.intellij.openapi.application.ModalityState +import com.intellij.openapi.observable.properties.PropertyGraph +import java.nio.file.Path +import kotlin.io.path.writeText +import kotlin.time.Duration.Companion.seconds +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +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.DisplayName +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.RegisterExtension +import org.junit.jupiter.api.io.TempDir + +@DisplayName("Creator Loading Tests") +class CreatorLoadingTest : CreatorTemplateProcessorTestBase() { + + @JvmField + @RegisterExtension + val http = HttpMockExtension() + + @TempDir + lateinit var templateDir: Path + + private val forgeUrl = "https://files.minecraftforge.net/maven/net/minecraftforge/forge/maven-metadata.xml" + 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 template = """ + { + "version": ${TemplateDescriptor.LATEST_FORMAT_VERSION}, + "properties": [ + { + "name": "FORGE_VERSIONS", + "type": "forge_versions" + }, + { + "name": "PAPER_VERSION", + "type": "paper_versions", + "default": "1.21" + }, + { + "name": "GREMLIN_VERSION", + "type": "maven_artifact_version", + "parameters": { + "sourceUrl": "$gremlinUrl" + } + } + ] + } + """.trimIndent() + + private fun test(block: suspend () -> Unit) = runBlocking { withTimeout(30.seconds) { block() } } + + private suspend fun loadTemplate(): LoadedTemplate { + templateDir.resolve("test.mcdev.template.json").writeText(template) + val repo = MinecraftSettings.TemplateRepo("Test", "local", templateDir.toString()) + return TemplateProvider.get("local")!!.loadTemplates(wizardContext, repo).single() + } + + private suspend fun setUpAndWait(processor: CreatorTemplateProcessor, template: LoadedTemplate) { + val reporter = TemplateValidationReporterImpl() + processor.setupTemplate(template, reporter) + assertFalse(reporter.hasErrors, "Template errors: ${reporter.items}") + assertFalse(reporter.hasWarns, "Template warnings: ${reporter.items}") + processor.context.session.awaitIdle() + } + + private fun forgeVersions(processor: CreatorTemplateProcessor = this.processor): ForgeVersions = + checkNotNull(processor.context.property("FORGE_VERSIONS").get()) + + private fun stubForge(vararg versions: String) { + val versionTags = versions.joinToString("") { "$it" } + val body = "$versionTags" + http.server.stubFor(get(mockUrl(forgeUrl)).willReturn(ok(body))) + } + + 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 fun v(version: String) = SemanticVersion.parse(version) + + @Test + @DisplayName("A local template loads and its version properties finish loading from the fixtures") + fun loadFromFixtures() = test { + LogCapture().use { log -> + val template = loadTemplate() + setUpAndWait(processor, template) + + assertEquals(ForgeVersions(v("26.3"), v("66.1.8")), forgeVersions()) + assertTrue(session.isIdle) + for (url in listOf(forgeUrl, paperUrl, gremlinUrl)) { + assertEquals(1, http.server.requestsTo(url).size, "Requests to $url") + } + log.assertNoErrors() + } + } + + // This test and the next override the same endpoint differently, and pass in either order + @Test + @DisplayName("Forge versions come from an overridden response") + fun overrideForgeOld() = test { + stubForge("1.20.1-47.1.0", "1.20.1-47.2.0", "1.19.4-45.1.0") + setUpAndWait(processor, loadTemplate()) + assertEquals(ForgeVersions(v("1.20.1"), v("47.2.0")), forgeVersions()) + } + + @Test + @DisplayName("Forge versions come from a differently overridden response") + fun overrideForgeNew() = test { + stubForge("26.1-62.0.5", "1.21.1-52.0.1") + setUpAndWait(processor, loadTemplate()) + assertEquals(ForgeVersions(v("26.1"), v("62.0.5")), forgeVersions()) + } + + @Test + @DisplayName("Clearing the caches makes the next creator download versions again") + fun clearCaches() = test { + val template = loadTemplate() + stubForge("1.20.1-47.1.0") + setUpAndWait(processor, template) + assertEquals(ForgeVersions(v("1.20.1"), v("47.1.0")), forgeVersions()) + + stubForge("26.1-62.0.5") + val cached = newProcessor() + setUpAndWait(cached, template) + assertEquals(ForgeVersions(v("1.20.1"), v("47.1.0")), forgeVersions(cached), "Without a reset") + assertEquals(1, http.server.requestsTo(forgeUrl).size) + + CreatorCaches.clear() + val fresh = newProcessor() + setUpAndWait(fresh, template) + assertEquals(ForgeVersions(v("26.1"), v("62.0.5")), forgeVersions(fresh), "After a reset") + assertEquals(2, http.server.requestsTo(forgeUrl).size) + } +} Index: src/test/kotlin/creator/CreatorSessionTest.kt =================================================================== --- src/test/kotlin/creator/CreatorSessionTest.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) +++ src/test/kotlin/creator/CreatorSessionTest.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) @@ -0,0 +1,146 @@ +/* + * 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.creator.custom.CreatorSession +import com.demonwav.mcdev.creator.custom.TemplateService +import com.intellij.openapi.Disposable +import com.intellij.openapi.util.Disposer +import com.intellij.testFramework.fixtures.BareTestFixture +import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory +import kotlin.time.Duration.Companion.seconds +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.launch +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 + +@DisplayName("Creator Session Tests") +class CreatorSessionTest { + + private lateinit var fixture: BareTestFixture + private lateinit var disposable: Disposable + private lateinit var session: CreatorSession + + @BeforeEach + fun setUp() { + fixture = IdeaTestFixtureFactory.getFixtureFactory().createBareFixture() + fixture.setUp() + disposable = Disposer.newDisposable(fixture.testRootDisposable, "creator session") + session = TemplateService.instance.openSession("Creator Session Test", disposable) + } + + @AfterEach + fun tearDown() { + fixture.tearDown() + } + + private fun test(block: suspend CoroutineScope.() -> Unit) = runBlocking { withTimeout(10.seconds) { block() } } + + @Test + @DisplayName("A session with no work is idle") + fun idleWithoutWork() = test { + session.childScope("unused") + assertTrue(session.isIdle) + session.awaitIdle() + } + + @Test + @DisplayName("Work in a child scope keeps the session busy until it finishes") + fun childScopeWork() = test { + val gate = CompletableDeferred() + session.childScope("work").launch { gate.await() } + assertFalse(session.isIdle) + + val waiter = async { session.awaitIdle() } + assertFalse(waiter.isCompleted) + gate.complete(Unit) + waiter.await() + assertTrue(session.isIdle) + } + + @Test + @DisplayName("Work launched directly in the main scope counts") + fun mainScopeWork() = test { + val gate = CompletableDeferred() + session.scope.launch { gate.await() } + assertFalse(session.isIdle) + gate.complete(Unit) + session.awaitIdle() + assertTrue(session.isIdle) + } + + @Test + @DisplayName("Waiting includes work launched by work that already finished") + fun followUpWork() = test { + val firstGate = CompletableDeferred() + val secondGate = CompletableDeferred() + val secondStarted = CompletableDeferred() + session.childScope("first").launch { + firstGate.await() + session.childScope("second").launch { + secondStarted.complete(Unit) + secondGate.await() + } + } + + val waiter = async { session.awaitIdle() } + firstGate.complete(Unit) + secondStarted.await() + assertFalse(waiter.isCompleted) + assertFalse(session.isIdle) + + secondGate.complete(Unit) + waiter.await() + assertTrue(session.isIdle) + } + + @Test + @DisplayName("Disposing the session cancels its work and removes it from the active sessions") + fun dispose() = test { + assertTrue(session in TemplateService.instance.activeSessions) + val job = session.childScope("forever").launch { awaitCancellation() } + + Disposer.dispose(disposable) + + job.join() + assertTrue(job.isCancelled) + assertTrue(session.isIdle) + assertFalse(session in TemplateService.instance.activeSessions) + } + + @Test + @DisplayName("Sessions are listed oldest first") + fun activeSessionsOrder() { + val second = TemplateService.instance.openSession("Second", disposable) + val sessions = TemplateService.instance.activeSessions + assertEquals(listOf(session, second), sessions.filter { it === session || it === second }) + } +} Index: src/test/kotlin/creator/CreatorTemplateProcessorTestBase.kt =================================================================== --- src/test/kotlin/creator/CreatorTemplateProcessorTestBase.kt (revision 108d68f45ff493303afa9be9187a60d6384c1f0e) +++ src/test/kotlin/creator/CreatorTemplateProcessorTestBase.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) @@ -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 @@ -20,18 +20,25 @@ package com.demonwav.mcdev.creator +import com.demonwav.mcdev.creator.custom.CreatorCaches +import com.demonwav.mcdev.creator.custom.CreatorSession import com.demonwav.mcdev.creator.custom.CreatorTemplateProcessor import com.demonwav.mcdev.creator.custom.ExternalTemplatePropertyProvider 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.providers.LoadedTemplate +import com.demonwav.mcdev.framework.InMemoryPropertiesComponent import com.google.gson.Gson +import com.intellij.ide.util.PropertiesComponent import com.intellij.ide.util.projectWizard.WizardContext +import com.intellij.openapi.application.ApplicationManager +import com.intellij.openapi.application.ModalityState import com.intellij.openapi.observable.properties.GraphProperty import com.intellij.openapi.observable.properties.PropertyGraph import com.intellij.testFramework.fixtures.BareTestFixture import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory +import com.intellij.testFramework.replaceService import org.intellij.lang.annotations.Language import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach @@ -63,6 +70,8 @@ lateinit var fixture: BareTestFixture lateinit var propertyGraph: PropertyGraph + lateinit var wizardContext: WizardContext + lateinit var session: CreatorSession lateinit var processor: CreatorTemplateProcessor @BeforeEach @@ -70,11 +79,18 @@ fixture = IdeaTestFixtureFactory.getFixtureFactory().createBareFixture() fixture.setUp() + CreatorCaches.clear() + // Properties remember their last value across creators, so start each test with nothing remembered + ApplicationManager.getApplication() + .replaceService(PropertiesComponent::class.java, InMemoryPropertiesComponent(), fixture.testRootDisposable) + propertyGraph = PropertyGraph() - val wizardContext = WizardContext(null, fixture.testRootDisposable) - val scope = TemplateService.instance.scope("MinecraftDev Creator Test") + wizardContext = WizardContext(null, fixture.testRootDisposable) + wizardContext.overrideModalityState(ModalityState.nonModal()) + // Cancelled when the fixture is torn down, so no work leaks into the next test + session = TemplateService.instance.openSession("MinecraftDev Creator Test", fixture.testRootDisposable) val externalPropertyProvider = TestExternalTemplatePropertyProvider(propertyGraph) - processor = CreatorTemplateProcessor(propertyGraph, wizardContext, scope, externalPropertyProvider) + processor = CreatorTemplateProcessor(propertyGraph, wizardContext, session, externalPropertyProvider) processor.initBuiltinProperties() } Index: src/test/kotlin/creator/TemplateServiceTest.kt =================================================================== --- src/test/kotlin/creator/TemplateServiceTest.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) +++ src/test/kotlin/creator/TemplateServiceTest.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) @@ -0,0 +1,178 @@ +/* + * 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.creator.custom.TemplateService +import com.demonwav.mcdev.framework.LogCapture +import com.intellij.openapi.project.Project +import com.intellij.testFramework.fixtures.IdeaProjectTestFixture +import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory +import com.intellij.testFramework.runInEdtAndWait +import java.util.concurrent.CopyOnWriteArrayList +import kotlin.time.Duration.Companion.seconds +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.async +import kotlinx.coroutines.cancel +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 + +@DisplayName("Template Service Tests") +class TemplateServiceTest { + + private lateinit var fixture: IdeaProjectTestFixture + private val project: Project + get() = fixture.project + private val service: TemplateService + get() = TemplateService.instance + + @BeforeEach + fun setUp() { + fixture = IdeaTestFixtureFactory.getFixtureFactory() + .createLightFixtureBuilder(null, "mcdev_template_service_test") + .fixture + // Light fixtures must be set up and torn down on the EDT + runInEdtAndWait { fixture.setUp() } + } + + @AfterEach + fun tearDown() { + try { + // Don't leave a pending action behind for a later test using the same light project + runBlocking { service.executeFinalizer(project) } + } finally { + runInEdtAndWait { fixture.tearDown() } + } + } + + private fun test(block: suspend CoroutineScope.() -> Unit) = runBlocking { withTimeout(10.seconds) { block() } } + + @Test + @DisplayName("A registered action waits for executeFinalizer") + fun registeredAction() = test { + val ran = CompletableDeferred() + service.registerFinalizerAction(project) { ran.complete(Unit) } + assertTrue(service.isFinalizing(project)) + assertFalse(ran.isCompleted) + + service.executeFinalizer(project) + + assertTrue(ran.isCompleted) + assertFalse(service.isFinalizing(project)) + } + + @Test + @DisplayName("Executing with nothing registered does nothing") + fun nothingRegistered() = test { + service.executeFinalizer(project) + assertFalse(service.isFinalizing(project)) + } + + @Test + @DisplayName("isFinalizing stays true while the action runs") + fun runningAction() = test { + val started = CompletableDeferred() + val gate = CompletableDeferred() + service.registerFinalizerAction(project) { + started.complete(Unit) + gate.await() + } + + val execution = async { service.executeFinalizer(project) } + started.await() + assertTrue(service.isFinalizing(project)) + + val waiter = async { service.awaitFinalizers(project) } + assertFalse(waiter.isCompleted) + + gate.complete(Unit) + execution.await() + waiter.await() + assertFalse(service.isFinalizing(project)) + } + + @Test + @DisplayName("A second registration for the same project logs an error and keeps the first") + fun duplicateRegistration() = test { + val ran = CopyOnWriteArrayList() + service.registerFinalizerAction(project) { ran += "first" } + + val errors = LogCapture().use { capture -> + service.registerFinalizerAction(project) { ran += "second" } + capture.errors.toList() + } + assertEquals(1, errors.size, "Expected one logged error, got $errors") + assertTrue("More than one finalizer action" in errors.single(), errors.single()) + + service.executeFinalizer(project) + assertEquals(listOf("first"), ran) + } + + @Test + @DisplayName("A launched action is tracked until it finishes") + fun launchedAction() = test { + val gate = CompletableDeferred() + val job = service.launchFinalizer(project, this) { gate.await() } + assertTrue(service.isFinalizing(project)) + + val waiter = async { service.awaitFinalizers(project) } + assertFalse(waiter.isCompleted) + + gate.complete(Unit) + job.join() + waiter.await() + assertFalse(service.isFinalizing(project)) + } + + @Test + @DisplayName("A launched action cancelled before it starts stops being tracked") + fun launchedActionCancelled() = test { + val scope = CoroutineScope(Job()) + scope.cancel() + val job = service.launchFinalizer(project, scope) { error("Should not run") } + job.join() + assertTrue(job.isCancelled) + assertFalse(service.isFinalizing(project)) + } + + @Test + @DisplayName("Pending and running actions are both tracked") + fun pendingAndLaunched() = test { + val gate = CompletableDeferred() + service.registerFinalizerAction(project) {} + val job = service.launchFinalizer(project, this) { gate.await() } + + service.executeFinalizer(project) + assertTrue(service.isFinalizing(project), "The launched action is still running") + + gate.complete(Unit) + job.join() + assertFalse(service.isFinalizing(project)) + } +} Index: src/test/kotlin/framework/InMemoryPropertiesComponent.kt =================================================================== --- src/test/kotlin/framework/InMemoryPropertiesComponent.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) +++ src/test/kotlin/framework/InMemoryPropertiesComponent.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) @@ -0,0 +1,77 @@ +/* + * 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.framework + +import com.intellij.ide.util.PropertiesComponent +import java.util.concurrent.ConcurrentHashMap + +/** + * A [PropertiesComponent] that starts empty and never saves. Register it with `replaceService` to keep values a test + * stores from reaching later tests. + */ +class InMemoryPropertiesComponent : PropertiesComponent() { + private val values = ConcurrentHashMap() + private val lists = ConcurrentHashMap>() + + override fun unsetValue(name: String) { + values.remove(name) + lists.remove(name) + } + + override fun isValueSet(name: String): Boolean = values.containsKey(name) || lists.containsKey(name) + + override fun getValue(name: String): String? = values[name] + + override fun setValue(name: String, value: String?) { + if (value == null) values.remove(name) else values[name] = value + } + + override fun setValue(name: String, value: String?, defaultValue: String?) { + setValue(name, value.takeUnless { it == defaultValue }) + } + + override fun setValue(name: String, value: Float, defaultValue: Float) { + setValue(name, value.toString(), defaultValue.toString()) + } + + override fun setValue(name: String, value: Int, defaultValue: Int) { + setValue(name, value.toString(), defaultValue.toString()) + } + + override fun setValue(name: String, value: Boolean, defaultValue: Boolean) { + setValue(name, value.toString(), defaultValue.toString()) + } + + override fun updateValue(name: String, value: Boolean): Boolean = + values.put(name, value.toString()) != value.toString() + + override fun getValues(name: String): Array? = lists[name]?.toTypedArray() + + override fun setValues(name: String, values: Array?) { + setList(name, values?.toList()) + } + + override fun getList(name: String): List? = lists[name] + + override fun setList(name: String, values: Collection?) { + if (values.isNullOrEmpty()) lists.remove(name) else lists[name] = values.toList() + } +} Index: src/test/kotlin/framework/LogCapture.kt =================================================================== --- src/test/kotlin/framework/LogCapture.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) +++ src/test/kotlin/framework/LogCapture.kt (revision 37f735141f4e949bcceb52111e97c58496353e55) @@ -0,0 +1,66 @@ +/* + * 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.framework + +import com.intellij.testFramework.LoggedErrorProcessor +import java.util.concurrent.CopyOnWriteArrayList + +/** + * Collects the errors and warnings logged from any thread until closed. While open, logged errors don't fail the test + * on their own, so check [errors] or call [assertNoErrors]. + */ +class LogCapture : AutoCloseable { + + val errors: MutableList = CopyOnWriteArrayList() + val warnings: MutableList = CopyOnWriteArrayList() + + private val token = LoggedErrorProcessor.executeWith( + object : LoggedErrorProcessor() { + override fun processError( + category: String, + message: String, + details: Array, + t: Throwable?, + ): Set { + errors += describe(category, message, t) + return Action.NONE + } + + override fun processWarn(category: String, message: String, t: Throwable?): Boolean { + warnings += describe(category, message, t) + return true + } + }, + ) + + fun assertNoErrors() { + if (errors.isNotEmpty()) { + throw AssertionError("Errors were logged:\n" + errors.joinToString("\n") { " $it" }) + } + } + + override fun close() { + token.finish() + } + + private fun describe(category: String, message: String, t: Throwable?): String = + if (t == null) "[$category] $message" else "[$category] $message: $t" +}