-
Notifications
You must be signed in to change notification settings - Fork 29
/
DevEnvUtils.java
83 lines (70 loc) · 3.12 KB
/
DevEnvUtils.java
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
/*
* Copyright (c) NeoForged and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.neoforged.fml.util;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import net.neoforged.fml.ModLoadingException;
import net.neoforged.fml.ModLoadingIssue;
import org.jetbrains.annotations.ApiStatus;
@ApiStatus.Internal
public final class DevEnvUtils {
private DevEnvUtils() {}
public static List<Path> findFileSystemRootsOfFileOnClasspath(String relativePath) {
// If we're loaded through a module, it means the original classpath is inaccessible through the context CL
var classLoader = Thread.currentThread().getContextClassLoader();
if (DevEnvUtils.class.getModule().isNamed()) {
classLoader = ClassLoader.getSystemClassLoader();
}
// Find the directory that contains the Minecraft classes via the system classpath
Iterator<URL> resourceIt;
try {
resourceIt = classLoader.getResources(relativePath).asIterator();
} catch (IOException e) {
throw new IllegalArgumentException("Failed to enumerate classpath locations of " + relativePath);
}
List<Path> result = new ArrayList<>();
while (resourceIt.hasNext()) {
var resourceUrl = resourceIt.next();
if ("jar".equals(resourceUrl.getProtocol())) {
var fileUri = URI.create(resourceUrl.toString().split("!")[0].substring("jar:".length()));
result.add(Paths.get(fileUri));
} else {
Path resourcePath;
try {
resourcePath = Paths.get(resourceUrl.toURI());
} catch (URISyntaxException e) {
throw new IllegalArgumentException("Failed to convert " + resourceUrl + " to URI");
}
// Walk back from the resource path up to the content root that contained it
var current = Paths.get(relativePath);
while (current != null) {
current = current.getParent();
resourcePath = resourcePath.getParent();
if (resourcePath == null) {
throw new IllegalArgumentException("Resource " + resourceUrl + " did not have same nesting depth as " + relativePath);
}
}
result.add(resourcePath);
}
}
return result;
}
public static Path findFileSystemRootOfFileOnClasspath(String relativePath) {
var paths = findFileSystemRootsOfFileOnClasspath(relativePath);
if (paths.isEmpty()) {
throw new ModLoadingException(ModLoadingIssue.error("fml.modloading.failed_to_find_on_classpath", relativePath));
} else if (paths.size() > 1) {
throw new ModLoadingException(ModLoadingIssue.error("fml.modloading.multiple_copies_on_classpath", relativePath, paths));
}
return paths.getFirst();
}
}