Skip to content

Commit 5bd43a1

Browse files
committed
Miscellany
I'm great at organizing my commits I know - better logging - fix def hashes not accounting for everything - only extract natives if necessary
1 parent b10ae0a commit 5bd43a1

22 files changed

+257
-120
lines changed

build.gradle.kts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@ val mc by minecraft.creating {
2222
}
2323

2424
dependencies {
25-
println("adding dependencies")
2625
implementation(mc.dependency)
2726

2827
// mc.transformer(fileTree("src/main/resources/transformers"))

plugin/src/main/java/fish/cichlidmc/cichlid_gradle/cache/mcmaven/JarProcessor.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,8 @@ public static void run(Path inputJar, Path outputJar, CacheFunction function) th
3434

3535
try (FileSystem inputFs = FileSystems.newFileSystem(inputJar); FileSystem outputFs = FileSystems.newFileSystem(outputJar)) {
3636
// jars should have 1 root
37-
Path inputRoot = Utils.getOnly(inputFs.getRootDirectories());
38-
Path outputRoot = Utils.getOnly(outputFs.getRootDirectories());
37+
Path inputRoot = FileUtils.getSingleRoot(inputFs);
38+
Path outputRoot = FileUtils.getSingleRoot(outputFs);
3939

4040
Input input = collectInput(inputRoot);
4141
for (ClassGroup group : input.groups.values()) {

plugin/src/main/java/fish/cichlidmc/cichlid_gradle/cache/mcmaven/McMavenResourceAccessor.java

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,16 +28,12 @@ public McMavenResourceAccessor(MinecraftMaven mcMaven) {
2828
public <T> T withContent(ExternalResourceName location, boolean revalidate,
2929
ExternalResource.ContentAndMetadataAction<T> action) throws ResourceException {
3030
URI uri = location.getUri();
31-
System.out.println("checking " + uri);
3231

3332
try {
3433
InputStream stream = this.mcMaven.get(uri);
35-
if (stream == null) {
36-
System.out.println("nope :( " + uri);
34+
if (stream == null)
3735
return null;
38-
}
3936

40-
System.out.println("yep :)");
4137
return action.execute(stream, this.getMetaData(location, revalidate));
4238
} catch (Exception e) {
4339
logger.error("Error while getting URL from mcmaven: {}", uri, e);
@@ -49,7 +45,6 @@ public <T> T withContent(ExternalResourceName location, boolean revalidate,
4945
@Override
5046
public ExternalResourceMetaData getMetaData(ExternalResourceName location, boolean revalidate) throws ResourceException {
5147
URI uri = location.getUri();
52-
System.out.println("checking " + uri);
5348

5449
try {
5550
return this.mcMaven.get(uri) == null ? null : new DefaultExternalResourceMetaData(uri, -1, -1);

plugin/src/main/java/fish/cichlidmc/cichlid_gradle/cache/mcmaven/MinecraftMaven.java

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ public InputStream get(URI uri) throws IOException {
7171
throw new InvalidUserDataException("Minecraft definition '" + request.def + "' does not exist");
7272
}
7373

74-
String version = def.getVersionOrThrow();
74+
String version = def.version();
7575

7676
Iterable<File> transformerFiles = def.resolvableTransformers().getIncoming().getFiles();
7777
Transformers transformers = new Transformers(transformerFiles, request.hash);
@@ -90,13 +90,17 @@ public InputStream get(URI uri) throws IOException {
9090
private InputStream getArtifact(String versionId, Distribution dist, Transformers transformers, Request request) throws IOException {
9191
// see if this version actually exists
9292
Version version = ManifestCache.getVersion(versionId);
93-
if (version == null)
93+
if (version == null) {
94+
logger.warn("Minecraft version does not exist: {}", versionId);
9495
return null;
96+
}
9597

9698
FullVersion fullVersion = ManifestCache.expand(version);
9799
// and the dist. all versions have a client, check for server
98-
if (dist != Distribution.CLIENT && fullVersion.downloads.server.isEmpty())
100+
if (dist != Distribution.CLIENT && fullVersion.downloads.server.isEmpty()) {
101+
logger.warn("Minecraft version doesn't have a server, but it was requested: {}", versionId);
99102
return null;
103+
}
100104

101105
if (fullVersion.downloads.clientMappings.isEmpty()) {
102106
throw new InvalidUserDataException("Versions pre-mojmap are not currently supported!");
@@ -141,7 +145,9 @@ private InputStream getPom(FullVersion version, Distribution dist, Request reque
141145

142146
// file should now exist
143147
String content = Files.readString(template);
144-
String filled = content.replace(PomGenerator.VERSION_PLACEHOLDER, request.gradleRequestedVersion());
148+
// of course & has special meaning in xml
149+
String escaped = request.gradleRequestedVersion().replace("&", "&amp;");
150+
String filled = content.replace(PomGenerator.VERSION_PLACEHOLDER, escaped);
145151
return new ByteArrayInputStream(filled.getBytes(StandardCharsets.UTF_8));
146152
}
147153

@@ -195,7 +201,7 @@ private static Request extractRequest(URI uri) {
195201
}
196202
}
197203

198-
logger.quiet("Intercepted request for Minecraft definition {}, {}, {}", defName, artifact, hashAlgorithm);
204+
logger.debug("Intercepted request for Minecraft definition {}, {}, {}", defName, artifact, hashAlgorithm);
199205

200206
return new Request(defName, hash, artifact, Optional.ofNullable(hashAlgorithm));
201207
}

plugin/src/main/java/fish/cichlidmc/cichlid_gradle/cache/storage/VersionStorage.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,14 @@
22

33
import java.nio.file.Path;
44

5-
public class VersionStorage extends LockableStorage {
5+
public class VersionStorage {
66

77
public final MappingsStorage mappings;
88
public final JarsStorage jars;
99
public final Path natives;
1010
public final RunTemplateStorage runs;
1111

1212
public VersionStorage(Path root) {
13-
super(root);
1413
this.mappings = new MappingsStorage(root.resolve("mappings"));
1514
this.jars = new JarsStorage(root.resolve("jars"));
1615
this.natives = root.resolve("natives");
Lines changed: 30 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,54 @@
11
package fish.cichlidmc.cichlid_gradle.cache.task;
22

3-
import org.gradle.api.logging.Logger;
4-
import org.gradle.api.logging.Logging;
3+
import org.jetbrains.annotations.Nullable;
54

65
import java.io.IOException;
76
import java.io.UncheckedIOException;
7+
import java.util.function.Supplier;
88

9-
public abstract class CacheTask implements Runnable {
9+
public abstract class CacheTask {
1010
public final String name;
1111

1212
protected final CacheTaskEnvironment env;
13-
protected final Logger logger;
1413

1514
protected CacheTask(String name, CacheTaskEnvironment env) {
1615
this.name = name;
1716
this.env = env;
18-
this.logger = Logging.getLogger(this.getClass());
1917
}
2018

21-
protected abstract void doRun() throws IOException;
19+
/**
20+
* @return a feedback message to be printed with the completion notice
21+
*/
22+
@Nullable
23+
protected abstract String run() throws IOException;
2224

25+
/**
26+
* Perform any necessary cleanup, including in the case of an exception being thrown by {@link #run()}.
27+
*/
2328
protected void cleanup() throws IOException {
2429
}
2530

26-
@Override
27-
public final void run() {
28-
try {
29-
this.doRun();
30-
this.cleanup();
31-
} catch (IOException e) {
31+
record Runner(CacheTask task, long startTime) implements Supplier<@Nullable String> {
32+
Runner(CacheTask task) {
33+
this(task, System.currentTimeMillis());
34+
}
35+
36+
@Override
37+
@Nullable
38+
public String get() {
3239
try {
33-
this.cleanup();
34-
} catch (IOException suppressed) {
35-
e.addSuppressed(suppressed);
40+
String message = this.task.run();
41+
this.task.cleanup();
42+
return message;
43+
} catch (IOException e) {
44+
try {
45+
this.task.cleanup();
46+
} catch (IOException suppressed) {
47+
e.addSuppressed(suppressed);
48+
}
49+
50+
throw new UncheckedIOException(e);
3651
}
37-
38-
throw new UncheckedIOException(e);
3952
}
4053
}
4154
}

plugin/src/main/java/fish/cichlidmc/cichlid_gradle/cache/task/CacheTaskEnvironment.java

Lines changed: 33 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,10 @@
44
import fish.cichlidmc.cichlid_gradle.cache.Transformers;
55
import fish.cichlidmc.cichlid_gradle.util.Distribution;
66
import fish.cichlidmc.pistonmetaparser.FullVersion;
7+
import fish.cichlidmc.tinycodecs.util.Either;
78
import org.gradle.api.logging.Logger;
89
import org.gradle.api.logging.Logging;
10+
import org.jetbrains.annotations.Nullable;
911

1012
import java.util.ArrayList;
1113
import java.util.Collections;
@@ -24,9 +26,9 @@ public class CacheTaskEnvironment {
2426
public final Distribution dist;
2527
public final Transformers transformers;
2628

27-
private final Map<CacheTask, CompletableFuture<Void>> futures = Collections.synchronizedMap(new IdentityHashMap<>());
28-
private final Set<CacheTask> incompleteTasks = Collections.synchronizedSet(new HashSet<>());
29-
private final Map<CacheTask, Throwable> errors = Collections.synchronizedMap(new IdentityHashMap<>());
29+
private final Map<CacheTask.Runner, CompletableFuture<Void>> futures = Collections.synchronizedMap(new IdentityHashMap<>());
30+
private final Set<CacheTask.Runner> incompleteTasks = Collections.synchronizedSet(new HashSet<>());
31+
private final Map<CacheTask.Runner, Throwable> errors = Collections.synchronizedMap(new IdentityHashMap<>());
3032

3133
public CacheTaskEnvironment(FullVersion version, CichlidCache cache, Distribution dist, Transformers transformers) {
3234
this.version = version;
@@ -46,23 +48,25 @@ public CompletableFuture<Void> submit(TaskFactory factory) {
4648
public CompletableFuture<Void> submit(CacheTask task) {
4749
logger.quiet("Starting new task: {}", task.name);
4850

49-
CompletableFuture<Void> future = CompletableFuture.runAsync(task)
50-
.thenRun(() -> this.finishTask(task))
51+
CacheTask.Runner runner = new CacheTask.Runner(task);
52+
this.incompleteTasks.add(runner);
53+
54+
CompletableFuture<Void> future = CompletableFuture.supplyAsync(runner)
55+
.thenAccept(message -> this.finishTask(runner, Either.left(message)))
5156
.exceptionally(error -> {
52-
this.finishTask(task);
53-
this.errors.put(task, error);
57+
this.finishTask(runner, Either.right(error));
5458
return null;
5559
});
5660

57-
this.futures.put(task, future);
58-
this.incompleteTasks.add(task);
61+
this.futures.put(runner, future);
62+
5963
return future;
6064
}
6165

6266
public void join() {
6367
while (!this.incompleteTasks.isEmpty()) {
64-
CacheTask task = this.incompleteTasks.iterator().next();
65-
CompletableFuture<Void> future = this.futures.get(task);
68+
CacheTask.Runner runner = this.incompleteTasks.iterator().next();
69+
CompletableFuture<Void> future = this.futures.get(runner);
6670
try {
6771
future.join();
6872
} catch (Throwable ignored) {}
@@ -77,16 +81,30 @@ public void report() {
7781
return;
7882
}
7983

80-
RuntimeException root = new RuntimeException("One or more CichlidGradle cache tasks failed!");
84+
RuntimeException root = new RuntimeException(this.errors.size() + " CichlidGradle cache task(s) failed!");
8185
this.errors.values().forEach(root::addSuppressed);
8286

8387
logger.error(root.getMessage(), root);
8488
throw root;
8589
}
8690

87-
private void finishTask(CacheTask task) {
88-
this.incompleteTasks.remove(task);
89-
logger.quiet("Task complete: {}", task.name);
91+
private void finishTask(CacheTask.Runner runner, Either<@Nullable String, Throwable> result) {
92+
this.incompleteTasks.remove(runner);
93+
94+
if (result.isRight()) {
95+
this.errors.put(runner, result.right());
96+
}
97+
98+
String name = runner.task().name;
99+
String verb = result.isLeft() ? "finished" : "failed";
100+
String seconds = String.format("%.2f", (System.currentTimeMillis() - runner.startTime()) / 1000f);
101+
String message = result.isLeft() ? result.left() : result.right().getMessage();
102+
103+
if (message != null) {
104+
logger.quiet("Task '{}' {} after {} seconds: {}", name, verb, seconds, message);
105+
} else {
106+
logger.quiet("Task '{}' {} after {} seconds", name, verb, seconds);
107+
}
90108
}
91109

92110
@FunctionalInterface

plugin/src/main/java/fish/cichlidmc/cichlid_gradle/cache/task/impl/AssetsTask.java

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -4,48 +4,48 @@
44
import fish.cichlidmc.cichlid_gradle.cache.storage.LockableStorage;
55
import fish.cichlidmc.cichlid_gradle.cache.task.CacheTask;
66
import fish.cichlidmc.cichlid_gradle.cache.task.CacheTaskEnvironment;
7+
import fish.cichlidmc.cichlid_gradle.util.hash.Encoding;
8+
import fish.cichlidmc.cichlid_gradle.util.hash.HashAlgorithm;
79
import fish.cichlidmc.cichlid_gradle.util.io.Download;
810
import fish.cichlidmc.cichlid_gradle.util.io.DownloadBatch;
911
import fish.cichlidmc.cichlid_gradle.util.io.FileUtils;
10-
import fish.cichlidmc.cichlid_gradle.util.hash.Encoding;
11-
import fish.cichlidmc.cichlid_gradle.util.hash.HashAlgorithm;
1212
import fish.cichlidmc.pistonmetaparser.version.assets.Asset;
1313
import fish.cichlidmc.pistonmetaparser.version.assets.AssetIndex;
1414
import fish.cichlidmc.pistonmetaparser.version.assets.FullAssetIndex;
1515
import fish.cichlidmc.tinyjson.TinyJson;
1616
import fish.cichlidmc.tinyjson.value.JsonValue;
17+
import org.gradle.api.logging.Logger;
18+
import org.gradle.api.logging.Logging;
1719

1820
import java.io.IOException;
1921
import java.nio.file.Files;
2022
import java.nio.file.Path;
2123
import java.util.Map;
2224

2325
public class AssetsTask extends CacheTask {
26+
private static final Logger logger = Logging.getLogger(AssetsTask.class);
27+
2428
private LockableStorage.Lock lock;
2529

2630
public AssetsTask(CacheTaskEnvironment env) {
2731
super("Download asset index " + env.version.assets, env);
2832
}
2933

3034
@Override
31-
public void doRun() throws IOException {
35+
public String run() throws IOException {
3236
AssetStorage assets = this.env.cache.assets;
3337
this.lock = assets.lockLoudly("Assets are currently locked by {}, awaiting release");
3438
// see if it's done now
3539
AssetIndex index = this.env.version.assetIndex;
3640
if (assets.isComplete(index)) {
37-
this.logger.quiet("Asset index {} is now cached.", index.id);
38-
return;
41+
return "Asset index " + index.id + " is now cached.";
3942
}
4043

41-
this.logger.quiet("Asset index {} is not cached, downloading", index.id);
42-
4344
Path indexFile = assets.index(index);
4445
new Download(index, indexFile).run();
4546
// read downloaded file to avoid downloading again with expand()
4647
JsonValue indexJson = TinyJson.parse(indexFile);
4748
FullAssetIndex fullIndex = FullAssetIndex.parse(indexJson);
48-
long startTime = System.currentTimeMillis();
4949

5050
DownloadBatch.Builder builder = new DownloadBatch.Builder();
5151
for (Asset asset : fullIndex.objects.values()) {
@@ -55,24 +55,22 @@ public void doRun() throws IOException {
5555
}
5656
}
5757

58-
this.logger.quiet("Downloading {} asset objects...", builder.size());
58+
logger.quiet("Downloading {} asset object(s)...", builder.size());
5959

6060
builder.build().execute();
6161

62-
long endTime = System.currentTimeMillis();
63-
long seconds = (endTime - startTime) / 1000;
64-
this.logger.quiet("Finished downloading assets in {} seconds.", seconds);
65-
6662
if (fullIndex.isVirtual()) {
67-
this.logger.quiet("Extracting virtual assets");
63+
logger.quiet("Extracting virtual assets...");
6864
this.extractVirtualAssets(index, fullIndex);
6965
}
7066

7167
assets.markComplete(index);
68+
return "Index contained " + fullIndex.objects.size() + " object(s), " + builder.size() + " of which were missing.";
7269
}
7370

7471
@Override
7572
protected void cleanup() throws IOException {
73+
// unlock here in case run throws
7674
if (this.lock != null) {
7775
this.lock.close();
7876
}
@@ -96,13 +94,13 @@ private boolean shouldDownload(Asset asset, Path dest) throws IOException {
9694

9795
long existingSize = Files.size(dest);
9896
if (asset.size != existingSize) {
99-
this.logger.warn("Found an existing asset that has changed size: {}. Bad download? Overwriting.", asset.path);
97+
logger.warn("Found an existing asset that has changed size: {}. Bad download? Overwriting.", asset.path);
10098
return true;
10199
}
102100

103101
String existingHash = Encoding.HEX.encode(HashAlgorithm.SHA1.hash(dest));
104102
if (!asset.hash.equals(existingHash)) {
105-
this.logger.warn("Found an existing asset that has changed hashes: {}. Bad download? Overwriting.", asset.path);
103+
logger.warn("Found an existing asset that has changed hashes: {}. Bad download? Overwriting.", asset.path);
106104
return true;
107105
}
108106

0 commit comments

Comments
 (0)