aboutsummaryrefslogtreecommitdiff
path: root/build.gradle
blob: 8b5242fc8f0b7920bf1886a1c91fc4d4fbb2e2eb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        // Needed for bytecode manipulation
        classpath 'org.ow2.asm:asm-all:5.2'
    }
}

plugins {
  id 'net.minecrell.licenser' version '0.3'
  id 'org.ajoberstar.grgit' version '2.3.0'
  //id 'com.github.johnrengelman.shadow' version '2.0.4'
}

import java.nio.file.Paths
import org.objectweb.asm.ClassReader
import org.objectweb.asm.ClassWriter
import org.objectweb.asm.Opcodes
import org.objectweb.asm.tree.ClassNode
import org.objectweb.asm.tree.MethodInsnNode
import org.objectweb.asm.tree.VarInsnNode
import org.objectweb.asm.tree.InsnNode

import java.util.jar.JarFile

apply plugin: 'java'
apply plugin: 'maven-publish'
apply plugin: 'eclipse'

group = 'net.minecraftforge'
version = gitVersion()
def gitVersion() {
    def raw = grgit.describe(longDescr: true)
    def desc = (raw == null ? 'unknown-unknown-unknown' : raw).split('-') as List
    def hash = desc.remove(desc.size() - 1)
    def offset = desc.remove(desc.size() - 1)
    def tag = desc.join('-')
    def branch = grgit.branch.current().name
    return "${tag}.${offset}" //${t -> if (branch != 'master') t << '-' + branch}"
}

sourceSets {
    api
    shared
    gradlecomp
    java9
}

repositories {
    jcenter()
    mavenCentral()
}

configurations {
    sharedImplementation.extendsFrom apiImplementation
    gradlecompImplementation.extendsFrom sharedImplementation

    compile.extendsFrom sharedImplementation
    compile.extendsFrom gradlecompImplementation
}

dependencies {
    java9Implementation files(sourceSets.main.output.classesDirs) { builtBy compileJava }
    
    sharedImplementation sourceSets.api.output
    sharedImplementation 'commons-io:commons-io:2.4'

    gradlecompImplementation sourceSets.shared.output
    gradlecompImplementation gradleApi()
    gradlecompImplementation 'com.google.guava:guava:26.0-jre'
    gradlecompImplementation 'commons-io:commons-io:2.4'

    compile sourceSets.api.output
    compile sourceSets.shared.output
    compile sourceSets.gradlecomp.output
}


// Default all standard Java compile tasks to Java 8
// We'll specify Java 9 only for the java9 compile task
tasks.withType(JavaCompile) {
    options.encoding = 'utf-8'
    options.deprecation = true
    sourceCompatibility = 8
    targetCompatibility = 8
    options.compilerArgs.addAll(['--release', '8'])
}

project(':artifactural9') {
    apply plugin: 'java'
    apply plugin: 'eclipse'
    sourceCompatibility = targetCompatibility = 9
    group = rootProject.group
    
    sourceSets {
        java9.java.srcDirs = [rootProject.file('src/java9').getAbsolutePath()]
    }
    
    eclipse {
        project {
            name rootProject.name + '9'
            linkedResource name: 'java9', type: '2', location: rootProject.file('src/java9').getAbsolutePath()
        }
        jdt {
            sourceCompatibility = targetCompatibility = 9
        }
    }
    
    tasks.withType(JavaCompile) {
        options.encoding = 'utf-8'
        sourceCompatibility = 9
        targetCompatibility = 9
        options.compilerArgs.addAll(['--release', '9'])
    }
}

def gradleRepositoryAdapterPath = Paths.get("com", "amadornes", "artifactural", "gradle", "GradleRepositoryAdapter.class")
def classesDirs = sourceSets.gradlecomp.output.classesDirs.getFiles().first().toPath()


def _constructorName = "<init>"
def _constructorDesc = "(Lcom/amadornes/artifactural/api/repository/Repository;Lorg/gradle/api/internal/artifacts/repositories/DefaultMavenLocalArtifactRepository;)V"
def _modifiedSuperDesc = "()V"

// This task patches 'GradleRepositoryAdapter' to make it compatibile with both Gradle 4.9 and 4.10
// In Gradle 4.9, the constructor of AbstractArtifactRepository changes has zero arguments
// (instead of the one-argument constructor in 4.10, which we compile against)
// It's not possible to write a normal Java class that calls a constructor which doesn't exist at compile time.
// Therefore, we need to patch the bytecode of the class to properly call the non-arg super() constrcutor
class PatchGradleRepositoryAdapter extends DefaultTask {

    @Input String constructorName
    @Input String constructorDesc
    @Input String modifiedSuperDesc
    @Input File gradleRepositoryAdapter
    @Input File classesDir
    @OutputDirectory java.nio.file.Path outputDir


