From 9f2b9cbd5c39c2dedd6f772717de70a484f67922 Mon Sep 17 00:00:00 2001 From: Adam <897017+aSemy@users.noreply.github.com> Date: Sun, 18 Dec 2022 01:40:40 +0100 Subject: [PATCH] big ol' refactor of the Gradle Factorio Mod - handle launching in multiple OSes - specific tasks for specific mod operations - extension object for settings - ground work for multiple mods --- ...iptToLuaTask.kt => TypeScriptToLuaTask.kt} | 20 +- .../factorio-gradle/build.gradle.kts | 9 + .../factorio/FactorioModConfigurations.kt | 9 + .../gradle/factorio/FactorioModInstallTask.kt | 43 ---- .../factorio/FactorioModLibraryPlugin.kt | 48 ++++ .../gradle/factorio/FactorioModPlugin.kt | 91 ++++++- .../gradle/factorio/FactorioModSettings.kt | 63 ++++- .../gradle/factorio/FactorioModSourceSet.kt | 38 +++ .../gradle/factorio/artifactDistributions.kt | 8 +- .../gradle/factorio/configureDistribution.kt | 42 ++++ .../adamko/gradle/factorio/configureIdea.kt | 66 +++++ .../gradle/factorio/configureModSettings.kt | 99 ++++++++ .../adamko/gradle/factorio/configureTasks.kt | 137 +++++++++++ .../factorio/mod/FactorioModProperties.kt | 19 ++ .../FactorioModPortalPublishClient.kt | 15 +- .../tasks/AssembleFactorioModContents.kt | 40 +++ .../tasks/GenerateFactorioModInfoTask.kt | 132 ++++++++++ .../tasks/LaunchFactorioClientTask.kt | 89 +++++++ .../tasks/LocalPublishFactorioModTask.kt | 40 +++ .../factorio/tasks/PackageFactorioModTask.kt | 6 + gradle/libs.versions.toml | 1 + modules/events-library/build.gradle.kts | 2 +- modules/events-mod/build.gradle.kts | 228 +++++++++--------- .../main/resources/mod-data => }/info.json | 0 .../main/resources => }/kafkatorio-logo.png | Bin .../resources => }/mod-portal-description.md | 0 .../resources/{mod-data => }/changelog.txt | 0 .../{mod-data => }/locale/en/locale.cfg | 0 .../resources/{mod-data => }/thumbnail.png | Bin modules/events-processors/build.gradle.kts | 1 + .../infra-factorio-client/build.gradle.kts | 92 +++---- .../infra-factorio-server/build.gradle.kts | 2 +- settings.gradle.kts | 2 + 33 files changed, 1098 insertions(+), 244 deletions(-) rename gradle-plugins/builder-plugins/src/main/kotlin/kafkatorio/tasks/{TypescriptToLuaTask.kt => TypeScriptToLuaTask.kt} (63%) create mode 100644 gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/FactorioModConfigurations.kt delete mode 100644 gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/FactorioModInstallTask.kt create mode 100644 gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/FactorioModLibraryPlugin.kt create mode 100644 gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/FactorioModSourceSet.kt create mode 100644 gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/configureDistribution.kt create mode 100644 gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/configureIdea.kt create mode 100644 gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/configureModSettings.kt create mode 100644 gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/configureTasks.kt create mode 100644 gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/mod/FactorioModProperties.kt create mode 100644 gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/tasks/AssembleFactorioModContents.kt create mode 100644 gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/tasks/GenerateFactorioModInfoTask.kt create mode 100644 gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/tasks/LaunchFactorioClientTask.kt create mode 100644 gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/tasks/LocalPublishFactorioModTask.kt create mode 100644 gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/tasks/PackageFactorioModTask.kt rename modules/events-mod/{src/main/resources/mod-data => }/info.json (100%) rename modules/events-mod/{src/main/resources => }/kafkatorio-logo.png (100%) rename modules/events-mod/{src/main/resources => }/mod-portal-description.md (100%) rename modules/events-mod/src/main/resources/{mod-data => }/changelog.txt (100%) rename modules/events-mod/src/main/resources/{mod-data => }/locale/en/locale.cfg (100%) rename modules/events-mod/src/main/resources/{mod-data => }/thumbnail.png (100%) diff --git a/gradle-plugins/builder-plugins/src/main/kotlin/kafkatorio/tasks/TypescriptToLuaTask.kt b/gradle-plugins/builder-plugins/src/main/kotlin/kafkatorio/tasks/TypeScriptToLuaTask.kt similarity index 63% rename from gradle-plugins/builder-plugins/src/main/kotlin/kafkatorio/tasks/TypescriptToLuaTask.kt rename to gradle-plugins/builder-plugins/src/main/kotlin/kafkatorio/tasks/TypeScriptToLuaTask.kt index d3c090d..a057288 100644 --- a/gradle-plugins/builder-plugins/src/main/kotlin/kafkatorio/tasks/TypescriptToLuaTask.kt +++ b/gradle-plugins/builder-plugins/src/main/kotlin/kafkatorio/tasks/TypeScriptToLuaTask.kt @@ -2,40 +2,32 @@ package kafkatorio.tasks import com.github.gradle.node.npm.task.NpmTask import javax.inject.Inject -import org.gradle.api.file.ConfigurableFileTree +import org.gradle.api.file.ConfigurableFileCollection import org.gradle.api.file.DirectoryProperty import org.gradle.api.file.FileSystemOperations import org.gradle.api.plugins.BasePlugin -import org.gradle.api.tasks.CacheableTask -import org.gradle.api.tasks.IgnoreEmptyDirectories -import org.gradle.api.tasks.InputDirectory -import org.gradle.api.tasks.Internal -import org.gradle.api.tasks.OutputDirectory -import org.gradle.api.tasks.PathSensitive -import org.gradle.api.tasks.PathSensitivity -import org.gradle.api.tasks.SkipWhenEmpty -import org.gradle.api.tasks.TaskAction +import org.gradle.api.tasks.* import org.gradle.work.NormalizeLineEndings import org.jetbrains.kotlin.util.parseSpaceSeparatedArgs @CacheableTask -abstract class TypescriptToLuaTask @Inject constructor( +abstract class TypeScriptToLuaTask @Inject constructor( private val fs: FileSystemOperations ) : NpmTask() { - @get:InputDirectory + @get:InputFiles @get:SkipWhenEmpty @get:PathSensitive(PathSensitivity.RELATIVE) @get:NormalizeLineEndings @get:IgnoreEmptyDirectories - abstract val sourceFiles: DirectoryProperty + abstract val sourceFiles: ConfigurableFileCollection @get:OutputDirectory abstract val outputDirectory: DirectoryProperty init { super.setGroup(BasePlugin.BUILD_GROUP) - super.setDescription("Convert Typescript To Lua") + super.setDescription("Convert TypeScript To Lua") super.execOverrides { standardOutput = System.out } super.npmCommand.set(listOf("run", "build")) super.ignoreExitValue.set(false) diff --git a/gradle-plugins/factorio-gradle/build.gradle.kts b/gradle-plugins/factorio-gradle/build.gradle.kts index 77a630f..ea4c623 100644 --- a/gradle-plugins/factorio-gradle/build.gradle.kts +++ b/gradle-plugins/factorio-gradle/build.gradle.kts @@ -31,6 +31,8 @@ dependencies { implementation(libs.ktorClient.cio) implementation(libs.ktorClient.resources) implementation(libs.ktorSerialization.kotlinxJson) + + implementation("org.jetbrains.kotlin:kotlin-compiler-embeddable:${libs.versions.kotlin.get()}") } gradlePlugin { @@ -41,6 +43,13 @@ gradlePlugin { implementationClass = "dev.adamko.gradle.factorio.FactorioModPlugin" } } + plugins { + create("factorioModLibrary") { + displayName = "Factorio Mod Library" + id = "dev.adamko.factorio-mod-library" + implementationClass = "dev.adamko.gradle.factorio.FactorioModLibraryPlugin" + } + } } overrideKotlinLanguageVersion("1.7") // required for Kotlinx Serialization diff --git a/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/FactorioModConfigurations.kt b/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/FactorioModConfigurations.kt new file mode 100644 index 0000000..ab13cee --- /dev/null +++ b/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/FactorioModConfigurations.kt @@ -0,0 +1,9 @@ +package dev.adamko.gradle.factorio + +import org.gradle.api.NamedDomainObjectProvider +import org.gradle.api.artifacts.Configuration + +internal data class FactorioModConfigurations( + val factorioMod: NamedDomainObjectProvider, + val factorioModProvider: NamedDomainObjectProvider, + ) diff --git a/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/FactorioModInstallTask.kt b/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/FactorioModInstallTask.kt deleted file mode 100644 index f49ecb9..0000000 --- a/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/FactorioModInstallTask.kt +++ /dev/null @@ -1,43 +0,0 @@ -package dev.adamko.gradle.factorio - -import javax.inject.Inject -import org.gradle.api.DefaultTask -import org.gradle.api.file.ConfigurableFileCollection -import org.gradle.api.file.DirectoryProperty -import org.gradle.api.file.FileSystemOperations -import org.gradle.api.internal.file.FileOperations -import org.gradle.api.tasks.InputFiles -import org.gradle.api.tasks.Internal -import org.gradle.api.tasks.TaskAction - -abstract class FactorioModInstallTask @Inject constructor( - private val files: FileSystemOperations, -) : DefaultTask() { - - @get:Internal - abstract val clientModDirectory: DirectoryProperty - - @get:InputFiles - abstract val modFiles: ConfigurableFileCollection - - init { - description = "Copy the mod to the Factorio client" - group = FactorioModPlugin.TASK_GROUP - - super.onlyIf { - require(it is FactorioModInstallTask) - it.clientModDirectory.asFile.get().exists() - } - } - - @TaskAction - fun install() { - logger.lifecycle("Copying mod from $modFiles to $clientModDirectory") - - files.copy { - from(modFiles) - into(clientModDirectory) - } - } - -} diff --git a/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/FactorioModLibraryPlugin.kt b/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/FactorioModLibraryPlugin.kt new file mode 100644 index 0000000..0e96e2f --- /dev/null +++ b/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/FactorioModLibraryPlugin.kt @@ -0,0 +1,48 @@ +package dev.adamko.gradle.factorio + +import javax.inject.Inject +import org.gradle.api.Plugin +import org.gradle.api.Project +import org.slf4j.LoggerFactory + +/** + * Configure a [Project] to produce components that will be used in a Factorio mod, but no tasks + * that will create a Factorio mod. + */ +abstract class FactorioModLibraryPlugin @Inject constructor( +// private val objects: ObjectFactory, +// private val providers: ProviderFactory, +// private val layout: ProjectLayout, +// private val files: FileSystemOperations, +) : Plugin { + + internal val logger = LoggerFactory.getLogger(this::class.java) + + internal var factorioModConfigurations: FactorioModConfigurations? = null + private set + + override fun apply(target: Project) { + factorioModConfigurations = target.createConfigurations() + } + + private fun Project.createConfigurations(): FactorioModConfigurations { + return FactorioModConfigurations( + factorioMod = project.configurations.register(CONFIGURATION_NAME__FACTORIO_MOD) { + asConsumer() + factorioModAttributes(objects) + }, + + factorioModProvider = project.configurations.register( + CONFIGURATION_NAME__FACTORIO_MOD_PROVIDER + ) { + asProvider() + factorioModAttributes(objects) + }, + ) + } + + companion object { + const val CONFIGURATION_NAME__FACTORIO_MOD = "factorioMod" + const val CONFIGURATION_NAME__FACTORIO_MOD_PROVIDER = "factorioModProvider" + } +} diff --git a/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/FactorioModPlugin.kt b/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/FactorioModPlugin.kt index 920a7d6..aee6ba0 100644 --- a/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/FactorioModPlugin.kt +++ b/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/FactorioModPlugin.kt @@ -1,37 +1,104 @@ package dev.adamko.gradle.factorio +import dev.adamko.gradle.factorio.tasks.AssembleFactorioModContents +import dev.adamko.gradle.factorio.tasks.GenerateFactorioModInfoTask +import dev.adamko.gradle.factorio.tasks.LaunchFactorioClientTask +import dev.adamko.gradle.factorio.tasks.LocalPublishFactorioModTask +import dev.adamko.gradle.factorio.tasks.PackageFactorioModTask import javax.inject.Inject import org.gradle.api.Plugin import org.gradle.api.Project +import org.gradle.api.file.FileSystemOperations +import org.gradle.api.file.ProjectLayout import org.gradle.api.model.ObjectFactory +import org.gradle.api.provider.ProviderFactory +import org.gradle.api.tasks.TaskProvider import org.gradle.kotlin.dsl.create +import org.gradle.kotlin.dsl.newInstance +import org.gradle.kotlin.dsl.register +import org.slf4j.LoggerFactory abstract class FactorioModPlugin @Inject constructor( private val objects: ObjectFactory, + private val providers: ProviderFactory, + private val layout: ProjectLayout, + private val files: FileSystemOperations, ) : Plugin { + internal val logger = LoggerFactory.getLogger(this::class.java) + override fun apply(target: Project) { - target.createSettings() - val factorioModConfiguration = - target.configurations.register(FACTORIO_GRADLE_CONFIGURATION_NAME) { - asConsumer() - factorioModAttributes(objects) - } + val settings = target.extensions.create(FACTORIO_GRADLE_EXTENSION_NAME) + + val factorioModLibraryPlugin = objects.newInstance() + factorioModLibraryPlugin.apply(target) + val factorioModConfigurations = factorioModLibraryPlugin.factorioModConfigurations + ?: error("Could not create Factorio Mod Configurations") + + val context = PluginContext( + target, + + settings, + target.createTasks(), + factorioModConfigurations, + + objects, + providers, + layout, + files, + ) + + context.configureModSettings() + + context.configureTasks() + + context.configureIdea() + +// context.configureDistribution() } - private fun Project.createSettings(): FactorioModSettings { - return extensions.create(FACTORIO_GRADLE_EXTENSION_NAME).apply { - - } + private fun Project.createTasks(): PluginContext.Tasks { + return PluginContext.Tasks( + launchFactorioClient = project.tasks.register("launchFactorioClient"), + assembleModContents = project.tasks.register("assembleFactorioModContents"), + packageMod = project.tasks.register("packageFactorioMod"), + publishModToLocalClient = project.tasks.register("publishFactorioModToLocalClient"), + generateModInfoJson = project.tasks.register("generateFactorioModInfoJson"), + ) } + internal class PluginContext( + val project: Project, + val settings: FactorioModSettings, + val tasks: Tasks, + val configurations: FactorioModConfigurations, + + val objects: ObjectFactory, + val providers: ProviderFactory, + val layout: ProjectLayout, + val files: FileSystemOperations, + ) { + internal val logger = LoggerFactory.getLogger(this::class.java) + + data class Tasks( + val launchFactorioClient: TaskProvider, + val assembleModContents: TaskProvider, + val packageMod: TaskProvider, + val publishModToLocalClient: TaskProvider, + val generateModInfoJson: TaskProvider, + ) + } + + companion object { const val FACTORIO_GRADLE_EXTENSION_NAME = "factorioMod" - const val FACTORIO_GRADLE_CONFIGURATION_NAME = "factorioMod" - const val TASK_GROUP = "factorioMod" + const val CONFIGURATION_NAME__FACTORIO_MOD = "factorioMod" + const val CONFIGURATION_NAME__FACTORIO_MOD_PROVIDER = "factorioModProvider" + + const val TASK_GROUP = "factorio mod" /** Lifecycle task for publishing the mod locally */ const val PUBLISH_MOD_LOCAL_TASK_NAME = "publishModLocal" diff --git a/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/FactorioModSettings.kt b/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/FactorioModSettings.kt index bc427d2..1acb4f2 100644 --- a/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/FactorioModSettings.kt +++ b/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/FactorioModSettings.kt @@ -1,16 +1,69 @@ package dev.adamko.gradle.factorio +import javax.inject.Inject import org.gradle.api.file.DirectoryProperty +import org.gradle.api.file.ProjectLayout import org.gradle.api.file.RegularFileProperty +import org.gradle.api.model.ObjectFactory +import org.gradle.api.provider.ListProperty import org.gradle.api.provider.Property +import org.gradle.api.provider.ProviderFactory +import org.gradle.kotlin.dsl.newInstance -interface FactorioModSettings { +abstract class FactorioModSettings @Inject constructor( + internal val objects: ObjectFactory, + internal val providers: ProviderFactory, + internal val layout: ProjectLayout, +) { - val factorioClientModsDirectory: DirectoryProperty + abstract val modName: Property + abstract val modTitle: Property + abstract val modDescription: Property + abstract val modAuthor: Property + abstract val modVersion: Property + abstract val modDependencies: ListProperty - val steamExe: RegularFileProperty + // version of Factorio that the mod is compatible with (must only be "major.minor" - patch causes error) + abstract val factorioCompatibility: Property - val factorioGameSteamId: Property + abstract val distributionZipName: Property - val factorioServerDataDirectory: DirectoryProperty + val mainSources: FactorioModSourceSet.WithResources = objects.newInstance("Main") + val testSources: FactorioModSourceSet.WithResources = objects.newInstance("Test") + val generatedSources: FactorioModSourceSet = objects.newInstance("Generated") + + +// abstract val typescriptSrcDir: DirectoryProperty +// abstract val resourcesDir: DirectoryProperty +// abstract val modDataResourcesDir: DirectoryProperty +// abstract val generatedLuaSrcDir: DirectoryProperty + + + abstract val factorioServerDataDirectory: DirectoryProperty + + + val localDev: LocalDev = objects.newInstance() + + fun localDev(configure: LocalDev.() -> Unit) { + localDev.configure() + } + + interface LocalDev { + val currentOs: Property + + val windowsSteamExe: Property + + val factorioSteamId: Property + + val serverConnectHost: Property + + val clientModsDirectory: RegularFileProperty + + val macApplicationSupportDir: RegularFileProperty + + val macFactorioApp: RegularFileProperty + + /** Supported local dev OSes */ + enum class OS { WINDOWS, MAC_OS, UNSUPPORTED } + } } diff --git a/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/FactorioModSourceSet.kt b/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/FactorioModSourceSet.kt new file mode 100644 index 0000000..fcf4849 --- /dev/null +++ b/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/FactorioModSourceSet.kt @@ -0,0 +1,38 @@ +package dev.adamko.gradle.factorio + +import javax.inject.Inject +import org.gradle.api.Named +import org.gradle.api.file.SourceDirectorySet +import org.gradle.api.model.ObjectFactory + +abstract class FactorioModSourceSet @Inject constructor( + private val named: String, + objects: ObjectFactory, +) : Named { + + val typescript: SourceDirectorySet = objects + .sourceDirectorySet("ts${named}", "TypeScript $named source files") + .apply { + include("**/*.d.ts", "**/*.ts") + } + + val lua: SourceDirectorySet = objects + .sourceDirectorySet("lua${named}", "Lua $named source files") + .apply { + include("**/*.lua") + } + + override fun getName(): String = named + + abstract class WithResources @Inject constructor( + type: String, + objects: ObjectFactory, + ) : FactorioModSourceSet(type, objects) { + + val resources: SourceDirectorySet = objects + .sourceDirectorySet("resources${type}", "$type resources") + .apply { + exclude("**/*.d.ts", "**/*.ts", "**/*.lua") + } + } +} diff --git a/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/artifactDistributions.kt b/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/artifactDistributions.kt index 38256af..bcb7e5c 100644 --- a/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/artifactDistributions.kt +++ b/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/artifactDistributions.kt @@ -12,15 +12,15 @@ import org.gradle.api.model.ObjectFactory import org.gradle.kotlin.dsl.named -fun Configuration.asProvider() { - isVisible = false +fun Configuration.asProvider(visible: Boolean = false) { + isVisible = visible isCanBeResolved = false isCanBeConsumed = true } -fun Configuration.asConsumer() { - isVisible = false +fun Configuration.asConsumer(visible: Boolean = false) { + isVisible = visible isCanBeResolved = true isCanBeConsumed = false } diff --git a/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/configureDistribution.kt b/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/configureDistribution.kt new file mode 100644 index 0000000..72f4c81 --- /dev/null +++ b/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/configureDistribution.kt @@ -0,0 +1,42 @@ +package dev.adamko.gradle.factorio + +import org.gradle.api.distribution.DistributionContainer +import org.gradle.api.distribution.plugins.DistributionPlugin +import org.gradle.api.tasks.bundling.Zip +import org.gradle.kotlin.dsl.apply +import org.gradle.kotlin.dsl.getByType +import org.gradle.kotlin.dsl.named + +internal fun FactorioModPlugin.PluginContext.configureDistribution() { + + project.plugins.apply(DistributionPlugin::class) + + val distributions = project.extensions.getByType() + + distributions.named(DistributionPlugin.MAIN_DISTRIBUTION_NAME) { + + distributionBaseName.set(settings.modName) + + contents { + includeEmptyDirs = false + + from(settings.mainSources.resources) { + include("**/**") + } + + exclude { + // exclude empty files + it.file.run { + isFile && useLines { lines -> lines.all { line -> line.isBlank() } } + } + } + } + } + + val distZipTask = project.tasks.named("distZip") + + configurations.factorioModProvider.configure { + outgoing.artifact(distZipTask.flatMap { it.archiveFile }) + } + +} diff --git a/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/configureIdea.kt b/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/configureIdea.kt new file mode 100644 index 0000000..15b63ee --- /dev/null +++ b/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/configureIdea.kt @@ -0,0 +1,66 @@ +package dev.adamko.gradle.factorio + +import org.gradle.kotlin.dsl.configure +import org.gradle.kotlin.dsl.withType +import org.gradle.plugins.ide.idea.IdeaPlugin +import org.gradle.plugins.ide.idea.model.IdeaModel +import org.gradle.plugins.ide.idea.model.Module + +internal fun FactorioModPlugin.PluginContext.configureIdea() { + project.plugins.withType().configureEach { + +// project.afterEvaluate { + project.extensions.configure { + module { +// this.scopes["MAIN"]?.plusAssign(mutableMapOf("plus" to listOf(project.configurations.create("main")))) +// + sourceDirs.plusAssign(settings.mainSources.typescript.srcDirs) + sourceDirs.plusAssign(settings.mainSources.lua.srcDirs) + sourceDirs.plusAssign(settings.generatedSources.lua.srcDirs) + + testSources.from(settings.testSources.typescript) + testSources.from(settings.testSources.lua) + + resourceDirs.plusAssign(settings.mainSources.resources.srcDirs) + testResources.from(settings.testSources.resources) + + generatedSourceDirs.plusAssign(settings.generatedSources.lua.srcDirs) + generatedSourceDirs.plusAssign(settings.generatedSources.typescript.srcDirs) + +// sourceDirs.plusAssign( +// listOf( +// settings.typescriptSrcDir.get().asFile, +// settings.generatedLuaSrcDir.get().asFile, +// ) +// ) +//// sourceDirs = sourceDirs + file("src/main/lua") +// resourceDirs = resourceDirs + settings.modDataResourcesDir +// testSources.from(typescriptTestSrcDir) +//// testSourceDirs = testSourceDirs + typescriptTestSrcDir +// +// generatedSourceDirs = generatedSourceDirs + generatedSrcDir +//// excludeDirs = excludeDirs + generatedSrcDir + + iml { + whenMerged { + require(this is Module) + +// sourceDirs.plusAssign(settings.mainSources.typescript.srcDirs) +// sourceDirs.plusAssign(settings.mainSources.lua.srcDirs) +// sourceDirs.plusAssign(settings.generatedSources.lua.srcDirs) +// +// testSources.from(settings.testSources.typescript) +// testSources.from(settings.testSources.lua) +// +// resourceDirs.plusAssign(settings.mainSources.resources.srcDirs) +// testResources.from(settings.testSources.resources) +// +// generatedSourceDirs.plusAssign(settings.generatedSources.lua.srcDirs) +// generatedSourceDirs.plusAssign(settings.generatedSources.typescript.srcDirs) + } + } +// } + } + } + } +} diff --git a/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/configureModSettings.kt b/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/configureModSettings.kt new file mode 100644 index 0000000..a587b30 --- /dev/null +++ b/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/configureModSettings.kt @@ -0,0 +1,99 @@ +package dev.adamko.gradle.factorio + +import dev.adamko.gradle.factorio.FactorioModSettings.LocalDev.OS +import java.io.File +import org.gradle.api.internal.provider.Providers +import org.gradle.api.provider.ProviderFactory + + +internal fun FactorioModPlugin.PluginContext.configureModSettings() = with(settings) { + modName.convention(providers.provider { project.name }) + modTitle.convention(modName) + modDescription.convention(providers.provider { project.description ?: "" }) + modVersion.convention(providers.provider { project.version.toString() }) + + distributionZipName.convention(providers.zip(modName, modVersion) { name, version -> + "${name}_${version}.zip" + }) + + val srcBaseMain = layout.projectDirectory.dir("src/main") + mainSources.lua.srcDir(srcBaseMain.dir("lua")) + mainSources.typescript.srcDir(srcBaseMain.dir("typescript")) + mainSources.resources.srcDir(srcBaseMain.dir("resources")) + + + val srcBaseTest = layout.projectDirectory.dir("src/test") + testSources.lua.srcDir(srcBaseTest.dir("lua")) + testSources.typescript.srcDir(srcBaseTest.dir("typescript")) + testSources.resources.srcDir(srcBaseTest.dir("resources")) + + + val srcBaseGenerated = layout.buildDirectory.dir("generated-src").get() + generatedSources.lua.srcDir(srcBaseGenerated.dir("lua")) + generatedSources.typescript.srcDir(srcBaseGenerated.dir("typescript")) + + mainSources.typescript.destinationDirectory.convention(srcBaseGenerated.dir("lua")) + + configureLocalDev() +} + + +private fun FactorioModPlugin.PluginContext.configureLocalDev() = with(settings) { + + val userHome = providers.systemProperty("user.home") + .map { home -> File(home) } + + + localDev { + + currentOs.convention(providers.systemProperty("os.name").map { osName -> + val currentOS = osName.lowercase() + when { + "windows" in currentOS -> OS.WINDOWS + "mac" in currentOS -> OS.MAC_OS + else -> { + logger.warn("cannot select OS for Factorio local dev - '${osName}' is unsupported") + OS.UNSUPPORTED + } + } + }) + + windowsSteamExe.convention("""C:\Program Files (x86)\Steam\steam.exe""") + factorioSteamId.convention("427520") +// serverConnectHost.convention("localhost") + + macApplicationSupportDir.convention(layout.file(userHome.map { home -> + home.resolve("""Library/Application Support/""") + })) + + macFactorioApp.convention(layout.file(macApplicationSupportDir.map { appSupport -> + appSupport.asFile.resolve("""Steam/steamapps/common/Factorio/factorio.app/Contents/MacOS/factorio""") + })) + + clientModsDirectory.convention(layout.file( + currentOs.flatMap { os -> + when (os) { + OS.WINDOWS -> userHome.map { home -> + home.resolve("""AppData/Roaming/Factorio/mods""") + } + + OS.MAC_OS -> macApplicationSupportDir.map { appSupport -> + appSupport.asFile.resolve("""factorio/mods""") + + } + + OS.UNSUPPORTED -> { + logger.warn("cannot automatically determine Factorio client mod directory, $os is unsupported") + Providers.notDefined() // https://github.com/gradle/gradle/issues/12388 + } + } + } + )) + } +} + + +private fun ProviderFactory.factorioModProp(name: String) { + environmentVariable("FACTORIO_MOD_$name") + .orElse(gradleProperty("factorioMod_$name")) +} diff --git a/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/configureTasks.kt b/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/configureTasks.kt new file mode 100644 index 0000000..5876803 --- /dev/null +++ b/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/configureTasks.kt @@ -0,0 +1,137 @@ +package dev.adamko.gradle.factorio + +import dev.adamko.gradle.factorio.tasks.AssembleFactorioModContents +import dev.adamko.gradle.factorio.tasks.GenerateFactorioModInfoTask +import dev.adamko.gradle.factorio.tasks.LaunchFactorioClientTask +import dev.adamko.gradle.factorio.tasks.LocalPublishFactorioModTask +import dev.adamko.gradle.factorio.tasks.PackageFactorioModTask +import org.gradle.kotlin.dsl.withType + +internal fun FactorioModPlugin.PluginContext.configureTasks() { + + tasks.launchFactorioClient.configure { + + } + tasks.assembleModContents.configure { + modFiles.apply { + from(settings.mainSources.typescript.destinationDirectory) + from(tasks.generateModInfoJson) + from(settings.mainSources.resources) + } + } + tasks.packageMod.configure { + from(tasks.assembleModContents) + } + tasks.publishModToLocalClient.configure { + dependsOn(tasks.packageMod) + } + tasks.generateModInfoJson.configure { + + } + + + project.tasks.withType().configureEach { + description = "Copy the mod to the Factorio client" + group = FactorioModPlugin.TASK_GROUP + + onlyIf { + require(it is LocalPublishFactorioModTask) + it.clientModDirectory.asFile.get().exists() + } + + modFiles.from( + configurations.factorioMod.map { + it.incoming + .artifactView { lenient(true) } + .files + } + ) + + doLast { + logger.lifecycle("Published Factorio Mod to '${clientModDirectory.asFile.get()}'") + } + } + + configureLaunchFactorioClientTasks() + + project.tasks.withType().configureEach { + description = "Generate info.json (required for Factorio Mods)" + group = FactorioModPlugin.TASK_GROUP + + modName.convention(settings.modName) + modTitle.convention(settings.modTitle) + modDescription.convention(settings.modDescription) + modAuthor.convention(settings.modAuthor) + modVersion.convention(settings.modVersion) + factorioCompatibility.convention(settings.factorioCompatibility) + modDependencies.convention(settings.modDependencies) + infoJson.convention( + layout.file( + providers.provider { + temporaryDir.resolve("info.json") + } + ) + ) + } + + project.tasks.withType().configureEach { + description = "Gather the mod files that will be packaged into the mod zip" + group = FactorioModPlugin.TASK_GROUP + + modName.convention(settings.modName) + modVersion.convention(settings.modVersion) + + destination.convention(layout.dir(providers.provider { temporaryDir })) + } + + project.tasks.withType().configureEach { + description = "Package the Factorio mod" + group = FactorioModPlugin.TASK_GROUP + + archiveFileName.convention(settings.distributionZipName) + + includeEmptyDirs = false + + exclude { + // exclude empty files + it.file.run { + isFile && useLines { lines -> lines.all { line -> line.isBlank() } } + } + } + } + + project.tasks.withType().configureEach { + description = "Launch local Factorio Steam game client" + group = FactorioModPlugin.TASK_GROUP + + modFiles.from(project.tasks.withType()) + clientModDirectory.convention(layout.dir(settings.localDev.clientModsDirectory.asFile)) + } +} + + +private fun FactorioModPlugin.PluginContext.configureLaunchFactorioClientTasks() { + + val localDev = settings.localDev + +// // convert to local props -> try to comply with Gradle config cache +// val localDevCurrentOs = localDev.currentOs +// val localDevWindowsSteamExe = localDev.windowsSteamExe +// val localDevFactorioSteamId = localDev.factorioSteamId +// val localDevServerConnectHost = localDev.serverConnectHost +// val localDevClientModDirectory = localDev.clientModDirectory +// val localDevMacApplicationSupportDir = localDev.macApplicationSupportDir +// val localDevMacFactorioApp = localDev.macFactorioApp + + project.tasks.withType().configureEach { + description = "Launch local Factorio Steam game client" + group = FactorioModPlugin.TASK_GROUP + + currentOs.convention(localDev.currentOs) + windowsSteamExe.convention(localDev.windowsSteamExe) + factorioSteamId.convention(localDev.factorioSteamId) + serverConnectHost.convention(localDev.serverConnectHost) + clientModsPath.convention(localDev.clientModsDirectory.map { it.asFile.canonicalPath }) + macFactorioApp.convention(localDev.macFactorioApp) + } +} diff --git a/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/mod/FactorioModProperties.kt b/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/mod/FactorioModProperties.kt new file mode 100644 index 0000000..8c73c13 --- /dev/null +++ b/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/mod/FactorioModProperties.kt @@ -0,0 +1,19 @@ +package dev.adamko.gradle.factorio.mod + +// to be used in a NamedDomainObject container? + +//import org.gradle.api.Named +//import org.gradle.api.provider.Property +// +//abstract class FactorioModProperties : Named { +// +// abstract val modName: Property +// abstract val modTitle: Property +// abstract val modDescription: Property +// abstract val modVersion: Property +// +// // version of Factorio that the mod is compatible with (must only be "major.minor" - patch causes error) +// abstract val factorioCompatibility: Property +// +// abstract val distributionZipName: Property +//} diff --git a/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/mod_portal/FactorioModPortalPublishClient.kt b/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/mod_portal/FactorioModPortalPublishClient.kt index f8d8667..b382bc3 100644 --- a/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/mod_portal/FactorioModPortalPublishClient.kt +++ b/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/mod_portal/FactorioModPortalPublishClient.kt @@ -69,14 +69,13 @@ class FactorioModPortalPublishClient( client().useToRun { val initUploadResponse = initUpload() - val enteredVersion = userInputHandler - .askQuestion( - """ - |Are you sure you want to publish $modName:$modVersion? - |Enter the version number to confirm: - """.trimMargin(), - "", - ) + val enteredVersion = userInputHandler.askQuestion( + """ + |Are you sure you want to publish $modName:$modVersion? + |Enter the version number to confirm: + """.trimMargin(), + "", + ) val confirmed = enteredVersion.trim().equals(modVersion.trim(), ignoreCase = true) diff --git a/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/tasks/AssembleFactorioModContents.kt b/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/tasks/AssembleFactorioModContents.kt new file mode 100644 index 0000000..d1ca05c --- /dev/null +++ b/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/tasks/AssembleFactorioModContents.kt @@ -0,0 +1,40 @@ +package dev.adamko.gradle.factorio.tasks + +import javax.inject.Inject +import org.gradle.api.* +import org.gradle.api.file.* +import org.gradle.api.internal.file.* +import org.gradle.api.provider.Property +import org.gradle.api.tasks.* + +abstract class AssembleFactorioModContents @Inject constructor( + private val files: FileSystemOperations, +) : DefaultTask() { + + @get:Input + abstract val modName: Property + + @get:Input + abstract val modVersion: Property + + @get:InputFiles + @get:SkipWhenEmpty + @get:PathSensitive(PathSensitivity.NAME_ONLY) + @get:IgnoreEmptyDirectories + abstract val modFiles: ConfigurableFileCollection + + @get:OutputDirectory + abstract val destination: DirectoryProperty + + @TaskAction + fun assemble() { + val modName = modName.get() + val modVersion = modVersion.get() + val modDirectory = "${modName}_${modVersion}" + + files.sync { + from(modFiles) + into(destination.dir(modDirectory)) + } + } +} diff --git a/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/tasks/GenerateFactorioModInfoTask.kt b/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/tasks/GenerateFactorioModInfoTask.kt new file mode 100644 index 0000000..e01dab0 --- /dev/null +++ b/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/tasks/GenerateFactorioModInfoTask.kt @@ -0,0 +1,132 @@ +package dev.adamko.gradle.factorio.tasks + +import javax.inject.Inject +import kotlinx.serialization.* +import kotlinx.serialization.json.* +import org.gradle.api.DefaultTask +import org.gradle.api.file.RegularFileProperty +import org.gradle.api.provider.ListProperty +import org.gradle.api.provider.Property +import org.gradle.api.tasks.Input +import org.gradle.api.tasks.Optional +import org.gradle.api.tasks.OutputFile +import org.gradle.api.tasks.TaskAction + +abstract class GenerateFactorioModInfoTask @Inject constructor( + +) : DefaultTask() { + + /** + * Mandatory field. The internal name of mod. The game accepts anything as a mod name, however the mod portal restricts mod names to only consist of alphanumeric characters, dashes and underscores. Note that the mod folder or mod zip file name has to contain the mod name, where the restrictions of the file system apply. + * + * The game accepts mod names with a maximum length of 100 characters. The mod portal only accepts mods with names that are longer than 3 characters and shorter than 50 characters. + */ + @get:Input + abstract val modName: Property + + /** + * Mandatory field. The display name of the mod, so it is not recommended to use someUgly_pRoGrAmMeR-name here. Can be overwritten with a locale entry in the mod-name category, using the internal mod name as the key. + * + * The game will reject a title field that is longer than 100 characters. However, this can be worked around by using the locale entry. The mod portal does not restrict mod title length. + */ + @get:Input + abstract val modTitle: Property + + /** + * Optional field. A short description of what your mod does. This is all that people get to see in-game. Can be overwritten with a locale entry in the mod-description category, using the internal mod name as the key. + */ + @get:Input + @get:Optional + abstract val modDescription: Property + + /** + * Optional field. Where the mod can be found on the internet. Note that the in-game mod browser shows the mod portal link additionally to this field. Please don't put "None" here, it makes the field on the mod portal website look ugly. Just leave the field empty if the mod doesn't have a website/forum thread/discord. + */ + @get:Input + @get:Optional + abstract val modHomepage: Property + + /** + * Mandatory field. The author of the mod. This field does not have restrictions, it can also be a list of authors etc. The mod portal ignores this field, it will simply display the uploader's name as the author. + */ + @get:Input + abstract val modAuthor: Property + + /** + * Mandatory field. Defines the version of the mod in the format `number.number.number` for `Major.Middle.Minor`, for example `0.6.4`. Each number can range from 0 to 65535. + */ + @get:Input + abstract val modVersion: Property + + /** + * Optional field in the format "major.minor". The Factorio version that this mod supports. This can only be one Factorio version, not multiple. However, it includes all .sub versions. While the field is optional, usually mods are developed for versions higher than the default 0.12, so the field has to be added anyway. + * + * Adding a sub part, e.g. "0.18.27" will make the mod portal reject the mod and the game act weirdly. That means this shouldn't be done; use only the major and minor components "major.minor", for example "1.0". + * + * Mods with the factorio_version "0.18" can also be loaded in 1.0 and the mod portal will return them when queried for factorio_version 1.0 mods. + */ + @get:Input + @get:Optional + abstract val factorioCompatibility: Property + + /** + * Optional field. Mods that this mod depends on or is incompatible with. + * If this mod depends on another, the other mod will load first, see Data-Lifecycle. + * An empty array allows get around the default and have no dependencies at all. + * + * Example: + * + * `"dependencies": ["mod-a", "? mod-c > 0.4.3", "! mod-g"]` + * + * Each dependency is a string that consists of up to three parts: ` internal-mod-name `, for example `? some-mod-everyone-loves >= 4.2.0`. + * + * The equality operator (`<`, `<=`, `=`, `>=` or `>`) combined with the version allows to define dependencies that require certain mod versions, but it is not required. + * + * Incompatibility does not support versions; if incompatibility is used, version is ignored. + * + * The possible prefixes are: + * * `!` for incompatibility + * * `?` for an optional dependency + * * `(?)` for a hidden optional dependency + * * `~` for a dependency that does not affect load order + * * no prefix for a hard requirement for the other mod. + */ + @get:Input + @get:Optional + abstract val modDependencies: ListProperty + + @get:OutputFile + abstract val infoJson: RegularFileProperty + + @TaskAction + fun generate() { + val infoJsonObject = buildJsonObject { + put("name", modName.get()) + put("title", modTitle.get()) + put("version", modVersion.get()) + put("author", modAuthor.get()) + + modDescription.orNull?.let { put("description", it) } + modHomepage.orNull?.let { put("homepage", it) } + factorioCompatibility.orNull?.let { put("factorio_version", it) } + modDependencies.orNull?.let { + putJsonArray("dependencies") { it.forEach(::add) } + } + } + + val infoJsonContent = encoder.encodeToString(infoJsonObject) + .replace("[\n ]", "[]") + + val infoJson = infoJson.get().asFile + infoJson.parentFile.mkdirs() + infoJson.writeText(infoJsonContent + "\n") + } + + companion object { + @OptIn(ExperimentalSerializationApi::class) + private val encoder = Json { + prettyPrint = true + prettyPrintIndent = " " + } + } +} diff --git a/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/tasks/LaunchFactorioClientTask.kt b/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/tasks/LaunchFactorioClientTask.kt new file mode 100644 index 0000000..04d4ae7 --- /dev/null +++ b/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/tasks/LaunchFactorioClientTask.kt @@ -0,0 +1,89 @@ +package dev.adamko.gradle.factorio.tasks + +import dev.adamko.gradle.factorio.FactorioModSettings +import javax.inject.Inject +import org.gradle.api.DefaultTask +import org.gradle.api.file.RegularFileProperty +import org.gradle.api.provider.Property +import org.gradle.api.tasks.Input +import org.gradle.api.tasks.InputFile +import org.gradle.api.tasks.Optional +import org.gradle.api.tasks.TaskAction +import org.gradle.process.ExecOperations +import org.gradle.work.DisableCachingByDefault +import org.jetbrains.kotlin.util.parseSpaceSeparatedArgs + +@DisableCachingByDefault(because = "Not a cacheable task") +abstract class LaunchFactorioClientTask @Inject constructor( + private val executor: ExecOperations +) : DefaultTask() { + + @get:Input + abstract val currentOs: Property + + @get:Input + @get:Optional + abstract val windowsSteamExe: Property + + @get:Input + @get:Optional + abstract val factorioSteamId: Property + + @get:Input + @get:Optional + abstract val serverConnectHost: Property + + @get:Input + @get:Optional + abstract val clientModsPath: Property + + @get:InputFile + @get:Optional + abstract val macFactorioApp: RegularFileProperty + + @get:Input + @get:Optional + abstract val launchFactorioCommand: Property + + @TaskAction + fun launch() { + val launchCommand = + launchFactorioCommand.orNull ?: when (currentOs.orNull) { + FactorioModSettings.LocalDev.OS.WINDOWS -> windowsCmd() + FactorioModSettings.LocalDev.OS.MAC_OS -> macOSCmd() + null, FactorioModSettings.LocalDev.OS.UNSUPPORTED -> error("no can do, unsupported OS") + } + + logger.lifecycle("Launching Factorio client\n > $launchCommand") + + executor.exec { + commandLine = parseSpaceSeparatedArgs(launchCommand) + } + } + + private fun windowsCmd(): String { + val steamExe = windowsSteamExe.orNull ?: error("missing Steam exe") + val factorioId = factorioSteamId.orNull ?: error("missing Factorio Steam ID") + val modsDirFlag = clientModsPath.map { """--mod-directory "$it"""" }.getOrElse("") + val mpConnectFlag = serverConnectHost.map { "--mp-connect $it" }.getOrElse("") + + return """ + $steamExe --applaunch $factorioId $modsDirFlag $mpConnectFlag + """.trimIndent() + } + + private fun macOSCmd(): String { +// val factorioApp = macFactorioApp.orNull ?: error("missing Factorio app") + + val modsDirFlag = "" //clientModsPath.map { """--mod-directory "$it"""" }.getOrElse("") + val mpConnectFlag = serverConnectHost.map { "-mp-connect $it" }.getOrElse("") + + return """ + /Applications/Steam.app/Contents/MacOS/steam_osx -applaunch 427520 $modsDirFlag $mpConnectFlag + """.trimIndent() + +// return """ +// open -a "$factorioApp" --args $modsDirFlag $mpConnectFlag +// """.trimIndent() + } +} diff --git a/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/tasks/LocalPublishFactorioModTask.kt b/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/tasks/LocalPublishFactorioModTask.kt new file mode 100644 index 0000000..51aaae5 --- /dev/null +++ b/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/tasks/LocalPublishFactorioModTask.kt @@ -0,0 +1,40 @@ +package dev.adamko.gradle.factorio.tasks + +import javax.inject.Inject +import org.gradle.api.DefaultTask +import org.gradle.api.file.ConfigurableFileCollection +import org.gradle.api.file.DirectoryProperty +import org.gradle.api.file.FileSystemOperations +import org.gradle.api.tasks.IgnoreEmptyDirectories +import org.gradle.api.tasks.InputFiles +import org.gradle.api.tasks.OutputDirectory +import org.gradle.api.tasks.PathSensitive +import org.gradle.api.tasks.PathSensitivity +import org.gradle.api.tasks.SkipWhenEmpty +import org.gradle.api.tasks.TaskAction + +abstract class LocalPublishFactorioModTask @Inject constructor( + private val files: FileSystemOperations, +) : DefaultTask() { + + @get:OutputDirectory + abstract val clientModDirectory: DirectoryProperty + + @get:InputFiles + @get:SkipWhenEmpty + @get:PathSensitive(PathSensitivity.NAME_ONLY) + @get:IgnoreEmptyDirectories + abstract val modFiles: ConfigurableFileCollection + + @TaskAction + fun install() { + logger.lifecycle("Copying mod from ${modFiles.files} to ${clientModDirectory.asFile.get()}") + + files.copy { + from(modFiles) { + include("*.zip") + } + into(clientModDirectory) + } + } +} diff --git a/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/tasks/PackageFactorioModTask.kt b/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/tasks/PackageFactorioModTask.kt new file mode 100644 index 0000000..13586e8 --- /dev/null +++ b/gradle-plugins/factorio-gradle/src/main/kotlin/dev/adamko/gradle/factorio/tasks/PackageFactorioModTask.kt @@ -0,0 +1,6 @@ +package dev.adamko.gradle.factorio.tasks + +import org.gradle.api.tasks.bundling.Zip + + +abstract class PackageFactorioModTask : Zip() diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 0223be4..9e54ae4 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -93,6 +93,7 @@ loggingCapabilities = { id = "dev.jacomet.logging-capabilities", vers ## kotlin ## kotlin-bom = { group = "org.jetbrains.kotlin", name = "kotlin-bom", version.ref = "kotlin" } +kotlin-embeddableCompiler = { module = "org.jetbrains.kotlin:kotlin-compiler-embeddable" } kotlinScripting-common = { group = "org.jetbrains.kotlin", name = "kotlin-scripting-common" } kotlinScripting-jvm = { group = "org.jetbrains.kotlin", name = "kotlin-scripting-jvm" } diff --git a/modules/events-library/build.gradle.kts b/modules/events-library/build.gradle.kts index 2236884..96d4725 100644 --- a/modules/events-library/build.gradle.kts +++ b/modules/events-library/build.gradle.kts @@ -7,7 +7,7 @@ import dev.adamko.gradle.factorio.typescriptAttributes plugins { id("kafkatorio.conventions.lang.kotlin-multiplatform") - id("dev.adamko.factorio-mod") apply false // only needed for 'attributes' - need to split up the plugin? + id("dev.adamko.factorio-mod-library") // only needed for 'attributes' - need to split up the plugin? kotlin("plugin.serialization") distribution } diff --git a/modules/events-mod/build.gradle.kts b/modules/events-mod/build.gradle.kts index 89e2bf6..f4d466f 100644 --- a/modules/events-mod/build.gradle.kts +++ b/modules/events-mod/build.gradle.kts @@ -1,38 +1,40 @@ import dev.adamko.gradle.factorio.mod_portal.FactorioModPublishTask import dev.adamko.gradle.factorio.typescriptAttributes -import dev.adamko.gradle.factorio.factorioModAttributes -import kafkatorio.tasks.TypescriptToLuaTask +import kafkatorio.tasks.TypeScriptToLuaTask import kotlinx.serialization.json.put import kotlinx.serialization.json.putJsonObject -import net.swiftzer.semver.SemVer -import org.apache.tools.ant.filters.ReplaceTokens -import org.gradle.plugins.ide.idea.model.Module as IdeaImlModule -import org.gradle.plugins.ide.idea.model.Path as IdeaImlPath plugins { id("kafkatorio.conventions.lang.node") id("dev.adamko.factorio-mod") distribution + idea } description = "Sends in-game information to a server over the internet (requires additional setup)" +factorioMod { + modName.set("kafkatorio-events") + modTitle.set("Kafkatorio Events") + modAuthor.set("adam@adamko.dev") + factorioCompatibility.set(libs.versions.factorio.map { it.substringBeforeLast(".") }) +} + // Factorio required format is: // - filename: `mod-name_version.zip` // - zip contains one directory, `mod-name` //val modName: String by extra { "${rootProject.name}-events" } -extra.set("modName", "kafkatorio-events") -val modName = extra.get("modName") as String +//extra.set("modName", "kafkatorio-events") +//val modName = extra.get("modName") as String -val modDescription: String by project.extra { project.description ?: "" } - -val distributionZipName: String by extra { "${modName}_${rootProject.version}.zip" } +//val modDescription: String by project.extra { project.description ?: "" } // version of Factorio that the mod is compatible with (must only be "major.minor" - patch causes error) -val modFactorioCompatibility: Provider = - libs.versions.factorio.map { SemVer.parse(it).run { "$major.$minor" } } +//val modFactorioCompatibility: Provider = +// libs.versions.factorio.map { SemVer.parse(it).run { "$major.$minor" } } +//rootProject.layout.projectDirectory.file("LICENSE") val licenseFile: RegularFile by rootProject.extra @Suppress("UNCHECKED_CAST") @@ -42,13 +44,13 @@ val projectTokens: MapProperty = //val projectTokens: MapProperty by rootProject.extra val projectTokensX1 = projectTokens.apply { - put("mod.name", modName) - put("mod.title", "Kafkatorio Events") - put("mod.description", modDescription) - put("factorio.version", modFactorioCompatibility) + put("mod.name", factorioMod.modName) + put("mod.title", factorioMod.modTitle) + put("mod.description", factorioMod.modDescription) + put("factorio.version", factorioMod.factorioCompatibility) } -val tsSrcDir: Directory = layout.projectDirectory.dir("src/main/typescript") +//val tsSrcDir: Directory = layout.projectDirectory.dir("src/main/typescript") node { @@ -68,7 +70,7 @@ dependencies { } -val typescriptToLua by tasks.registering(TypescriptToLuaTask::class) { +val typescriptToLua by tasks.registering(TypeScriptToLuaTask::class) { dependsOn( tasks.npmInstall, installEventsTsSchema, @@ -77,21 +79,18 @@ val typescriptToLua by tasks.registering(TypescriptToLuaTask::class) { inputs.file(tasks.updatePackageJson.map { it.packageJsonFile }) - sourceFiles.set(tsSrcDir) + sourceFiles.from(factorioMod.mainSources.typescript.sourceDirectories) - outputDirectory.set(layout.projectDirectory.dir("src/generated/lua")) + outputDirectory.set(factorioMod.mainSources.typescript.destinationDirectory) } val installEventsTsSchema by tasks.registering(Sync::class) { - description = "Fetch the latest shared data-model" + description = "Fetch the latest shared TypeScript data-model" group = project.name dependsOn(typescriptEventsSchema) - val outputDir = layout.projectDirectory.dir("src/main/typescript/generated/") - outputs.dir(outputDir) - from( provider { typescriptEventsSchema } .map { eventsSchema -> @@ -107,73 +106,80 @@ val installEventsTsSchema by tasks.registering(Sync::class) { // eachFile { relativePath = dropDirectory() } includeEmptyDirs = false } - into(outputDir) + into(layout.projectDirectory.dir("src/main/typescript/generated")) } -val zipNameProvider = provider { distributionZipName } +//val zipNameProvider = provider { distributionZipName } tasks.distZip { - val projectTokensXX22 = projectTokensX1 +// val projectTokensXX22 = projectTokensX1 - inputs.property("zipNameProvider", zipNameProvider) - inputs.property("projectTokens", projectTokensXX22) - - archiveFileName.set(zipNameProvider) +// inputs.property("zipNameProvider", zipNameProvider) +// inputs.property("projectTokens", projectTokensXX22) + val distributionZipName = factorioMod.distributionZipName + archiveFileName.set(distributionZipName) } - val publishModToPortal by tasks.registering(FactorioModPublishTask::class) { dependsOn(tasks.check) distributionZip.set(tasks.distZip.flatMap { it.archiveFile }) - val projectModName = project.extra.get("modName") as String - modName.set(projectModName) - modVersion.set(project.version.toString()) +// val projectModName = project.extra.get("modName") as String + modName.set(factorioMod.modName) + modVersion.set(factorioMod.modVersion) +// modVersion.set(project.version.toString()) } - -distributions { - main { - - distributionBaseName.set(modName) - val tokens333: MutableMap = projectTokensX1.get() - - contents { - from(layout.projectDirectory.dir("src/main/resources/mod-data")) { - include("**/**") - } - from(licenseFile) - from(typescriptToLua.map { it.outputDirectory }) - filesNotMatching("**/*.png") { - // maybe make a bug report for projectTokensX1 causing null$null$null error? - // val tokens333: MutableMap = projectTokensX1.get() - filter("tokens" to tokens333) - } - includeEmptyDirs = false - exclude { - // exclude empty files - it.file.run { - isFile && useLines { lines -> lines.all { line -> line.isBlank() } } - } - } - } +tasks.assembleFactorioModContents { + modFiles.apply { + from(typescriptToLua.map { it.outputDirectory }) + from(licenseFile) } } +//distributions { +// main { +// +//// distributionBaseName.set(factorioMod.modName) +// val tokens333: MutableMap = projectTokensX1.get() +// +// contents { +//// from(factorioMod.mainSources.resources) { +//// include("**/**") +//// } +// from(licenseFile) +// from(typescriptToLua.map { it.outputDirectory }) +// filesNotMatching("**/*.png") { +// // maybe make a bug report for projectTokensX1 causing null$null$null error? +// // val tokens333: MutableMap = projectTokensX1.get() +// filter("tokens" to tokens333) +// } +//// includeEmptyDirs = false +//// exclude { +//// // exclude empty files +//// it.file.run { +//// isFile && useLines { lines -> lines.all { line -> line.isBlank() } } +//// } +//// } +// } +// } +//} + + tasks.withType().configureEach { val projectTokensXX444 = projectTokensX1 inputs.property("projectTokens", projectTokensXX444) } -val factorioModProvider by configurations.registering { - asProvider() - factorioModAttributes(objects) - outgoing.artifact(tasks.distZip.flatMap { it.archiveFile }) -} +//val factorioModProvider by configurations.registering { +// asProvider() +// factorioModAttributes(objects) +// outgoing.artifact(tasks.distZip.flatMap { it.archiveFile }) +//} val projectPackageJsonName: Provider = @@ -202,49 +208,51 @@ tasks.updatePackageJson { tasks.assemble { dependsOn(installEventsTsSchema, tasks.updatePackageJson) } -val typescriptSrcDir: File = file("src/main/typescript") -val luaSrcDir: File = file("src/generated/lua") -val resourcesDir: File = file("src/main/resources") -val typescriptTestSrcDir: File = file("src/test/typescript") -val generatedSrcDir: File = file("src/generated") - - -idea { - module { - sourceDirs.plusAssign( - listOf( - typescriptSrcDir, - luaSrcDir, - ) - ) -// sourceDirs = sourceDirs + file("src/main/lua") - resourceDirs = resourceDirs + resourcesDir - testSourceDirs = testSourceDirs + typescriptTestSrcDir - - generatedSourceDirs = generatedSourceDirs + generatedSrcDir -// excludeDirs = excludeDirs + generatedSrcDir - - iml { - whenMerged { - require(this is IdeaImlModule) - - sourceDirs.plusAssign( - listOf( - typescriptSrcDir, - luaSrcDir, - ) - ) - - generatedSourceFolders.plusAssign( - IdeaImlPath(luaSrcDir.toURI().toString()) - ) - resourceDirs = resourceDirs + resourcesDir - testSourceDirs = testSourceDirs + typescriptTestSrcDir -// excludeDirs = excludeDirs + generatedSrcDir - } - } - } -} +//val typescriptSrcDir: File = file("src/main/typescript") +//val luaSrcDir: File = file("src/generated/lua") +//val resourcesDir: File = file("src/main/resources") +//val typescriptTestSrcDir: File = file("src/test/typescript") +//val generatedSrcDir: File = file("src/generated") +// +// +//idea { +// module { +// sourceDirs.plusAssign( +// listOf( +// typescriptSrcDir, +// luaSrcDir, +// ) +// ) +//// sourceDirs = sourceDirs + file("src/main/lua") +// resourceDirs = resourceDirs + resourcesDir +// testSources.from(typescriptTestSrcDir) +//// testSourceDirs = testSourceDirs + typescriptTestSrcDir +// +// generatedSourceDirs = generatedSourceDirs + generatedSrcDir +//// excludeDirs = excludeDirs + generatedSrcDir +// +// iml { +// whenMerged { +// require(this is IdeaImlModule) +// +// sourceDirs.plusAssign( +// listOf( +// typescriptSrcDir, +// luaSrcDir, +// ) +// ) +// +// generatedSourceFolders.plusAssign( +// IdeaImlPath(luaSrcDir.toURI().toString()) +// ) +// resourceDirs = resourceDirs + resourcesDir +// testSources.from(typescriptTestSrcDir) +//// testSourceDirs = testSourceDirs + typescriptTestSrcDir +//// excludeDirs = excludeDirs + generatedSrcDir +// } +// } +// } +//} // trying to get Gradle+idea to recognise the ts-src... diff --git a/modules/events-mod/src/main/resources/mod-data/info.json b/modules/events-mod/info.json similarity index 100% rename from modules/events-mod/src/main/resources/mod-data/info.json rename to modules/events-mod/info.json diff --git a/modules/events-mod/src/main/resources/kafkatorio-logo.png b/modules/events-mod/kafkatorio-logo.png similarity index 100% rename from modules/events-mod/src/main/resources/kafkatorio-logo.png rename to modules/events-mod/kafkatorio-logo.png diff --git a/modules/events-mod/src/main/resources/mod-portal-description.md b/modules/events-mod/mod-portal-description.md similarity index 100% rename from modules/events-mod/src/main/resources/mod-portal-description.md rename to modules/events-mod/mod-portal-description.md diff --git a/modules/events-mod/src/main/resources/mod-data/changelog.txt b/modules/events-mod/src/main/resources/changelog.txt similarity index 100% rename from modules/events-mod/src/main/resources/mod-data/changelog.txt rename to modules/events-mod/src/main/resources/changelog.txt diff --git a/modules/events-mod/src/main/resources/mod-data/locale/en/locale.cfg b/modules/events-mod/src/main/resources/locale/en/locale.cfg similarity index 100% rename from modules/events-mod/src/main/resources/mod-data/locale/en/locale.cfg rename to modules/events-mod/src/main/resources/locale/en/locale.cfg diff --git a/modules/events-mod/src/main/resources/mod-data/thumbnail.png b/modules/events-mod/src/main/resources/thumbnail.png similarity index 100% rename from modules/events-mod/src/main/resources/mod-data/thumbnail.png rename to modules/events-mod/src/main/resources/thumbnail.png diff --git a/modules/events-processors/build.gradle.kts b/modules/events-processors/build.gradle.kts index 05835ab..fff7f2c 100644 --- a/modules/events-processors/build.gradle.kts +++ b/modules/events-processors/build.gradle.kts @@ -18,6 +18,7 @@ dependencies { implementation(platform(projects.modules.versionsPlatform)) implementation(libs.kafka.streams) + implementation(kotlin("reflect")) testImplementation(libs.kafka.streamsTestUtils) diff --git a/modules/infra-factorio-client/build.gradle.kts b/modules/infra-factorio-client/build.gradle.kts index a53c310..61ed6ae 100644 --- a/modules/infra-factorio-client/build.gradle.kts +++ b/modules/infra-factorio-client/build.gradle.kts @@ -18,13 +18,13 @@ val clientModsDirectory: DirectoryProperty = objects.directoryProperty().apply { set(modDir) } } -val factorioGameId = "427520" -val steamExe: RegularFileProperty = objects.fileProperty().apply { - val steam = File("""C:\Program Files (x86)\Steam\steam.exe""") - if (steam.exists()) { - set(steam) - } -} +//val factorioGameId = "427520" +//val steamExe: RegularFileProperty = objects.fileProperty().apply { +// val steam = File("""C:\Program Files (x86)\Steam\steam.exe""") +// if (steam.exists()) { +// set(steam) +// } +//} //val factorioMod: Configuration by configurations.creating { // asConsumer() @@ -37,21 +37,21 @@ dependencies { // -val deployModToLocalClient by tasks.registering(Copy::class) { - description = "Copy the mod to the Factorio client" - group = FactorioModPlugin.TASK_GROUP - - val clientModsDirectory123 = clientModsDirectory - - onlyIf { clientModsDirectory123.orNull?.asFile?.exists() == true } - - from(configurations.factorioMod.map { it.incoming.artifactView { lenient(true) }.files }) - into(clientModsDirectory) - - doLast { - logger.lifecycle("Copying mod from ${source.files} to $destinationDir") - } -} +//val deployModToLocalClient by tasks.registering(Copy::class) { +// description = "Copy the mod to the Factorio client" +// group = FactorioModPlugin.TASK_GROUP +// +// val clientModsDirectory123 = clientModsDirectory +// +// onlyIf { clientModsDirectory123.orNull?.asFile?.exists() == true } +// +// from(configurations.factorioMod.map { it.incoming.artifactView { lenient(true) }.files }) +// into(clientModsDirectory) +// +// doLast { +// logger.lifecycle("Copying mod from ${source.files} to $destinationDir") +// } +//} // @@ -59,27 +59,27 @@ val deployModToLocalClient by tasks.registering(Copy::class) { fun ExecOperations.isFactorioRunning(): Spec = ProcessRunningSpec(this, "factorio.exe") -val clientLaunch by tasks.registering(Exec::class) { - description = "Run local Factorio Steam game client" - group = FactorioModPlugin.TASK_GROUP - - val steamExe123 = steamExe - val clientModsDirectory444 = clientModsDirectory - - onlyIf(!serviceOf().isFactorioRunning()) - onlyIf { steamExe123.orNull?.asFile?.exists() == true } - onlyIf { clientModsDirectory444.orNull?.asFile?.exists() == true } - - dependsOn(deployModToLocalClient) - mustRunAfter(clientKill, ":modules:infra-factorio-server:processRun") - - commandLine = parseSpaceSeparatedArgs( -// """explorer "steam://rungameid/$factorioGameId// --mp-connect localhost/" """ // not working -// """explorer "steam://run/$factorioGameId//--mp-connect localhost/" """ // works! But has annoying pop-up - """ ${steamExe.asFile.orNull?.canonicalPath} -applaunch $factorioGameId --mp-connect localhost --mod-directory ${clientModsDirectory.asFile.orNull?.canonicalPath} """ - ) - doFirst { logger.lifecycle("Launching factorio.exe") } -} +//val clientLaunch by tasks.registering(Exec::class) { +// description = "Run local Factorio Steam game client" +// group = FactorioModPlugin.TASK_GROUP +// +// val steamExe123 = steamExe +// val clientModsDirectory444 = clientModsDirectory +// +// onlyIf(!serviceOf().isFactorioRunning()) +// onlyIf { steamExe123.orNull?.asFile?.exists() == true } +// onlyIf { clientModsDirectory444.orNull?.asFile?.exists() == true } +// +// dependsOn(deployModToLocalClient) +// mustRunAfter(clientKill, ":modules:infra-factorio-server:processRun") +// +// commandLine = parseSpaceSeparatedArgs( +//// """explorer "steam://rungameid/$factorioGameId// --mp-connect localhost/" """ // not working +//// """explorer "steam://run/$factorioGameId//--mp-connect localhost/" """ // works! But has annoying pop-up +// """ ${steamExe.asFile.orNull?.canonicalPath} -applaunch $factorioGameId --mp-connect localhost --mod-directory ${clientModsDirectory.asFile.orNull?.canonicalPath} """ +// ) +// doFirst { logger.lifecycle("Launching factorio.exe") } +//} val clientKill by tasks.registering(Exec::class) { description = "Stop the local Factorio Steam game client" @@ -95,14 +95,14 @@ val clientKill by tasks.registering(Exec::class) { tasks.register(FactorioModPlugin.PUBLISH_MOD_LOCAL_TASK_NAME) { group = FactorioModPlugin.TASK_GROUP - dependsOn(deployModToLocalClient) +// dependsOn(deployModToLocalClient) } tasks.processRun { dependsOn( - deployModToLocalClient, - clientLaunch, +// deployModToLocalClient, + tasks.launchFactorioClient, ) } diff --git a/modules/infra-factorio-server/build.gradle.kts b/modules/infra-factorio-server/build.gradle.kts index 2093c80..8b40fe3 100644 --- a/modules/infra-factorio-server/build.gradle.kts +++ b/modules/infra-factorio-server/build.gradle.kts @@ -3,7 +3,7 @@ import dev.adamko.gradle.factorio.FactorioModPlugin plugins { id("kafkatorio.conventions.base") id("dev.adamko.geedeecee") - id("dev.adamko.factorio-mod") + id("dev.adamko.factorio-mod-library") idea } diff --git a/settings.gradle.kts b/settings.gradle.kts index 8cc8ca9..04b6e42 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -48,7 +48,9 @@ include( ) +//enableFeaturePreview(org.gradle.api.internal.FeaturePreviews.Feature.TYPESAFE_PROJECT_ACCESSORS.name) enableFeaturePreview("TYPESAFE_PROJECT_ACCESSORS") +enableFeaturePreview("STABLE_CONFIGURATION_CACHE") //apply(from = "./buildSrc/repositories.settings.gradle.kts")