forked from DimensionalDevelopment/ForgeGradle
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathBasePlugin.java
More file actions
888 lines (772 loc) · 33.9 KB
/
BasePlugin.java
File metadata and controls
888 lines (772 loc) · 33.9 KB
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
/*
* A Gradle plugin for the creation of Minecraft mods and MinecraftForge plugins.
* Copyright (C) 2013-2018 Minecraft Forge
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package net.minecraftforge.gradle.common;
import com.google.common.base.Charsets;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.io.ByteStreams;
import com.google.common.io.Files;
import com.google.gson.reflect.TypeToken;
import groovy.lang.Closure;
import net.minecraftforge.gradle.tasks.*;
import net.minecraftforge.gradle.util.FileLogListenner;
import net.minecraftforge.gradle.util.GradleConfigurationException;
import net.minecraftforge.gradle.util.delayed.*;
import net.minecraftforge.gradle.util.json.JsonFactory;
import net.minecraftforge.gradle.util.json.fgversion.FGBuildStatus;
import net.minecraftforge.gradle.util.json.fgversion.FGVersion;
import net.minecraftforge.gradle.util.json.fgversion.FGVersionWrapper;
import net.minecraftforge.gradle.util.json.version.ManifestVersion;
import net.minecraftforge.gradle.util.json.version.Version;
import org.gradle.api.*;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.Configuration.State;
import org.gradle.api.artifacts.Dependency;
import org.gradle.api.artifacts.dsl.DependencyHandler;
import org.gradle.api.artifacts.repositories.FlatDirectoryArtifactRepository;
import org.gradle.api.artifacts.repositories.MavenArtifactRepository;
import org.gradle.api.logging.Logger;
import org.gradle.api.logging.Logging;
import org.gradle.api.plugins.ExtraPropertiesExtension;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.Delete;
import org.gradle.testfixtures.ProjectBuilder;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static net.minecraftforge.gradle.common.Constants.*;
public abstract class BasePlugin<K extends BaseExtension> implements Plugin<Project>
{
private static final Logger LOGGER = Logging.getLogger(BasePlugin.class);
public Project project;
public BasePlugin<?> otherPlugin;
public ReplacementProvider replacer = new ReplacementProvider();
private Map<String, ManifestVersion> mcManifest;
private Version mcVersionJson;
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public final void apply(Project arg)
{
project = arg;
// check for gradle version
{
List<String> split = Splitter.on('.').splitToList(project.getGradle().getGradleVersion());
int major = Integer.parseInt(split.get(0));
int minor = Integer.parseInt(split.get(1).split("-")[0]);
if (major <= 1 || (major == 2 && minor < 3))
throw new RuntimeException("ForgeGradle 2.0 requires Gradle 2.3 or above.");
}
// check for java version
{
if ("9".equals(System.getProperty("java.specification.version")) && !"true".equals(System.getProperty("forgegradle.overrideJava9Check")))
throw new RuntimeException("ForgeGradle does not currently support Java 9");
}
if (project.getBuildDir().getAbsolutePath().contains("!"))
{
LOGGER.error("Build path has !, This will screw over a lot of java things as ! is used to denote archive paths, REMOVE IT if you want to continue");
throw new RuntimeException("Build path contains !");
}
// set the obvious replacements
replacer.putReplacement(REPLACE_CACHE_DIR, cacheFile("").getAbsolutePath());
replacer.putReplacement(REPLACE_BUILD_DIR, project.getBuildDir().getAbsolutePath());
// logging
{
File projectCacheDir = project.getGradle().getStartParameter().getProjectCacheDir();
if (projectCacheDir == null)
projectCacheDir = new File(project.getProjectDir(), ".gradle");
replacer.putReplacement(REPLACE_PROJECT_CACHE_DIR, projectCacheDir.getAbsolutePath());
FileLogListenner listener = new FileLogListenner(new File(projectCacheDir, "gradle.log"));
project.getLogging().addStandardOutputListener(listener);
project.getLogging().addStandardErrorListener(listener);
project.getGradle().addBuildListener(listener);
}
// extension objects
{
Type t = getClass().getGenericSuperclass();
while (t instanceof Class)
{
t = ((Class) t).getGenericSuperclass();
}
project.getExtensions().create(EXT_NAME_MC, (Class<K>) ((ParameterizedType) t).getActualTypeArguments()[0], this);
}
// add buildscript usable tasks
{
ExtraPropertiesExtension ext = project.getExtensions().getExtraProperties();
ext.set("SignJar", SignJar.class);
ext.set("Download", Download.class);
ext.set("EtagDownload", EtagDownloadTask.class);
ext.set("CrowdinDownload", CrowdinDownload.class);
ext.set("JenkinsChangelog", JenkinsChangelog.class);
}
// repos
project.allprojects(new Action<Project>() {
public void execute(Project proj)
{
addMavenRepo(proj, "forge", URL_FORGE_MAVEN);
proj.getRepositories().mavenCentral();
addMavenRepo(proj, "minecraft", URL_LIBRARY);
}
});
// do Mcp Snapshots Stuff
getRemoteJsons();
project.getConfigurations().maybeCreate(CONFIG_MCP_DATA);
project.getConfigurations().maybeCreate(CONFIG_MAPPINGS);
// set other useful configs
project.getConfigurations().maybeCreate(CONFIG_MC_DEPS);
project.getConfigurations().maybeCreate(CONFIG_MC_DEPS_CLIENT);
project.getConfigurations().maybeCreate(CONFIG_NATIVES);
project.getConfigurations().maybeCreate(CONFIG_FFI_DEPS);
addFernFlowerInvokerDeps();
// should be assumed until specified otherwise
project.getConfigurations().getByName(CONFIG_MC_DEPS).extendsFrom(project.getConfigurations().getByName(CONFIG_MC_DEPS_CLIENT));
// after eval
project.afterEvaluate(new Action<Project>() {
@Override
public void execute(Project project)
{
// dont continue if its already failed!
if (project.getState().getFailure() != null)
return;
afterEvaluate();
}
});
// some default tasks
makeCommonTasks();
// at last, apply the child plugins
applyPlugin();
}
public abstract void applyPlugin();
private static boolean displayBanner = true;
private void getRemoteJsons()
{
// MCP json
File jsonCache = cacheFile("McpMappings.json");
File etagFile = new File(jsonCache.getAbsolutePath() + ".etag");
String mcpJson = getWithEtag(URLS_MCP_JSON, jsonCache, etagFile);
getExtension().mcpJson = JsonFactory.GSON.fromJson(mcpJson, new TypeToken<Map<String, Map<String, int[]>>>() {}.getType());
// MC manifest json
jsonCache = cacheFile("McManifest.json");
etagFile = new File(jsonCache.getAbsolutePath() + ".etag");
mcManifest = JsonFactory.GSON.fromJson(getWithEtag(URL_MC_MANIFEST, jsonCache, etagFile), new TypeToken<Map<String, ManifestVersion>>() {}.getType());
}
protected void afterEvaluate()
{
// validate MC version
if (Strings.isNullOrEmpty(getExtension().getVersion()))
{
throw new GradleConfigurationException("You must set the Minecraft version!");
}
// JavaPluginConvention javaConv = (JavaPluginConvention) project.getConvention().getPlugins().get("java");
// ApplyFernFlowerTask ffTask = ((ApplyFernFlowerTask) project.getTasks().getByName("decompileJar"));
// ffTask.setClasspath(javaConv.getSourceSets().getByName("main").getCompileClasspath());
// http://files.minecraftforge.net/maven/de/oceanlabs/mcp/mcp_config/1.13.1/mcp_config-1.13.1.zip
project.getDependencies().add(CONFIG_MAPPINGS, ImmutableMap.of(
"group", "de.oceanlabs.mcp",
"name", delayedString("mcp_" + REPLACE_MCP_CHANNEL).call(),
"version", delayedString(REPLACE_MCP_VERSION + "-" + REPLACE_MCP_MCVERSION).call(),
"ext", "zip"
));
project.getDependencies().add(CONFIG_MCP_DATA, ImmutableMap.of(
"group", "de.oceanlabs.mcp",
"name", "mcp_config",
"version", delayedString(REPLACE_MC_VERSION).call(),
"ext", "zip"
));
// Check FG Version, unless its disabled
List<String> lines = Lists.newArrayListWithExpectedSize(5);
Object disableUpdateCheck = project.getProperties().get("net.minecraftforge.gradle.disableUpdateChecker");
if (!"true".equals(disableUpdateCheck) && !"yes".equals(disableUpdateCheck) && !new Boolean(true).equals(disableUpdateCheck))
{
doFGVersionCheck(lines);
}
if (!displayBanner)
return;
LOGGER.lifecycle("#################################################");
LOGGER.lifecycle(" ForgeGradle {} ", this.getVersionString());
LOGGER.lifecycle(" https://github.com/MinecraftForge/ForgeGradle ");
LOGGER.lifecycle("#################################################");
LOGGER.lifecycle(" Powered by MCP ");
LOGGER.lifecycle(" http://modcoderpack.com ");
LOGGER.lifecycle(" by: Searge, ProfMobius, R4wk, ZeuX ");
LOGGER.lifecycle(" Fesh0r, IngisKahn, bspkrs, LexManos ");
LOGGER.lifecycle("#################################################");
for (String str : lines)
LOGGER.lifecycle(str);
displayBanner = false;
}
private String getVersionString()
{
String version = this.getClass().getPackage().getImplementationVersion();
if (Strings.isNullOrEmpty(version))
{
version = this.getExtension().forgeGradleVersion + "-unknown";
}
return version;
}
protected void doFGVersionCheck(List<String> outLines)
{
String version = getExtension().forgeGradleVersion;
if (version.endsWith("-SNAPSHOT"))
{
// no version checking necessary if the are on the snapshot already
return;
}
final String checkUrl = "https://www.abrarsyed.com/ForgeGradleVersion.json";
final File jsonCache = cacheFile("ForgeGradleVersion.json");
final File etagFile = new File(jsonCache.getAbsolutePath() + ".etag");
FGVersionWrapper wrapper = JsonFactory.GSON.fromJson(getWithEtag(checkUrl, jsonCache, etagFile), FGVersionWrapper.class);
FGVersion webVersion = wrapper.versionObjects.get(version);
String latestVersion = wrapper.versions.get(wrapper.versions.size()-1);
if (webVersion == null || webVersion.status == FGBuildStatus.FINE)
{
return;
}
// broken implies outdated
if (webVersion.status == FGBuildStatus.BROKEN)
{
outLines.add("ForgeGradle "+webVersion.version+" HAS " + (webVersion.bugs.length > 1 ? "SERIOUS BUGS" : "a SERIOUS BUG") + "!");
outLines.add("UPDATE TO "+latestVersion+" IMMEDIATELY!");
outLines.add(" Bugs:");
for (String str : webVersion.bugs)
{
outLines.add(" -- "+str);
}
outLines.add("****************************");
return;
}
else if (webVersion.status == FGBuildStatus.OUTDATED)
{
outLines.add("ForgeGradle "+latestVersion + " is out! You should update!");
outLines.add(" Features:");
for (int i = webVersion.index; i < wrapper.versions.size(); i++)
{
for (String feature : wrapper.versionObjects.get(wrapper.versions.get(i)).changes)
{
outLines.add(" -- " + feature);
}
}
outLines.add("****************************");
}
onVersionCheck(webVersion, wrapper);
}
/**
* Function to do stuff with the version check json information. Is called afterEvaluate
*
* @param version The ForgeGradle version
* @param wrapper Version wrapper
*/
protected void onVersionCheck(FGVersion version, FGVersionWrapper wrapper)
{
// not required.. but you probably wanan implement this
}
private void addFernFlowerInvokerDeps()
{
DependencyHandler deps = project.getDependencies();
// Get dependencies from current FG
Project parent = project;
Dependency fgDepTemp = null;
Configuration buildscriptClasspath = null;
while (parent != null && fgDepTemp == null) {
buildscriptClasspath = parent.getBuildscript().getConfigurations().getByName("classpath");
fgDepTemp = Iterables.getFirst(buildscriptClasspath.getDependencies().matching(new Spec<Dependency>() {
@Override
public boolean isSatisfiedBy(Dependency element)
{
return element.getName().equals(GROUP_FG);
}
}), null);
parent = parent.getParent();
}
final Dependency fgDep = fgDepTemp;
if (fgDep == null) {
// This shouldn't happen, unless people are doing really wonky stuff
LOGGER.warn("Missing FG dep in buildscript classpath. Forking decompilation is likely to break.");
return;
}
// This adds all of the dependencies of FG
deps.add(CONFIG_FFI_DEPS, project.files(buildscriptClasspath.getResolvedConfiguration().getFiles(new Spec<Dependency>() {
@Override
public boolean isSatisfiedBy(Dependency element)
{
return element.contentEquals(fgDep);
}
})));
// And this adds the groovy dep. FFI shouldn't need Gradle.
deps.add(CONFIG_FFI_DEPS, deps.localGroovy());
}
@SuppressWarnings("serial")
private void makeCommonTasks()
{
EtagDownloadTask getVersionJson = makeTask(TASK_DL_VERSION_JSON, EtagDownloadTask.class);
{
getVersionJson.setUrl(new Closure<String>(BasePlugin.class) {
@Override
public String call()
{
return mcManifest.get(getExtension().getVersion()).url;
}
});
getVersionJson.setFile(delayedFile(JSON_VERSION));
getVersionJson.setDieWithError(false);
getVersionJson.doLast(new Closure<Boolean>(BasePlugin.class) // normalizes to linux endings
{
@Override
public Boolean call()
{
try
{
// normalize the line endings...
File json = delayedFile(JSON_VERSION).call();
if (!json.exists())
return true;
List<String> lines = Files.readLines(json, Charsets.UTF_8);
StringBuilder buf = new StringBuilder();
for (String line : lines)
{
buf = buf.append(line).append('\n');
}
Files.write(buf.toString().getBytes(Charsets.UTF_8), json);
// grab the AssetIndex if it isnt already there
if (!replacer.hasReplacement(REPLACE_ASSET_INDEX))
{
parseAndStoreVersion(json, json.getParentFile());
}
//TODO: Find a better way to do this but lets hack this together like I asked Abrar to do years ago -.-
File jsondir = new File(BasePlugin.this.project.getProjectDir(), "jsons");
if (jsondir.isDirectory()) // If the file exists this is a forge workspace, lets assume we're caching it.
{
Files.write(buf.toString().getBytes(Charsets.UTF_8), delayedFile("jsons/" + Constants.REPLACE_MC_VERSION + ".json").call());
}
}
catch (IOException e)
{
throw new RuntimeException(e);
}
return true;
}
});
}
ExtractConfigTask extractNatives = makeTask(TASK_EXTRACT_NATIVES, ExtractConfigTask.class);
{
extractNatives.setDestinationDir(delayedFile(DIR_NATIVES));
extractNatives.setConfig(CONFIG_NATIVES);
extractNatives.exclude("META-INF/**", "META-INF/**");
extractNatives.setDoesCache(true);
extractNatives.dependsOn(getVersionJson);
}
EtagDownloadTask getAssetsIndex = makeTask(TASK_DL_ASSET_INDEX, EtagDownloadTask.class);
{
getAssetsIndex.setUrl(new Closure<String>(BasePlugin.class) {
@Override
public String call()
{
return mcVersionJson.assetIndex.url;
}
});
getAssetsIndex.setFile(delayedFile(JSON_ASSET_INDEX));
getAssetsIndex.setDieWithError(false);
getAssetsIndex.dependsOn(getVersionJson);
}
DownloadAssetsTask getAssets = makeTask(TASK_DL_ASSETS, DownloadAssetsTask.class);
{
getAssets.setAssetsDir(delayedFile(DIR_ASSETS));
getAssets.setAssetsIndex(delayedFile(JSON_ASSET_INDEX));
getAssets.dependsOn(getAssetsIndex);
}
Download dlClient = makeTask(TASK_DL_CLIENT, Download.class);
{
dlClient.setOutput(delayedFile(JAR_CLIENT_FRESH));
dlClient.setUrl(new Closure<String>(BasePlugin.class) {
@Override
public String call()
{
return mcVersionJson.getClientUrl();
}
});
dlClient.dependsOn(getVersionJson);
}
Download dlServer = makeTask(TASK_DL_SERVER, Download.class);
{
dlServer.setOutput(delayedFile(JAR_SERVER_FRESH));
dlServer.setUrl(new Closure<String>(BasePlugin.class) {
@Override
public String call()
{
return mcVersionJson.getServerUrl();
}
});
dlServer.dependsOn(getVersionJson);
}
SplitJarTask splitServer = makeTask(TASK_SPLIT_SERVER, SplitJarTask.class);
{
splitServer.setInJar(delayedFile(JAR_SERVER_FRESH));
splitServer.setOutFirst(delayedFile(JAR_SERVER_PURE));
splitServer.setOutSecond(delayedFile(JAR_SERVER_DEPS));
splitServer.exclude("org/bouncycastle", "org/bouncycastle/*", "org/bouncycastle/**");
splitServer.exclude("org/apache", "org/apache/*", "org/apache/**");
splitServer.exclude("com/google", "com/google/*", "com/google/**");
splitServer.exclude("com/mojang/authlib", "com/mojang/authlib/*", "com/mojang/authlib/**");
splitServer.exclude("com/mojang/util", "com/mojang/util/*", "com/mojang/util/**");
splitServer.exclude("gnu/trove", "gnu/trove/*", "gnu/trove/**");
splitServer.exclude("io/netty", "io/netty/*", "io/netty/**");
splitServer.exclude("javax/annotation", "javax/annotation/*", "javax/annotation/**");
splitServer.exclude("argo", "argo/*", "argo/**");
splitServer.exclude("it", "it/*", "it/**");
splitServer.dependsOn(dlServer);
}
MergeJars merge = makeTask(TASK_MERGE_JARS, MergeJars.class);
{
merge.setClient(delayedFile(JAR_CLIENT_FRESH));
merge.setServer(delayedFile(JAR_SERVER_PURE));
merge.setOutJar(delayedFile(JAR_MERGED));
merge.dependsOn(dlClient, splitServer);
merge.setGroup(null);
merge.setDescription(null);
}
ExtractConfigTask extractMcpData = makeTask(TASK_EXTRACT_MCP, ExtractMcpConfigTask.class);
{
extractMcpData.setDestinationDir(delayedFile(DIR_MCP_DATA));
extractMcpData.setConfig(CONFIG_MCP_DATA);
extractMcpData.setDoesCache(true);
}
ExtractConfigTask extractMcpMappings = makeTask(TASK_EXTRACT_MAPPINGS, ExtractConfigTask.class);
{
extractMcpMappings.setDestinationDir(delayedFile(DIR_MCP_MAPPINGS));
extractMcpMappings.setConfig(CONFIG_MAPPINGS);
extractMcpMappings.setDoesCache(true);
}
GenSrgs genSrgs = makeTask(TASK_GENERATE_SRGS, GenSrgs.class);
{
genSrgs.setInSrg(delayedFile(MCP_DATA_SRG));
genSrgs.setInConstructors(delayedFile(MCP_DATA_CONSTRUCTORS));
genSrgs.setInStatics(delayedFile(MCP_DATA_STATICS));
genSrgs.setMethodsCsv(delayedFile(CSV_METHOD));
genSrgs.setFieldsCsv(delayedFile(CSV_FIELD));
genSrgs.setNotchToSrg(delayedFile(Constants.SRG_NOTCH_TO_SRG));
genSrgs.setNotchToMcp(delayedFile(Constants.SRG_NOTCH_TO_MCP));
genSrgs.setSrgToMcp(delayedFile(SRG_SRG_TO_MCP));
genSrgs.setMcpToSrg(delayedFile(SRG_MCP_TO_SRG));
genSrgs.setMcpToNotch(delayedFile(SRG_MCP_TO_NOTCH));
genSrgs.setSrgExc(delayedFile(EXC_SRG));
genSrgs.setMcpExc(delayedFile(EXC_MCP));
genSrgs.setDoesCache(true);
genSrgs.dependsOn(extractMcpData, extractMcpMappings);
}
Delete clearCache = makeTask(TASK_CLEAN_CACHE, Delete.class);
{
clearCache.delete(delayedFile(REPLACE_CACHE_DIR), delayedFile(DIR_LOCAL_CACHE));
clearCache.setGroup(GROUP_FG);
clearCache.setDescription("Cleares the ForgeGradle cache. DONT RUN THIS unless you want a fresh start, or the dev tells you to.");
}
}
/**
* @return the extension object with name
* @see Constants#EXT_NAME_MC
*/
@SuppressWarnings("unchecked")
public final K getExtension()
{
return (K) project.getExtensions().getByName(EXT_NAME_MC);
}
public DefaultTask makeTask(String name)
{
return makeTask(name, DefaultTask.class);
}
public DefaultTask maybeMakeTask(String name)
{
return maybeMakeTask(name, DefaultTask.class);
}
public <T extends Task> T makeTask(String name, Class<T> type)
{
return makeTask(project, name, type);
}
public <T extends Task> T maybeMakeTask(String name, Class<T> type)
{
return maybeMakeTask(project, name, type);
}
public static <T extends Task> T maybeMakeTask(Project proj, String name, Class<T> type)
{
return (T) proj.getTasks().maybeCreate(name, type);
}
public static <T extends Task> T makeTask(Project proj, String name, Class<T> type)
{
return (T) proj.getTasks().create(name, type);
}
public static Project buildProject(File buildFile, Project parent)
{
ProjectBuilder builder = ProjectBuilder.builder();
if (buildFile != null)
{
builder = builder.withProjectDir(buildFile.getParentFile()).withName(buildFile.getParentFile().getName());
}
else
{
builder = builder.withProjectDir(new File("."));
}
if (parent != null)
{
builder = builder.withParent(parent);
}
Project project = builder.build();
if (buildFile != null)
{
project.apply(ImmutableMap.of("from", buildFile.getAbsolutePath()));
}
return project;
}
public void applyExternalPlugin(String plugin)
{
project.apply(ImmutableMap.of("plugin", plugin));
}
public MavenArtifactRepository addMavenRepo(Project proj, final String name, final String url)
{
return proj.getRepositories().maven(new Action<MavenArtifactRepository>() {
@Override
public void execute(MavenArtifactRepository repo)
{
repo.setName(name);
repo.setUrl(url);
}
});
}
public FlatDirectoryArtifactRepository addFlatRepo(Project proj, final String name, final Object... dirs)
{
return proj.getRepositories().flatDir(new Action<FlatDirectoryArtifactRepository>() {
@Override
public void execute(FlatDirectoryArtifactRepository repo)
{
repo.setName(name);
repo.dirs(dirs);
}
});
}
protected String getWithEtag(String strUrl, File cache, File etagFile)
{
return getWithEtag(Collections.singletonList(strUrl), cache, etagFile);
}
protected String getWithEtag(List<String> strUrls, File cache, File etagFile)
{
for (String strUrl : strUrls)
{
try
{
if (project.getGradle().getStartParameter().isOffline()) // dont even try the internet
return Files.toString(cache, Charsets.UTF_8);
// dude, its been less than 1 minute since the last time..
if (cache.exists() && cache.lastModified() + 60000 >= System.currentTimeMillis())
return Files.toString(cache, Charsets.UTF_8);
String etag;
if (etagFile.exists())
{
etag = Files.toString(etagFile, Charsets.UTF_8);
}
else
{
etagFile.getParentFile().mkdirs();
etag = "";
}
URL url = new URL(strUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setInstanceFollowRedirects(true);
con.setRequestProperty("User-Agent", USER_AGENT);
con.setIfModifiedSince(cache.lastModified());
if (!Strings.isNullOrEmpty(etag))
{
con.setRequestProperty("If-None-Match", etag);
}
con.connect();
if (con.getResponseCode() == 304)
{
// the existing file is good
Files.touch(cache); // touch it to update last-modified time, to wait another minute
return Files.toString(cache, Charsets.UTF_8);
}
else if (con.getResponseCode() == 200)
{
byte[] data;
try (InputStream stream = con.getInputStream())
{
data = ByteStreams.toByteArray(stream);
}
Files.write(data, cache);
// write etag
etag = con.getHeaderField("ETag");
if (Strings.isNullOrEmpty(etag))
{
Files.touch(etagFile);
}
else
{
Files.write(etag, etagFile, Charsets.UTF_8);
}
return new String(data);
}
else
{
LOGGER.error("Etag download for " + strUrl + " failed with code " + con.getResponseCode());
}
con.disconnect();
}
catch (Exception e)
{
e.printStackTrace();
}
}
if (cache.exists())
{
try
{
return Files.toString(cache, Charsets.UTF_8);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
throw new RuntimeException("Unable to obtain url (" + strUrls + ") with etag!");
}
/**
* Parses the version json in the provided file, and saves it in memory.
* Also populates the McDeps and natives configurations.
* Also sets the ASSET_INDEX replacement string
* Does nothing (returns null) if the file is not found, but hard-crashes if it could not be parsed.
* @param file version file to parse
* @param inheritanceDirs folders to look for the parent json, should include DIR_JSON
* @return NULL if the file doesnt exist
*/
protected Version parseAndStoreVersion(File file, File... inheritanceDirs)
{
if (!file.exists())
return null;
Version version = null;
if (version == null)
{
try
{
version = JsonFactory.loadVersion(file, delayedString(REPLACE_MC_VERSION).call(), inheritanceDirs);
}
catch (IOException e)
{
LOGGER.error("" + file + " could not be parsed");
throw new RuntimeException(e);
}
}
// apply the dep info.
DependencyHandler handler = project.getDependencies();
// actual dependencies
if (project.getConfigurations().getByName(CONFIG_MC_DEPS).getState() == State.UNRESOLVED)
{
for (net.minecraftforge.gradle.util.json.version.Library lib : version.getLibraries())
{
if (lib.natives == null)
{
String configName = CONFIG_MC_DEPS;
if (lib.name.contains("java3d")
|| lib.name.contains("paulscode")
|| lib.name.contains("twitch")
|| lib.name.contains("jinput"))
{
configName = CONFIG_MC_DEPS_CLIENT;
}
handler.add(configName, lib.getArtifactName());
}
}
}
else
LOGGER.debug("RESOLVED: " + CONFIG_MC_DEPS);
// the natives
if (project.getConfigurations().getByName(CONFIG_NATIVES).getState() == State.UNRESOLVED)
{
for (net.minecraftforge.gradle.util.json.version.Library lib : version.getLibraries())
{
if (lib.natives != null)
{
if (lib.getArtifactName().contains("java-objc-bridge") && lib.getArtifactName().contains("natives-osx")) //Normal repo bundles this in the mian jar so we need to just use the main jar
handler.add(CONFIG_NATIVES, lib.getArtifactNameSkipNatives());
else
handler.add(CONFIG_NATIVES, lib.getArtifactName());
}
}
}
else
LOGGER.debug("RESOLVED: " + CONFIG_NATIVES);
// set asset index
replacer.putReplacement(REPLACE_ASSET_INDEX, version.assetIndex.id);
this.mcVersionJson = version;
return version;
}
// DELAYED STUFF ONLY ------------------------------------------------------------------------
private LoadingCache<String, TokenReplacer> replacerCache = CacheBuilder.newBuilder()
.weakValues()
.build(
new CacheLoader<String, TokenReplacer>() {
public TokenReplacer load(String key)
{
return new TokenReplacer(replacer, key);
}
});
private LoadingCache<String, DelayedString> stringCache = CacheBuilder.newBuilder()
.weakValues()
.build(
new CacheLoader<String, DelayedString>() {
public DelayedString load(String key)
{
return new DelayedString(CacheLoader.class, replacerCache.getUnchecked(key));
}
});
private LoadingCache<String, DelayedFile> fileCache = CacheBuilder.newBuilder()
.weakValues()
.build(
new CacheLoader<String, DelayedFile>() {
public DelayedFile load(String key)
{
return new DelayedFile(CacheLoader.class, project, replacerCache.getUnchecked(key));
}
});
public DelayedString delayedString(String path)
{
return stringCache.getUnchecked(path);
}
public DelayedFile delayedFile(String path)
{
return fileCache.getUnchecked(path);
}
public DelayedFileTree delayedTree(String path)
{
return new DelayedFileTree(BasePlugin.class, project, replacerCache.getUnchecked(path));
}
protected File cacheFile(String path)
{
return new File(project.getGradle().getGradleUserHomeDir(), "caches/minecraft/" + path);
}
}