diff --git a/.github/workflows/update_buildscript.yml b/.github/workflows/update_buildscript.yml new file mode 100644 index 00000000..e97adc16 --- /dev/null +++ b/.github/workflows/update_buildscript.yml @@ -0,0 +1,35 @@ +# Checks daily to see if the buildscript is in need of an update +name: Buildscript Updating + +on: + schedule: + - cron: "0 0 * * *" # "min hr day month year", so run once per day + +jobs: + buildscript-update: + runs-on: ubuntu-latest + # Avoid running this workflow on forks + if: github.repository == 'GregTechCEu/gregicality-multiblocks' + permissions: + contents: write + pull-requests: write + steps: + - name: Checkout + uses: actions/checkout@v3 + + - name: Ensure build script version is up to date + id: update-buildscript + run: | + curl https://raw.githubusercontent.com/GregTechCEu/Buildscripts/master/build.gradle --output build.gradle + new_version=$(head -1 build.gradle | sed -r 's|//version: (.*)|\1|g') + echo "NEW_VERSION=$new_version" >> "$GITHUB_OUTPUT" + + - name: Create Pull Request + id: create-pull-request + uses: peter-evans/create-pull-request@v4 + with: + add-paths: build.gradle + commit-message: 'update build script version to ${{ steps.update-buildscript.outputs.NEW_VERSION }}' + branch: gha-update-buildscript + title: Update build script version to ${{ steps.update-buildscript.outputs.NEW_VERSION }} + body: This pull request is created by the buildscript-update workflow diff --git a/build.gradle b/build.gradle index e064efab..32460265 100644 --- a/build.gradle +++ b/build.gradle @@ -1,166 +1,500 @@ -//file:noinspection DependencyNotationArgument -// TODO remove when fixed in RFG ^ - +//version: 1685501596 +/* + * DO NOT CHANGE THIS FILE! + * Also, you may replace this file at any time if there is an update available. + * Please check https://github.com/GregTechCEu/Buildscripts/blob/master/build.gradle for updates. + */ + +import com.modrinth.minotaur.dependencies.ModDependency +import com.modrinth.minotaur.dependencies.VersionDependency import org.gradle.api.tasks.testing.logging.TestExceptionFormat import org.gradle.api.tasks.testing.logging.TestLogEvent +import org.gradle.internal.logging.text.StyledTextOutputFactory import org.jetbrains.gradle.ext.Gradle +import static org.gradle.internal.logging.text.StyledTextOutput.Style + plugins { id 'java' id 'java-library' - id 'maven-publish' id 'eclipse' - id 'org.jetbrains.gradle.plugin.idea-ext' version "$idea_ext_version" - id 'com.gtnewhorizons.retrofuturagradle' version "$rfg_version" - id 'net.darkhax.curseforgegradle' version "$curseforge_gradle_version" apply false - id 'com.modrinth.minotaur' version "$minotaur_version" apply false + id 'org.jetbrains.gradle.plugin.idea-ext' version '1.1.7' + id 'com.gtnewhorizons.retrofuturagradle' version '1.3.+' + id 'net.darkhax.curseforgegradle' version '1.0.+' apply false + id 'com.modrinth.minotaur' version '2.7.+' apply false + id 'com.diffplug.spotless' version '6.13.0' apply false + id 'com.palantir.git-version' version '3.0.0' apply false +} + +if (verifySettingsGradle()) { + throw new GradleException("Settings has been updated, please re-run task.") +} + +def out = services.get(StyledTextOutputFactory).create('an-output') + + +// Project properties + +// Required properties: we don't know how to handle these being missing gracefully +checkPropertyExists("modName") +checkPropertyExists("modId") +checkPropertyExists("modGroup") +checkPropertyExists("modVersion") +checkPropertyExists("minecraftVersion") // hard-coding this makes it harder to immediately tell what version a mod is in (even though this only really supports 1.12.2) +checkPropertyExists("apiPackage") +checkPropertyExists("accessTransformersFile") +checkPropertyExists("usesMixins") +checkPropertyExists("mixinsPackage") +checkPropertyExists("coreModClass") +checkPropertyExists("containsMixinsAndOrCoreModOnly") + +// Optional properties: we can assume some default behavior if these are missing +propertyDefaultIfUnset("autoUpdateBuildScript", false) +propertyDefaultIfUnset("modArchivesBaseName", project.modId) +propertyDefaultIfUnsetWithEnvVar("developmentEnvironmentUserName", "Developer", "DEV_USERNAME") +propertyDefaultIfUnset("generateGradleTokenClass", "") +propertyDefaultIfUnset("gradleTokenModId", "") +propertyDefaultIfUnset("gradleTokenModName", "") +propertyDefaultIfUnset("gradleTokenVersion", "") +propertyDefaultIfUnset("includeWellKnownRepositories", true) +propertyDefaultIfUnset("includeCommonDevEnvMods", true) +propertyDefaultIfUnset("noPublishedSources", false) +propertyDefaultIfUnset("forceEnableMixins", false) +propertyDefaultIfUnset("modrinthProjectId", "") +propertyDefaultIfUnset("modrinthRelations", "") +propertyDefaultIfUnset("curseForgeProjectId", "") +propertyDefaultIfUnset("curseForgeRelations", "") +propertyDefaultIfUnset("releaseType", "release") +propertyDefaultIfUnset("enableModernJavaSyntax", false) +propertyDefaultIfUnset("enableSpotless", false) +propertyDefaultIfUnset("enableJUnit", false) +propertyDefaultIfUnsetWithEnvVar("deploymentDebug", false, "DEPLOYMENT_DEBUG") + + +// Project property assertions + +final String javaSourceDir = 'src/main/java/' +// If Scala or Kotlin are supported, add those paths here + +final String modGroupPath = modGroup.toString().replace('.' as char, '/' as char) +final String apiPackagePath = apiPackage.toString().replace('.' as char, '/' as char) + +String targetPackageJava = javaSourceDir + modGroupPath +// If Scala or Kotlin are supported, add those paths here + +if (!getFile(targetPackageJava).exists()) { + throw new GradleException("Could not resolve \"modGroup\"! Could not find " + targetPackageJava) +} + +if (apiPackage) { + targetPackageJava = javaSourceDir + modGroupPath + '/' + apiPackagePath + if (!getFile(targetPackageJava).exists()) { + throw new GradleException("Could not resolve \"apiPackage\"! Could not find " + targetPackageJava) + } +} + +if (accessTransformersFile) { + for (atFile in accessTransformersFile.split(",")) { + String targetFile = 'src/main/resources/' + atFile.trim() + if (!getFile(targetFile).exists()) { + throw new GradleException("Could not resolve \"accessTransformersFile\"! Could not find " + targetFile) + } + tasks.deobfuscateMergedJarToSrg.accessTransformerFiles.from(targetFile) + tasks.srgifyBinpatchedJar.accessTransformerFiles.from(targetFile) + } +} + +if (usesMixins.toBoolean()) { + if (mixinsPackage.isEmpty()) { + throw new GradleException("\"usesMixins\" requires \"mixinsPackage\" to be set!") + } + final String mixinPackagePath = mixinsPackage.toString().replaceAll('\\.', '/') + targetPackageJava = javaSourceDir + modGroupPath + '/' + mixinPackagePath + if (!getFile(targetPackageJava).exists()) { + throw new GradleException("Could not resolve \"mixinsPackage\"! Could not find " + targetPackageJava) + } +} + +if (coreModClass) { + final String coreModPath = coreModClass.toString().replaceAll('\\.', '/') + String targetFileJava = javaSourceDir + modGroupPath + '/' + coreModPath + '.java' + if (!getFile(targetFileJava).exists()) { + throw new GradleException("Could not resolve \"coreModClass\"! Could not find " + targetFileJava) + } +} + + +// Plugin application + +// Spotless +//noinspection GroovyAssignabilityCheck +project.extensions.add(com.diffplug.blowdryer.Blowdryer, 'Blowdryer', com.diffplug.blowdryer.Blowdryer) // make Blowdryer available in plugin application +if (enableSpotless.toBoolean()) { + apply plugin: 'com.diffplug.spotless' + + // Spotless auto-formatter + // See https://github.com/diffplug/spotless/tree/main/plugin-gradle + // Can be locally toggled via spotless:off/spotless:on comments + spotless { + encoding 'UTF-8' + + format 'misc', { + target '.gitignore' + + trimTrailingWhitespace() + indentWithSpaces(4) + endWithNewline() + } + java { + target 'src/main/java/**/*.java', 'src/test/java/**/*.java' // exclude api as they are not our files + + def orderFile = project.file('spotless.importorder') + if (!orderFile.exists()) { + orderFile = Blowdryer.file('spotless.importorder') + } + def formatFile = project.file('spotless.eclipseformat.xml') + if (!formatFile.exists()) { + formatFile = Blowdryer.file('spotless.eclipseformat.xml') + } + + toggleOffOn() + importOrderFile(orderFile) + removeUnusedImports() + endWithNewline() + //noinspection GroovyAssignabilityCheck + eclipse('4.19.0').configFile(formatFile) + } + } +} + +// Git submodules +if (project.file('.git/HEAD').isFile() || project.file('.git').isFile()) { + apply plugin: 'com.palantir.git-version' } -version = project.mod_version -group = project.maven_group -archivesBaseName = project.archives_base_name -// Set the toolchain version to decouple the Java we run Gradle with from the Java used to compile and run the mod +// Configure Java + java { toolchain { - // Azul covers the most platforms for Java 8 toolchains, crucially including MacOS arm64 + if (enableModernJavaSyntax.toBoolean()) { + languageVersion.set(JavaLanguageVersion.of(17)) + } else { + languageVersion.set(JavaLanguageVersion.of(8)) + } + // Azul covers the most platforms for Java 8+ toolchains, crucially including MacOS arm64 vendor.set(JvmVendorSpec.AZUL) - languageVersion.set(JavaLanguageVersion.of(project.java_version)) } - - // Generate sources when building and publishing - withSourcesJar() - // javadoc jar throws errors on incomplete docs - // docs are also contained in the sources jar, so omit the javadoc-only jar + if (!noPublishedSources.toBoolean()) { + withSourcesJar() + } } tasks.withType(JavaCompile).configureEach { - options.encoding 'UTF-8' -} + options.encoding = 'UTF-8' -configurations { - embed - implementation.extendsFrom(embed) + if (enableModernJavaSyntax.toBoolean()) { + if (it.name in ['compileMcLauncherJava', 'compilePatchedMcJava']) { + return + } + + sourceCompatibility = 17 + options.release.set(8) + + javaCompiler.set(javaToolchains.compilerFor { + languageVersion.set(JavaLanguageVersion.of(17)) + vendor.set(JvmVendorSpec.AZUL) + }) + } } -minecraft { - mcVersion = project.mc_version - def args = [ - "-ea:${project.group}", -// "-Dfml.coreMods.load=${coremod_plugin_class_name}" - ] - extraRunJvmArguments.addAll(args) +// Configure Minecraft + +version = modVersion +group = modGroup +archivesBaseName = modArchivesBaseName + +minecraft { + mcVersion = minecraftVersion + username = developmentEnvironmentUserName.toString() useDependencyAccessTransformers = true - injectedTags.put('VERSION', project.version) + // Automatic token injection with RetroFuturaGradle + if (gradleTokenModId) { + injectedTags.put gradleTokenModId, modId + } + if (gradleTokenModName) { + injectedTags.put gradleTokenModName, modName + } + if (gradleTokenVersion) { + injectedTags.put gradleTokenVersion, modVersion + } + + // JVM arguments + extraRunJvmArguments.add("-ea:${modGroup}") + if (usesMixins.toBoolean()) { + extraRunJvmArguments.addAll([ + '-Dmixin.hotSwap=true', + '-Dmixin.checks.interfaces=true', + '-Dmixin.debug.export=true' + ]) + } + if (coreModClass) { + extraRunJvmArguments.add("-Dfml.coreMods.load=${modGroup}.${coreModClass}") + } +} + +if (generateGradleTokenClass) { + tasks.injectTags.outputClassName.set(generateGradleTokenClass) +} + +tasks.named('processIdeaSettings').configure { + dependsOn('injectTags') +} + + +// Allow others using this buildscript to have custom gradle code run +if (getFile('addon.gradle').exists()) { + apply from: 'addon.gradle' +} + + +// Repositories + +// Allow unsafe repos but warn +repositories.configureEach { repo -> + if (repo instanceof UrlArtifactRepository) { + if (repo.getUrl() != null && repo.getUrl().getScheme() == "http" && !repo.allowInsecureProtocol) { + logger.warn("Deprecated: Allowing insecure connections for repo '${repo.name}' - add 'allowInsecureProtocol = true'") + repo.allowInsecureProtocol = true + } + } } -// Generate the InternalTags class with the version number as a field -tasks.injectTags.configure { - outputClassName.set("${project.group}.GCYMInternalTags") +// Allow adding custom repositories to the buildscript +if (getFile('repositories.gradle').exists()) { + apply from: 'repositories.gradle' } repositories { - maven { - // MixinBooter - name 'Cleanroom Maven' - url 'https://maven.cleanroommc.com' - } - maven { - // JEI - name 'Progwml6 Maven' - url 'https://dvs1.progwml6.com/files/maven/' - } - maven { - // CraftTweaker and JEI Backup - name 'BlameJared Maven' - url 'https://maven.blamejared.com' - } - maven { - // TOP, CTM, GRS, AE2 - name 'Curse Maven' - url 'https://www.cursemaven.com' - content { - includeGroup 'curse.maven' + if (includeWellKnownRepositories.toBoolean() || includeCommonDevEnvMods.toBoolean()) { + exclusiveContent { + forRepository { + //noinspection ForeignDelegate + maven { + name = 'Curse Maven' + url = 'https://www.cursemaven.com' + } + } + filter { + includeGroup 'curse.maven' + } + } + exclusiveContent { + forRepository { + //noinspection ForeignDelegate + maven { + name = 'Modrinth' + url = 'https://api.modrinth.com/maven' + } + } + filter { + includeGroup 'maven.modrinth' + } + } + maven { + name 'Cleanroom Maven' + url 'https://maven.cleanroommc.com' + } + maven { + name 'BlameJared Maven' + url 'https://maven.blamejared.com' } } - maven { - // Mixin - name 'Sponge Maven' - url 'https://repo.spongepowered.org/maven' + if (usesMixins.toBoolean() || forceEnableMixins.toBoolean()) { + maven { + name 'Sponge Maven' + url 'https://repo.spongepowered.org/maven' + } + // need to add this here even if we did not above + if (!includeWellKnownRepositories.toBoolean()) { + maven { + name 'Cleanroom Maven' + url 'https://maven.cleanroommc.com' + } + } } mavenLocal() // Must be last for caching to work } -dependencies { - // Hard Dependencies - // the CCL deobf jar uses very old MCP mappings, making it error at runtime in runClient/runServer - // therefore we manually deobf the regular jar - implementation rfg.deobf("curse.maven:codechicken-lib-1-8-${ccl_pid}:${ccl_fid}") - // manually deobf the jar to prevent extra configuration for handling obf/deobf separation - implementation rfg.deobf("curse.maven:gregtech-ce-unofficial-${gt_pid}:${gt_fid}-sources-${gt_sources_fid}") +// Dependencies + +// Configure dependency configurations +configurations { + embed + implementation.extendsFrom(embed) +} - // Soft Dependencies - implementation "mezz.jei:jei_1.12.2:${project.jei_version}" - implementation "CraftTweaker2:CraftTweaker2-MC1120-Main:1.12-${project.crt_version}" - implementation rfg.deobf("curse.maven:top-${top_pid}:${top_fid}") - implementation rfg.deobf("curse.maven:ctm-${ctm_pid}:${ctm_fid}") - //implementation rfg.deobf("curse.maven:groovyscript-${grs_pid}:${grs_fid}") - implementation files("libs/groovyscript-0.4.0.jar") +dependencies { + if (usesMixins.toBoolean() || forceEnableMixins.toBoolean()) { + implementation 'zone.rong:mixinbooter:7.0' + api('org.spongepowered:mixin:0.8.3') { + transitive = false + } + annotationProcessor('org.spongepowered:mixin:0.8.3') { + transitive = false + } - // Tests - testImplementation "org.junit.jupiter:junit-jupiter:${junit_version}" - testImplementation "org.hamcrest:hamcrest:${hamcrest_version}" + annotationProcessor 'org.ow2.asm:asm-debug-all:5.2' + // should use 24.1.1 but 30.0+ has a vulnerability fix + annotationProcessor 'com.google.guava:guava:30.0-jre' + // should use 2.8.6 but 2.8.9+ has a vulnerability fix + annotationProcessor 'com.google.code.gson:gson:2.8.9' + } - // GroovyScript dependency - implementation "zone.rong:mixinbooter:${mixinbooter_version}" + if (enableJUnit.toBoolean()) { + testImplementation 'org.junit.jupiter:junit-jupiter:5.9.1' + testImplementation 'org.hamcrest:hamcrest:2.2' + } - // Mixin dependencies - api("org.spongepowered:mixin:${mixin_version}") { - transitive = false + if (enableModernJavaSyntax.toBoolean()) { + annotationProcessor 'com.github.bsideup.jabel:jabel-javac-plugin:1.0.0' + compileOnly('com.github.bsideup.jabel:jabel-javac-plugin:1.0.0') { + transitive = false + } + // workaround for https://github.com/bsideup/jabel/issues/174 + annotationProcessor 'net.java.dev.jna:jna-platform:5.13.0' + // Allow jdk.unsupported classes like sun.misc.Unsafe, workaround for JDK-8206937 and fixes Forge crashes in tests. + patchedMinecraft 'me.eigenraven.java8unsupported:java-8-unsupported-shim:1.0.0' + + // allow Jabel to work in tests + testAnnotationProcessor "com.github.bsideup.jabel:jabel-javac-plugin:1.0.0" + testCompileOnly("com.github.bsideup.jabel:jabel-javac-plugin:1.0.0") { + transitive = false // We only care about the 1 annotation class + } + testCompileOnly "me.eigenraven.java8unsupported:java-8-unsupported-shim:1.0.0" } - annotationProcessor("org.spongepowered:mixin:${mixin_version}") { - transitive = false + + compileOnlyApi 'org.jetbrains:annotations:23.0.0' + annotationProcessor 'org.jetbrains:annotations:23.0.0' + + if (includeCommonDevEnvMods.toBoolean()) { + implementation 'mezz.jei:jei_1.12.2:4.16.1.302' + //noinspection DependencyNotationArgument + implementation rfg.deobf('curse.maven:top-245211:2667280') // TOP 1.4.28 } +} + +if (getFile('dependencies.gradle').exists()) { + apply from: 'dependencies.gradle' +} - annotationProcessor "org.ow2.asm:asm-debug-all:${asm_debug_version}" - annotationProcessor "com.google.guava:guava:${guava_version}-jre" - annotationProcessor "com.google.code.gson:gson:${gson_version}" + +// Test configuration + +// Ensure tests have access to minecraft classes +sourceSets { + test { + java { + compileClasspath += patchedMc.output + mcLauncher.output + runtimeClasspath += patchedMc.output + mcLauncher.output + } + } } -//noinspection ConfigurationAvoidance -for (File at : sourceSets.getByName('main').resources.files) { - if (at.name.toLowerCase().endsWith('_at.cfg')) { - tasks.deobfuscateMergedJarToSrg.accessTransformerFiles.from at - tasks.srgifyBinpatchedJar.accessTransformerFiles.from at +test { + // ensure tests are run with java8 + javaLauncher = javaToolchains.launcherFor { + languageVersion = JavaLanguageVersion.of(8) + }.get() + + testLogging { + events TestLogEvent.STARTED, TestLogEvent.PASSED, TestLogEvent.FAILED + exceptionFormat TestExceptionFormat.FULL + showExceptions true + showStackTraces true + showCauses true + showStandardStreams true + } + + if (enableJUnit.toBoolean()) { + useJUnitPlatform() } } + +// Resource processing and jar building + processResources { // this will ensure that this task is redone when the versions change. - inputs.property 'version', project.version - inputs.property 'mcversion', project.minecraft.version + inputs.property 'version', modVersion + inputs.property 'mcversion', minecraftVersion + // Blowdryer puts these files into the resource directory, so + // exclude them from builds (doesn't hurt to exclude even if not present) + exclude('spotless.importorder') + exclude('spotless.eclipseformat.xml') + // replace stuff in mcmod.info, nothing else filesMatching(['mcmod.info', 'pack.mcmeta']) { fcd -> // replace version and mcversion fcd.expand( - 'version': project.version, - 'mcversion': project.minecraft.version + 'version': modVersion, + 'mcversion': minecraftVersion ) } +} - rename '(.+_at.cfg)', 'META-INF/$1' // Access Transformers +// Automatically generate a mixin json file if it does not already exist +tasks.register('generateAssets') { + group = 'GT Buildscript' + description = 'Generates a mixin config file at /src/main/resources/mixins.modid.json if needed' + onlyIf { + usesMixins.toBoolean() + } + doLast { + def mixinConfigFile = getFile("src/main/resources/mixins.${modId}.json") + if (!mixinConfigFile.exists()) { + def mixinConfigRefmap = "mixins.${modId}.refmap.json" + + mixinConfigFile.text = """{ + "package": "${modGroup}.${mixinsPackage}", + "refmap": "${mixinConfigRefmap}", + "target": "@env(DEFAULT)", + "minVersion": "0.8", + "compatibilityLevel": "JAVA_8", + "mixins": [], + "client": [], + "server": [] +} +""" + } + } +} + +if (usesMixins.toBoolean()) { + tasks.named('processResources').configure { + dependsOn('generateAssets') + } } jar { manifest { def attribute_map = [:] -// attribute_map['FMLCorePlugin'] = coremod_plugin_class_name -// attribute_map['FMLCorePluginContainsFMLMod'] = true -// attribute_map['ForceLoadAsMod'] = project.gradle.startParameter.taskNames[0] == 'build' -// attribute_map['FMLAT'] = archives_base_name + '_at.cfg' + if (coreModClass) { + attribute_map['FMLCorePlugin'] = "${modGroup}.${coreModClass}" + } + if (!containsMixinsAndOrCoreModOnly.toBoolean() && (usesMixins.toBoolean() || coreModClass)) { + attribute_map['FMLCorePluginContainsFMLMod'] = true + } + if (accessTransformersFile) { + attribute_map['FMLAT'] = accessTransformersFile.toString() + } + + if (usesMixins.toBoolean()) { + attribute_map['ForceLoadAsMod'] = !containsMixinsAndOrCoreModOnly.toBoolean() + } attributes(attribute_map) } @@ -172,17 +506,26 @@ jar { } } -test { - testLogging { - events TestLogEvent.STARTED, TestLogEvent.PASSED, TestLogEvent.FAILED - exceptionFormat TestExceptionFormat.FULL - showExceptions true - showStackTraces true - showCauses true - showStandardStreams true +// Create API library jar +tasks.register('apiJar', Jar) { + archiveClassifier.set 'api' + from(sourceSets.main.java) { + include "${modGroupPath}/${apiPackagePath}/**" } - useJUnitPlatform() + from(sourceSets.main.output) { + include "${modGroupPath}/${apiPackagePath}/**" + } +} + + +// IDE Configuration + +eclipse { + classpath { + downloadSources = true + downloadJavadoc = true + } } idea { @@ -206,6 +549,17 @@ idea { '4. Run Obfuscated Server'(Gradle) { taskNames = ['runObfServer'] } + if (enableSpotless.toBoolean()) { + "5. Apply Spotless"(Gradle) { + taskNames = ["spotlessApply"] + } + } + 'Update Buildscript'(Gradle) { + taskNames = ['updateBuildScript'] + } + 'FAQ'(Gradle) { + taskNames = ['faq'] + } } compiler.javac { afterEvaluate { @@ -221,103 +575,261 @@ idea { } } -// Create API library jar -tasks.register('apiJar', Jar) { - archiveClassifier.set 'api' - from(sourceSets.main.java) { - include 'gregicality.multiblocks/api/**' + +// Deployment + +final boolean isCIEnv = providers.environmentVariable('CI').getOrElse('false').toBoolean() +def final changelogEnv = providers.environmentVariable('CHANGELOG_LOCATION') +File changelogFile = new File(changelogEnv.getOrElse('CHANGELOG.md')) + +if (isCIEnv || deploymentDebug.toBoolean()) { + artifacts { + if (!noPublishedSources.toBoolean()) { + archives sourcesJar + } + if (apiPackage) { + archives apiJar + } } +} - from(sourceSets.main.output) { - include 'gregicality.multiblocks/api/**' +// Curseforge +def final cfApiKey = providers.environmentVariable('CURSEFORGE_API_KEY') +if (cfApiKey.isPresent() || deploymentDebug.toBoolean()) { + apply plugin: 'net.darkhax.curseforgegradle' + //noinspection UnnecessaryQualifiedReference + tasks.register('curseforge', net.darkhax.curseforgegradle.TaskPublishCurseForge) { + apiToken = cfApiKey.get() + def projectIdVar = providers.environmentVariable('CURSEFORGE_PROJECT_ID') + + def mainFile = upload(projectIdVar.getOrElse(curseForgeProjectId), reobfJar) + def changelogRaw = changelogFile.exists() ? changelogFile.getText('UTF-8') : "" + + mainFile.releaseType = getReleaseType() + mainFile.changelog = changelogRaw + mainFile.changelogType = 'markdown' + mainFile.addModLoader 'Forge' + mainFile.addJavaVersion "Java 8" + mainFile.addGameVersion minecraftVersion + + if (curseForgeRelations.size() != 0) { + String[] deps = curseForgeRelations.split(';') + deps.each { dep -> + if (dep.size() == 0) { + return + } + String parts = dep.split(':') + String type = parts[0], slug = parts[1] + if(!(type in ['requiredDependency', 'embeddedLibrary', 'optionalDependency', 'tool', 'incompatible'])) { + throw new Exception('Invalid Curseforge dependency type: ' + type) + } + mainFile.addRelation(slug, type) + } + } + + for (artifact in getSecondaryArtifacts()) { + def additionalFile = mainFile.withAdditionalFile(artifact) + additionalFile.changelog = changelogRaw + } + disableVersionDetection() + debugMode = deploymentDebug.toBoolean() } + tasks.curseforge.dependsOn(build) } -sourceSets { - main { - java { - srcDirs = ['src/main/java', 'src/api/java'] +// Modrinth +def final modrinthApiKey = providers.environmentVariable('MODRINTH_API_KEY') +if (modrinthApiKey.isPresent() || deploymentDebug.toBoolean()) { + apply plugin: 'com.modrinth.minotaur' + def final projectIdVar = providers.environmentVariable('MODRINTH_PROJECT_ID') + + modrinth { + token = modrinthApiKey.get() + projectId = projectIdVar.getOrElse(modrinthProjectId) + changelog = changelogFile.exists() ? changelogFile.getText('UTF-8') : "" + versionType = getReleaseType() + versionNumber = modVersion + gameVersions = [minecraftVersion] + loaders = ["forge"] + debugMode = deploymentDebug.toBoolean() + uploadFile = file("build/libs/${archivesBaseName}-${version}.jar") + additionalFiles = getSecondaryArtifacts() + } + if (modrinthRelations.size() != 0) { + String[] deps = modrinthRelations.split(';') + deps.each { dep -> + if (dep.size() == 0) { + return + } + String[] parts = dep.split(':') + String qual = parts[0].split('-') + addModrinthDep(qual[0], qual[1], parts[1]) } } - test { - java { - compileClasspath += patchedMc.output + mcLauncher.output - runtimeClasspath += patchedMc.output + mcLauncher.output + tasks.modrinth.dependsOn(build) +} + +def addModrinthDep(String scope, String type, String name) { + com.modrinth.minotaur.dependencies.Dependency dep + if (!(scope in ['required', 'optional', 'incompatible', 'embedded'])) { + throw new Exception('Invalid modrinth dependency scope: ' + scope) + } + switch (type) { + case 'project': + dep = new ModDependency(name, scope) + break + case 'version': + dep = new VersionDependency(name, scope) + break + default: + throw new Exception('Invalid modrinth dependency type: ' + type) + } + project.modrinth.dependencies.add(dep) +} + + +// Buildscript updating + +def buildscriptGradleVersion = '8.1.1' + +tasks.named('wrapper', Wrapper).configure { + gradleVersion = buildscriptGradleVersion +} + +tasks.register('updateBuildScript') { + group = 'GT Buildscript' + description = 'Updates the build script to the latest version' + + if (gradle.gradleVersion != buildscriptGradleVersion && !Boolean.getBoolean('DISABLE_BUILDSCRIPT_GRADLE_UPDATE')) { + dependsOn('wrapper') + } + + doLast { + if (performBuildScriptUpdate()) return + print('Build script already up to date!') + } +} + +if (!project.getGradle().startParameter.isOffline() && !Boolean.getBoolean('DISABLE_BUILDSCRIPT_UPDATE_CHECK') && isNewBuildScriptVersionAvailable()) { + if (autoUpdateBuildScript.toBoolean()) { + performBuildScriptUpdate() + } else { + out.style(Style.SuccessHeader).println("Build script update available! Run 'gradle updateBuildScript'") + if (gradle.gradleVersion != buildscriptGradleVersion) { + out.style(Style.SuccessHeader).println("updateBuildScript can update gradle from ${gradle.gradleVersion} to ${buildscriptGradleVersion}\n") } } } -tasks.named('processIdeaSettings').configure { - dependsOn('injectTags') +static URL availableBuildScriptUrl() { + new URL("https://raw.githubusercontent.com/GregTechCEu/Buildscripts/master/build.gradle") } -// Deployment +static URL exampleSettingsGradleUrl() { + new URL("https://raw.githubusercontent.com/GregTechCEu/Buildscripts/master/settings.gradle") +} -final boolean is_ci_env = providers.environmentVariable('CI').getOrElse('false').toBoolean() -final boolean deployment_debug = providers.environmentVariable('DEPLOYMENT_DEBUG').getOrElse("$deployment_debug").toBoolean() +boolean verifySettingsGradle() { + def settingsFile = getFile("settings.gradle") + if (!settingsFile.exists()) { + println("Downloading default settings.gradle") + exampleSettingsGradleUrl().withInputStream { i -> settingsFile.withOutputStream { it << i } } + return true + } + return false +} -if (is_ci_env || deployment_debug) { - artifacts { - archives jar - archives apiJar - archives sourcesJar +boolean performBuildScriptUpdate() { + if (isNewBuildScriptVersionAvailable()) { + def buildscriptFile = getFile("build.gradle") + availableBuildScriptUrl().withInputStream { i -> buildscriptFile.withOutputStream { it << i } } + def out = services.get(StyledTextOutputFactory).create('buildscript-update-output') + out.style(Style.Success).print("Build script updated. Please REIMPORT the project or RESTART your IDE!") + if (verifySettingsGradle()) { + throw new GradleException("Settings has been updated, please re-run task.") + } + return true } + return false } -def final cf_api_key = providers.environmentVariable('CURSEFORGE_API_KEY') -if (cf_api_key.isPresent() || deployment_debug) { - apply plugin: 'net.darkhax.curseforgegradle' - //noinspection UnnecessaryQualifiedReference - tasks.register('curseforge', net.darkhax.curseforgegradle.TaskPublishCurseForge) { - apiToken = cf_api_key.get() - def final projectId = providers.environmentVariable('CURSEFORGE_PROJECT_ID').get() +boolean isNewBuildScriptVersionAvailable() { + Map parameters = ["connectTimeout": 10000, "readTimeout": 10000] - def mainFile = upload(projectId, reobfJar) - mainFile.releaseType = providers.environmentVariable('RELEASE_TYPE').get() - mainFile.changelog = providers.environmentVariable('CHANGELOG_LOCATION').get() - mainFile.changelogType = 'markdown' - mainFile.addRequirement 'codechicken-lib-1-8' - mainFile.addRequirement 'gregtech-ce-unofficial' - mainFile.addIncompatibility 'gregtechce' - mainFile.addModLoader 'Forge' - mainFile.addJavaVersion "Java ${java_version}" - mainFile.addGameVersion "$mc_version" + String currentBuildScript = getFile("build.gradle").getText() + String currentBuildScriptHash = getVersionHash(currentBuildScript) + String availableBuildScript = availableBuildScriptUrl().newInputStream(parameters).getText() + String availableBuildScriptHash = getVersionHash(availableBuildScript) + + boolean isUpToDate = currentBuildScriptHash.empty || availableBuildScriptHash.empty || currentBuildScriptHash == availableBuildScriptHash + return !isUpToDate +} - def sourcesFile = mainFile.withAdditionalFile(sourcesJar) - sourcesFile.changelog = providers.environmentVariable('CHANGELOG_LOCATION').get() +static String getVersionHash(String buildScriptContent) { + String versionLine = buildScriptContent.find("^//version: [a-z0-9]*") + if (versionLine != null) { + return versionLine.split(": ").last() + } + return "" +} - def devFile = mainFile.withAdditionalFile(jar) - devFile.changelog = providers.environmentVariable('CHANGELOG_LOCATION').get() - disableVersionDetection() +// Faq + +tasks.register('faq') { + group = 'GT Buildscript' + description = 'Prints frequently asked questions about building a project' + doLast { + print("\nTo update this buildscript to the latest version, run 'gradlew updateBuildScript' or run the generated run configuration if you are using IDEA.\n" + + "To set up the project, run the 'setupDecompWorkspace' task, which you can run as './gradlew setupDecompWorkspace' in a terminal, or find in the 'modded minecraft' gradle category.\n\n" + + "To add new dependencies to your project, place them in 'dependencies.gradle', NOT in 'build.gradle' as they would be replaced when the script updates.\n" + + "To add new repositories to your project, place them in 'repositories.gradle'.\n" + + "If you need additional gradle code to run, you can place it in a file named 'addon.gradle' (or either of the above, up to you for organization).\n\n" + + "If your build fails to recognize the syntax of newer Java versions, enable Jabel in your 'gradle.properties' under the option name 'enableModernJavaSyntax'.\n" + + "To see information on how to configure your IDE properly for Java 17, see https://github.com/GregTechCEu/Buildscripts/blob/master/jabel.md\n\n" + + "Report any issues or feature requests you have for this build script to https://github.com/GregTechCEu/Buildscripts/issues\n") } +} - tasks.curseforge.dependsOn(build) + +// Helpers + +def getFile(String relativePath) { + return new File(projectDir, relativePath) } -def final modrinth_api_key = providers.environmentVariable('MODRINTH_API_KEY') -if (modrinth_api_key.isPresent() || deployment_debug) { - apply plugin: 'com.modrinth.minotaur' +def checkPropertyExists(String propertyName) { + if (!project.hasProperty(propertyName)) { + throw new GradleException("This project requires a property \"" + propertyName + "\"! Please add it your \"gradle.properties\". You can find all properties and their description here: https://github.com/GregTechCEu/Buildscripts/blob/main/gradle.properties") + } +} - modrinth { - token = modrinth_api_key.get() - projectId = providers.environmentVariable("MODRINTH_PROJECT_ID").get() - changelog = providers.environmentVariable("CHANGELOG_LOCATION").get() - versionType = providers.environmentVariable("RELEASE_TYPE").get() +def propertyDefaultIfUnset(String propertyName, defaultValue) { + if (!project.hasProperty(propertyName) || project.property(propertyName) == "") { + project.ext.setProperty(propertyName, defaultValue) + } +} - versionNumber = "$version".split('-')[0] // strip out the EXTRA field, if present - gameVersions = ["$mc_version"] - loaders = ["forge"] +def propertyDefaultIfUnsetWithEnvVar(String propertyName, defaultValue, String envVarName) { + def envVar = providers.environmentVariable(envVarName) + if (envVar.isPresent()) { + project.ext.setProperty(propertyName, envVar.get()) + } else { + propertyDefaultIfUnset(propertyName, defaultValue) + } +} - def main_artifact = "${archivesBaseName}-${version}.jar" - uploadFile = file("build/libs/${main_artifact}") - file('build/libs/').eachFile { file -> - if (file.name.endsWith('.jar') && file.name != main_artifact) { - additionalFiles.add file - } - } +def getSecondaryArtifacts() { + def secondaryArtifacts = [jar] + if (!noPublishedSources.toBoolean()) secondaryArtifacts += [sourcesJar] + if (apiPackage) secondaryArtifacts += [apiJar] + return secondaryArtifacts +} - debugMode = deployment_debug +def getReleaseType() { + String type = releaseType + if (!(type in ['release', 'beta', 'alpha'])) { + throw new Exception("Release type invalid! Found \"" + type + "\", allowed: \"release\", \"beta\", \"alpha\"") } - tasks.modrinth.dependsOn(build) + return type } diff --git a/dependencies.gradle b/dependencies.gradle new file mode 100644 index 00000000..732235ea --- /dev/null +++ b/dependencies.gradle @@ -0,0 +1,38 @@ +//file:noinspection DependencyNotationArgument +// TODO remove when fixed in RFG ^ +/* + * Add your dependencies here. Common configurations: + * - implementation("group:name:version:classifier"): if you need this for internal implementation details of the mod. + * Available at compiletime and runtime for your environment. + * + * - compileOnlyApi("g:n:v:c"): if you need this for internal implementation details of the mod. + * Available at compiletime but not runtime for your environment. + * + * - annotationProcessor("g:n:v:c"): mostly for java compiler plugins, if you know you need this, use it, otherwise don't worry + * + * - testCONFIG("g:n:v:c"): replace CONFIG by one of the above, same as above but for the test sources instead of main + * + * You can exclude transitive dependencies (dependencies of the chosen dependency) by appending { transitive = false } if needed. + * + * To add a mod with CurseMaven, replace '("g:n:v:c")' in the above with 'rfg.deobf("curse.maven:project_slug-project_id:file_id")' + * Example: implementation rfg.deobf("curse.maven:gregtech-ce-unofficial-557242:4527757") + * + * For more details, see https://docs.gradle.org/8.0.1/userguide/java_library_plugin.html#sec:java_library_configurations_graph + */ +dependencies { + + // Hard Dependencies + + // the CCL deobf jar uses very old MCP mappings, making it error at runtime in runClient/runServer + // therefore we manually deobf the regular jar + implementation rfg.deobf("curse.maven:codechicken-lib-1-8-242818:2779848") // CCL 3.2.3.358 + // manually deobf the jar to prevent extra configuration for handling obf/deobf separation + implementation rfg.deobf("curse.maven:gregtech-ce-unofficial-557242:4527757-sources-4527758") // GTCEu 2.6.2-beta + + // Soft Dependencies + + implementation "CraftTweaker2:CraftTweaker2-MC1120-Main:1.12-4.1.20.684" + implementation rfg.deobf("curse.maven:ctm-267602:2915363") // CTM 1.0.2.31 + //implementation rfg.deobf("curse.maven:groovyscript-687577:4487379") // GRS 0.3.0 + implementation files("libs/groovyscript-0.4.0.jar") +} diff --git a/gradle.properties b/gradle.properties index a67491e9..984e4064 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,61 +1,129 @@ -# Mod Information -archives_base_name = GregicalityMultiblocks -mc_version = 1.12.2 -mod_version = 1.2.3 -maven_group = gregicality - -## Hard Dependencies -ccl_pid = 242818 -ccl_fid = 2779848 -gt_pid = 557242 -gt_fid = 4527757 -gt_sources_fid = 4527758 - -## Soft Dependencies -jei_version = 4.16.1.302 -crt_version = 4.1.20.684 -### TOP 1.4.28 -top_pid = 245211 -top_fid = 2667280 -### CTM 1.0.2.31 -ctm_pid = 267602 -ctm_fid = 2915363 -### GRS 0.3.0 -# suppress inspection "UnusedProperty" -grs_pid = 687577 -# suppress inspection "UnusedProperty" -grs_fid = 4487379 - -## Mixin Dependencies -mixinbooter_version = 7.0 -mixin_version = 0.8.3 -asm_debug_version = 5.2 -### should use 24.1.1 but 30.0+ has a vulnerability fix -guava_version = 30.0 -### should use 2.8.6 but 2.8.9+ has a vulnerability fix -gson_version = 2.8.9 - -## Test Dependencies -junit_version = 5.9.1 -hamcrest_version = 2.2 - -## Gradle Dependencies -foojay_version = 0.4.0 -idea_ext_version = 1.1.7 -rfg_version = 1.3.10 -java_version = 8 - -# Deployment -deployment_debug = false - -## Dependencies -curseforge_gradle_version = 1.0.+ -minotaur_version = 2.7.+ - -# Gradle Settings (do not rename values) -org.gradle.welcome = never +modName = Gregicality Multiblocks + +# This is a case-sensitive string to identify your mod. Convention is to use lower case. +modId = gcym + +modGroup = gregicality.multiblocks + +modVersion = 1.2.3 + +# The name of your jar when you produce builds, not including any versioning info +modArchivesBaseName = GregicalityMultiblocks + +# Will update your build.gradle automatically whenever an update is available +autoUpdateBuildScript = false + +minecraftVersion = 1.12.2 + +# Select a username for testing your mod with breakpoints. You may leave this empty for a random username each time you +# restart Minecraft in development. Choose this dependent on your mod: +# Do you need consistent player progressing (for example Thaumcraft)? -> Select a name +# Do you need to test how your custom blocks interacts with a player that is not the owner? -> leave name empty +# Alternatively this can be set with the 'DEV_USERNAME' environment variable. +developmentEnvironmentUserName = Developer + +# Enables using modern java syntax (up to version 17) via Jabel, while still targeting JVM 8. +# See https://github.com/bsideup/jabel for details on how this works. +# Using this requires that you use a Java 17 JDK for development. +enableModernJavaSyntax = true + +# Generate a class with String fields for the mod id, name and version named with the fields below +generateGradleTokenClass = gregicality.multiblocks.GCYMInternalTags +gradleTokenModId = +gradleTokenModName = +gradleTokenVersion = VERSION + +# In case your mod provides an API for other mods to implement you may declare its package here. Otherwise, you can +# leave this property empty. +# Example value: apiPackage = api + modGroup = com.myname.mymodid -> com.myname.mymodid.api +apiPackage = + +# Specify the configuration file for Forge's access transformers here. It must be placed into /src/main/resources/ +# There can be multiple files in a comma-separated list. +# Example value: mymodid_at.cfg,jei_at.cfg +accessTransformersFile = + +# Provides setup for Mixins if enabled. If you don't know what mixins are: Keep it disabled! +usesMixins = false +# Specify the package that contains all of your Mixins. You may only place Mixins in this package or the build will fail! +mixinsPackage = +# Specify the core mod entry class if you use a core mod. This class must implement IFMLLoadingPlugin! +# Example value: coreModClass = asm.FMLPlugin + modGroup = com.myname.mymodid -> com.myname.mymodid.asm.FMLPlugin +coreModClass = +# If your project is only a consolidation of mixins or a core mod and does NOT contain a 'normal' mod (meaning that +# there is no class annotated with @Mod) you want this to be true. When in doubt: leave it on false! +containsMixinsAndOrCoreModOnly = false + +# Enables Mixins even if this mod doesn't use them, useful if one of the dependencies uses mixins. +forceEnableMixins = true + +# Adds CurseMaven, Modrinth Maven, BlameJared maven, and some more well-known 1.12.2 repositories +includeWellKnownRepositories = true + +# Adds JEI and TheOneProbe to your development environment. Adds them as 'implementation', meaning they will +# be available at compiletime and runtime for your mod (in-game and in-code). +# Overrides the above setting to be always true, as these repositories are needed to fetch the mods +includeCommonDevEnvMods = true + + +# Publishing to modrinth requires you to set the MODRINTH_API_KEY environment variable to your current modrinth API token. + +# The project's ID on Modrinth. Can be either the slug or the ID. +# Leave this empty if you don't want to publish on Modrinth. +# Alternatively this can be set with the 'MODRINTH_PROJECT_ID' environment variable. +modrinthProjectId = + +# The project's relations on Modrinth. You can use this to refer to other projects on Modrinth. +# Syntax: scope1-type1:name1;scope2-type2:name2;... +# Where scope can be one of [required, optional, incompatible, embedded], +# type can be one of [project, version], +# and the name is the Modrinth project or version slug/id of the other mod. +# Example: required-project:jei;optional-project:top;incompatible-project:gregtech +modrinthRelations = required-project:gregtech-ce-unofficial + + +# Publishing to CurseForge requires you to set the CURSEFORGE_API_KEY environment variable to one of your CurseForge API tokens. + +# The project's numeric ID on CurseForge. You can find this in the About Project box. +# Leave this empty if you don't want to publish on CurseForge. +# Alternatively this can be set with the 'CURSEFORGE_PROJECT_ID' environment variable. +curseForgeProjectId = + +# The project's relations on CurseForge. You can use this to refer to other projects on CurseForge. +# Syntax: type1:name1;type2:name2;... +# Where type can be one of [requiredDependency, embeddedLibrary, optionalDependency, tool, incompatible], +# and the name is the CurseForge project slug of the other mod. +# Example: requiredDependency:railcraft;embeddedLibrary:cofhlib;incompatible:buildcraft +curseForgeRelations = requiredDependency:gregtech-ce-unofficial;requiredDependency:codechicken-lib-1-8;incompatible:gregtechce + +# This project's release type on CurseForge and/or Modrinth +# Allowed types: release, beta, alpha +releaseType = beta + +# Prevent the source code from being published +noPublishedSources = false + +# Enable spotless checks +# Enforces code formatting on your source code +# By default this will use the files found here: https://github.com/GregTechCEu/Buildscripts/tree/master/spotless +# to format your code. However, you can create your own version of these files and place them in your project's +# root directory to apply your own formatting options instead. +enableSpotless = false + +# Enable JUnit testing platform used for testing your code. +# Uses JUnit 5. See guide and documentation here: https://junit.org/junit5/docs/current/user-guide/ +enableJUnit = true + +# Deployment debug setting +# Uncomment this to test deployments to CurseForge and Modrinth +# Alternatively, you can set the 'DEPLOYMENT_DEBUG' environment variable. +deploymentDebug = false + + +# Gradle Settings +# Effectively applies the '--stacktrace' flag by default org.gradle.logging.stacktrace = all -## Sets default memory used for gradle commands. Can be overridden by user or command line properties. -## This is required to provide enough memory for the Minecraft decompilation process. +# Sets default memory used for gradle commands. Can be overridden by user or command line properties. +# This is required to provide enough memory for the Minecraft decompilation process. org.gradle.jvmargs = -Xmx3G -org.gradle.daemon = false + diff --git a/settings.gradle b/settings.gradle index 561ac48a..99acff8d 100644 --- a/settings.gradle +++ b/settings.gradle @@ -19,8 +19,15 @@ pluginManagement { } plugins { + id 'com.diffplug.blowdryerSetup' version '1.6.0' // Automatic toolchain provisioning - id 'org.gradle.toolchains.foojay-resolver-convention' version "${foojay_version}" + id 'org.gradle.toolchains.foojay-resolver-convention' version '0.4.0' } -rootProject.name = archives_base_name +blowdryerSetup { + repoSubfolder 'spotless' + github('GregTechCEu/Buildscripts', 'commit', 'a1e1f2dfebb66f8fc652cd3e020b871fbd8604cb') + //devLocal '.' // Use this when testing config updates locally +} + +rootProject.name = modArchivesBaseName diff --git a/src/main/java/gregicality/multiblocks/GregicalityMultiblocks.java b/src/main/java/gregicality/multiblocks/GregicalityMultiblocks.java index 4d0f7ec0..acc5300b 100644 --- a/src/main/java/gregicality/multiblocks/GregicalityMultiblocks.java +++ b/src/main/java/gregicality/multiblocks/GregicalityMultiblocks.java @@ -18,7 +18,7 @@ public class GregicalityMultiblocks { public static final String MODID = "gcym"; public static final String NAME = "Gregicality Multiblocks"; - public static final String VERSION = "1.2.2"; + public static final String VERSION = GCYMInternalTags.VERSION; @SidedProxy(modId = MODID, clientSide = "gregicality.multiblocks.common.ClientProxy", serverSide = "gregicality.multiblocks.common.CommonProxy") public static CommonProxy proxy;