diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..2ca3795 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,40 @@ +# Automatically build the project and run any configured tests for every push +# and submitted pull request. This can help catch issues that only occur on +# certain platforms or Java versions, and provides a first line of defence +# against bad commits. + +name: build +on: [pull_request, push] + +jobs: + build: + strategy: + matrix: + # Use these Java versions + java: [ + 17, # Current Java LTS & minimum supported by Minecraft + ] + # and run on both Linux and Windows + os: [ubuntu-22.04, windows-2022] + runs-on: ${{ matrix.os }} + steps: + - name: checkout repository + uses: actions/checkout@v3 + - name: validate gradle wrapper + uses: gradle/wrapper-validation-action@v1 + - name: setup jdk ${{ matrix.java }} + uses: actions/setup-java@v3 + with: + java-version: ${{ matrix.java }} + distribution: 'microsoft' + - name: make gradle wrapper executable + if: ${{ runner.os != 'Windows' }} + run: chmod +x ./gradlew + - name: build + run: ./gradlew build + - name: capture build artifacts + if: ${{ runner.os == 'Linux' && matrix.java == '17' }} # Only upload artifacts built from latest java on one OS + uses: actions/upload-artifact@v3 + with: + name: Artifacts + path: build/libs/ \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c476faf --- /dev/null +++ b/.gitignore @@ -0,0 +1,40 @@ +# gradle + +.gradle/ +build/ +out/ +classes/ + +# eclipse + +*.launch + +# idea + +.idea/ +*.iml +*.ipr +*.iws + +# vscode + +.settings/ +.vscode/ +bin/ +.classpath +.project + +# macos + +*.DS_Store + +# fabric + +run/ + +# java + +hs_err_*.log +replay_*.log +*.hprof +*.jfr diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..ae2916d --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Moulberry + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..5774f13 --- /dev/null +++ b/build.gradle @@ -0,0 +1,85 @@ +plugins { + id 'fabric-loom' version '1.6-SNAPSHOT' + id "com.vanniktech.maven.publish" version "0.28.0" +} + +version = "1.0.0" +group = project.maven_group + +base { + archivesName = project.archives_base_name +} + +repositories { + maven { + url = "https://jitpack.io" + } + mavenCentral() +} + +dependencies { + // To change the versions see the gradle.properties file + minecraft "com.mojang:minecraft:${project.minecraft_version}" + mappings loom.officialMojangMappings() + modImplementation "net.fabricmc:fabric-loader:${project.loader_version}" + +} + +tasks.withType(JavaCompile).configureEach { + it.options.release = 17 +} + +java { + // Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task + // if it is present. + // If you remove this line, sources will not be generated. + withSourcesJar() + + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 +} + +jar { + manifest { + attributes( + "Fabric-Loom-Remap": "true" + ) + } +} + +import com.vanniktech.maven.publish.JavaLibrary +import com.vanniktech.maven.publish.JavadocJar +import com.vanniktech.maven.publish.SonatypeHost + +mavenPublishing { + configure(new JavaLibrary(new JavadocJar.Javadoc(), true)) + + publishToMavenCentral(SonatypeHost.CENTRAL_PORTAL) + + signAllPublications() + + coordinates("com.moulberry", "mixinconstraints", version) + + pom { + name = 'MixinConstraints' + description = 'Library to enable/disable mixins using annotations' + url = "https://github.com/Moulberry/MixinConstraints" + + licenses { + license { + name = 'MIT License' + url = 'https://opensource.org/license/mit' + } + } + developers { + developer { + name = 'Moulberry' + } + } + scm { + url = "https://github.com/Moulberry/MixinConstraints/" + connection = "scm:git:git://github.com/Moulberry/MixinConstraints.git" + developerConnection = "scm:git:ssh://git@github.com/Moulberry/MixinConstraints.git" + } + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..e179af1 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,16 @@ +# Done to increase the memory available to gradle. +org.gradle.jvmargs=-Xmx1G +org.gradle.parallel=true + +# Fabric Properties +# check these on https://fabricmc.net/develop +minecraft_version=1.20.6 +yarn_mappings=1.20.6+build.1 +loader_version=0.15.11 + +# Mod Properties +maven_group=com.moulberry.axiomclientapi +archives_base_name=axiomclientapi + +# Dependencies +fabric_version=0.98.0+1.20.6 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..033e24c Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..a80b22c --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..fcb6fca --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/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##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && 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=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=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, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +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/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..6689b85 --- /dev/null +++ b/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/settings.gradle b/settings.gradle new file mode 100644 index 0000000..3198616 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,11 @@ +pluginManagement { + repositories { + maven { + name = 'Fabric' + url = 'https://maven.fabricmc.net/' + } + mavenCentral() + gradlePluginPortal() + } +} + diff --git a/src/main/java/com/moulberry/mixinconstraints/ConstraintsMixinPlugin.java b/src/main/java/com/moulberry/mixinconstraints/ConstraintsMixinPlugin.java new file mode 100644 index 0000000..1b31b0e --- /dev/null +++ b/src/main/java/com/moulberry/mixinconstraints/ConstraintsMixinPlugin.java @@ -0,0 +1,51 @@ +package com.moulberry.mixinconstraints; + +import com.moulberry.mixinconstraints.mixin.MixinConstraintsBootstrap; +import org.objectweb.asm.tree.ClassNode; +import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; + +import java.util.List; +import java.util.Set; + +public class ConstraintsMixinPlugin implements IMixinConfigPlugin { + + private String mixinPackage; + + @Override + public boolean shouldApplyMixin(String targetClassName, String mixinClassName) { + if (this.mixinPackage != null && !mixinClassName.startsWith(this.mixinPackage)) { + return true; + } + return MixinConstraints.shouldApplyMixin(targetClassName, mixinClassName); + } + + @Override + public void onLoad(String mixinPackage) { + this.mixinPackage = mixinPackage; + MixinConstraintsBootstrap.init(mixinPackage); + } + + @Override + public String getRefMapperConfig() { + return null; + } + + + @Override + public void acceptTargets(Set myTargets, Set otherTargets) { + } + + @Override + public List getMixins() { + return null; + } + + @Override + public void preApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { + } + + @Override + public void postApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { + } +} diff --git a/src/main/java/com/moulberry/mixinconstraints/MixinConstraints.java b/src/main/java/com/moulberry/mixinconstraints/MixinConstraints.java new file mode 100644 index 0000000..4401657 --- /dev/null +++ b/src/main/java/com/moulberry/mixinconstraints/MixinConstraints.java @@ -0,0 +1,43 @@ +package com.moulberry.mixinconstraints; + +import com.moulberry.mixinconstraints.checker.AnnotationChecker; +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.ClassNode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.spongepowered.asm.service.MixinService; + +import java.io.IOException; + +public class MixinConstraints { + + public static final Logger LOGGER = LoggerFactory.getLogger("mixinconstraints"); + public static boolean VERBOSE = "true".equals(System.getProperty("mixinconstraints.verbose")); + + public static boolean shouldApplyMixin(String targetClassName, String mixinClassName) { + try { + // Use classNode instead of Class.forName to avoid loading at the wrong time + ClassNode classNode = MixinService.getService().getBytecodeProvider().getClassNode(mixinClassName); + + if (VERBOSE) { + LOGGER.info("Checking class-level mixin constraints for {}", mixinClassName); + } + + if (classNode.visibleAnnotations != null) { + for (AnnotationNode node : classNode.visibleAnnotations) { + if (!AnnotationChecker.checkAnnotationNode(node)) { + if (VERBOSE) { + LOGGER.warn("Preventing application of mixin {} due to failing constraint", mixinClassName); + } + return false; + } + } + } + + return true; + } catch (ClassNotFoundException | IOException e) { + throw new RuntimeException(e); + } + } + +} diff --git a/src/main/java/com/moulberry/mixinconstraints/annotations/IfDevEnvironment.java b/src/main/java/com/moulberry/mixinconstraints/annotations/IfDevEnvironment.java new file mode 100644 index 0000000..2a6912e --- /dev/null +++ b/src/main/java/com/moulberry/mixinconstraints/annotations/IfDevEnvironment.java @@ -0,0 +1,14 @@ +package com.moulberry.mixinconstraints.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD}) +public @interface IfDevEnvironment { + + boolean negate() default false; + +} diff --git a/src/main/java/com/moulberry/mixinconstraints/annotations/IfMinecraftVersion.java b/src/main/java/com/moulberry/mixinconstraints/annotations/IfMinecraftVersion.java new file mode 100644 index 0000000..03b3969 --- /dev/null +++ b/src/main/java/com/moulberry/mixinconstraints/annotations/IfMinecraftVersion.java @@ -0,0 +1,16 @@ +package com.moulberry.mixinconstraints.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD}) +public @interface IfMinecraftVersion { + + String minVersion() default ""; + String maxVersion() default ""; + boolean negate() default false; + +} diff --git a/src/main/java/com/moulberry/mixinconstraints/annotations/IfModAbsent.java b/src/main/java/com/moulberry/mixinconstraints/annotations/IfModAbsent.java new file mode 100644 index 0000000..80e6c8f --- /dev/null +++ b/src/main/java/com/moulberry/mixinconstraints/annotations/IfModAbsent.java @@ -0,0 +1,17 @@ +package com.moulberry.mixinconstraints.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD}) +public @interface IfModAbsent { + + String value(); + String[] aliases() default {}; + String minVersion() default ""; + String maxVersion() default ""; + +} diff --git a/src/main/java/com/moulberry/mixinconstraints/annotations/IfModLoaded.java b/src/main/java/com/moulberry/mixinconstraints/annotations/IfModLoaded.java new file mode 100644 index 0000000..1209a53 --- /dev/null +++ b/src/main/java/com/moulberry/mixinconstraints/annotations/IfModLoaded.java @@ -0,0 +1,17 @@ +package com.moulberry.mixinconstraints.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD}) +public @interface IfModLoaded { + + String value(); + String[] aliases() default {}; + String minVersion() default ""; + String maxVersion() default ""; + +} diff --git a/src/main/java/com/moulberry/mixinconstraints/checker/AnnotationChecker.java b/src/main/java/com/moulberry/mixinconstraints/checker/AnnotationChecker.java new file mode 100644 index 0000000..d9339d7 --- /dev/null +++ b/src/main/java/com/moulberry/mixinconstraints/checker/AnnotationChecker.java @@ -0,0 +1,113 @@ +package com.moulberry.mixinconstraints.checker; + +import com.moulberry.mixinconstraints.MixinConstraints; +import com.moulberry.mixinconstraints.annotations.IfDevEnvironment; +import com.moulberry.mixinconstraints.annotations.IfMinecraftVersion; +import com.moulberry.mixinconstraints.annotations.IfModAbsent; +import com.moulberry.mixinconstraints.annotations.IfModLoaded; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.AnnotationNode; + +import java.util.List; + +public class AnnotationChecker { + + private static final String IF_MOD_LOADED_DESC = Type.getDescriptor(IfModLoaded.class); + private static final String IS_MOD_ABSENT_DESC = Type.getDescriptor(IfModAbsent.class); + private static final String IF_DEV_ENVIRONMENT_DESC = Type.getDescriptor(IfDevEnvironment.class); + private static final String IF_MINECRAFT_VERSION_DESC = Type.getDescriptor(IfMinecraftVersion.class); + + public static boolean isConstraintAnnotationNode(AnnotationNode node) { + return IF_MOD_LOADED_DESC.equals(node.desc) || IS_MOD_ABSENT_DESC.equals(node.desc) || + IF_DEV_ENVIRONMENT_DESC.equals(node.desc) || IF_MINECRAFT_VERSION_DESC.equals(node.desc); + } + + public static boolean checkAnnotationNode(AnnotationNode node) { + if (IF_MOD_LOADED_DESC.equals(node.desc)) { + String value = getAnnotationValue(node, "value", ""); + if (value.isEmpty()) throw new IllegalArgumentException("modid must not be empty"); + + List aliases = getAnnotationValue(node, "aliases", List.of()); + String minVersion = getAnnotationValue(node, "minVersion", null); + String maxVersion = getAnnotationValue(node, "maxVersion", null); + + boolean pass = ConstraintChecker.checkModLoaded(value, aliases, minVersion, maxVersion); + + if (MixinConstraints.VERBOSE) { + String result = pass ? "PASS" : "FAILED"; + MixinConstraints.LOGGER.info("@IfModLoaded(value={}, minVersion={}, maxVersion={}) {}", value, minVersion, maxVersion, result); + } + + return pass; + } else if (IS_MOD_ABSENT_DESC.equals(node.desc)) { + String value = getAnnotationValue(node, "value", ""); + if (value.isEmpty()) throw new IllegalArgumentException("modid must not be empty"); + + List aliases = getAnnotationValue(node, "aliases", List.of()); + String minVersion = getAnnotationValue(node, "minVersion", null); + String maxVersion = getAnnotationValue(node, "maxVersion", null); + + boolean pass = ConstraintChecker.checkModAbsent(value, aliases, minVersion, maxVersion); + + if (MixinConstraints.VERBOSE) { + String result = pass ? "PASS" : "FAILED"; + MixinConstraints.LOGGER.info("@IfModAbsent(value={}, minVersion={}, maxVersion={}) {}", value, minVersion, maxVersion, result); + } + + return pass; + } else if (IF_DEV_ENVIRONMENT_DESC.equals(node.desc)) { + boolean negate = getAnnotationValue(node, "negate", false); + + boolean pass = ConstraintChecker.checkDevEnvironment() != negate; + + if (MixinConstraints.VERBOSE) { + String result = pass ? "PASS" : "FAILED"; + MixinConstraints.LOGGER.info("@IfDevEnvironment(negate={}) {}", negate, result); + } + + return pass; + } else if (IF_MINECRAFT_VERSION_DESC.equals(node.desc)) { + String minVersion = getAnnotationValue(node, "minVersion", null); + String maxVersion = getAnnotationValue(node, "maxVersion", null); + boolean negate = getAnnotationValue(node, "negate", false); + + boolean pass = ConstraintChecker.checkMinecraftVersion(minVersion, maxVersion) != negate; + + if (MixinConstraints.VERBOSE) { + String result = pass ? "PASS" : "FAILED"; + MixinConstraints.LOGGER.info("@IfMinecraftVersion(minVersion={}, maxVersion={}, negate={}) {}", minVersion, maxVersion, negate, result); + } + + return pass; + } + return true; + } + + private static T getAnnotationValue(AnnotationNode annotation, String key, T defaultValue) { + boolean getNextValue = false; + boolean skipNextValue = false; + + if (annotation == null || annotation.values == null) { + return defaultValue; + } + + // Keys and value are stored in successive pairs, search for the key and if found return the following entry + for (Object value : annotation.values) { + if (skipNextValue) { + skipNextValue = false; + continue; + } + if (getNextValue) { + return (T) value; + } + if (value.equals(key)) { + getNextValue = true; + } else { + skipNextValue = true; + } + } + + return defaultValue; + } + +} diff --git a/src/main/java/com/moulberry/mixinconstraints/checker/ConstraintChecker.java b/src/main/java/com/moulberry/mixinconstraints/checker/ConstraintChecker.java new file mode 100644 index 0000000..4788f9f --- /dev/null +++ b/src/main/java/com/moulberry/mixinconstraints/checker/ConstraintChecker.java @@ -0,0 +1,84 @@ +package com.moulberry.mixinconstraints.checker; + +import net.fabricmc.loader.api.FabricLoader; +import net.fabricmc.loader.api.ModContainer; +import net.fabricmc.loader.api.Version; +import net.fabricmc.loader.api.VersionParsingException; + +import java.util.Optional; + +public class ConstraintChecker { + + /** + * Check if *ANY* of the modIds provided are loaded + */ + public static boolean checkModLoaded(String main, Iterable aliases, String minVersion, String maxVersion) { + if (isModLoadedWithinVersion(main, minVersion, maxVersion)) { + return true; + } + + for (String modId : aliases) { + if (isModLoadedWithinVersion(modId, minVersion, maxVersion)) { + return true; + } + } + + return false; + } + + /** + * Check if *ALL* the modIds provided are absent + */ + public static boolean checkModAbsent(String main, Iterable modIds, String minVersion, String maxVersion) { + return !checkModLoaded(main, modIds, minVersion, maxVersion); + } + + public static boolean checkDevEnvironment() { + return FabricLoader.getInstance().isDevelopmentEnvironment(); + } + + public static boolean checkMinecraftVersion(String minVersion, String maxVersion) { + return isModLoadedWithinVersion("minecraft", minVersion, maxVersion); + } + + private static boolean isModLoadedWithinVersion(String modId, String minVersion, String maxVersion) { + Optional modContainer = FabricLoader.getInstance().getModContainer(modId); + if (modContainer.isEmpty()) { + return false; + } + + return isVersionInRange(modContainer.get().getMetadata().getVersion(), minVersion, maxVersion); + } + + private static boolean isVersionInRange(Version version, String minVersion, String maxVersion) { + Version min = minVersion == null || minVersion.isEmpty() ? null : tryParseVersion(minVersion); + Version max = maxVersion == null || maxVersion.isEmpty() ? null : tryParseVersion(maxVersion); + + // Ensure range is valid (min <= max) + if (min != null && max != null && min.compareTo(max) > 0) { + throw new IllegalArgumentException("invalid range: minVersion (" + minVersion + ") > maxVersion (" + maxVersion + ")"); + } + + // Check version >= min + if (min != null && version.compareTo(min) < 0) { + return false; + } + + // Check version <= max + if (max != null && version.compareTo(max) > 0) { + return false; + } + + return true; + } + + private static Version tryParseVersion(String version) { + try { + return Version.parse(version); + } catch (VersionParsingException e) { + System.err.println("Invalid version string: " + version + "..."); + throw new RuntimeException(e); + } + } + +} diff --git a/src/main/java/com/moulberry/mixinconstraints/mixin/ConstraintsMixinExtension.java b/src/main/java/com/moulberry/mixinconstraints/mixin/ConstraintsMixinExtension.java new file mode 100644 index 0000000..09b1765 --- /dev/null +++ b/src/main/java/com/moulberry/mixinconstraints/mixin/ConstraintsMixinExtension.java @@ -0,0 +1,45 @@ +package com.moulberry.mixinconstraints.mixin; + +import com.llamalad7.mixinextras.lib.apache.commons.tuple.Pair; +import com.llamalad7.mixinextras.utils.MixinInternals; +import org.objectweb.asm.tree.ClassNode; +import org.spongepowered.asm.mixin.MixinEnvironment; +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; +import org.spongepowered.asm.mixin.transformer.ext.IExtension; +import org.spongepowered.asm.mixin.transformer.ext.ITargetClassContext; + +public class ConstraintsMixinExtension implements IExtension { + + private final String mixinPackage; + + public ConstraintsMixinExtension(String mixinPackage) { + if (!mixinPackage.endsWith(".")) { + mixinPackage += "."; + } + this.mixinPackage = mixinPackage; + } + + @Override + public boolean checkActive(MixinEnvironment environment) { + return true; + } + + @Override + public void preApply(ITargetClassContext context) { + for (Pair pair : MixinInternals.getMixinsFor(context)) { + if (pair.getLeft().getConfig().getMixinPackage().equals(this.mixinPackage)) { + MixinTransformer.transform(pair.getLeft(), pair.getRight()); + } + } + } + + @Override + public void postApply(ITargetClassContext context) { + + } + + @Override + public void export(MixinEnvironment env, String name, boolean force, ClassNode classNode) { + + } +} diff --git a/src/main/java/com/moulberry/mixinconstraints/mixin/MixinConstraintsBootstrap.java b/src/main/java/com/moulberry/mixinconstraints/mixin/MixinConstraintsBootstrap.java new file mode 100644 index 0000000..254f631 --- /dev/null +++ b/src/main/java/com/moulberry/mixinconstraints/mixin/MixinConstraintsBootstrap.java @@ -0,0 +1,19 @@ +package com.moulberry.mixinconstraints.mixin; + +import com.llamalad7.mixinextras.utils.MixinInternals; + +import java.util.HashSet; +import java.util.Set; + +public class MixinConstraintsBootstrap { + + private static final Set initializedMixinPackages = new HashSet<>(); + + public static void init(String mixinPackage) { + if (!initializedMixinPackages.contains(mixinPackage)) { + initializedMixinPackages.add(mixinPackage); + MixinInternals.registerExtension(new ConstraintsMixinExtension(mixinPackage), true); + } + } + +} diff --git a/src/main/java/com/moulberry/mixinconstraints/mixin/MixinTransformer.java b/src/main/java/com/moulberry/mixinconstraints/mixin/MixinTransformer.java new file mode 100644 index 0000000..bd06075 --- /dev/null +++ b/src/main/java/com/moulberry/mixinconstraints/mixin/MixinTransformer.java @@ -0,0 +1,57 @@ +package com.moulberry.mixinconstraints.mixin; + +import com.moulberry.mixinconstraints.checker.AnnotationChecker; +import com.moulberry.mixinconstraints.MixinConstraints; +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.ClassNode; +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; + +import java.util.Iterator; +import java.util.List; + +public class MixinTransformer { + + + public static void transform(IMixinInfo info, ClassNode classNode) { + if (MixinConstraints.VERBOSE) { + MixinConstraints.LOGGER.info("Checking inner mixin constraints for {}", info.getClassName()); + } + + if (classNode.visibleAnnotations != null) { + classNode.visibleAnnotations.removeIf(AnnotationChecker::isConstraintAnnotationNode); + } + + classNode.fields.removeIf(field -> shouldRemoveTarget("field " + field.name, field.visibleAnnotations)); + classNode.methods.removeIf(method -> shouldRemoveTarget("method " + method.name, method.visibleAnnotations)); + } + + private static boolean shouldRemoveTarget(String targetName, List annotations) { + if (annotations == null) { + return false; + } + + boolean remove = false; + + Iterator annotationIterator = annotations.iterator(); + while (annotationIterator.hasNext()) { + AnnotationNode annotationNode = annotationIterator.next(); + + if (!remove && !AnnotationChecker.checkAnnotationNode(annotationNode)) { + if (MixinConstraints.VERBOSE) { + MixinConstraints.LOGGER.warn("Preventing application of mixin {} due to failing constraint", targetName); + } + + remove = true; + annotationIterator.remove(); + } else if (AnnotationChecker.isConstraintAnnotationNode(annotationNode)) { + annotationIterator.remove(); + } + } + + return remove; + } + + + + +}