    @TaskAction
    void patchClass() {
        def originalGradleRepositoryAdapter = Paths.get(classesDir.toString(), gradleRepositoryAdapter.toString())

        ClassNode node = new ClassNode()
        ClassReader reader = new ClassReader(new FileInputStream(originalGradleRepositoryAdapter.toFile()))
        reader.accept(node, 0)


        def constructor = node.methods.find {
            it.name == constructorName && it.desc == constructorDesc
        }

        def getDescriptor = node.methods.find {
            it.name == "getDescriptor"
        }

        if (constructor == null) {
            throw new RuntimeException("Failed to find target constructor!")
        }

        if (getDescriptor == null) {
            throw new RuntimeException("Failed to find getDescriptor()")
        }

        // Strip out this method - it only exists
        // so that GradleRepositoryAdapter will compile
        node.methods.remove(getDescriptor)

        def superInvoc = constructor.instructions.find {
            it instanceof MethodInsnNode && it.owner == "org/gradle/api/internal/artifacts/repositories/AbstractArtifactRepository"
        } as MethodInsnNode

        if (superInvoc == null) {
            throw new RuntimeException("Failed to find target super() invocation!")
        }

        superInvoc.desc = modifiedSuperDesc

        def aconstNull = superInvoc.previous
        if (!(aconstNull instanceof InsnNode) || aconstNull.type != 0) {
            throw new RuntimeException("Unexpected instruction: " + aconstNull)
        }

        constructor.instructions.remove(aconstNull)

        // Push first parameter of constructor (the ObjectFactory) onto the stack.
        // This has the effect of calling super(objectFactory)
        //constructor.instructions.insertBefore(superInvoc, new VarInsnNode(Opcodes.ALOAD, 1))

        ClassWriter writer = new ClassWriter(0)
        node.accept(writer)

        def outputFile = outputDir.resolve(gradleRepositoryAdapter.toPath()).toFile()

        outputFile.parentFile.mkdirs()
        FileOutputStream fs = new FileOutputStream(outputFile)
        fs.write(writer.toByteArray())
    }
}

task patchConstructor(type: PatchGradleRepositoryAdapter) {
    constructorName = _constructorName
    constructorDesc = _constructorDesc
    modifiedSuperDesc = _modifiedSuperDesc
    classesDir = classesDirs.toFile()
    outputDir = Paths.get(buildDir.toString(), "modifiedclasses")
    gradleRepositoryAdapter = gradleRepositoryAdapterPath.toFile()
}

jar {
    from sourceSets.api.output
    from sourceSets.shared.output
    from(sourceSets.gradlecomp.output) {
        exclude gradleRepositoryAdapterPath.toString()
    }

    from patchConstructor.outputs
    
    into('META-INF/versions/9') {
        from project(':artifactural9').sourceSets.java9.output
    }
    
    manifest {
        attributes(
            'Multi-Release': 'true'
        )
    }
}

jar.doLast {
    def jarPath = it.outputs.files.getFiles().first()
    def jarFile = new JarFile(jarPath)
    def entry = jarFile.getEntry(gradleRepositoryAdapterPath.toString().replace('\\', '/'))
    def stream = jarFile.getInputStream(entry)

    ClassReader reader = new ClassReader(stream)
    ClassNode node = new ClassNode()
    reader.accept(node, 0)

    def constructor = node.methods.find {
        it.name == _constructorName && it.desc == _constructorDesc
    }

    def superInvoc = constructor.instructions.find {
        it instanceof MethodInsnNode && it.owner == "org/gradle/api/internal/artifacts/repositories/AbstractArtifactRepository"
    } as MethodInsnNode

    if (superInvoc.desc == _modifiedSuperDesc) {
        println("Successfully modified super() call!")
    } else {
        throw new RuntimeException("Failed to modify super() invocation - got desc of " + superInvoc.desc)
    }

    def getDescriptor = node.methods.find { it.name == "getDescriptor"}
    if (getDescriptor != null) {
        throw new RuntimeException("Failed to remove getDescriptor with signature: " + getDescriptor.signature)
    } else {
        println("Successfully stripped getDescriptor method!")
    }
}

task sourcesJar(type: Jar, dependsOn: classes) {
    classifier = 'sources'
    from sourceSets.api.allSource
    from sourceSets.shared.allSource
    from sourceSets.gradlecomp.allSource
}


license {
    header = file("$rootDir/LICENSE-header.txt")
}

publishing {
    publications {
        mavenJava(MavenPublication) {
            from components.java
            artifact tasks.sourcesJar
            pom {
                groupId = project.group
                version = project.version
                artifactId = project.archivesBaseName
                name = project.archivesBaseName
                packaging = 'jar'
                description = 'A Gradle artifact processing and management tool'
                url = 'https://github.com/MinecraftForge/Artifactural/'

                scm {
                    url = 'https://github.com/MinecraftForge/Artifactural/'
                    connection = 'scm:git:git://github.com/MinecraftForge/Artifactural.git'
                    developerConnection = 'scm:git:git@github.com:MinecraftForge/Artifactural.git'
                }
                issueManagement {
                    system = 'github'
                    url = 'https://github.com/MinecraftForge/Artifactural/issues'
                }
                licenses {
                    license {
                        name = 'LGPL-2.1'
                        url = 'https://www.gnu.org/licenses/lgpl-2.1.txt'
                        distribution = 'repo'
                    }
                }
            }
        }
    }
    repositories {
        maven {
            if (project.hasProperty('mavenPassword')) {
                credentials {
                    username = project.properties.mavenUser
                    password = project.properties.mavenPassword
                }
                url 'https://files.minecraftforge.net/maven/manage/upload'
            } else {
                url 'file://' + rootProject.file('repo').getAbsolutePath()
            }
        }
    }
}

if (!JavaVersion.current().java9Compatible) {
    println("You must build this with JDK 9")
    System.exit(1)
}