├── .gitignore ├── gradle.properties ├── settings.gradle.kts ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── tools ├── src │ └── main │ │ └── java │ │ └── io │ │ └── github │ │ └── tox1cozz │ │ └── cutter │ │ ├── CutterTarget.java │ │ ├── function │ │ ├── ByteSupplier.java │ │ ├── CharSupplier.java │ │ ├── FloatSupplier.java │ │ └── ShortSupplier.java │ │ ├── CutterTargetOnly.java │ │ └── Cutter.java └── build.gradle.kts ├── plugin ├── src │ └── main │ │ └── kotlin │ │ └── io │ │ └── github │ │ └── tox1cozz │ │ └── cutter │ │ ├── task │ │ ├── TargetTask.kt │ │ ├── cutter │ │ │ ├── ClassFile.kt │ │ │ ├── ClassTransformer.kt │ │ │ └── CutterTask.kt │ │ └── cutterjar │ │ │ └── CutterJarTask.kt │ │ ├── util │ │ ├── StringExtensions.kt │ │ └── FileExtensions.kt │ │ ├── configuration │ │ ├── ReplaceTokensConfiguration.kt │ │ ├── TargetConfiguration.kt │ │ ├── TargetTypeConfiguration.kt │ │ └── CutterExtension.kt │ │ └── CutterPlugin.kt └── build.gradle.kts ├── README.md ├── gradlew.bat └── gradlew /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | .gradle 3 | build -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | kotlin.code.style=official -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "cutter-gradle-plugin" 2 | include("tools", "plugin") -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tox1cozZ/cutter-gradle-plugin/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /tools/src/main/java/io/github/tox1cozz/cutter/CutterTarget.java: -------------------------------------------------------------------------------- 1 | package io.github.tox1cozz.cutter; 2 | 3 | public enum CutterTarget { 4 | CLIENT, SERVER, DEBUG 5 | } -------------------------------------------------------------------------------- /tools/src/main/java/io/github/tox1cozz/cutter/function/ByteSupplier.java: -------------------------------------------------------------------------------- 1 | package io.github.tox1cozz.cutter.function; 2 | 3 | @FunctionalInterface 4 | public interface ByteSupplier { 5 | 6 | byte getAsByte(); 7 | } -------------------------------------------------------------------------------- /tools/src/main/java/io/github/tox1cozz/cutter/function/CharSupplier.java: -------------------------------------------------------------------------------- 1 | package io.github.tox1cozz.cutter.function; 2 | 3 | @FunctionalInterface 4 | public interface CharSupplier { 5 | 6 | char getAsChar(); 7 | } -------------------------------------------------------------------------------- /tools/src/main/java/io/github/tox1cozz/cutter/function/FloatSupplier.java: -------------------------------------------------------------------------------- 1 | package io.github.tox1cozz.cutter.function; 2 | 3 | @FunctionalInterface 4 | public interface FloatSupplier { 5 | 6 | float getAsFloat(); 7 | } -------------------------------------------------------------------------------- /tools/src/main/java/io/github/tox1cozz/cutter/function/ShortSupplier.java: -------------------------------------------------------------------------------- 1 | package io.github.tox1cozz.cutter.function; 2 | 3 | @FunctionalInterface 4 | public interface ShortSupplier { 5 | 6 | short getAsShort(); 7 | } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists -------------------------------------------------------------------------------- /plugin/src/main/kotlin/io/github/tox1cozz/cutter/task/TargetTask.kt: -------------------------------------------------------------------------------- 1 | package io.github.tox1cozz.cutter.task 2 | 3 | import io.github.tox1cozz.cutter.configuration.TargetConfiguration 4 | 5 | interface TargetTask { 6 | 7 | val target: TargetConfiguration 8 | } -------------------------------------------------------------------------------- /plugin/src/main/kotlin/io/github/tox1cozz/cutter/util/StringExtensions.kt: -------------------------------------------------------------------------------- 1 | package io.github.tox1cozz.cutter.util 2 | 3 | @Suppress("NOTHING_TO_INLINE") 4 | inline fun String.capitalized() = replaceFirstChar { if (it.isLowerCase()) it.titlecase() else it.toString() } -------------------------------------------------------------------------------- /tools/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | `maven-publish` 3 | } 4 | 5 | dependencies { 6 | compileOnly("org.jetbrains", "annotations", "23.0.0") 7 | } 8 | 9 | publishing { 10 | publications { 11 | create(project.name) { 12 | from(components["java"]) 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /plugin/src/main/kotlin/io/github/tox1cozz/cutter/task/cutter/ClassFile.kt: -------------------------------------------------------------------------------- 1 | package io.github.tox1cozz.cutter.task.cutter 2 | 3 | import org.objectweb.asm.tree.ClassNode 4 | import java.nio.file.Path 5 | 6 | internal class ClassFile(val path: Path, val originalBytes: ByteArray, val node: ClassNode) { 7 | 8 | var changed = false 9 | } -------------------------------------------------------------------------------- /tools/src/main/java/io/github/tox1cozz/cutter/CutterTargetOnly.java: -------------------------------------------------------------------------------- 1 | package io.github.tox1cozz.cutter; 2 | 3 | import java.lang.annotation.Retention; 4 | import java.lang.annotation.Target; 5 | 6 | import static java.lang.annotation.ElementType.*; 7 | import static java.lang.annotation.RetentionPolicy.RUNTIME; 8 | 9 | @Retention(RUNTIME) 10 | @Target({PACKAGE, TYPE, FIELD, METHOD, CONSTRUCTOR}) 11 | public @interface CutterTargetOnly { 12 | 13 | CutterTarget value(); 14 | } -------------------------------------------------------------------------------- /plugin/src/main/kotlin/io/github/tox1cozz/cutter/util/FileExtensions.kt: -------------------------------------------------------------------------------- 1 | package io.github.tox1cozz.cutter.util 2 | 3 | import java.nio.file.Files 4 | import java.nio.file.Path 5 | import kotlin.io.path.createDirectories 6 | import kotlin.io.path.deleteExisting 7 | import kotlin.io.path.exists 8 | 9 | fun Path.deleteDirectoryRecursively() = 10 | Files.walk(this).sorted(Comparator.reverseOrder()).forEach { it.deleteExisting() } 11 | 12 | fun Path.cleanDirectory() { 13 | if (exists()) deleteDirectoryRecursively() 14 | createDirectories() 15 | } -------------------------------------------------------------------------------- /plugin/src/main/kotlin/io/github/tox1cozz/cutter/configuration/ReplaceTokensConfiguration.kt: -------------------------------------------------------------------------------- 1 | package io.github.tox1cozz.cutter.configuration 2 | 3 | import org.gradle.api.model.ObjectFactory 4 | import org.gradle.api.provider.MapProperty 5 | import org.gradle.api.tasks.Input 6 | import javax.inject.Inject 7 | 8 | abstract class ReplaceTokensConfiguration @Inject constructor(objects: ObjectFactory) { 9 | 10 | @get:Input 11 | val tokens: MapProperty = objects.mapProperty(String::class.java, String::class.java).empty() 12 | 13 | fun token(key: String, value: Any) = tokens.put(key, value.toString()) 14 | fun tokens(map: MutableMap) = map.forEach { (key, value) -> token(key, value) } 15 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # cutter-gradle-plugin 2 | A Gradle plugin for splitting code into client and server builds. 3 | 4 | Requires Gradle 5.6 and newer. 5 | 6 | ``` 7 | import io.github.tox1cozz.cutter.task.cutter.CutterTask 8 | import io.github.tox1cozz.cutter.task.cutterjar.CutterJarTask 9 | 10 | buildscript { 11 | repositories { 12 | maven { url 'https://jitpack.io' } 13 | } 14 | dependencies { 15 | classpath 'com.github.tox1cozZ.cutter-gradle-plugin:plugin:master-SNAPSHOT' 16 | } 17 | } 18 | 19 | apply plugin: 'io.github.tox1cozz.cutter' 20 | 21 | repositories { 22 | maven { url 'https://jitpack.io' } 23 | } 24 | 25 | dependencies { 26 | compileOnly 'com.github.tox1cozZ.cutter-gradle-plugin:tools:master-SNAPSHOT' 27 | } 28 | 29 | cutter { 30 | packages.include("your/package/for/processing/**") 31 | targets { 32 | minecraftForgeSideOnlyLegacy() // Forge 1.7.10 and older 33 | minecraftForgeSideOnly() // Forge 1.8-1.13 34 | minecraftForgeOnlyIn() // Forge 1.14+ 35 | minecraftFabricEnvironment() // Fabric 36 | } 37 | 38 | configureTasks(CutterTask) { 39 | replaceTokens { 40 | token '${VERSION}', project.version 41 | } 42 | } 43 | 44 | configureServerTasks(CutterJarTask) { 45 | excludeMinecraftAssets() 46 | } 47 | } 48 | ``` 49 | -------------------------------------------------------------------------------- /plugin/src/main/kotlin/io/github/tox1cozz/cutter/task/cutterjar/CutterJarTask.kt: -------------------------------------------------------------------------------- 1 | package io.github.tox1cozz.cutter.task.cutterjar 2 | 3 | import io.github.tox1cozz.cutter.CutterPlugin 4 | import io.github.tox1cozz.cutter.configuration.TargetConfiguration 5 | import io.github.tox1cozz.cutter.task.TargetTask 6 | import org.gradle.api.tasks.CacheableTask 7 | import org.gradle.api.tasks.Internal 8 | import org.gradle.api.tasks.TaskAction 9 | import org.gradle.api.tasks.util.PatternSet 10 | import org.gradle.jvm.tasks.Jar 11 | import javax.inject.Inject 12 | 13 | @CacheableTask 14 | abstract class CutterJarTask @Inject constructor( 15 | @get:Internal final override val target: TargetConfiguration 16 | ) : Jar(), TargetTask { 17 | 18 | init { 19 | description = "Assembles a jar archive with ${target.name} target build" 20 | group = CutterPlugin.GROUP 21 | } 22 | 23 | @TaskAction 24 | fun process() { 25 | } 26 | 27 | @JvmOverloads 28 | fun excludeMinecraftAssets( 29 | vararg keep: String = arrayOf( 30 | "**/lang/*.lang", 31 | "**/lang/*.json" 32 | ) 33 | ) = excludeResources("assets", *keep) 34 | 35 | fun excludeResources(resourcesDir: String, vararg keep: String) { 36 | val keepPattern = PatternSet().apply { 37 | include(*keep) 38 | isCaseSensitive = false 39 | }.asSpec 40 | filesMatching("$resourcesDir/**") { 41 | if (!keepPattern.isSatisfiedBy(it)) { 42 | it.exclude() 43 | } 44 | } 45 | } 46 | } -------------------------------------------------------------------------------- /plugin/src/main/kotlin/io/github/tox1cozz/cutter/configuration/TargetConfiguration.kt: -------------------------------------------------------------------------------- 1 | package io.github.tox1cozz.cutter.configuration 2 | 3 | import groovy.lang.Closure 4 | import org.gradle.api.Action 5 | import org.gradle.api.Named 6 | import org.gradle.api.NamedDomainObjectContainer 7 | import org.gradle.api.model.ObjectFactory 8 | import org.gradle.api.provider.Property 9 | import javax.inject.Inject 10 | 11 | internal typealias TargetConfigurationContainer = NamedDomainObjectContainer 12 | 13 | abstract class TargetConfiguration @Inject constructor( 14 | private val name: String, 15 | objects: ObjectFactory 16 | ) : Named { 17 | 18 | companion object { 19 | 20 | const val CLIENT_NAME = "client" 21 | const val SERVER_NAME = "server" 22 | const val DEBUG_NAME = "debug" 23 | } 24 | 25 | override fun getName() = name 26 | 27 | val cutAlways: Property = objects.property(Boolean::class.java).convention(false) 28 | 29 | val types: TargetTypeConfigurationContainer = objects.domainObjectContainer(TargetTypeConfiguration::class.java) 30 | 31 | fun types(config: Action) = config.execute(types) 32 | fun types(config: Closure): TargetTypeConfigurationContainer = types.configure(config) 33 | fun types(config: TargetTypeConfigurationContainer.() -> Unit) { 34 | types.configure(object : Closure(this, this) { 35 | fun doCall() { 36 | @Suppress("UNCHECKED_CAST") 37 | config(delegate as TargetTypeConfigurationContainer) 38 | } 39 | }) 40 | } 41 | } -------------------------------------------------------------------------------- /plugin/build.gradle.kts: -------------------------------------------------------------------------------- 1 | import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar 2 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile 3 | 4 | plugins { 5 | kotlin("jvm") 6 | `java-gradle-plugin` 7 | `maven-publish` 8 | id("com.gradle.plugin-publish") version "1.0.0" 9 | id("com.github.johnrengelman.shadow") version "7.1.2" 10 | } 11 | 12 | dependencies { 13 | implementation(kotlin("stdlib-jdk8")) 14 | implementation("org.ow2.asm:asm-tree:9.3") 15 | api(project(":tools")) 16 | } 17 | 18 | tasks.withType { 19 | kotlinOptions { 20 | jvmTarget = JavaVersion.VERSION_1_8.toString() 21 | } 22 | } 23 | 24 | tasks.named("shadowJar") { 25 | archiveClassifier.set("") 26 | relocate("org.objectweb.asm", "io.github.tox1cozz.cutter.lib.org.objectweb.asm") 27 | relocate("kotlin", "io.github.tox1cozz.cutter.lib.kotlin") 28 | dependencies { 29 | exclude(dependency("org.jetbrains:annotations")) 30 | } 31 | minimize() 32 | } 33 | 34 | tasks.named("jar") { 35 | enabled = false 36 | } 37 | 38 | afterEvaluate { 39 | publishing { 40 | publications { 41 | named("pluginMaven") { 42 | pom { 43 | name.set("cutter-gradle-plugin") 44 | description.set("A Gradle plugin for splitting code into client and server builds") 45 | url.set("https://github.com/tox1cozZ/cutter-gradle-plugin") 46 | licenses { 47 | license { 48 | name.set("MIT License") 49 | url.set("https://opensource.org/licenses/MIT") 50 | } 51 | } 52 | developers { 53 | developer { 54 | id.set("tox1cozZ") 55 | name.set("Dmytro Tukin") 56 | } 57 | } 58 | } 59 | } 60 | } 61 | } 62 | } 63 | 64 | gradlePlugin { 65 | plugins { 66 | create("cutter") { 67 | id = "io.github.tox1cozz.cutter" 68 | displayName = "Cutter Plugin" 69 | description = "A Gradle plugin for splitting code into client and server builds." 70 | implementationClass = "io.github.tox1cozz.cutter.CutterPlugin" 71 | } 72 | } 73 | } 74 | 75 | pluginBundle { 76 | website = "https://github.com/tox1cozZ/cutter-gradle-plugin" 77 | vcsUrl = "https://github.com/tox1cozZ/cutter-gradle-plugin.git" 78 | description = "A Gradle plugin for splitting code into client and server builds." 79 | tags = listOf("cut", "jar", "build", "client build", "server build") 80 | } -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /plugin/src/main/kotlin/io/github/tox1cozz/cutter/configuration/TargetTypeConfiguration.kt: -------------------------------------------------------------------------------- 1 | package io.github.tox1cozz.cutter.configuration 2 | 3 | import org.gradle.api.Action 4 | import org.gradle.api.Named 5 | import org.gradle.api.NamedDomainObjectContainer 6 | import org.gradle.api.model.ObjectFactory 7 | import org.gradle.api.provider.ListProperty 8 | import org.gradle.api.provider.Property 9 | import java.util.* 10 | import javax.inject.Inject 11 | 12 | internal typealias TargetTypeConfigurationContainer = NamedDomainObjectContainer 13 | 14 | abstract class TargetTypeConfiguration @Inject constructor( 15 | private val name: String, 16 | private val objects: ObjectFactory 17 | ) : Named { 18 | 19 | override fun getName() = name 20 | 21 | val annotations: ListProperty = 22 | objects.listProperty(TargetTypeAnnotationConfiguration::class.java).empty() 23 | 24 | val executors: ListProperty = 25 | objects.listProperty(TargetTypeExecutorConfiguration::class.java).empty() 26 | 27 | fun annotation(builder: TargetTypeAnnotationConfiguration.() -> Unit) = 28 | annotations.add(TargetTypeAnnotationConfiguration(objects).apply(builder)) 29 | 30 | fun annotation(action: Action) = 31 | annotations.add(TargetTypeAnnotationConfiguration(objects).apply { action.execute(this) }) 32 | 33 | fun executor(builder: TargetTypeExecutorConfiguration.() -> Unit) = 34 | executors.add(TargetTypeExecutorConfiguration(objects).apply(builder)) 35 | 36 | fun executor(action: Action) = 37 | executors.add(TargetTypeExecutorConfiguration(objects).apply { action.execute(this) }) 38 | } 39 | 40 | class TargetTypeAnnotationConfiguration(objects: ObjectFactory) { 41 | 42 | val type: Property = objects.property(String::class.java) 43 | val parameter: Property = objects.property(String::class.java).convention("value") 44 | val value: Property = objects.property(String::class.java) 45 | 46 | override fun equals(other: Any?): Boolean { 47 | if (other !is TargetTypeAnnotationConfiguration) return false 48 | if (type.get() != other.type.get()) return false 49 | if (parameter.get() != other.parameter.get()) return false 50 | if (value.get() != other.value.get()) return false 51 | return true 52 | } 53 | 54 | override fun hashCode() = Objects.hash(type.get(), parameter.get(), value.get()) 55 | 56 | override fun toString() = "TargetTypeAnnotationConfiguration(type=${type.get()}, parameter=${parameter.get()}, value=${value.get()})" 57 | } 58 | 59 | class TargetTypeExecutorConfiguration(objects: ObjectFactory) { 60 | 61 | val invoke: Property = objects.property(String::class.java) 62 | val value: Property = objects.property(String::class.java) 63 | 64 | override fun equals(other: Any?): Boolean { 65 | if (other !is TargetTypeExecutorConfiguration) return false 66 | if (invoke.get() != other.invoke.get()) return false 67 | if (value.get() != other.value.get()) return false 68 | return true 69 | } 70 | 71 | override fun hashCode() = Objects.hash(invoke.get(), value.get()) 72 | 73 | override fun toString() = "TargetTypeExecutorConfiguration(invoke=${invoke.get()}, value=${value.get()})" 74 | } -------------------------------------------------------------------------------- /plugin/src/main/kotlin/io/github/tox1cozz/cutter/CutterPlugin.kt: -------------------------------------------------------------------------------- 1 | package io.github.tox1cozz.cutter 2 | 3 | import io.github.tox1cozz.cutter.configuration.CutterExtension 4 | import io.github.tox1cozz.cutter.task.cutter.CutterTask 5 | import io.github.tox1cozz.cutter.task.cutterjar.CutterJarTask 6 | import io.github.tox1cozz.cutter.util.capitalized 7 | import org.gradle.api.Plugin 8 | import org.gradle.api.Project 9 | import java.io.File 10 | 11 | abstract class CutterPlugin : Plugin { 12 | 13 | companion object { 14 | 15 | const val NAME = "cutter" 16 | const val GROUP = "cutter" 17 | const val EXTENSION = "cutter" 18 | } 19 | 20 | override fun apply(project: Project) { 21 | val extension = project.extensions.create(EXTENSION, CutterExtension::class.java, project) 22 | project.afterEvaluate { 23 | setup(it, extension) 24 | } 25 | } 26 | 27 | private fun setup(project: Project, extension: CutterExtension) { 28 | val jars = extension.jars.get() 29 | if (jars.isEmpty()) { 30 | project.logger.warn("No Jar task found, so Cutter is inactive. Specify jar with processJar method in 'cutter' configuration.") 31 | return 32 | } 33 | 34 | val buildTask = project.tasks.getByName("build") 35 | 36 | extension.targets.all { target -> 37 | if (target.types.isEmpty()) { 38 | project.logger.warn("Types in target '${target.name}' not specified.") 39 | return@all 40 | } else { 41 | target.types.filter { it.annotations.get().isEmpty() && it.executors.get().isEmpty() }.forEach { 42 | project.logger.warn("Type '${it.name}' in target '${target.name}' is empty, specify annotations or/and executors.") 43 | } 44 | } 45 | 46 | if (target.cutAlways.get()) { 47 | return@all 48 | } 49 | 50 | jars.forEach { jar -> 51 | val jarTaskName = jar.name 52 | val taskPostfix = if (jar.name == "jar") "" else jar.name.capitalized() 53 | val cutterDir = File(project.buildDir, NAME) 54 | 55 | val cutterName = "cutter${target.name.capitalized()}$taskPostfix" 56 | val cutterTask = project.tasks.create(cutterName, CutterTask::class.java, target, extension) 57 | 58 | val cutterJarName = "${target.name}Jar${taskPostfix}" 59 | val cutterJarTask = project.tasks.create(cutterJarName, CutterJarTask::class.java, target) 60 | 61 | cutterTask.also { 62 | it.archiveFile.set(jar.archiveFile) 63 | it.targetClassesDir.set(File(cutterDir, "$jarTaskName/transformed/${target.name}")) 64 | it.originalFilesDir.set(File(cutterDir, "$jarTaskName/files/${target.name}")) 65 | 66 | it.inputs.property("packages", extension.packages.hashCode()) 67 | 68 | it.inputs.property("target", target.name) 69 | it.inputs.property("target.cutAlways", target.cutAlways) 70 | target.types.forEach { type -> 71 | val typeKey = "target.type.${type.name}" 72 | it.inputs.property(typeKey, type.name) 73 | it.inputs.property("$typeKey.annotations", type.annotations.get().hashCode()) 74 | it.inputs.property("$typeKey.executors", type.executors.get().hashCode()) 75 | } 76 | } 77 | 78 | cutterJarTask.also { task -> 79 | task.dependsOn(cutterTask) 80 | buildTask.dependsOn(task) 81 | 82 | task.from(cutterTask.targetClassesDir) 83 | task.from(cutterTask.originalFilesDir) 84 | task.manifest.from(jar.manifest.effectiveManifest) 85 | 86 | task.archiveClassifier.set(target.name) 87 | jar.archiveFile.get().asFile.also { 88 | task.archiveFileName.set("${it.nameWithoutExtension}-${target.name}.${it.extension}") 89 | } 90 | task.includeEmptyDirs = false 91 | } 92 | } 93 | } 94 | } 95 | } -------------------------------------------------------------------------------- /plugin/src/main/kotlin/io/github/tox1cozz/cutter/task/cutter/ClassTransformer.kt: -------------------------------------------------------------------------------- 1 | package io.github.tox1cozz.cutter.task.cutter 2 | 3 | import io.github.tox1cozz.cutter.configuration.CutterExtension 4 | import io.github.tox1cozz.cutter.configuration.ReplaceTokensConfiguration 5 | import io.github.tox1cozz.cutter.configuration.TargetConfiguration 6 | import org.objectweb.asm.tree.AnnotationNode 7 | import org.objectweb.asm.tree.LdcInsnNode 8 | 9 | internal class ClassTransformer( 10 | private val target: TargetConfiguration, 11 | private val extension: CutterExtension, 12 | private val replaceTokens: ReplaceTokensConfiguration, 13 | private val inputClasses: Map 14 | ) { 15 | 16 | private val annotations: List = target.types.flatMap { type -> 17 | type.annotations.get().map { annotation -> 18 | val target = annotation.value.get().split('.', limit = 2) 19 | AnnotationType( 20 | desc = "L${annotation.type.get()};", 21 | parameter = annotation.parameter.get(), 22 | targetType = target[0], 23 | targetValue = target[1] 24 | ) 25 | } 26 | } 27 | 28 | private val executors: List = target.types.flatMap { type -> 29 | type.executors.get().map { executor -> 30 | val invoke = executor.invoke.get().split(':', limit = 3) 31 | val target = executor.value.get().split(':', limit = 3) 32 | ExecutorType( 33 | invokeOwner = invoke[0], 34 | invokeName = invoke[1], 35 | invokeDesc = invoke[2], 36 | targetOwner = target[0], 37 | targetName = target[1], 38 | targetDesc = target[2], 39 | ) 40 | } 41 | } 42 | 43 | fun process(): List { 44 | val outputClasses = inputClasses.values.toList() 45 | outputClasses.forEach(::replaceTokens) 46 | return outputClasses 47 | } 48 | 49 | fun validate(): List { 50 | return emptyList() 51 | } 52 | 53 | private fun replaceTokens(classFile: ClassFile) { 54 | val tokens = replaceTokens.tokens.get() 55 | if (tokens.isEmpty()) return 56 | 57 | fun replaceInAnnotations(annotations: MutableList?) { 58 | if (annotations.isNullOrEmpty()) return 59 | for (annotation in annotations) { 60 | if (annotation.values.isNullOrEmpty()) continue 61 | for (i in 0 until annotation.values.size step 2) { 62 | val value = annotation.values[i + 1] 63 | if (value is String && value in tokens) { 64 | annotation.values[i + 1] = tokens[value] 65 | classFile.changed = true 66 | } else if (value is List<*> && value.isNotEmpty() && value.first() is String) { 67 | annotation.values[i + 1] = value.map { 68 | if (it in tokens) { 69 | classFile.changed = true 70 | return@map tokens[it] 71 | } 72 | it 73 | } 74 | } 75 | } 76 | } 77 | } 78 | 79 | val classNode = classFile.node 80 | replaceInAnnotations(classNode.visibleAnnotations) 81 | replaceInAnnotations(classNode.invisibleAnnotations) 82 | 83 | for (field in classNode.fields) { 84 | if (field.value is String && field.value in tokens) { 85 | field.value = tokens[field.value] 86 | classFile.changed = true 87 | } 88 | replaceInAnnotations(field.visibleAnnotations) 89 | replaceInAnnotations(field.invisibleAnnotations) 90 | } 91 | 92 | for (method in classNode.methods) { 93 | for (insn in method.instructions) { 94 | if (insn is LdcInsnNode && insn.cst is String) { 95 | tokens.forEach { (key, value) -> 96 | val string = insn.cst as String 97 | if (string.contains(key)) { 98 | insn.cst = string.replace(key, value) 99 | classFile.changed = true 100 | } 101 | } 102 | } 103 | } 104 | 105 | replaceInAnnotations(method.visibleAnnotations) 106 | replaceInAnnotations(method.invisibleAnnotations) 107 | method.visibleParameterAnnotations?.forEach(::replaceInAnnotations) 108 | method.invisibleParameterAnnotations?.forEach(::replaceInAnnotations) 109 | } 110 | } 111 | 112 | private data class RemovedClass(val name: String) 113 | private data class RemovedField(val owner: String, val name: String, val desc: String) 114 | private data class RemovedMethod(val owner: String, val name: String, val desc: String) 115 | 116 | private data class AnnotationType( 117 | val desc: String, 118 | val parameter: String, 119 | val targetType: String, 120 | val targetValue: String 121 | ) 122 | 123 | private data class ExecutorType( 124 | val invokeOwner: String, 125 | val invokeName: String, 126 | val invokeDesc: String, 127 | val targetOwner: String, 128 | val targetName: String, 129 | val targetDesc: String 130 | ) 131 | } -------------------------------------------------------------------------------- /plugin/src/main/kotlin/io/github/tox1cozz/cutter/task/cutter/CutterTask.kt: -------------------------------------------------------------------------------- 1 | package io.github.tox1cozz.cutter.task.cutter 2 | 3 | import groovy.lang.Closure 4 | import io.github.tox1cozz.cutter.CutterPlugin 5 | import io.github.tox1cozz.cutter.configuration.CutterExtension 6 | import io.github.tox1cozz.cutter.configuration.ReplaceTokensConfiguration 7 | import io.github.tox1cozz.cutter.configuration.TargetConfiguration 8 | import io.github.tox1cozz.cutter.task.TargetTask 9 | import io.github.tox1cozz.cutter.util.cleanDirectory 10 | import org.gradle.api.Action 11 | import org.gradle.api.DefaultTask 12 | import org.gradle.api.GradleException 13 | import org.gradle.api.file.DirectoryProperty 14 | import org.gradle.api.file.FileTreeElement 15 | import org.gradle.api.file.RegularFileProperty 16 | import org.gradle.api.file.RelativePath 17 | import org.gradle.api.specs.Spec 18 | import org.gradle.api.tasks.CacheableTask 19 | import org.gradle.api.tasks.InputFile 20 | import org.gradle.api.tasks.Internal 21 | import org.gradle.api.tasks.Nested 22 | import org.gradle.api.tasks.OutputDirectory 23 | import org.gradle.api.tasks.PathSensitive 24 | import org.gradle.api.tasks.PathSensitivity 25 | import org.gradle.api.tasks.TaskAction 26 | import org.objectweb.asm.ClassReader 27 | import org.objectweb.asm.ClassWriter 28 | import org.objectweb.asm.tree.ClassNode 29 | import java.io.File 30 | import java.io.IOException 31 | import java.io.OutputStream 32 | import java.net.URI 33 | import java.nio.file.FileSystems 34 | import java.nio.file.FileVisitResult 35 | import java.nio.file.FileVisitor 36 | import java.nio.file.Files 37 | import java.nio.file.Path 38 | import java.nio.file.StandardCopyOption.COPY_ATTRIBUTES 39 | import java.nio.file.StandardCopyOption.REPLACE_EXISTING 40 | import java.nio.file.attribute.BasicFileAttributes 41 | import javax.inject.Inject 42 | import kotlin.io.path.createDirectories 43 | import kotlin.io.path.extension 44 | import kotlin.io.path.name 45 | import kotlin.io.path.readBytes 46 | import kotlin.io.path.writeBytes 47 | 48 | @CacheableTask 49 | abstract class CutterTask @Inject constructor( 50 | @get:Internal final override val target: TargetConfiguration, 51 | private val extension: CutterExtension 52 | ) : DefaultTask(), TargetTask { 53 | 54 | init { 55 | description = "Classes transforming for ${target.name} target build" 56 | group = CutterPlugin.GROUP 57 | } 58 | 59 | @get:InputFile 60 | @get:PathSensitive(PathSensitivity.RELATIVE) 61 | abstract val archiveFile: RegularFileProperty 62 | 63 | @get:Nested 64 | abstract val replaceTokens: ReplaceTokensConfiguration 65 | fun replaceTokens(config: Action) = config.execute(replaceTokens) 66 | fun replaceTokens(config: Closure): Any = project.configure(replaceTokens, config) 67 | 68 | @get:OutputDirectory 69 | internal abstract val targetClassesDir: DirectoryProperty 70 | 71 | @get:OutputDirectory 72 | internal abstract val originalFilesDir: DirectoryProperty 73 | 74 | @TaskAction 75 | fun process() { 76 | val archive = archiveFile.get().asFile.toPath() 77 | val classesDir = targetClassesDir.get().asFile.toPath().also { it.cleanDirectory() } 78 | val otherFilesDir = originalFilesDir.get().asFile.toPath().also { it.cleanDirectory() } 79 | 80 | val inputClasses = processJar(archive, otherFilesDir).associateTo(mutableMapOf()) { 81 | val classNode = ClassNode() 82 | val classReader = ClassReader(it.second) 83 | classReader.accept(classNode, 0) 84 | classNode.name to ClassFile(it.first, it.second, classNode) 85 | } 86 | 87 | val transformer = ClassTransformer(target, extension, replaceTokens, inputClasses) 88 | val outputClasses = transformer.process() 89 | 90 | val errors = transformer.validate() 91 | if (errors.isEmpty()) { 92 | outputClasses.forEach { classFile -> 93 | if (classFile.changed) { 94 | val writer = ClassWriter(ClassWriter.COMPUTE_MAXS) 95 | classFile.node.accept(writer) 96 | 97 | val destPath = classesDir.resolve(classFile.path.toString()) 98 | destPath.parent.createDirectories() 99 | destPath.writeBytes(writer.toByteArray()) 100 | } else { 101 | val destPath = otherFilesDir.resolve(classFile.path.toString()) 102 | destPath.parent.createDirectories() 103 | destPath.writeBytes(classFile.originalBytes) 104 | } 105 | } 106 | } else { 107 | val details = errors.map { "$it\n" } 108 | throw GradleException("Validation is failed. Details:\n$details") 109 | } 110 | } 111 | 112 | private fun processJar(archive: Path, otherFilesDir: Path): MutableList> { 113 | val classesSpec = extension.packages.asSpec 114 | 115 | return FileSystems.newFileSystem( 116 | URI.create("jar:${archive.toUri()}"), 117 | mapOf("create" to "false", "encoding" to "UTF-8") 118 | ).use { 119 | val classes = mutableListOf>() 120 | val rootPath = it.getPath("/") 121 | Files.walkFileTree(rootPath, object : FileVisitor { 122 | override fun preVisitDirectory(dir: Path, attrs: BasicFileAttributes): FileVisitResult { 123 | return FileVisitResult.CONTINUE 124 | } 125 | 126 | override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult { 127 | val relativeFile = rootPath.relativize(file) 128 | if (relativeFile.isTargetClassFile(classesSpec)) { 129 | classes.add(Pair(relativeFile, relativeFile.readBytes())) 130 | } else { 131 | val otherFile = otherFilesDir.resolve(relativeFile.toString()) 132 | otherFile.parent.createDirectories() 133 | Files.copy(relativeFile, otherFile, COPY_ATTRIBUTES, REPLACE_EXISTING) 134 | } 135 | return FileVisitResult.CONTINUE 136 | } 137 | 138 | override fun visitFileFailed(file: Path, ex: IOException) = 139 | throw GradleException("Failed to visit file in jar $archive: $file", ex) 140 | 141 | override fun postVisitDirectory(dir: Path, ex: IOException?) = FileVisitResult.CONTINUE 142 | }) 143 | 144 | classes 145 | } 146 | } 147 | 148 | private fun Path.isTargetClassFile(classesSpec: Spec): Boolean { 149 | class ClassFileChecker(private val path: Path) : FileTreeElement { 150 | override fun getFile() = error("Not used") 151 | override fun isDirectory() = false 152 | override fun getLastModified() = error("Not used") 153 | override fun getSize() = error("Not used") 154 | override fun open() = error("Not used") 155 | override fun copyTo(output: OutputStream) = error("Not used") 156 | override fun copyTo(target: File) = error("Not used") 157 | override fun getName() = path.name 158 | override fun getPath() = path.toString() 159 | override fun getRelativePath() = RelativePath(true, *getPath().split("/").toTypedArray()) 160 | override fun getMode() = error("Not used") 161 | } 162 | 163 | return extension == "class" && classesSpec.isSatisfiedBy(ClassFileChecker(this)) 164 | } 165 | } -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /plugin/src/main/kotlin/io/github/tox1cozz/cutter/configuration/CutterExtension.kt: -------------------------------------------------------------------------------- 1 | package io.github.tox1cozz.cutter.configuration 2 | 3 | import groovy.lang.Closure 4 | import io.github.tox1cozz.cutter.Cutter 5 | import io.github.tox1cozz.cutter.CutterTarget 6 | import io.github.tox1cozz.cutter.CutterTargetOnly 7 | import io.github.tox1cozz.cutter.task.TargetTask 8 | import org.gradle.api.Action 9 | import org.gradle.api.Project 10 | import org.gradle.api.Task 11 | import org.gradle.api.provider.ListProperty 12 | import org.gradle.api.provider.Property 13 | import org.gradle.api.tasks.util.PatternSet 14 | import org.gradle.jvm.tasks.Jar 15 | import org.objectweb.asm.Type 16 | import javax.inject.Inject 17 | 18 | abstract class CutterExtension @Inject constructor(private val project: Project) { 19 | 20 | val validation: Property = project.objects.property(Boolean::class.java).convention(true) 21 | val verbose: Property = project.objects.property(Boolean::class.java).convention(true) 22 | val jars: ListProperty = project.objects.listProperty(Jar::class.java).empty() 23 | 24 | val packages = PatternSet() 25 | 26 | val targets: TargetConfigurationContainer = project.objects.domainObjectContainer(TargetConfiguration::class.java) 27 | fun targets(config: Action) = config.execute(targets) 28 | fun targets(config: Closure): TargetConfigurationContainer = targets.configure(config) 29 | fun targets(config: TargetConfigurationContainer.() -> Unit) { 30 | targets.configure(object : Closure(this, this) { 31 | fun doCall() { 32 | @Suppress("UNCHECKED_CAST") 33 | config(delegate as TargetConfigurationContainer) 34 | } 35 | }) 36 | } 37 | 38 | init { 39 | project.tasks.findByName("jar")?.also { 40 | if (it is Jar) { 41 | jars.add(it) 42 | } 43 | } 44 | initDefaultTargets() 45 | } 46 | 47 | fun processJar(jarTask: Jar) = processJar(jarTask.name) 48 | 49 | fun processJar(jarTaskName: String) { 50 | jars.add( 51 | project.provider { 52 | project.tasks.getByName(jarTaskName).let { 53 | check(it is Jar) { "Task with name '$jarTaskName' is not a Jar type" } 54 | it 55 | } 56 | } 57 | ) 58 | } 59 | 60 | private fun initDefaultTargets() { 61 | val typeName = "cutter" 62 | 63 | fun TargetTypeConfiguration.registerType(targetName: String) { 64 | val annotationType = Type.getInternalName(CutterTargetOnly::class.java) 65 | val targetType = Type.getInternalName(CutterTarget::class.java) 66 | val cutterType = Type.getInternalName(Cutter::class.java) 67 | 68 | annotation { 69 | type.set(annotationType) 70 | value.set("$targetType.$targetName") 71 | } 72 | executor { 73 | invoke.set("$cutterType:execute:(Ljava/lang/Enum;Ljava/lang/Runnable;)V") 74 | value.set("$targetType:$targetName:L$targetType;") 75 | } 76 | } 77 | 78 | targets.register(TargetConfiguration.CLIENT_NAME) { client -> 79 | client.cutAlways.set(false) 80 | client.types.register(typeName) { 81 | it.registerType(CutterTarget.CLIENT.name) 82 | } 83 | } 84 | targets.register(TargetConfiguration.SERVER_NAME) { server -> 85 | server.cutAlways.set(false) 86 | server.types.register(typeName) { 87 | it.registerType(CutterTarget.SERVER.name) 88 | } 89 | } 90 | targets.register(TargetConfiguration.DEBUG_NAME) { debug -> 91 | debug.cutAlways.set(true) 92 | debug.types.register(typeName) { 93 | it.registerType(CutterTarget.DEBUG.name) 94 | } 95 | } 96 | } 97 | 98 | fun minecraftForgeSideOnlyLegacy() = clientServerTargetAnnotation( 99 | name = "minecraftForgeSideOnlyLegacy", 100 | annotationType = "cpw/mods/fml/relauncher/SideOnly", 101 | valueType = "cpw/mods/fml/relauncher/Side" 102 | ) 103 | 104 | fun minecraftForgeSideOnly() = clientServerTargetAnnotation( 105 | name = "minecraftForgeSideOnly", 106 | annotationType = "net/minecraftforge/fml/relauncher/SideOnly", 107 | valueType = "net/minecraftforge/fml/relauncher/Side" 108 | ) 109 | 110 | fun minecraftForgeOnlyIn() { 111 | val typeName = "minecraftForgeOnlyIn" 112 | val targetType = "net/minecraftforge/api/distmarker/Dist" 113 | 114 | clientServerTargetAnnotation( 115 | name = typeName, 116 | annotationType = "net/minecraftforge/api/distmarker/OnlyIn", 117 | valueType = targetType, 118 | serverValue = "DEDICATED_SERVER" 119 | ) 120 | 121 | fun TargetTypeConfiguration.registerKotlinForForgeExecutor(targetName: String) { 122 | executor { 123 | invoke.set("thedarkcolour/kotlinforforge/forge/ForgeKt:runWhenOn:(Lnet/minecraftforge/api/distmarker/Dist;Lkotlin/jvm/functions/Function0;)V") 124 | value.set("$targetType:$targetName:L$targetType;") 125 | } 126 | } 127 | 128 | fun TargetTypeConfiguration.registerForgeDistExecutor(executorMethod: String, targetName: String) { 129 | executor { 130 | invoke.set("net/minecraftforge/fml/DistExecutor:$executorMethod:(Lnet/minecraftforge/api/distmarker/Dist;Ljava/util/function/Supplier;)V") 131 | value.set("$targetType:$targetName:L$targetType;") 132 | } 133 | } 134 | 135 | targets.named(TargetConfiguration.CLIENT_NAME) { client -> 136 | client.types.named(typeName) { 137 | it.registerKotlinForForgeExecutor("CLIENT") 138 | it.registerForgeDistExecutor("runWhenOn", "CLIENT") 139 | it.registerForgeDistExecutor("unsafeRunWhenOn", "CLIENT") 140 | it.registerForgeDistExecutor("safeRunWhenOn", "CLIENT") 141 | } 142 | } 143 | targets.named(TargetConfiguration.SERVER_NAME) { server -> 144 | server.types.named(typeName) { 145 | it.registerKotlinForForgeExecutor("DEDICATED_SERVER") 146 | it.registerForgeDistExecutor("runWhenOn", "DEDICATED_SERVER") 147 | it.registerForgeDistExecutor("unsafeRunWhenOn", "DEDICATED_SERVER") 148 | it.registerForgeDistExecutor("safeRunWhenOn", "DEDICATED_SERVER") 149 | } 150 | } 151 | } 152 | 153 | fun minecraftFabricEnvironment() = clientServerTargetAnnotation( 154 | name = "minecraftFabricEnvironment", 155 | annotationType = "net/fabricmc/api/Environment", 156 | valueType = "net/fabricmc/api/EnvType" 157 | ) 158 | 159 | @JvmOverloads 160 | fun clientServerTargetAnnotation( 161 | name: String, 162 | annotationType: String, 163 | valueType: String, 164 | parameterName: String? = null, 165 | clientValue: String = "CLIENT", 166 | serverValue: String = "SERVER", 167 | ) { 168 | fun TargetTypeConfiguration.registerAnnotation(annotationValue: String) { 169 | annotation { 170 | type.set(annotationType) 171 | parameterName?.also { parameter.set(it) } 172 | value.set("$valueType.$annotationValue") 173 | } 174 | } 175 | 176 | targets.named(TargetConfiguration.CLIENT_NAME) { client -> 177 | client.types.register(name) { 178 | it.registerAnnotation(clientValue) 179 | } 180 | } 181 | targets.named(TargetConfiguration.SERVER_NAME) { server -> 182 | server.types.register(name) { 183 | it.registerAnnotation(serverValue) 184 | } 185 | } 186 | } 187 | 188 | fun configureClientTasks( 189 | taskType: Class, 190 | action: Action 191 | ) where T : Task, T : TargetTask = configureTasks(TargetConfiguration.CLIENT_NAME, taskType, action) 192 | 193 | fun configureClientTasks( 194 | taskType: Class, 195 | block: T.() -> Unit 196 | ) where T : Task, T : TargetTask = configureTasks(TargetConfiguration.CLIENT_NAME, taskType, block) 197 | 198 | fun configureServerTasks( 199 | taskType: Class, 200 | action: Action 201 | ) where T : Task, T : TargetTask = configureTasks(TargetConfiguration.SERVER_NAME, taskType, action) 202 | 203 | fun configureServerTasks( 204 | taskType: Class, 205 | block: T.() -> Unit 206 | ) where T : Task, T : TargetTask = configureTasks(TargetConfiguration.SERVER_NAME, taskType, block) 207 | 208 | @JvmOverloads 209 | fun configureTasks( 210 | targetName: String? = null, 211 | taskType: Class, 212 | block: T.() -> Unit 213 | ) where T : Task, T : TargetTask = configureTasks(targetName, taskType) { action -> block(action) } 214 | 215 | @JvmOverloads 216 | fun configureTasks( 217 | targetName: String? = null, 218 | taskType: Class, 219 | action: Action 220 | ) where T : Task, T : TargetTask { 221 | if (targetName != null) { 222 | val target = targets.getByName(targetName) 223 | project.tasks.withType(taskType) { 224 | if (it.target == target) { 225 | action.execute(it) 226 | } 227 | } 228 | } else { 229 | project.tasks.withType(taskType, action) 230 | } 231 | } 232 | } -------------------------------------------------------------------------------- /tools/src/main/java/io/github/tox1cozz/cutter/Cutter.java: -------------------------------------------------------------------------------- 1 | package io.github.tox1cozz.cutter; 2 | 3 | import io.github.tox1cozz.cutter.function.ByteSupplier; 4 | import io.github.tox1cozz.cutter.function.CharSupplier; 5 | import io.github.tox1cozz.cutter.function.FloatSupplier; 6 | import io.github.tox1cozz.cutter.function.ShortSupplier; 7 | import org.jetbrains.annotations.NotNull; 8 | import org.jetbrains.annotations.Nullable; 9 | 10 | import java.util.function.*; 11 | 12 | public final class Cutter { 13 | 14 | @Nullable 15 | private static Supplier runtimeTarget; 16 | 17 | static { 18 | String targetProperty = System.getProperty("cutter.runtimeTarget"); 19 | if (targetProperty != null) { 20 | setRuntimeTarget(() -> targetProperty); 21 | } 22 | } 23 | 24 | private Cutter() { 25 | throw new UnsupportedOperationException("This is a utility class and cannot be instantiated"); 26 | } 27 | 28 | /** 29 | * Initializing boolean primitive field value only for a specific target build 30 | * Another build target value is false 31 | * 32 | * @param target The target build, on which the field value should remain 33 | * @param value Boolean primitive field value 34 | */ 35 | public static boolean booleanValue(@NotNull Enum target, @NotNull BooleanSupplier value) { 36 | return booleanValue(target, () -> false, value); 37 | } 38 | 39 | /** 40 | * Initializing boolean primitive field value only for a specific target build 41 | * 42 | * @param target The target build, on which the field value should remain 43 | * @param value Boolean primitive field value 44 | * @param otherValue The value to use if the current target is not valid 45 | */ 46 | public static boolean booleanValue(@NotNull Enum target, @NotNull BooleanSupplier otherValue, @NotNull BooleanSupplier value) { 47 | return isRuntimeTarget(target) ? value.getAsBoolean() : otherValue.getAsBoolean(); 48 | } 49 | 50 | /** 51 | * Initializing byte primitive field value only for a specific target build 52 | * Another build target value is 0 53 | * 54 | * @param target The target build, on which the field value should remain 55 | * @param value Byte primitive field value 56 | */ 57 | public static byte byteValue(@NotNull Enum target, @NotNull ByteSupplier value) { 58 | return byteValue(target, () -> (byte)0, value); 59 | } 60 | 61 | /** 62 | * Initializing byte primitive field value only for a specific target build 63 | * 64 | * @param target The target build, on which the field value should remain 65 | * @param value Byte primitive field value 66 | * @param otherValue The value to use if the current target is not valid 67 | */ 68 | public static byte byteValue(@NotNull Enum target, @NotNull ByteSupplier otherValue, @NotNull ByteSupplier value) { 69 | return isRuntimeTarget(target) ? value.getAsByte() : otherValue.getAsByte(); 70 | } 71 | 72 | /** 73 | * Initializing short primitive field value only for a specific target build 74 | * Another build target value is 0 75 | * 76 | * @param target The target build, on which the field value should remain 77 | * @param value Short primitive field value 78 | */ 79 | public static short shortValue(@NotNull Enum target, @NotNull ShortSupplier value) { 80 | return shortValue(target, () -> (short)0, value); 81 | } 82 | 83 | /** 84 | * Initializing short primitive field value only for a specific target build 85 | * 86 | * @param target The target build, on which the field value should remain 87 | * @param value Short primitive field value 88 | * @param otherValue The value to use if the current target is not valid 89 | */ 90 | public static short shortValue(@NotNull Enum target, @NotNull ShortSupplier otherValue, @NotNull ShortSupplier value) { 91 | return isRuntimeTarget(target) ? value.getAsShort() : otherValue.getAsShort(); 92 | } 93 | 94 | /** 95 | * Initializing character primitive field value only for a specific target build 96 | * Another build target value is '\u0000' 97 | * 98 | * @param target The target build, on which the field value should remain 99 | * @param value Character primitive field value 100 | */ 101 | public static char charValue(@NotNull Enum target, @NotNull CharSupplier value) { 102 | return charValue(target, () -> '\u0000', value); 103 | } 104 | 105 | /** 106 | * Initializing character primitive field value only for a specific target build 107 | * 108 | * @param target The target build, on which the field value should remain 109 | * @param value Character primitive field value 110 | * @param otherValue The value to use if the current target is not valid 111 | */ 112 | public static char charValue(@NotNull Enum target, @NotNull CharSupplier otherValue, @NotNull CharSupplier value) { 113 | return isRuntimeTarget(target) ? value.getAsChar() : otherValue.getAsChar(); 114 | } 115 | 116 | /** 117 | * Initializing integer primitive field value only for a specific target build 118 | * Another build target value is 0 119 | * 120 | * @param target The target build, on which the field value should remain 121 | * @param value Integer primitive field value 122 | */ 123 | public static int intValue(@NotNull Enum target, @NotNull IntSupplier value) { 124 | return intValue(target, () -> 0, value); 125 | } 126 | 127 | /** 128 | * Initializing integer primitive field value only for a specific target build 129 | * 130 | * @param target The target build, on which the field value should remain 131 | * @param value Integer primitive field value 132 | * @param otherValue The value to use if the current target is not valid 133 | */ 134 | public static int intValue(@NotNull Enum target, @NotNull IntSupplier otherValue, @NotNull IntSupplier value) { 135 | return isRuntimeTarget(target) ? value.getAsInt() : otherValue.getAsInt(); 136 | } 137 | 138 | /** 139 | * Initializing long primitive field value only for a specific target build 140 | * Another build target value is 0L 141 | * 142 | * @param target The target build, on which the field value should remain 143 | * @param value Long primitive field value 144 | */ 145 | public static long longValue(@NotNull Enum target, @NotNull LongSupplier value) { 146 | return longValue(target, () -> 0L, value); 147 | } 148 | 149 | /** 150 | * Initializing long primitive field value only for a specific target build 151 | * 152 | * @param target The target build, on which the field value should remain 153 | * @param value Long primitive field value 154 | * @param otherValue The value to use if the current target is not valid 155 | */ 156 | public static long longValue(@NotNull Enum target, @NotNull LongSupplier otherValue, @NotNull LongSupplier value) { 157 | return isRuntimeTarget(target) ? value.getAsLong() : otherValue.getAsLong(); 158 | } 159 | 160 | /** 161 | * Initializing float primitive field value only for a specific target build 162 | * Another build target value is 0.0F 163 | * 164 | * @param target The target build, on which the field value should remain 165 | * @param value Float primitive field value 166 | */ 167 | public static float floatValue(@NotNull Enum target, @NotNull FloatSupplier value) { 168 | return floatValue(target, () -> 0.0F, value); 169 | } 170 | 171 | /** 172 | * Initializing float primitive field value only for a specific target build 173 | * 174 | * @param target The target build, on which the field value should remain 175 | * @param value Float primitive field value 176 | * @param otherValue The value to use if the current target is not valid 177 | */ 178 | public static float floatValue(@NotNull Enum target, @NotNull FloatSupplier otherValue, @NotNull FloatSupplier value) { 179 | return isRuntimeTarget(target) ? value.getAsFloat() : otherValue.getAsFloat(); 180 | } 181 | 182 | /** 183 | * Initializing double primitive field value only for a specific target build 184 | * Another build target value is 0.0 185 | * 186 | * @param target The target build, on which the field value should remain 187 | * @param value Double primitive field value 188 | */ 189 | public static double doubleValue(@NotNull Enum target, @NotNull DoubleSupplier value) { 190 | return doubleValue(target, () -> 0.0, value); 191 | } 192 | 193 | /** 194 | * Initializing double primitive field value only for a specific target build 195 | * 196 | * @param target The target build, on which the field value should remain 197 | * @param value Double primitive field value 198 | * @param otherValue The value to use if the current target is not valid 199 | */ 200 | public static double doubleValue(@NotNull Enum target, @NotNull DoubleSupplier otherValue, @NotNull DoubleSupplier value) { 201 | return isRuntimeTarget(target) ? value.getAsDouble() : otherValue.getAsDouble(); 202 | } 203 | 204 | /** 205 | * Initializing field value only for a specific target build 206 | * Another build target value is null 207 | *

208 | * If you are coding in Kotlin, you may need to add the '-Xno-call-assertions' flag to the compiler options, 209 | * otherwise there will be a NullPointerException exception at runtime, because compiler generate non-null assert 210 | * 211 | * @param target The target build, on which the field value should remain 212 | * @param value Field value 213 | */ 214 | public static T referenceValue(@NotNull Enum target, @NotNull Supplier<@Nullable T> value) { 215 | return referenceValue(target, () -> null, value); 216 | } 217 | 218 | /** 219 | * Initializing field value only for a specific target build 220 | * 221 | * @param target The target build, on which the field value should remain 222 | * @param value Field value 223 | * @param otherValue The value to use if the current target is not valid 224 | */ 225 | public static T referenceValue(@NotNull Enum target, @NotNull Supplier<@Nullable T> otherValue, @NotNull Supplier<@Nullable T> value) { 226 | return isRuntimeTarget(target) ? value.get() : otherValue.get(); 227 | } 228 | 229 | /** 230 | * Calling code only for a specific target build 231 | * 232 | * @param target The target build, on which the called code should remain 233 | * @param code Code to execute 234 | */ 235 | public static void execute(@NotNull Enum target, @NotNull Runnable code) { 236 | if (isRuntimeTarget(target)) { 237 | code.run(); 238 | } 239 | } 240 | 241 | /** 242 | * Allows the build target to be calculated dynamically during program execution 243 | * If the build target is persistent, use the JVM option -Dcutter.runtimeTarget 244 | * The call to this method will be cut when processing 245 | * 246 | * @param target Runtime target build 247 | */ 248 | // TODO: Вырезать ВСЕГДА 249 | public static void setRuntimeTarget(@NotNull Supplier target) { 250 | runtimeTarget = target; 251 | System.out.println("[Cutter] Setup runtime target: " + target.get()); 252 | } 253 | 254 | private static boolean isRuntimeTarget(@NotNull Enum target) { 255 | return runtimeTarget == null || target.name().equals(CutterTarget.DEBUG.name()) || runtimeTarget.get().equals(target.name()); 256 | } 257 | } --------------------------------------------------------------------------------