-
-
Notifications
You must be signed in to change notification settings - Fork 59
/
MixinExtension.groovy
1197 lines (1038 loc) · 43.1 KB
/
MixinExtension.groovy
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of MixinGradle, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* 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.
*/
package org.spongepowered.asm.gradle.plugins
import com.google.common.io.Files
import groovy.transform.PackageScope
import org.gradle.api.DefaultTask
import org.gradle.api.InvalidUserDataException
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.artifacts.Configuration
import org.gradle.api.artifacts.Dependency
import org.gradle.api.artifacts.ProjectDependency
import org.gradle.api.artifacts.ResolvedArtifact
import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.provider.ListProperty
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.SourceSet
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.bundling.AbstractArchiveTask
import org.gradle.api.tasks.compile.JavaCompile
import org.gradle.jvm.tasks.Jar
import org.gradle.util.VersionNumber
import org.spongepowered.asm.gradle.plugins.meta.Imports
import org.spongepowered.asm.gradle.plugins.struct.DynamicProperties
import java.util.Map.Entry
/**
* Extension object for mixin configuration, actually manages the configuration
* of the mixin annotation processor and extensions to sourcesets
*/
public class MixinExtension {
/**
* Task to contribute generated mappings from the AP to the downstream reobf
* tasks
*/
static abstract class ConfigureReobfTask extends DefaultTask {
/**
* Task to contribute mappings to, marked as <tt>@Internal</tt>
* since we don't care about up-to-date checking as this task is merely
* deferred configuration
*/
@Internal
Task reobfTask
/**
* Mapping files to contribute, marked as <tt>@Internal</tt> for the
* same reason as <tt>reobfTask</tt>.
*/
@Internal
Set<File> mappingFiles = []
ConfigureReobfTask() {
// No up-to-date checking, we want to run this always
outputs.upToDateWhen { false }
}
@TaskAction
def run() {
for (File mappingFile : this.mappingFiles) {
if (mappingFile.exists()) {
this.project.logger.info "Contributing tsrg mappings ({}) to {} in {}", mappingFile, reobfTask.name, reobfTask.project
this.addMappingFile(mappingFile)
} else {
this.project.logger.debug "Tsrg file ({}) not found, skipping", mappingFile
}
}
}
/**
* Stub
*/
protected abstract void addMappingFile(File mappingFile);
}
/**
* Reobf configuration task for userdev projects
*/
static class ConfigureReobfTaskForUserDev extends ConfigureReobfTask {
@Override
protected void addMappingFile(File mappingFile) {
def extraMappings = this.reobfTask.properties.extraMappings
// FG5+
if (extraMappings instanceof ConfigurableFileCollection) {
extraMappings.from(mappingFile)
return
}
// Versions of FG prior to 5
this.reobfTask.extraMapping(mappingFile)
}
}
/**
* Reobf configuration task for patcher projects
*/
static class ConfigureReobfTaskForPatcher extends ConfigureReobfTask {
@Override
protected void addMappingFile(File mappingFile) {
def add = [
'--srg-in', mappingFile.absolutePath
]
if (this.reobfTask.args instanceof ListProperty) {
this.reobfTask.args.addAll(add)
} else {
this.reobfTask.args += add
}
}
}
/**
* A simple decorated {@link File} struct which keeps the original refmap
* name internally, so that the relative paths can be preserved when adding
* the refmap to the jar
*/
static class ArtefactSpecificRefmap extends File {
/**
* Preserve original refmap path as-specified so that we can use the
* correct relative path inside the jar
*/
File refMap
ArtefactSpecificRefmap(File parent, String refMap) {
super(parent, refMap)
this.refMap = new File(refMap)
}
}
/**
* Task which contributes generated refmap from configured sourcesets, and
* configs declared by the user, to the (pre-obf) jar
*/
static class AddMixinsToJarTask extends DefaultTask {
@Internal
MixinExtension extension
@Input
Jar remappedJar
@Input
Set<Task> reobfTasks
@InputFiles
Set<File> jarRefMaps = []
@TaskAction
def run() {
// Add the refmap to all reobf'd jars
this.reobfTasks.each { reobfTask ->
def jarTasks = reobfTask.dependsOn.findAll { it == remappedJar }.toSet()
// ForgeGradle 5 uses a mapped task output provider instead of explicitly depending on the jar task.
// So, we need to find that task here.
try {
if (reobfTask.input instanceof org.gradle.api.internal.provider.ValueSupplier) {
reobfTask.input.producer.visitProducerTasks {
if (it == remappedJar) {
jarTasks.add it
}
}
}
} catch (Throwable e) {
// Swallow any issues, since ValueSupplier doesn't exist on Gradle 5 and lower
}
jarTasks.each { jar ->
jarRefMaps.each { artefactSpecificRefMap ->
project.logger.info "Contributing refmap ({}) to {} in {}", artefactSpecificRefMap.refMap, jar.archiveName, reobfTask.project
jar.getRefMaps().from(artefactSpecificRefMap)
jar.from(artefactSpecificRefMap) {
into artefactSpecificRefMap.refMap.parent
}
}
if (this.extension.configNames && !jar.manifest.attributes.containsKey("MixinConfigs")) {
def configNamesCsv = this.extension.configNames.join(',')
project.logger.info "Contributing configs ({}) to manifest of {} in {}", configNamesCsv, jar.archiveName, reobfTask.project
jar.manifest.attributes['MixinConfigs'] = configNamesCsv
}
}
}
}
}
/**
* Cached reference to containing project
*/
@PackageScope final Project project
/**
* ForgeGradle has two major types of projects, with slightly different setups
* 'patcher' is used for developing Forge itself, and any other project that edits Minecraft's source directly.
* 'userdev' is used by modders who are using Forge or other project based on the patcher plugin.
*/
@PackageScope final String projectType
/**
* Detected gradle major version, used in compatibility checks
*/
@PackageScope final int majorGradleVersion
/**
* Version number to include in error message when complaining about missing
* annotation processor
*/
@PackageScope VersionNumber mixinVersionForErrors = null
/**
* Until we add some sourcesets, we will assume that the user hasn't
* configured the plugin in any way (hasn't added a refMap setting on the
* sourceSet or added any sourceSets in the mixin block). If this is the
* case we will attach to all sourceSets in <tt>project.afterEvaluate</tt>
* as our default behaviour. This flag is set to false as soon as
* {@link #add} is called from any source.
*/
private boolean applyDefault = true
/**
* Avoid adding duplicates by adding sourceSets to this collection
*/
private Set<SourceSet> sourceSets = []
/**
* Mapping of refMap names to sourceSet names, used to avoid refMap
* conflicts (or at least notify the user that a conflict has occurred)
*/
private Map<String, String> refMaps = [:]
/**
* AP tokens, if this map is empty then the tokens argument will be omitted,
* otherwise it will be compiled to a semicolon-separated list and passed
* into the
*/
private Map<String, String> tokens = [:]
/**
* System properties to contribute to all runs
*/
@PackageScope DynamicProperties systemProperties = new DynamicProperties("mixin");
/**
* Reobf tasks we will target
*/
@PackageScope Set<Task> reobfTasks = []
/**
* Handles for tasks which add the mixin resources (refmaps, config manifest
* entries) to each jar, one per jar
*/
@PackageScope Set<AddMixinsToJarTask> addMixinsToJarTasks = []
/**
* Set of all specified mixin configs, added to run configurations and jar
* manifests
*/
@PackageScope Set<String> configNames = []
/**
* Collection of message properties
*/
HashMap<String, String> messages = [:]
/**
* If a refMap overlap is detected a warning will be output, however there
* are situations where a refMap overlap may be desired (for example if
* different sourceSets are going into different jars) and thus the warning
* can be ignored. Setting this value to true will suppress the warning.
*/
boolean disableRefMapWarning
/**
* Disables the target validator in the mixin annotation processor.
*/
boolean disableTargetValidator
/**
* Disables the target export in the mixin annotation processor, only
* useful if multiple compile tasks need to be separated from the point of
* view of the mixin AP.
*/
boolean disableTargetExport
/**
* Disables the part of this plugin that tries to add IDE
* integration for the AP to eclipse. Useful if something goes wrong, or
* you want to manage that part yourself.
*/
boolean disableEclipseAddon
/**
* Disables the overwrite checking functionality which raises warnings when
* overwrite methods are not appropriately decorated
*/
boolean disableOverwriteChecker
/**
* Disables the check for the annotation processor dependency on gradle 5
* and above. Potential reasons for doing so being that the AP is present
* but in a different dep, or the detection has just failed for some reason
* and the user wants to override
*/
boolean disableAnnotationProcessorCheck
/**
* Sets the overwrite checker error level, the default is to raise WARNING
* however this can be set to ERROR in order to cause missing decorations
* to be treated as errors
*/
Object overwriteErrorLevel
/**
* The default obfuscation environment to use when generating refMaps. This
* is the obfuscation set which will end up in the <tt>mappings</tt> node
* in the generated refMap.
*/
String defaultObfuscationEnv = "searge"
/**
* Mapping types list to pass to the AP. Mapping services may parse the
* supplied options to determine whether they should activate.
*/
List<Object> mappingTypes = [ "tsrg" ]
/**
* By default we will attempt to find the SRG file to feed to the AP by
* querying the <tt>genSrgs</tt> task, however the user can override the
* file by setting this argument
*/
Object reobfSrgFile
/**
* Instruction for the annotation processor to suppress informational
* messages such as the AP version, etc.
*/
boolean quiet
/**
* Instruction for the annotation processor to decorate all messages with
* the message type. This can be used to determine the type for messages you
* wish to specify custom levels for.
*/
boolean showMessageTypes
/**
* Additional TSRG mapping files to supply to the annotation processor. LTP.
*/
@PackageScope List<Object> extraMappings = []
/**
* Configurations to scan for dependencies when running AP
*/
private Set<Object> importConfigs = []
/**
* Additional libraries to scan when running AP
*/
private Set<Object> importLibs = []
/**
* ctor
*
* @param project reference to the containing project
*/
MixinExtension(Project project) {
this.project = project
this.majorGradleVersion = MixinExtension.detectGradleMajorVersion(project)
if (project.extensions.findByName('minecraft')) {
this.projectType = 'userdev'
} else if (project.extensions.findByName('patcher')) {
this.projectType = 'patcher'
} else {
throw new InvalidUserDataException("Could not find property 'minecraft', or 'patcher' on $project, ensure ForgeGradle is applied.")
}
if (!this.disableEclipseAddon) {
MixinEclipse.configureEclipse(this, this.project, this.projectType)
}
this.init(this.project, this.projectType)
}
/**
* Set up the project by extending relevant objects and adding the
* <tt>afterEvaluate</tt> handler
*/
private void init(Project project, String projectType) {
this.project.afterEvaluate {
// Gather reobf jars for processing
if (projectType == 'userdev') {
// ForgeGradle Modder facing plugin, can have multiple reobf tasks.
project.reobf.each { reobfTaskHandle ->
this.reobfTasks += reobfTaskHandle
}
} else if (projectType == 'patcher') {
// ForgeGradle Patcher plugin, only has one default reobf task.
this.reobfTasks += project.reobfJar
}
// Search for sourceSets with a refmap property and configure them
project.sourceSets.each { set ->
if (set.ext.has("refMap")) {
this.configure(set, projectType)
}
}
// Search for upstream projects and add our jars to their target set
def configuration = majorGradleVersion >= 7 ? project.configurations.implementation : project.configurations.compile
configuration.allDependencies.withType(ProjectDependency) { upstream ->
def mixinExt = upstream.dependencyProject.extensions.findByName("mixin")
if (mixinExt) {
project.reobf.each { reobfTaskWrapper ->
mixinExt.reobfTasks += reobfTaskWrapper
}
}
}
this.applyDefault()
this.configureRuns()
}
SourceSet.metaClass.getRefMap = {
delegate.ext.refMap
}
SourceSet.metaClass.setRefMap = { value ->
delegate.ext.refMap = value
}
AbstractArchiveTask.metaClass.getRefMaps = {
if (!delegate.ext.has('refMaps')) {
delegate.ext.refMaps = majorGradleVersion >= 7 ? project.objects.fileCollection() : project.layout.configurableFiles()
}
delegate.ext.refMaps
}
AbstractArchiveTask.metaClass.setRefMaps = { value ->
delegate.ext.refMaps = value
}
}
/**
* Directive version of {@link #disableRefMapWarning}
*/
void disableRefMapWarning() {
this.disableRefMapWarning = true
}
/**
* Directive version of {@link #disableTargetValidator}
*/
void disableTargetValidator() {
this.disableTargetValidator = true
}
/**
* Directive version of {@link #disableTargetExport}
*/
void disableTargetExport() {
this.disableTargetExport = true
}
/**
* Directive version of {@link #disableEclipseAddon}
*/
void disableEclipseAddon() {
this.disableEclipseAddon = true
}
/**
* Directive version of {@link #disableOverwriteChecker}
*/
void disableOverwriteChecker() {
this.disableOverwriteChecker = true
}
/**
* Directive version of {@link #disableAnnotationProcessorCheck}
*/
void disableAnnotationProcessorCheck() {
this.disableAnnotationProcessorCheck = true
}
/**
* Directive version of {@link #quiet}
*/
void quiet() {
quiet = true
}
/**
* Directive version of {@link #showMessageTypes}
*/
void showMessageTypes() {
showMessageTypes = true
}
/**
* Directive version of {@link #overwriteErrorLevel}
*/
void overwriteErrorLevel(Object errorLevel) {
this.overwriteErrorLevel = errorLevel
}
/**
* Getter for reobfSrgFile, fetch from the <tt>genSrgs</tt> task if not configured
*/
Object getMappings() {
if (this.reobfSrgFile != null) {
return project.file(this.reobfSrgFile)
} else if (this.projectType == 'userdev') {
return project.tasks.createMcpToSrg.outputs.files[0]
} else if (this.projectType == 'patcher') {
return project.tasks.createMcp2Srg.outputs.files[0]
}
return null
}
/**
* Adds an additional TSRG file for the AP to consume.
*
* @param file Object which resolves to a file
*/
void extraMappings(Object file) {
this.extraMappings += file
}
/**
* Adds a boolean token with the value true
*
* @param name boolean token name
*/
void token(Object name) {
token(name, "true")
}
/**
* Adds a token with the specified value
*
* @param name Token name
* @param value Token value
*/
void token(Object name, Object value) {
this.tokens.put(name.toString().trim(), value.toString().trim())
}
/**
* Add multiple tokens in one go by providing a map
*
* @param map map of tokens to add
* @return fluent interface
*/
MixinExtension tokens(Map<String, ?> map) {
for (Entry<String, ?> entry : map) {
this.tokens.put(entry.key.trim(), entry.value.toString().trim())
}
}
/**
* Return current tokens as an unmodifyable map
*/
Map<String, String> getTokens() {
Collections.unmodifiableMap(this.tokens)
}
/**
* Sanity check current tokens before passing them to the AP
*/
@PackageScope void checkTokens() {
this.tokens.find { it.value.contains(';') }.each {
throw new InvalidUserDataException("Invalid token value '${it.value}' for token '${it.key}'")
}
}
/**
* Handle the default behaviour of adding all sourceSets if no sourceSets
* were explicitly added
*/
@PackageScope void applyDefault() {
if (this.applyDefault) {
this.applyDefault = false
project.logger.info "No sourceSets added for mixin processing, applying defaults"
this.disableRefMapWarning = true
project.sourceSets.each { set ->
if (!set.ext.has("refMap")) {
set.ext.refMap = "mixin.refmap.json"
}
this.configure(set, this.projectType)
}
}
}
/**
* Configure all run configurations with mixin config args and any mixin
* debug args specified in the mixin closure
*/
@PackageScope void configureRuns() {
if (this.projectType == 'userdev') {
project.extensions.minecraft.runs.each { runConfig ->
if (project.tasks.findByName('createSrgToMcp')) {
def srgToMcpFile = project.tasks.createSrgToMcp.outputs.files[0].path
// Supply the legacy GradleStart property which identifies the remapping file
runConfig.property 'net.minecraftforge.gradle.GradleStart.srg.srg-mcp', srgToMcpFile
// If the user has already specified remapRefMap then we assume they either
// supplied a mapping file path manually, or mixin will fall back on the
// GradleStart property above. If the user has specified these options in
// the mixin closure then the values will be overwritten below anyway.
if (!runConfig.properties.containsKey('mixin.env.remapRefMap')) {
runConfig.property 'mixin.env.remapRefMap', 'true'
runConfig.property 'mixin.env.refMapRemappingFile', srgToMcpFile
}
}
this.configNames.each { configName ->
runConfig.args '--mixin.config', configName
}
this.systemProperties.args.each {
runConfig.property it.key, it.value.toString()
}
}
}
}
/**
* Searches the compile configuration of each SourceSet that has been
* registered via add() looking for the mixin dependency. If the mixin
* dependency is found and the current gradle version is 5 or higher then
* check that the Annotation Processor artefact has been added to the
* corresponding annotationProcessor configuration for the SourceSet and
* raise an error if the AP was not found.
*
* <p>This is necessary because in previous versions of gradle, APs in
* compile dependencies were automatically added, however since gradle 5
* they must be explicitly specified but knowing this assumes that all end
* users read the gradle upgrade notes when changing versions, which is not
* realistically the case. So thanks gradle.</p>
*/
@PackageScope void checkForAnnotationProcessors() {
if (this.disableAnnotationProcessorCheck || (this.majorGradleVersion < 5 && this.majorGradleVersion > 0)) {
return
}
def missingAPs = this.findMissingAnnotationProcessors()
if (missingAPs) {
def gradleVersion = this.majorGradleVersion > 4 ? "Gradle ${this.majorGradleVersion} " : "An unrecognised gradle version "
def missingAPNames = missingAPs.collect { it.annotationProcessorConfigurationName }
def addAPName = missingAPNames.size() > 1 ? '<configurationName>' : missingAPNames[0]
def eachOfThese = missingAPNames.size() > 1 ? " where <configurationName> is each of $missingAPNames." : ''
def mixinVersion = this.mixinVersionForErrors ?: '0.1.2-SNAPSHOT'
def message = "$gradleVersion was detected but the mixin dependency was missing from one or more Annotation Processor " +
"configurations: $missingAPNames. To enable the Mixin AP please include the mixin processor artefact in each Annotation " +
"Processor configuration. For example if you are using mixin dependency 'org.spongepowered:mixin:$mixinVersion' you " +
"should specify: dependencies { $addAPName 'org.spongepowered:mixin:$mixinVersion:processor' }$eachOfThese. If you " +
"believe you are seeing this message in error, you can disable this check via by adding disableAnnotationProcessorCheck() " +
"to your mixin { } block."
// Only promote the error message to an actual error if we're sure there's a gradle version mismatch
if (this.majorGradleVersion >= 5) {
throw new MixinGradleException(message)
} else {
this.project.logger.error message
}
}
}
/**
* Searches for the annotation processor dependency in all sourceset ap
* configurations which have a refmap. Returns true if the AP is found and
* false if it is not found in any added configuration.
*/
@PackageScope Set<SourceSet> findMissingAnnotationProcessors() {
Set<SourceSet> missingAPs = []
missingAPs += this.sourceSets.findResults { SourceSet sourceSet ->
sourceSet.ext.mixinDependency = majorGradleVersion >= 7
? this.findMixinDependency(sourceSet.implementationConfigurationName)
: (this.findMixinDependency(sourceSet.compileConfigurationName) ?: this.findMixinDependency(sourceSet.implementationConfigurationName))
if (sourceSet.ext.mixinDependency) {
VersionNumber mainVersion = this.getDependencyVersion(sourceSet.ext.mixinDependency)
if (mainVersion > this.mixinVersionForErrors) {
this.mixinVersionForErrors = mainVersion
}
sourceSet.ext.apDependency = this.findMixinDependency(sourceSet.annotationProcessorConfigurationName)
if (sourceSet.ext.apDependency) {
VersionNumber apVersion = this.getDependencyVersion(sourceSet.ext.apDependency)
if (mainVersion > apVersion) {
this.project.logger.warn "Mixin AP version ($apVersion) in configuration '${sourceSet.annotationProcessorConfigurationName}' is older than compile version ($mainVersion)"
}
} else {
return sourceSet
}
}
}
return missingAPs
}
/**
* Checks whether a configuration contains any mixin dependency in its
* explicit or resolved dependency artefacts
*
* @param configurationName Configuration name to check
* @return true if the configuration contains a mixin dependency
*/
@PackageScope def findMixinDependency(String configurationName) {
def configuration = project.configurations[configurationName]
return configuration.canBeResolved
? configuration.resolvedConfiguration.resolvedArtifacts.find { it.id =~ /:mixin:/ }
: configuration.allDependencies.find { it.group =~ /spongepowered/ && it.name =~ /mixin/ }
}
/**
* Detected dependencies might be a resolved artefact or a declared
* dependency (depending on where we are in the build lifecycle). This
* method abstracts parsing a dependency version from either supported
* object type.
*/
@PackageScope VersionNumber getDependencyVersion(def dependency) {
if (dependency instanceof ResolvedArtifact) {
return VersionNumber.parse(dependency.moduleVersion.id.version)
} else if (dependency instanceof Dependency) {
return VersionNumber.parse(dependency.version)
}
}
/**
* Register a mixin config which will be added to all reobf'd jar manifests
* and all run configurations
*/
void config(String path) {
this.configNames += path
}
/**
* Accessor for system properties starting with mixin.debug
*/
def getDebug() {
return this.systemProperties.debug
}
/**
* Accessor for system property mixin.debug
*/
def setDebug(def value) {
this.systemProperties.debug = value
}
/**
* Accessor for system properties starting with mixin.checks
*/
def getChecks() {
return this.systemProperties.checks
}
/**
* Accessor for system property mixin.checks
*/
def setChecks(def value) {
this.systemProperties.checks = value
}
/**
* Accessor for system property mixin.dumpTargetOnFailure
*/
def getDumpTargetOnFailure() {
return this.systemProperties.dumpTargetOnFailure
}
/**
* Accessor for system property mixin.dumpTargetOnFailure
*/
def setDumpTargetOnFailure(def value) {
this.systemProperties.dumpTargetOnFailure = value
}
/**
* Accessor for system property mixin.ignoreConstraints
*/
def getIgnoreConstraints() {
return this.systemProperties.ignoreConstraints
}
/**
* Accessor for system property mixin.ignoreConstraints
*/
def setIgnoreConstraints(def value) {
this.systemProperties.ignoreConstraints = value
}
/**
* Accessor for system property mixin.hotSwap
*/
def getHotSwap() {
return this.systemProperties.hotSwap
}
/**
* Accessor for system property mixin.hotSwap
*/
def setHotSwap(def value) {
this.systemProperties.hotSwap = value
}
/**
* Accessor for system properties starting with mixin.env
*/
def getEnv() {
return this.systemProperties.env
}
/**
* Accessor for system property mixin.env
*/
def setEnv(def value) {
this.systemProperties.env = value
}
/**
* Accessor for system property mixin.initialiserInjectionMode
*/
def getInitialiserInjectionMode() {
return this.systemProperties.initialiserInjectionMode
}
/**
* Accessor for system property mixin.initialiserInjectionMode
*/
def setInitialiserInjectionMode(def mode) {
this.systemProperties.initialiserInjectionMode = mode
}
def messages(Closure closure) {
closure.delegate = this.messages
closure()
}
/**
* Add a sourceSet for mixin processing by name, the sourceSet must exist
* and define the <tt>refMap</tt> property.
*
* @param set SourceSet name
*/
void add(String set) {
this.add(project.sourceSets[set])
}
/**
* Add a sourceSet for mixin processing, the sourceSet must define the
* <tt>refMap</tt> property.
*
* @param set SourceSet to add
*/
void add(SourceSet set) {
try {
set.getRefMap()
} catch (e) {
throw new InvalidUserDataException(sprintf('No \'refMap\' or \'ext.refMap\' defined on %s. Call \'add(sourceSet, refMapName)\' instead.', set))
}
this.manuallyAdd(set)
}
/**
* Add a sourceSet by name for mixin processing and specify the refMap name,
* the SourceSet must exist
*
* @param set SourceSet name
* @param refMapName RefMap name
*/
void add(String set, Object refMapName) {
SourceSet sourceSet = project.sourceSets.findByName(set)
if (sourceSet == null) {
throw new InvalidUserDataException(sprintf('No sourceSet \'%s\' was found', set))
}
sourceSet.ext.refMap = refMapName
this.manuallyAdd(sourceSet)
}
/**
* Add a sourceSet for mixin processing and specify the refMap name, the
* SourceSet must exist
*
* @param set SourceSet to add
* @param refMapName RefMap name
*/
void add(SourceSet set, Object refMapName) {
set.ext.refMap = refMapName.toString()
this.manuallyAdd(set)
}
/**
* We need to disable the flag early, because our main after evaluate happens before the one we are adding now.
*/
void manuallyAdd(SourceSet set) {
// Don't perform default behaviour, a sourceSet has been added manually
this.applyDefault = false
String pType = this.projectType
project.afterEvaluate {
this.configure(set, pType)
}
}
/**
* Configure a sourceSet for mixin processing and specify the refMap name,
* the SourceSet must exist
*
* @param set SourceSet to add
*/
void configure(SourceSet set, String projectType) {
// Check whether this sourceSet was already added
if (!this.sourceSets.add(set)) {
project.logger.info "Not adding {} to mixin processor, sourceSet already added", set
return
}
project.logger.info "Adding {} to mixin processor", set
// Get the sourceSet's compile task
def compileTask = project.tasks[set.compileJavaTaskName]
if (!(compileTask instanceof JavaCompile)) {
throw new InvalidUserDataException(sprintf('Cannot add non-java %s to mixin processor', set))
}
// Don't perform default behaviour, a sourceSet has been added manually
this.applyDefault = false
// For closures below
def refMaps = this.refMaps
// Refmap file
def refMapFile = project.file("${compileTask.temporaryDir}/${compileTask.name}-refmap.json")
// Generated tsrg file
def tsrgFile = project.file("${compileTask.temporaryDir}/${compileTask.name}-mappings.tsrg")
// Add our vars as extension properties to the sourceSet and compile
// tasks, this will allow them to be used in the build script if needed
compileTask.ext.outTsrgFile = tsrgFile
compileTask.ext.refMapFile = refMapFile
set.ext.refMapFile = refMapFile
compileTask.ext.refMap = set.ext.refMap.toString()
// We need createMcpToSrg to run in order to generate the mappings
// consumed by the AP
if (this.projectType == 'userdev') {
compileTask.dependsOn("createMcpToSrg")
} else if (this.projectType == 'patcher') {
compileTask.dependsOn("createMcp2Srg")
}
// Closure to prepare AP environment before compile task runs
compileTask.doFirst {
if (!this.disableRefMapWarning && refMaps[compileTask.ext.refMap]) {
project.logger.warn "Potential refmap conflict. Duplicate refmap name {} specified for sourceSet {}, already defined for sourceSet {}",
compileTask.ext.refMap, set.name, refMaps[compileTask.ext.refMap]
} else {
refMaps[compileTask.ext.refMap] = set.name
}
refMapFile.delete()
tsrgFile.delete()
this.checkTokens()
this.applyCompilerArgs(compileTask)
}
// Refmap is generated with a generic name, rename to sourceset-specific
// name ready for inclusion into target jar. We can't use rename in the