diff --git a/.idea/gradle.xml b/.idea/gradle.xml index ce08eaf..e306e94 100644 --- a/.idea/gradle.xml +++ b/.idea/gradle.xml @@ -11,6 +11,14 @@ + + + \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts index d9b0d9c..1ff358c 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,21 +1,92 @@ plugins { - kotlin("jvm") version "1.9.23" + kotlin("jvm") version "1.9.22" + `java-gradle-plugin` + `maven-publish` } -group = "xyz.wagyourtail.unimined" +group = "xyz.wagyourtail.unimined.expect-platform" version = "1.0-SNAPSHOT" +base { + archivesName.set("expect-platform") +} + +val annotations by sourceSets.creating {} + +java { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + + withJavadocJar() + withSourcesJar() +} + repositories { mavenCentral() } +val asmVersion: String by project.properties + dependencies { + implementation(gradleApi()) + implementation("org.ow2.asm:asm:${asmVersion}") + testImplementation(kotlin("test")) } tasks.test { useJUnitPlatform() } + +tasks.jar { + + manifest { + attributes( + "Manifest-Version" to "1.0", + "Implementation-Title" to project.name, + "Implementation-Version" to project.version, + ) + } +} + +val annotationJar = tasks.register("annotationJar") { + archiveClassifier.set("annotations") + from(annotations.output) + + manifest { + attributes( + "Manifest-Version" to "1.0", + "Implementation-Title" to project.name, + "Implementation-Version" to project.version, + ) + } +} + kotlin { jvmToolchain(8) -} \ No newline at end of file +} + +gradlePlugin { + plugins { + create("simplePlugin") { + id = "xyz.wagyourtail.unimined.expect-platform" + implementationClass = "xyz.wagyourtail.unimined.expect.ExpectPlatformPlugin" + } + } +} + +publishing { + publications { + create("mavenJava") { + groupId = "xyz.wagyourtail.unimined.expect-platform" + artifactId = "expect-platform" + version = project.version.toString() + + from(components["java"]) + + artifact(annotationJar) { + classifier = "annotations" + } + } + } +} diff --git a/expect-platform-test/build.gradle b/expect-platform-test/build.gradle index e69de29..fbdb4cc 100644 --- a/expect-platform-test/build.gradle +++ b/expect-platform-test/build.gradle @@ -0,0 +1,108 @@ +import xyz.wagyourtail.unimined.expect.task.ExpectPlatformFiles +import xyz.wagyourtail.unimined.expect.task.ExpectPlatformJar + +buildscript { + repositories { + mavenCentral() + flatDir { + dirs("../build/libs") + } + } + dependencies { + classpath "xyz.wagyourtail.unimined.expect-platform:expect-platform:1.0-SNAPSHOT" + classpath "org.ow2.asm:asm:9.7" + } +} + +plugins { + id 'java' +// id 'xyz.wagyourtail.unimined.expect-platform' +} + +apply plugin: 'xyz.wagyourtail.unimined.expect-platform' + + +sourceSets { + a { + compileClasspath += sourceSets.main.output + } + b { + compileClasspath += sourceSets.main.output + } + c { + compileClasspath += sourceSets.main.output + } +} + +repositories { + flatDir { + dirs "../build/libs" + } +} + +dependencies { + implementation(expectPlatform.annotationsDep) +} + +tasks.create("aExpectPlatform", ExpectPlatformFiles) { + platformName = "a" + inputCollection = sourceSets.main.output +} + +tasks.create("bExpectPlatform", ExpectPlatformFiles) { + platformName = "b" + inputCollection = sourceSets.main.output +} + +tasks.create("cExpectPlatform", ExpectPlatformFiles) { + platformName = "c" + inputCollection = sourceSets.main.output +} + +tasks.register('runA', JavaExec) { + dependsOn(tasks.aExpectPlatform) + classpath = sourceSets.a.runtimeClasspath + tasks.aExpectPlatform.outputCollection + mainClass = 'xyz.wagyourtail.ept.Main' + group = 'ept' + + System.out.println("classpath: " + classpath.files) +} + +tasks.register('runB', JavaExec) { + dependsOn(tasks.bExpectPlatform) + classpath = sourceSets.b.runtimeClasspath + tasks.bExpectPlatform.outputCollection + mainClass = 'xyz.wagyourtail.ept.Main' + group = 'ept' +} + +tasks.register('runC', JavaExec) { + dependsOn(tasks.cExpectPlatform) + classpath = sourceSets.c.runtimeClasspath + tasks.cExpectPlatform.outputCollection + mainClass = 'xyz.wagyourtail.ept.Main' + group = 'ept' +} + +tasks.register('jarA', ExpectPlatformJar) { + platformName = "a" + inputFiles = sourceSets.main.output + from sourceSets.a.output + archiveFileName = "a.jar" +} + +tasks.register('jarB', ExpectPlatformJar) { + platformName = "b" + inputFiles = sourceSets.main.output + from sourceSets.b.output + archiveFileName = "b.jar" +} + +tasks.register('jarC', ExpectPlatformJar) { + platformName = "c" + inputFiles = sourceSets.main.output + from sourceSets.c.output + archiveFileName = "c.jar" +} + +assemble.dependsOn(tasks.jarA) +assemble.dependsOn(tasks.jarB) +assemble.dependsOn(tasks.jarC) \ No newline at end of file diff --git a/expect-platform-test/gradle/wrapper/gradle-wrapper.jar b/expect-platform-test/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..d64cd49 Binary files /dev/null and b/expect-platform-test/gradle/wrapper/gradle-wrapper.jar differ diff --git a/expect-platform-test/gradle/wrapper/gradle-wrapper.properties b/expect-platform-test/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..1af9e09 --- /dev/null +++ b/expect-platform-test/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/expect-platform-test/gradlew b/expect-platform-test/gradlew new file mode 100755 index 0000000..1aa94a4 --- /dev/null +++ b/expect-platform-test/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/expect-platform-test/gradlew.bat b/expect-platform-test/gradlew.bat new file mode 100644 index 0000000..6689b85 --- /dev/null +++ b/expect-platform-test/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/expect-platform-test/settings.gradle b/expect-platform-test/settings.gradle index e69de29..2c6e611 100644 --- a/expect-platform-test/settings.gradle +++ b/expect-platform-test/settings.gradle @@ -0,0 +1,5 @@ +pluginManagement { + repositories { + mavenCentral() + } +} \ No newline at end of file diff --git a/expect-platform-test/src/a/java/xyz/wagyourtail/ept/a/MainImpl.java b/expect-platform-test/src/a/java/xyz/wagyourtail/ept/a/MainImpl.java index 2892d09..b53ad3a 100644 --- a/expect-platform-test/src/a/java/xyz/wagyourtail/ept/a/MainImpl.java +++ b/expect-platform-test/src/a/java/xyz/wagyourtail/ept/a/MainImpl.java @@ -1,4 +1,10 @@ package xyz.wagyourtail.ept.a; public class MainImpl { + + + public static String platformTest(String name) { + return "Hello a! " + name; + } + } diff --git a/expect-platform-test/src/b/java/xyz/wagyourtail/ept/b/MainImpl.java b/expect-platform-test/src/b/java/xyz/wagyourtail/ept/b/MainImpl.java index bd9d5e4..ad96887 100644 --- a/expect-platform-test/src/b/java/xyz/wagyourtail/ept/b/MainImpl.java +++ b/expect-platform-test/src/b/java/xyz/wagyourtail/ept/b/MainImpl.java @@ -1,4 +1,9 @@ package xyz.wagyourtail.ept.b; public class MainImpl { + + public static String platformTest(String name) { + return "Hello b! " + name; + } + } diff --git a/expect-platform-test/src/c/java/xyz/wagyourtail/ept/c/NotMain.java b/expect-platform-test/src/c/java/xyz/wagyourtail/ept/c/NotMain.java index 045821b..3a9cb0a 100644 --- a/expect-platform-test/src/c/java/xyz/wagyourtail/ept/c/NotMain.java +++ b/expect-platform-test/src/c/java/xyz/wagyourtail/ept/c/NotMain.java @@ -1,4 +1,9 @@ package xyz.wagyourtail.ept.c; public class NotMain { + + public static String platformTest(String name) { + return "Hello c! " + name; + } + } diff --git a/expect-platform-test/src/main/java/xyz/wagyourtail/ept/Main.java b/expect-platform-test/src/main/java/xyz/wagyourtail/ept/Main.java index 796fe93..836b67c 100644 --- a/expect-platform-test/src/main/java/xyz/wagyourtail/ept/Main.java +++ b/expect-platform-test/src/main/java/xyz/wagyourtail/ept/Main.java @@ -1,4 +1,21 @@ package xyz.wagyourtail.ept; +import xyz.wagyourtail.unimined.expect.annotation.ExpectPlatform; + public class Main { + + public static void main(String[] args) { + System.out.println(platformTest("test")); + } + + @ExpectPlatform( + platforms = @ExpectPlatform.Platform( + name = "c", + target = "xyz/wagyourtail/ept/c/NotMain" + ) + ) + public static String platformTest(String name) { + throw new AssertionError(); + } + } diff --git a/gradle.properties b/gradle.properties index 7fc6f1f..5216150 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1 +1,3 @@ kotlin.code.style=official + +asmVersion=9.7 \ No newline at end of file diff --git a/src/main/kotlin/xyz/wagyourtail/unimined/expect/ExpectPlatformExtension.kt b/src/main/kotlin/xyz/wagyourtail/unimined/expect/ExpectPlatformExtension.kt index 22ad13c..4a4c6f2 100644 --- a/src/main/kotlin/xyz/wagyourtail/unimined/expect/ExpectPlatformExtension.kt +++ b/src/main/kotlin/xyz/wagyourtail/unimined/expect/ExpectPlatformExtension.kt @@ -1,4 +1,47 @@ package xyz.wagyourtail.unimined.expect -class ExpectPlatformExtension { +import org.gradle.api.Project +import org.gradle.api.artifacts.Configuration +import org.gradle.api.attributes.Attribute +import org.gradle.api.file.FileCollection +import org.gradle.api.tasks.Internal +import xyz.wagyourtail.unimined.expect.transform.ExpectPlatformTransform + +abstract class ExpectPlatformExtension(val project: Project) { + @get:Internal + val version = ExpectPlatformExtension::class.java.`package`.implementationVersion ?: "1.0-SNAPSHOT" + + val annotationsDep = "xyz.wagyourtail.unimined:expect-platform:$version:annotations" + + + fun platform(platformName: String, configuration: Configuration) { + val expectPlatformAttribute = Attribute.of("expectPlatform.${configuration.name}", Boolean::class.javaObjectType) + + project.dependencies.apply { + attributesSchema { + it.attribute(expectPlatformAttribute) + } + + artifactTypes.getByName("jar") { + it.attributes.attribute(expectPlatformAttribute, false) + } +// artifactTypes.getByName("java-classes-directory") { +// it.attributes.attribute(expectPlatformAttribute, false) +// } + + registerTransform(ExpectPlatformTransform::class.java) { spec -> + spec.from.attribute(expectPlatformAttribute, false) + spec.to.attribute(expectPlatformAttribute, true) + + spec.parameters { + it.platformName.set(platformName) + } + } + } + + configuration.attributes { + it.attribute(expectPlatformAttribute, true) + } + } + } \ No newline at end of file diff --git a/src/main/kotlin/xyz/wagyourtail/unimined/expect/ExpectPlatformPlugin.kt b/src/main/kotlin/xyz/wagyourtail/unimined/expect/ExpectPlatformPlugin.kt index 0455856..67525ae 100644 --- a/src/main/kotlin/xyz/wagyourtail/unimined/expect/ExpectPlatformPlugin.kt +++ b/src/main/kotlin/xyz/wagyourtail/unimined/expect/ExpectPlatformPlugin.kt @@ -1,3 +1,13 @@ package xyz.wagyourtail.unimined.expect -class ExpectPlatformPlugin +import org.gradle.api.Plugin +import org.gradle.api.Project + +class ExpectPlatformPlugin : Plugin { + + override fun apply(target: Project) { + target.apply(mapOf("plugin" to "java")) + target.extensions.create("expectPlatform", ExpectPlatformExtension::class.java, target) + } + +} diff --git a/src/main/kotlin/xyz/wagyourtail/unimined/expect/TransformPlatform.kt b/src/main/kotlin/xyz/wagyourtail/unimined/expect/TransformPlatform.kt index a85ab8c..0a54f14 100644 --- a/src/main/kotlin/xyz/wagyourtail/unimined/expect/TransformPlatform.kt +++ b/src/main/kotlin/xyz/wagyourtail/unimined/expect/TransformPlatform.kt @@ -1,4 +1,129 @@ package xyz.wagyourtail.unimined.expect +import org.objectweb.asm.* +import java.nio.file.Path +import kotlin.io.path.* +import kotlin.math.max + object TransformPlatform { + + @OptIn(ExperimentalPathApi::class) + fun expectPlatform(inputRoot: Path, outputRoot: Path, platformName: String) { + for (path in inputRoot.walk()) { + if (path.isDirectory()) { + outputRoot.resolve(inputRoot.relativize(path).toString()).createDirectories() + } else { + if (path.extension == "class") { + val output = outputRoot.resolve(inputRoot.relativize(path).toString()) + val reader = ClassReader(path.readBytes()) + val writer = ClassWriter(reader, 0) + lateinit var className: String + + reader.accept(object : ClassVisitor(Opcodes.ASM9, writer) { + + override fun visit( + version: Int, + access: Int, + name: String, + signature: String?, + superName: String?, + interfaces: Array? + ) { + super.visit(version, access, name, signature, superName, interfaces) + className = name + } + + override fun visitMethod( + access: Int, + name: String, + descriptor: String, + signature: String?, + exceptions: Array? + ): MethodVisitor { + var hasExpectPlatforms: Boolean = false + var platformOverride: String? = null + val superDelegate = super.visitMethod(access, name, descriptor, signature, exceptions) + + return object : MethodVisitor(api, superDelegate) { + override fun visitAnnotation(descriptor: String?, visible: Boolean): AnnotationVisitor { + if (descriptor == "Lxyz/wagyourtail/unimined/expect/annotation/ExpectPlatform;") { + hasExpectPlatforms = true + return object : AnnotationVisitor(api, super.visitAnnotation(descriptor, visible)) { + override fun visitArray(name: String?): AnnotationVisitor { + if (name == "platforms") { + return object : AnnotationVisitor(api, super.visitArray(name)) { + override fun visitAnnotation( + name: String?, + descriptor: String? + ): AnnotationVisitor { + return object : AnnotationVisitor(api, super.visitAnnotation(name, descriptor)) { + var isPlatform = false + var target: String? = null + + override fun visit(name: String?, value: Any?) { + if (name == "name") { + if (value == platformName) { + isPlatform = true + } + } else if (name == "target") { + target = value as String + } + if (isPlatform && target != null) { + platformOverride = target + } + super.visit(name, value) + } + } + } + } + } + return super.visitArray(name) + } + } + } + return super.visitAnnotation(descriptor, visible) + } + + override fun visitCode() { + super.visitCode() + if (hasExpectPlatforms) { + mv = null + } + } + + override fun visitEnd() { + if (hasExpectPlatforms) { + if (access and Opcodes.ACC_STATIC == 0 || access and Opcodes.ACC_PUBLIC == 0) { + throw IllegalStateException("ExpectPlatform can only be applied to public static methods, found ${className};${name};${descriptor}") + } + val platformClassName = platformOverride ?: "${className.substringBeforeLast("/")}/${platformName}/${className.substringAfterLast("/")}Impl" + + superDelegate.visitCode() + var i = 0 + for (arg in Type.getArgumentTypes(descriptor)) { + superDelegate.visitVarInsn(arg.getOpcode(Opcodes.ILOAD), i) + i += arg.size + } + superDelegate.visitMethodInsn(Opcodes.INVOKESTATIC, platformClassName, name, descriptor, false) + val returnType = Type.getReturnType(descriptor) + superDelegate.visitInsn(returnType.getOpcode(Opcodes.IRETURN)) + superDelegate.visitMaxs(max(i, returnType.size), i) + superDelegate.visitEnd() + } + } + + } + } + }, 0) + output.createParentDirectories() + output.writeBytes(writer.toByteArray()) + } else { + outputRoot.resolve(inputRoot.relativize(path).toString()).writeBytes(path.readBytes()) + } + } + } + } + + + } \ No newline at end of file diff --git a/src/main/kotlin/xyz/wagyourtail/unimined/expect/task/ExpectPlatformFiles.kt b/src/main/kotlin/xyz/wagyourtail/unimined/expect/task/ExpectPlatformFiles.kt index d8b7614..0eaf951 100644 --- a/src/main/kotlin/xyz/wagyourtail/unimined/expect/task/ExpectPlatformFiles.kt +++ b/src/main/kotlin/xyz/wagyourtail/unimined/expect/task/ExpectPlatformFiles.kt @@ -1,3 +1,87 @@ package xyz.wagyourtail.unimined.expect.task -class ExpectPlatformFiles +import org.gradle.api.file.FileCollection +import org.gradle.api.internal.ConventionTask +import org.gradle.api.tasks.InputFiles +import org.gradle.api.tasks.Internal +import org.gradle.api.tasks.TaskAction +import xyz.wagyourtail.jvmdg.util.FinalizeOnRead +import xyz.wagyourtail.jvmdg.util.MustSet +import xyz.wagyourtail.unimined.expect.ExpectPlatformExtension +import xyz.wagyourtail.unimined.expect.TransformPlatform +import xyz.wagyourtail.unimined.expect.transform.ExpectPlatformParams +import xyz.wagyourtail.unimined.expect.utils.openZipFileSystem +import java.io.File +import java.nio.file.FileSystem +import kotlin.io.path.exists +import kotlin.io.path.isDirectory +import kotlin.io.path.name + +abstract class ExpectPlatformFiles : ConventionTask(), ExpectPlatformParams { + + @get:Internal + protected val ep by lazy { + project.extensions.getByType(ExpectPlatformExtension::class.java) + } + + @get:InputFiles + var inputCollection: FileCollection by FinalizeOnRead(MustSet()) + + @get:Internal + val outputMap: Map + get() = inputCollection.associateWith { temporaryDir.resolve(it.name) } + + /** + * this is the true output, gradle just doesn't have a + * \@OutputDirectoriesAndFiles + */ + @get:Internal + val outputCollection: FileCollection by lazy { + val fd = inputCollection.map { it to temporaryDir.resolve(it.name) } + + outputs.dirs(*fd.filter { it.first.isDirectory }.map { it.second }.toTypedArray()) + outputs.files(*fd.filter { it.first.isFile }.map { it.second }.toTypedArray()) + + outputs.files + } + + @TaskAction + fun doDowngrade() { + var toDowngrade = inputCollection.map { it.toPath() }.filter { it.exists() } + + val fileSystems = mutableSetOf() + + try { + + outputs.files.forEach { it.deleteRecursively() } + + val downgraded = toDowngrade.map { temporaryDir.resolve(it.name) }.map { + if (it.extension == "jar" || it.extension == "zip") { + val fs = it.toPath().openZipFileSystem(mapOf("create" to true)) + fileSystems.add(fs) + fs.getPath("/") + } else it.toPath() + } + + toDowngrade = toDowngrade.map { + if (it.isDirectory()) it else run { + val fs = it.openZipFileSystem() + fileSystems.add(fs) + fs.getPath("/") + } + } + for (i in toDowngrade.indices) { + val input = toDowngrade[i] + val output = downgraded[i] + TransformPlatform.expectPlatform(input, output, platformName.get()) + } + } finally { + fileSystems.forEach { it.close() } + } + } + + fun forInputs(files: Set): FileCollection { + return project.files(outputMap.filterKeys { it in files }.values) + } + +} \ No newline at end of file diff --git a/src/main/kotlin/xyz/wagyourtail/unimined/expect/task/ExpectPlatformJar.kt b/src/main/kotlin/xyz/wagyourtail/unimined/expect/task/ExpectPlatformJar.kt index de0c02e..4aad678 100644 --- a/src/main/kotlin/xyz/wagyourtail/unimined/expect/task/ExpectPlatformJar.kt +++ b/src/main/kotlin/xyz/wagyourtail/unimined/expect/task/ExpectPlatformJar.kt @@ -1,73 +1,53 @@ @file:Suppress("LeakingThis") -package xyz.wagyourtail.jvmdg.gradle.task +package xyz.wagyourtail.unimined.expect.task import org.gradle.api.file.FileCollection -import org.gradle.api.file.RegularFileProperty -import org.gradle.api.tasks.* +import org.gradle.api.provider.Provider +import org.gradle.api.tasks.InputFiles +import org.gradle.api.tasks.TaskAction import org.gradle.jvm.tasks.Jar -import xyz.wagyourtail.jvmdg.ClassDowngrader -import xyz.wagyourtail.jvmdg.compile.ZipDowngrader -import xyz.wagyourtail.jvmdg.gradle.flags.DowngradeFlags -import xyz.wagyourtail.jvmdg.gradle.JVMDowngraderExtension -import xyz.wagyourtail.jvmdg.gradle.flags.toFlags -import xyz.wagyourtail.jvmdg.util.* -import java.nio.file.StandardOpenOption -import kotlin.io.path.outputStream +import xyz.wagyourtail.jvmdg.util.FinalizeOnRead +import xyz.wagyourtail.jvmdg.util.MustSet +import xyz.wagyourtail.unimined.expect.ExpectPlatformExtension +import xyz.wagyourtail.unimined.expect.TransformPlatform +import xyz.wagyourtail.unimined.expect.transform.ExpectPlatformParams +import xyz.wagyourtail.unimined.expect.utils.openZipFileSystem -abstract class DowngradeJar : Jar(), DowngradeFlags { +abstract class ExpectPlatformJar : Jar(), ExpectPlatformParams { - private val jvmdg by lazy { - project.extensions.getByType(JVMDowngraderExtension::class.java) + private val ep by lazy { + project.extensions.getByType(ExpectPlatformExtension::class.java) } @get:InputFiles - @get:Optional - var classpath: FileCollection by FinalizeOnRead(LazyMutable { - project.extensions.getByType(SourceSetContainer::class.java).getByName("main").compileClasspath - }) - - @get:InputFile - abstract val inputFile: RegularFileProperty - - init { - group = "JVMDowngrader" - description = "Downgrades the jar to the specified version" - - downgradeTo.convention(jvmdg.downgradeTo).finalizeValueOnRead() - apiJar.convention(jvmdg.apiJar).finalizeValueOnRead() - quiet.convention(jvmdg.quiet).finalizeValueOnRead() - debug.convention(jvmdg.debug).finalizeValueOnRead() - debugSkipStubs.convention(jvmdg.debugSkipStubs).finalizeValueOnRead() - - } + var inputFiles: FileCollection by FinalizeOnRead(MustSet()) @TaskAction fun doDowngrade() { - val tempOutput = temporaryDir.resolve("downgradedInput.jar") - tempOutput.deleteIfExists() - - ClassDowngrader.downgradeTo(this.toFlags()).use { - ZipDowngrader.downgradeZip( - it, - inputFile.asFile.get().toPath(), - classpath.files.map { it.toURI().toURL() }.toSet(), - tempOutput.toPath() - ) - } + for (input in inputFiles) { + if (input.isDirectory) { + val output = temporaryDir.resolve(input.name + "-expect-platform") + TransformPlatform.expectPlatform(input.toPath(), output.toPath(), platformName.get()) + from(output) + } else if (input.extension == "jar") { + val output = temporaryDir.resolve(input.nameWithoutExtension + "-expect-platform." + input.extension) + input.toPath().openZipFileSystem().use { inputFs -> + output.toPath().openZipFileSystem(mapOf("create" to true)).use { outputFs -> + TransformPlatform.expectPlatform( + inputFs.getPath("/"), + outputFs.getPath("/"), + platformName.get() + ) + } + } + from(project.zipTree(output)) + } else if (input.exists()) { + throw IllegalStateException("ExpectPlatformJar: $input is not a directory or jar file") - inputFile.asFile.get().toPath().readZipInputStreamFor("META-INF/MANIFEST.MF", false) { inp -> - // write to temp file - val inpTmp = temporaryDir.toPath().resolve("input-manifest.MF") - inpTmp.outputStream(StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING).use { out -> - inp.copyTo(out) - } - this.manifest { - it.from(inpTmp) } } - from(project.zipTree(tempOutput)) copy() } diff --git a/src/main/kotlin/xyz/wagyourtail/unimined/expect/transform/ExpectPlatformParams.kt b/src/main/kotlin/xyz/wagyourtail/unimined/expect/transform/ExpectPlatformParams.kt index 9fe3ced..5309702 100644 --- a/src/main/kotlin/xyz/wagyourtail/unimined/expect/transform/ExpectPlatformParams.kt +++ b/src/main/kotlin/xyz/wagyourtail/unimined/expect/transform/ExpectPlatformParams.kt @@ -1,4 +1,12 @@ package xyz.wagyourtail.unimined.expect.transform -class ExpectPlatformParams { +import org.gradle.api.artifacts.transform.TransformParameters +import org.gradle.api.provider.Property +import org.gradle.api.tasks.Input + +interface ExpectPlatformParams : TransformParameters { + + @get:Input + val platformName: Property + } \ No newline at end of file diff --git a/src/main/kotlin/xyz/wagyourtail/unimined/expect/transform/ExpectPlatformTransform.kt b/src/main/kotlin/xyz/wagyourtail/unimined/expect/transform/ExpectPlatformTransform.kt index b6fa6a0..9d3509b 100644 --- a/src/main/kotlin/xyz/wagyourtail/unimined/expect/transform/ExpectPlatformTransform.kt +++ b/src/main/kotlin/xyz/wagyourtail/unimined/expect/transform/ExpectPlatformTransform.kt @@ -1,4 +1,41 @@ package xyz.wagyourtail.unimined.expect.transform -class ExpectPlatformTransform { +import org.gradle.api.artifacts.transform.InputArtifact +import org.gradle.api.artifacts.transform.TransformAction +import org.gradle.api.artifacts.transform.TransformOutputs +import org.gradle.api.file.FileCollection +import org.gradle.api.file.FileSystemLocation +import org.gradle.api.provider.Provider +import xyz.wagyourtail.unimined.expect.TransformPlatform +import xyz.wagyourtail.unimined.expect.utils.openZipFileSystem +import java.net.URI +import java.nio.file.FileSystem +import java.nio.file.FileSystems +import java.nio.file.Path +import java.util.zip.ZipOutputStream +import kotlin.io.path.exists +import kotlin.io.path.outputStream + +abstract class ExpectPlatformTransform : TransformAction { + + @get:InputArtifact + abstract val inputArtifact: Provider + + override fun transform(outputs: TransformOutputs) { + val input = inputArtifact.get().asFile + if (input.isDirectory) { + val output = outputs.dir(input.name + "-expect-platform") + TransformPlatform.expectPlatform(input.toPath(), output.toPath(), parameters.platformName.get()) + } else if (input.extension == "jar") { + val output = outputs.file(input.nameWithoutExtension + "-expect-platform." + input.extension) + input.toPath().openZipFileSystem().use { inputFs -> + output.toPath().openZipFileSystem(mapOf("create" to true)).use { outputFs -> + TransformPlatform.expectPlatform(inputFs.getPath("/"), outputFs.getPath("/"), parameters.platformName.get()) + } + } + } else { + outputs.file(input) + } + } + } \ No newline at end of file diff --git a/src/main/kotlin/xyz/wagyourtail/unimined/expect/utils/Utils.kt b/src/main/kotlin/xyz/wagyourtail/unimined/expect/utils/Utils.kt index d248cf4..5490521 100644 --- a/src/main/kotlin/xyz/wagyourtail/unimined/expect/utils/Utils.kt +++ b/src/main/kotlin/xyz/wagyourtail/unimined/expect/utils/Utils.kt @@ -1,2 +1,19 @@ package xyz.wagyourtail.unimined.expect.utils +import java.net.URI +import java.nio.file.FileSystem +import java.nio.file.FileSystems +import java.nio.file.Path +import java.util.zip.ZipOutputStream +import kotlin.io.path.exists +import kotlin.io.path.outputStream + +fun Path.openZipFileSystem(args: Map = mapOf()): FileSystem { + if (!exists() && args["create"] == true) { + ZipOutputStream(outputStream()).use { stream -> + stream.closeEntry() + } + } + + return FileSystems.newFileSystem(URI.create("jar:${toUri()}"), args, null) +} \ No newline at end of file