cleanup code

This commit is contained in:
FalsePattern committed 2023-07-16 13:21:51 +02:00
1 parent 6868e1f718
commit dfba569048
51 files changed
+637 -373

No files matched your search

@@ -171,23 +171,20 @@ public final class ConfigurationManagerImpl {
val opt = serializedNames.keySet().stream().filter((key) -> key.equals(serializedName)).findFirst();
if (!opt.isPresent()) {
input.skipBytes(dataSize);
Share.LOG
.warn("Server tried to sync config not registered on our side: " + serializedName);
Share.LOG.warn("Server tried to sync config not registered on our side: " + serializedName);
continue;
}
val clazz = serializedNames.get(opt.get());
val config = parsedConfigMap.get(clazz);
if (!config.sync) {
input.skipBytes(dataSize);
Share.LOG
.warn("Server tried to sync config without @Synchronize annotation on our side: " +
serializedName);
Share.LOG.warn("Server tried to sync config without @Synchronize annotation on our side: "
+ serializedName);
continue;
}
if (!ConfigSyncEvent.postStart(clazz)) {
input.skipBytes(dataSize);
Share.LOG.warn(
"Config synchronization was cancelled by event for: " + serializedName);
Share.LOG.warn("Config synchronization was cancelled by event for: " + serializedName);
continue;
}
val bytes = new byte[dataSize];
@@ -82,14 +82,19 @@ public class ParsedConfiguration {
public static ParsedConfiguration parseConfig(Class<?> configClass) throws ConfigException {
val cfg = Optional.ofNullable(configClass.getAnnotation(Config.class))
.orElseThrow(() -> new ConfigException(
"Class " + configClass.getName() + " does not have a @Config annotation!"));
.orElseThrow(() -> new ConfigException("Class "
+ configClass.getName()
+ " does not have a @Config annotation!"));
val category = Optional.of(cfg.category().trim())
.map((cat) -> cat.length() == 0 ? null : cat)
.orElseThrow(() -> new ConfigException(
"Config class " + configClass.getName() + " has an empty category!"));
.orElseThrow(() -> new ConfigException("Config class "
+ configClass.getName()
+ " has an empty category!"));
val rawConfig = ConfigurationManagerImpl.getForgeConfig(cfg.modid());
val parsedConfig = new ParsedConfiguration(configClass, cfg.modid(), category, rawConfig,
val parsedConfig = new ParsedConfiguration(configClass,
cfg.modid(),
category,
rawConfig,
configClass.isAnnotationPresent(Config.Synchronize.class));
try {
parsedConfig.reloadFields();
@@ -133,8 +138,10 @@ public class ParsedConfiguration {
val fieldName =
StringConfigField.receiveString(input, maxFieldNameLength, "field name", configClass.getName());
if (!syncFields.containsKey(fieldName)) {
throw new IOException("Invalid sync field name received: " + fieldName + " for config class " +
configClass.getName());
throw new IOException("Invalid sync field name received: "
+ fieldName
+ " for config class "
+ configClass.getName());
}
syncFields.remove(fieldName).receive(input);
}
@@ -180,9 +187,13 @@ public class ParsedConfiguration {
} else if (fieldClass.isEnum()) {
fields.put(name, configField = new EnumConfigField<>(field, rawConfig, category));
} else {
throw new ConfigException("Illegal config field: " + field.getName() + " in " + configClass.getName() +
": Unsupported type " + fieldClass.getName() +
"! Did you forget an @Ignore annotation?");
throw new ConfigException("Illegal config field: "
+ field.getName()
+ " in "
+ configClass.getName()
+ ": Unsupported type "
+ fieldClass.getName()
+ "! Did you forget an @Ignore annotation?");
}
if (field.isAnnotationPresent(Config.RequiresMcRestart.class)) {
cat.setRequiresMcRestart(true);
@@ -196,7 +207,8 @@ public class ParsedConfiguration {
save();
}));
}
rawConfig.setCategoryPropertyOrder(category, fieldsSorted().map((prop) -> prop.name).collect(Collectors.toList()));
rawConfig.setCategoryPropertyOrder(category,
fieldsSorted().map((prop) -> prop.name).collect(Collectors.toList()));
}
private Stream<AConfigField<?>> fieldsSorted() {
@@ -61,19 +61,23 @@ public class ClientEventHandlerPre {
public void onConfigSyncFinished(ConfigSyncEvent.End e) {
val cfg = e.configClass.getAnnotation(Config.class);
if (e.successful) {
GuiToast.add(new SimpleToast(ToastBG.TOAST_DARK, null,
GuiToast.add(new SimpleToast(ToastBG.TOAST_DARK,
null,
FormattedText.parse(EnumChatFormatting.GREEN + "Synced config")
.toChatText()
.get(0),
FormattedText.parse(cfg.modid() + ":" + cfg.category()).toChatText().get(0),
false, 5000));
false,
5000));
} else {
GuiToast.add(new SimpleToast(ToastBG.TOAST_DARK, null,
GuiToast.add(new SimpleToast(ToastBG.TOAST_DARK,
null,
FormattedText.parse(EnumChatFormatting.RED + "Failed to sync config")
.toChatText()
.get(0),
FormattedText.parse(cfg.modid() + ":" + cfg.category()).toChatText().get(0),
false, 5000));
false,
5000));
}
}
}
@@ -73,7 +73,9 @@ public abstract class AConfigField<T> {
}
property.setLanguageKey(langKey);
noSync = field.isAnnotationPresent(Config.NoSync.class);
order = Optional.ofNullable(field.getAnnotation(DeclOrderInternal.class)).map(DeclOrderInternal::value).orElse(-1);
order = Optional.ofNullable(field.getAnnotation(DeclOrderInternal.class))
.map(DeclOrderInternal::value)
.orElse(-1);
}
protected abstract T getField();
@@ -47,9 +47,11 @@ public abstract class AListConfigField<T> extends AConfigField<T> {
.map(Config.ListMaxLength::value)
.orElse(256);
if (maxLength < 0) {
throw new ConfigException(
"Negative length list configurations are not supported!\n" + "Field name: " + field.getName() +
", class: " + field.getDeclaringClass().getName());
throw new ConfigException("Negative length list configurations are not supported!\n"
+ "Field name: "
+ field.getName()
+ ", class: "
+ field.getDeclaringClass().getName());
}
property.setIsListLengthFixed(fixedLength);
property.setMaxListLength(maxLength);
@@ -105,8 +107,12 @@ public abstract class AListConfigField<T> extends AConfigField<T> {
public void receive(DataInput input) throws IOException {
int length = input.readInt();
if (length > maxLength || fixedLength && length(getDefault()) != length) {
throw new IOException("Error while retrieving config value for field " + field.getName() + " in class " +
field.getDeclaringClass().getName() + ":\n" + "Illegal array length received!");
throw new IOException("Error while retrieving config value for field "
+ field.getName()
+ " in class "
+ field.getDeclaringClass().getName()
+ ":\n"
+ "Illegal array length received!");
}
val arr = createArray(length);
receiveElements(input, arr);
@@ -44,10 +44,11 @@ public class BooleanConfigField extends AConfigField<Boolean> {
defaultValue = Optional.ofNullable(field.getAnnotation(Config.DefaultBoolean.class))
.map(Config.DefaultBoolean::value)
.orElseGet(() -> {
Share.LOG
.warn("The field " + field.getName() + " in class " +
field.getDeclaringClass().getName() +
" has no DefaultBoolean annotation!\nThis will be a crash in FalsePatternLib 0.11, update your code!");
Share.LOG.warn("The field "
+ field.getName()
+ " in class "
+ field.getDeclaringClass().getName()
+ " has no DefaultBoolean annotation!\nThis will be a crash in FalsePatternLib 0.11, update your code!");
try {
return field.getType().isPrimitive() ? field.getBoolean(null)
: (Boolean) field.get(null);
@@ -43,10 +43,11 @@ public class BooleanListConfigField extends AListConfigField<boolean[]> {
defaultValue = Optional.ofNullable(field.getAnnotation(Config.DefaultBooleanList.class))
.map(Config.DefaultBooleanList::value)
.orElseGet(() -> {
Share.LOG
.warn("The field " + field.getName() + " in class " +
field.getDeclaringClass().getName() +
" has no DefaultBooleanList annotation!\nThis will be a crash in FalsePatternLib 0.11, update your code!");
Share.LOG.warn("The field "
+ field.getName()
+ " in class "
+ field.getDeclaringClass().getName()
+ " has no DefaultBooleanList annotation!\nThis will be a crash in FalsePatternLib 0.11, update your code!");
try {
return (boolean[]) field.get(null);
} catch (IllegalAccessException e) {
@@ -50,10 +50,11 @@ public class DoubleConfigField extends AConfigField<Double> {
defaultValue = Optional.ofNullable(field.getAnnotation(Config.DefaultDouble.class))
.map(Config.DefaultDouble::value)
.orElseGet(() -> {
Share.LOG
.warn("The field " + field.getName() + " in class " +
field.getDeclaringClass().getName() +
" has no DefaultDouble annotation!\nThis will be a crash in FalsePatternLib 0.11, update your code!");
Share.LOG.warn("The field "
+ field.getName()
+ " in class "
+ field.getDeclaringClass().getName()
+ " has no DefaultDouble annotation!\nThis will be a crash in FalsePatternLib 0.11, update your code!");
try {
return field.getType().isPrimitive() ? field.getInt(null)
: (Double) field.get(null);
@@ -112,8 +113,11 @@ public class DoubleConfigField extends AConfigField<Double> {
if (value >= min && value <= max) {
return true;
}
ConfigValidationFailureEvent.postNumericRangeOutOfBounds(field, -1, Double.toString(value),
Double.toString(min), Double.toString(max));
ConfigValidationFailureEvent.postNumericRangeOutOfBounds(field,
-1,
Double.toString(value),
Double.toString(min),
Double.toString(max));
return false;
}
@@ -49,10 +49,11 @@ public class DoubleListConfigField extends AListConfigField<double[]> {
defaultValue = Optional.ofNullable(field.getAnnotation(Config.DefaultDoubleList.class))
.map(Config.DefaultDoubleList::value)
.orElseGet(() -> {
Share.LOG
.warn("The field " + field.getName() + " in class " +
field.getDeclaringClass().getName() +
" has no DefaultDoubleList annotation!\nThis will be a crash in FalsePatternLib 0.11, update your code!");
Share.LOG.warn("The field "
+ field.getName()
+ " in class "
+ field.getDeclaringClass().getName()
+ " has no DefaultDoubleList annotation!\nThis will be a crash in FalsePatternLib 0.11, update your code!");
try {
return (double[]) field.get(null);
} catch (IllegalAccessException e) {
@@ -107,8 +108,11 @@ public class DoubleListConfigField extends AListConfigField<double[]> {
for (int j = 0; j < doubles.length; j++) {
double d = doubles[j];
if (d < min || d > max) {
ConfigValidationFailureEvent.postNumericRangeOutOfBounds(field, j, Double.toString(d),
Double.toString(min), Double.toString(max));
ConfigValidationFailureEvent.postNumericRangeOutOfBounds(field,
j,
Double.toString(d),
Double.toString(min),
Double.toString(max));
valid = false;
}
}
@@ -58,13 +58,16 @@ public class EnumConfigField<T extends Enum<T>> extends AConfigField<T> {
.filter((e) -> e.name().equals(defName))
.findAny()
.orElseThrow(() -> new IllegalArgumentException(
"Default value \"" + defName +
"\" was not found in enum " + enumClass.getName())))
"Default value \""
+ defName
+ "\" was not found in enum "
+ enumClass.getName())))
.orElseGet(() -> {
Share.LOG
.warn("The field " + field.getName() + " in class " +
field.getDeclaringClass().getName() +
" has no DefaultEnum annotation!\nThis will be a crash in FalsePatternLib 0.11, update your code!");
Share.LOG.warn("The field "
+ field.getName()
+ " in class "
+ field.getDeclaringClass().getName()
+ " has no DefaultEnum annotation!\nThis will be a crash in FalsePatternLib 0.11, update your code!");
try {
return enumClass.cast(field.get(null));
} catch (IllegalAccessException e) {
@@ -77,8 +80,12 @@ public class EnumConfigField<T extends Enum<T>> extends AConfigField<T> {
if (!enumNameMap.containsValue(getConfig())) {
setToDefault();
}
property.comment += "\n[default: " + defaultValue + ", possible values: " +
Arrays.toString(enumNameMap.keySet().toArray(new String[0])) + "]";
property.comment += "\n[default: "
+ defaultValue
+ ", possible values: "
+ Arrays.toString(enumNameMap.keySet()
.toArray(new String[0]))
+ "]";
}
public static void transmitString(DataOutput output, String value) throws IOException {
@@ -90,9 +97,12 @@ public class EnumConfigField<T extends Enum<T>> extends AConfigField<T> {
throws IOException {
val length = input.readInt();
if (length > maxLength || length < 0) {
throw new IOException(
"Error while retrieving config value for field " + fieldName + " in class " + className + ":\n" +
"Illegal string length received!");
throw new IOException("Error while retrieving config value for field "
+ fieldName
+ " in class "
+ className
+ ":\n"
+ "Illegal string length received!");
}
val arr = new char[length];
for (int i = 0; i < arr.length; i++) {
@@ -103,11 +113,17 @@ public class EnumConfigField<T extends Enum<T>> extends AConfigField<T> {
private T getEnumByName(String name) {
if (!enumNameMap.containsKey(name)) {
Share.LOG
.warn("Invalid value " + name + " for enum configuration field " + field.getName() +
" of type " + enumClass.getName() + " in config class " +
field.getDeclaringClass().getName() + "! Using default value of " +
defaultValue.name() + "!");
Share.LOG.warn("Invalid value "
+ name
+ " for enum configuration field "
+ field.getName()
+ " of type "
+ enumClass.getName()
+ " in config class "
+ field.getDeclaringClass().getName()
+ "! Using default value of "
+ defaultValue.name()
+ "!");
return defaultValue;
}
return enumNameMap.get(name);
@@ -50,10 +50,11 @@ public class IntConfigField extends AConfigField<Integer> {
defaultValue = Optional.ofNullable(field.getAnnotation(Config.DefaultInt.class))
.map(Config.DefaultInt::value)
.orElseGet(() -> {
Share.LOG
.warn("The field " + field.getName() + " in class " +
field.getDeclaringClass().getName() +
" has no DefaultInt annotation!\nThis will be a crash in FalsePatternLib 0.11, update your code!");
Share.LOG.warn("The field "
+ field.getName()
+ " in class "
+ field.getDeclaringClass().getName()
+ " has no DefaultInt annotation!\nThis will be a crash in FalsePatternLib 0.11, update your code!");
try {
return field.getType().isPrimitive() ? field.getInt(null)
: (Integer) field.get(null);
@@ -112,8 +113,11 @@ public class IntConfigField extends AConfigField<Integer> {
if (value >= min && value <= max) {
return true;
}
ConfigValidationFailureEvent.postNumericRangeOutOfBounds(field, -1, Integer.toString(value),
Integer.toString(min), Integer.toString(max));
ConfigValidationFailureEvent.postNumericRangeOutOfBounds(field,
-1,
Integer.toString(value),
Integer.toString(min),
Integer.toString(max));
return false;
}
@@ -49,10 +49,11 @@ public class IntListConfigField extends AListConfigField<int[]> {
defaultValue = Optional.ofNullable(field.getAnnotation(Config.DefaultIntList.class))
.map(Config.DefaultIntList::value)
.orElseGet(() -> {
Share.LOG
.warn("The field " + field.getName() + " in class " +
field.getDeclaringClass().getName() +
" has no DefaultIntList annotation!\nThis will be a crash in FalsePatternLib 0.11, update your code!");
Share.LOG.warn("The field "
+ field.getName()
+ " in class "
+ field.getDeclaringClass().getName()
+ " has no DefaultIntList annotation!\nThis will be a crash in FalsePatternLib 0.11, update your code!");
try {
return (int[]) field.get(null);
} catch (IllegalAccessException e) {
@@ -107,8 +108,11 @@ public class IntListConfigField extends AListConfigField<int[]> {
for (int j = 0; j < ints.length; j++) {
int i = ints[j];
if (i < min || i > max) {
ConfigValidationFailureEvent.postNumericRangeOutOfBounds(field, j, Integer.toString(i),
Integer.toString(min), Integer.toString(max));
ConfigValidationFailureEvent.postNumericRangeOutOfBounds(field,
j,
Integer.toString(i),
Integer.toString(min),
Integer.toString(max));
valid = false;
}
}
@@ -49,10 +49,11 @@ public class StringConfigField extends AConfigField<String> {
defaultValue = Optional.ofNullable(field.getAnnotation(Config.DefaultString.class))
.map(Config.DefaultString::value)
.orElseGet(() -> {
Share.LOG
.warn("The field " + field.getName() + " in class " +
field.getDeclaringClass().getName() +
" has no DefaultString annotation!\nThis will be a crash in FalsePatternLib 0.11, update your code!");
Share.LOG.warn("The field "
+ field.getName()
+ " in class "
+ field.getDeclaringClass().getName()
+ " has no DefaultString annotation!\nThis will be a crash in FalsePatternLib 0.11, update your code!");
try {
return (String) field.get(null);
} catch (IllegalAccessException e) {
@@ -63,9 +64,12 @@ public class StringConfigField extends AConfigField<String> {
.map(Config.StringMaxLength::value)
.orElse(256);
property.setDefaultValue(defaultValue);
property.comment +=
"\n[max length: " + maxLength + (pattern != null ? ", pattern: \"" + pattern.pattern() + "\"" : "") +
", default: \"" + defaultValue + "\"]";
property.comment += "\n[max length: "
+ maxLength
+ (pattern != null ? ", pattern: \"" + pattern.pattern() + "\"" : "")
+ ", default: \""
+ defaultValue
+ "\"]";
}
public static boolean validateString(String value, int maxLength, Pattern pattern, Field field, int listIndex) {
@@ -93,8 +97,12 @@ public class StringConfigField extends AConfigField<String> {
throws IOException {
val length = input.readInt();
if (length > maxLength || length < 0) {
throw new IOException("Error while retrieving value for " + valueName + " in class " + className + ":\n" +
"Illegal string length received!");
throw new IOException("Error while retrieving value for "
+ valueName
+ " in class "
+ className
+ ":\n"
+ "Illegal string length received!");
}
val arr = new char[length];
for (int i = 0; i < arr.length; i++) {
@@ -49,10 +49,11 @@ public class StringListConfigField extends AListConfigField<String[]> {
defaultValue = Optional.ofNullable(field.getAnnotation(Config.DefaultStringList.class))
.map(Config.DefaultStringList::value)
.orElseGet(() -> {
Share.LOG
.warn("The field " + field.getName() + " in class " +
field.getDeclaringClass().getName() +
" has no DefaultStringList annotation!\nThis will be a crash in FalsePatternLib 0.11, update your code!");
Share.LOG.warn("The field "
+ field.getName()
+ " in class "
+ field.getDeclaringClass().getName()
+ " has no DefaultStringList annotation!\nThis will be a crash in FalsePatternLib 0.11, update your code!");
try {
return (String[]) field.get(null);
} catch (IllegalAccessException e) {
@@ -66,9 +67,13 @@ public class StringListConfigField extends AListConfigField<String[]> {
if (!property.isList()) {
setToDefault();
}
property.comment += "\n[max string length: " + maxLength +
(pattern != null ? ", pattern: \"" + pattern.pattern() + "\"" : "") + ", default: \"" +
stringify(defaultValue) + "\"]";
property.comment +=
"\n[max string length: "
+ maxLength
+ (pattern != null ? ", pattern: \"" + pattern.pattern() + "\"" : "")
+ ", default: \""
+ stringify(defaultValue)
+ "\"]";
}
private static String stringify(String[] arr) {
@@ -102,7 +107,9 @@ public class StringListConfigField extends AListConfigField<String[]> {
@Override
protected void receiveElements(DataInput input, String[] arr) throws IOException {
for (int i = 0; i < arr.length; i++) {
arr[i] = StringConfigField.receiveString(input, maxStringLength, field.getName(),
arr[i] = StringConfigField.receiveString(input,
maxStringLength,
field.getName(),
field.getDeclaringClass().getName());
}
}
@@ -115,12 +115,17 @@ public class DependencyLoaderImpl {
}
}
if (oldLibDir.exists()) {
LOG.info("Migrating old library folder. From: " + oldLibDir.getAbsolutePath() + ", To: " + libDir.getAbsolutePath());
LOG.info("Migrating old library folder. From: "
+ oldLibDir.getAbsolutePath()
+ ", To: "
+ libDir.getAbsolutePath());
val oldFiles = oldLibDir.listFiles();
if (oldFiles != null) {
for (val file: oldFiles) {
for (val file : oldFiles) {
try {
Files.move(file.toPath(), libDir.toPath().resolve(oldLibDir.toPath().relativize(file.toPath())), StandardCopyOption.REPLACE_EXISTING);
Files.move(file.toPath(),
libDir.toPath().resolve(oldLibDir.toPath().relativize(file.toPath())),
StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
LOG.warn("Failed to move file " + file.getName() + " to new dir! Deleting instead.");
try {
@@ -214,9 +219,14 @@ public class DependencyLoaderImpl {
public static CompletableFuture<Void> loadLibrariesAsync(Library... libraries) {
val futures = new ArrayList<CompletableFuture<Void>>();
for (val library : libraries) {
val task = new DependencyLoadTask(library.loadingModId, library.groupId, library.artifactId,
library.minVersion, library.maxVersion, library.preferredVersion,
library.regularSuffix, library.devSuffix);
val task = new DependencyLoadTask(library.loadingModId,
library.groupId,
library.artifactId,
library.minVersion,
library.maxVersion,
library.preferredVersion,
library.regularSuffix,
library.devSuffix);
futures.add(CompletableFuture.runAsync(task::load, executor));
}
return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
@@ -230,7 +240,8 @@ public class DependencyLoaderImpl {
boolean found = false;
if (fileName.endsWith(".jar")) {
//Scan jar file for json in META-INF, add them to the list
try (val inputStream = new BufferedInputStream(source.openStream(), 65536); val jarFile = new JarInputStream(inputStream)) {
try (val inputStream = new BufferedInputStream(source.openStream(), 65536);
val jarFile = new JarInputStream(inputStream)) {
ZipEntry entry;
while ((entry = jarFile.getNextEntry()) != null) {
if (!entry.getName().startsWith("META-INF") || !entry.getName().endsWith(".json")) {
@@ -301,11 +312,12 @@ public class DependencyLoaderImpl {
return mapper.apply(pair.b).map(b -> new Pair<>(a, b));
}
private static final Pattern VERSION_PATTERN = Pattern.compile(""
+ "(0|[1-9]\\d*)(?:\\.(0|[1-9]\\d*))?(?:\\.(0|[1-9]\\d*))?"
+ "(?:-((?:(?:[0-9]+[a-zA-Z-][\\w-]*)|(?:[a-zA-Z][\\w-]*)|(?:[1-9]\\d*)|0)"
+ "(?:\\.(?:(?:[0-9]+[a-zA-Z-][\\w-]*)|(?:[a-zA-Z][\\w-]*)|(?:[1-9]\\d*)|0))*))?"
+ "(?:\\+([\\w-]+(\\.[\\w-]+)*))?");
private static final Pattern VERSION_PATTERN =
Pattern.compile("(0|[1-9]\\d*)(?:\\.(0|[1-9]\\d*))?(?:\\.(0|[1-9]\\d*))?"
+ "(?:-((?:(?:[0-9]+[a-zA-Z-][\\w-]*)|(?:[a-zA-Z][\\w-]*)|(?:[1-9]\\d*)|0)"
+ "(?:\\.(?:(?:[0-9]+[a-zA-Z-][\\w-]*)|(?:[a-zA-Z][\\w-]*)|(?:[1-9]\\d*)|0))*))?"
+ "(?:\\+([\\w-]+(\\.[\\w-]+)*))?");
public static void scanDeps() {
LOG.debug("Discovering dependency source candidates...");
val modsDir = new File(FileUtil.getMinecraftHome(), "mods");
@@ -327,48 +339,43 @@ public class DependencyLoaderImpl {
.filter((url) -> !urlsWithoutDeps.contains(url.toString()))
.collect(Collectors.toList());
val urls = new ArrayList<URL>();
for (val candidate: candidates) {
for (val candidate : candidates) {
if (!scanForDepSpecs(candidate, urls)) {
urlsWithoutDeps.add(candidate.toString());
}
}
try (val out = Files.newBufferedWriter(depCache.toPath())) {
for (val noDep: urlsWithoutDeps) {
for (val noDep : urlsWithoutDeps) {
out.append(noDep).append(System.lineSeparator());
}
} catch (IOException e) {
LOG.error("Could not write dependency scanner cache", e);
}
val dependencySpecs = urls.stream()
.map((source) -> {
//Convert source to GSON json
try (val is = new BufferedInputStream(source.openStream())) {
val jsonRaw = new JsonParser().parse(new InputStreamReader(is));
if (!jsonRaw.isJsonObject()) {
return null;
}
val json = jsonRaw.getAsJsonObject();
if (!(json.has("identifier") &&
json.get("identifier")
val dependencySpecs = urls.stream().map((source) -> {
//Convert source to GSON json
try (val is = new BufferedInputStream(source.openStream())) {
val jsonRaw = new JsonParser().parse(new InputStreamReader(is));
if (!jsonRaw.isJsonObject()) {
return null;
}
val json = jsonRaw.getAsJsonObject();
if (!(json.has("identifier") && json.get("identifier")
.getAsString()
.equals("falsepatternlib_dependencies")
)) {
return null;
}
val builder = new GsonBuilder();
builder.excludeFieldsWithoutExposeAnnotation();
val gson = builder.create();
json.remove("identifier");
val root = gson.fromJson(json, DepRoot.class);
root.source(source.toString());
return root;
} catch (Exception e) {
LOG.error("Failed to read json from source {}: {}", source, e);
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toSet());
.equals("falsepatternlib_dependencies"))) {
return null;
}
val builder = new GsonBuilder();
builder.excludeFieldsWithoutExposeAnnotation();
val gson = builder.create();
json.remove("identifier");
val root = gson.fromJson(json, DepRoot.class);
root.source(source.toString());
return root;
} catch (Exception e) {
LOG.error("Failed to read json from source {}: {}", source, e);
return null;
}
}).filter(Objects::nonNull).collect(Collectors.toSet());
long end = System.currentTimeMillis();
LOG.debug("Discovered {} dependency source candidates in {}ms", dependencySpecs.size(), end - start);
mavenRepositories.addAll(dependencySpecs.stream()
@@ -376,11 +383,16 @@ public class DependencyLoaderImpl {
.collect(Collectors.toSet()));
val artifacts = dependencySpecs.stream()
.map((root) -> new Pair<>(root.source(), root.dependencies()))
.flatMap(pair -> flatMap(pair, (dep) -> Stream.of(dep.always(), Share.DEV_ENV ? dep.dev() : dep.obf())))
.flatMap(pair -> flatMap(pair, (dep) -> Stream.concat(dep.common().stream(),
FMLLaunchHandler.side().isClient() ?
dep.client().stream() :
dep.server().stream())))
.flatMap(pair -> flatMap(pair,
(dep) -> Stream.of(dep.always(),
Share.DEV_ENV ? dep.dev()
: dep.obf())))
.flatMap(pair -> flatMap(pair,
(dep) -> Stream.concat(dep.common().stream(),
FMLLaunchHandler.side()
.isClient()
? dep.client().stream()
: dep.server().stream())))
.map((pair) -> {
val source = pair.a;
val dep = pair.b;
@@ -398,38 +410,57 @@ public class DependencyLoaderImpl {
throw new IllegalArgumentException("Invalid version: " + parts[2]);
}
val major = Integer.parseInt(matcher.group(1));
val minor = matcher.group(2) == null ? -1 : Integer.parseInt(matcher.group(2));
val patch = matcher.group(3) == null ? -1 : Integer.parseInt(matcher.group(3));
val minor = matcher.group(2) == null ? -1
: Integer.parseInt(matcher.group(2));
val patch = matcher.group(3) == null ? -1
: Integer.parseInt(matcher.group(3));
val preRelease = matcher.group(4);
val build = matcher.group(5);
version = new SemanticVersion(major, minor, patch, preRelease, build);
} catch (IllegalArgumentException e) {
LOG.warn("Unparseable dependency version {}:{}:{} from {}", groupId, artifactId, parts[2], source);
LOG.warn("Unparseable dependency version {}:{}:{} from {}",
groupId,
artifactId,
parts[2],
source);
version = new RawVersion(parts[2]);
}
final String classifier = parts.length > 3 ? parts[3] : null;
if (classifier != null) {
LOG.info("Found dependency: {}:{}:{}:{} from {}", groupId, artifactId,
version, classifier, source);
LOG.info("Found dependency: {}:{}:{}:{} from {}",
groupId,
artifactId,
version,
classifier,
source);
} else {
LOG.info("Found dependency: {}:{}:{} from {}", groupId, artifactId,
version, source);
LOG.info("Found dependency: {}:{}:{} from {}",
groupId,
artifactId,
version,
source);
}
return new DependencyLoadTask(source, groupId, artifactId,
version, null, version,
classifier, classifier);
return new DependencyLoadTask(source,
groupId,
artifactId,
version,
null,
version,
classifier,
classifier);
})
.filter(Objects::nonNull)
.collect(Collectors.toSet());
val artifactMap = new HashMap<String, DependencyLoadTask>();
for (val artifact: artifacts) {
for (val artifact : artifacts) {
val id = artifact.getGroupArtifact();
if (artifactMap.containsKey(id)) {
val otherArtifact = artifactMap.get(id);
//TODO: Check for conflicts
if (artifact.preferredVersion.compareTo(otherArtifact.preferredVersion) > 0) {
LOG.info("Replacing dependency {}:{} from {} with version {} from {}",
otherArtifact.getGroupArtifact(), otherArtifact.preferredVersion,
otherArtifact.getGroupArtifact(),
otherArtifact.preferredVersion,
otherArtifact.loadingModId,
artifact.preferredVersion,
artifact.loadingModId);
@@ -495,16 +526,18 @@ public class DependencyLoaderImpl {
}
private void crashCouldNotDownload() {
val errorMessage = "Failed to download library " + groupId + ":" + artifactId + ":" + preferredVersion +
((suffix != null) ? ":" + suffix : "") + " from any repository! Requested by mod: " +
loadingModId;
val errorMessage = "Failed to download library " + groupId + ":" + artifactId + ":" + preferredVersion + (
(suffix != null) ? ":" + suffix : "") + " from any repository! Requested by mod: " + loadingModId;
LOG.fatal(errorMessage);
throw new IllegalStateException(errorMessage);
}
private void setupLibraryNames() {
suffix = Share.DEV_ENV ? devSuffix : regularSuffix;
artifactLogName = String.format("%s:%s:%s%s", groupId, artifactId, preferredVersion,
artifactLogName = String.format("%s:%s:%s%s",
groupId,
artifactId,
preferredVersion,
suffix != null ? "-" + suffix : "");
LOG.info("Adding library {}, requested by mod {}", artifactLogName, loadingModId);
artifact = groupId + ":" + artifactId + ":" + suffix;
@@ -520,19 +553,31 @@ public class DependencyLoaderImpl {
for (int i = 0; i < 16; i++) {
LOG.fatal("ALERT VVVVVVVVVVVV ALERT");
}
LOG.fatal("Library {}:{}{} already loaded with version {}, " +
"but a version in the range {} was requested! Thing may go horribly wrong! " +
"Requested by mod: {}, previously loaded by mod: {}", groupId, artifactId,
suffix != null ? ":" + suffix : "", currentVer, rangeString, loadingModId,
LOG.fatal("Library {}:{}{} already loaded with version {}, "
+ "but a version in the range {} was requested! Thing may go horribly wrong! "
+ "Requested by mod: {}, previously loaded by mod: {}",
groupId,
artifactId,
suffix != null ? ":" + suffix : "",
currentVer,
rangeString,
loadingModId,
loadedLibraryMods.get(artifact));
for (int i = 0; i < 16; i++) {
LOG.fatal("ALERT ^^^^^^^^^^^^ ALERT");
}
} else {
LOG.info("Attempted loading of library {}:{}{} with preferred version {}, " +
"but version {} was already loaded, which matched the range {}. This is not an " + "error. " +
"Requested by mod: {}, previously loaded by mod: {}", groupId, artifactId,
suffix != null ? ":" + suffix : "", preferredVersion, currentVer, rangeString, loadingModId,
LOG.info("Attempted loading of library {}:{}{} with preferred version {}, "
+ "but version {} was already loaded, which matched the range {}. This is not an "
+ "error. "
+ "Requested by mod: {}, previously loaded by mod: {}",
groupId,
artifactId,
suffix != null ? ":" + suffix : "",
preferredVersion,
currentVer,
rangeString,
loadingModId,
loadedLibraryMods.get(artifact));
}
}
@@ -553,8 +598,8 @@ public class DependencyLoaderImpl {
if (status == ChecksumStatus.FAILED) {
return false;
} else if (status == ChecksumStatus.MISSING) {
LOG.debug("Library {} is missing checksum data! Either it was manually deleted, " +
"or the source repo didn't have it in the first place", artifactLogName);
LOG.debug("Library {} is missing checksum data! Either it was manually deleted, "
+ "or the source repo didn't have it in the first place", artifactLogName);
}
} catch (IOException e) {
LOG.error("Failed to execute validation check for " + artifactLogName, e);
@@ -575,10 +620,18 @@ public class DependencyLoaderImpl {
private void validateDownloadsAllowed() {
if (!LibraryConfig.ENABLE_LIBRARY_DOWNLOADS) {
val errorMessage = "Failed to load library " + groupId + ":" + artifactId + ":" + preferredVersion +
((suffix != null) ? ":" + suffix : "") + ": " + Tags.MODNAME +
" library downloading has been disabled in the config, and the library is not present " +
"on disk! Requested by mod: " + loadingModId;
val errorMessage = "Failed to load library "
+ groupId
+ ":"
+ artifactId
+ ":"
+ preferredVersion
+ ((suffix != null) ? ":" + suffix : "")
+ ": "
+ Tags.MODNAME
+ " library downloading has been disabled in the config, and the library is not present "
+ "on disk! Requested by mod: "
+ loadingModId;
LOG.fatal(errorMessage);
throw new IllegalStateException(errorMessage);
}
@@ -589,7 +642,11 @@ public class DependencyLoaderImpl {
if (!repo.endsWith("/")) {
repo = repo + "/";
}
val url = String.format("%s%s/%s/%s/%s", repo, groupId.replace('.', '/'), artifactId, preferredVersion,
val url = String.format("%s%s/%s/%s/%s",
repo,
groupId.replace('.', '/'),
artifactId,
preferredVersion,
mavenJarName);
String finalRepo = repo;
int retryCount = 0;
@@ -601,12 +658,15 @@ public class DependencyLoaderImpl {
val success = new AtomicBoolean(false);
Internet.connect(new URL(url),
(ex) -> LOG.debug("Artifact {} could not be downloaded from repo {}: {}",
artifactLogName, finalRepo, ex.getMessage()), (input) -> {
LOG.debug("Downloading {} from {}", artifactLogName, finalRepo);
download(input, file);
LOG.debug("Downloaded {} from {}", artifactLogName, finalRepo);
success.set(true);
});
artifactLogName,
finalRepo,
ex.getMessage()),
(input) -> {
LOG.debug("Downloading {} from {}", artifactLogName, finalRepo);
download(input, file);
LOG.debug("Downloaded {} from {}", artifactLogName, finalRepo);
success.set(true);
});
if (success.get()) {
LOG.debug("Validating checksum for {}", artifactLogName);
val hadChecksum = validateChecksum(url);
@@ -616,9 +676,9 @@ public class DependencyLoaderImpl {
case OK:
break;
case MISSING:
LOG.warn("The library {} had no checksum available on the repository.\n" +
"There's a chance it might have gotten corrupted during download,\n" +
"but we're loading it anyways.", artifactLogName);
LOG.warn("The library {} had no checksum available on the repository.\n"
+ "There's a chance it might have gotten corrupted during download,\n"
+ "but we're loading it anyways.", artifactLogName);
}
loadedLibraries.put(artifact, preferredVersion);
loadedLibraryMods.put(artifact, loadingModId);
@@ -638,13 +698,16 @@ public class DependencyLoaderImpl {
LOG.debug("Attempting to get {} checksum...", checksumType);
val success = new AtomicBoolean(false);
Internet.connect(new URL(checksumURL),
(ex) -> LOG.debug("Could not get {} checksum for {}: {}", checksumType,
artifactLogName, ex.getMessage()), (input) -> {
LOG.debug("Downloading {} checksum for {}", checksumType, artifactLogName);
download(input, checksumFile);
LOG.debug("Downloaded {} checksum for {}", checksumType, artifactLogName);
success.set(true);
});
(ex) -> LOG.debug("Could not get {} checksum for {}: {}",
checksumType,
artifactLogName,
ex.getMessage()),
(input) -> {
LOG.debug("Downloading {} checksum for {}", checksumType, artifactLogName);
download(input, checksumFile);
LOG.debug("Downloaded {} checksum for {}", checksumType, artifactLogName);
success.set(true);
});
if (success.get()) {
return getChecksumStatus(file, checksumType, checksumFile);
}
@@ -28,9 +28,11 @@ import org.jetbrains.annotations.NotNull;
public class RawVersion extends Version {
public final String versionString;
public RawVersion(String versionString) {
this.versionString = versionString;
}
@Override
public int compareTo(@NotNull Version o) {
if (o instanceof RawVersion) {
@@ -99,8 +99,9 @@ public class GuiToastImpl extends Gui {
@Nullable
public <T extends IToast> T getToast(Class<? extends T> toastClass, Object type) {
for (val toast : this.visible) {
if (toast != null && toastClass.isAssignableFrom(toast.getToast().getClass()) &&
toast.getToast().getType().equals(type)) {
if (toast != null && toastClass.isAssignableFrom(toast.getToast().getClass()) && toast.getToast()
.getType()
.equals(type)) {
return toastClass.cast(toast);
}
}
@@ -100,30 +100,33 @@ public final class UpdateCheckerImpl {
continue;
}
val latest = parsedVersions.get(0).getAsJsonObject();
result.add(new ModUpdateInfo(modid, currentVersion, latest.get("version").getAsString(), latest.get("url").getAsString()));
result.add(new ModUpdateInfo(modid,
currentVersion,
latest.get("version").getAsString(),
latest.get("url").getAsString()));
}
return result;
} catch (Exception e) {
throw new UpdateCheckException("Failed to check for updates!", e);
}
}
public static List<IChatComponent> updateListToChatMessages(String initiator, List<ModUpdateInfo> updates) {
if (updates == null || updates.size() == 0) {
return null;
}
val updateText = new ArrayList<IChatComponent>(
FormattedText.parse(I18n.format("falsepatternlib.chat.updatesavailable", initiator)).toChatText());
val updateText = new ArrayList<IChatComponent>(FormattedText.parse(I18n.format(
"falsepatternlib.chat.updatesavailable",
initiator)).toChatText());
val mods = Loader.instance().getIndexedModList();
for (val update : updates) {
val mod = mods.get(update.modID);
updateText.addAll(
FormattedText.parse(I18n.format("falsepatternlib.chat.modname", mod.getName())).toChatText());
updateText.addAll(
FormattedText.parse(I18n.format("falsepatternlib.chat.currentversion", update.currentVersion))
.toChatText());
updateText.addAll(
FormattedText.parse(I18n.format("falsepatternlib.chat.latestversion", update.latestVersion))
.toChatText());
updateText.addAll(FormattedText.parse(I18n.format("falsepatternlib.chat.modname", mod.getName()))
.toChatText());
updateText.addAll(FormattedText.parse(I18n.format("falsepatternlib.chat.currentversion",
update.currentVersion)).toChatText());
updateText.addAll(FormattedText.parse(I18n.format("falsepatternlib.chat.latestversion",
update.latestVersion)).toChatText());
if (!update.updateURL.isEmpty()) {
val pre = FormattedText.parse(I18n.format("falsepatternlib.chat.updateurlpre")).toChatText();
val link = FormattedText.parse(I18n.format("falsepatternlib.chat.updateurl")).toChatText();
@@ -184,7 +187,7 @@ public final class UpdateCheckerImpl {
private static CompletableFuture<JsonArray> parseVersionSpecs(JsonArray versions) {
return CompletableFuture.supplyAsync(() -> {
val result = new JsonArray();
for (val entry: versions) {
for (val entry : versions) {
if (!entry.isJsonObject()) {
continue;
}
@@ -238,17 +241,20 @@ public final class UpdateCheckerImpl {
val response = new AtomicReference<JsonObject>();
val result = new JsonObject();
Internet.connect(new URL("https://api.github.com/repos/" + owner + "/" + name + "/releases/latest"),
Internet.constructHeaders("Accept", "application/vnd.github+json",
"X-GitHub-Api-Version", "2022-11-28"),
(e) -> {throw new CompletionException(e);
Internet.constructHeaders("Accept",
"application/vnd.github+json",
"X-GitHub-Api-Version",
"2022-11-28"),
(e) -> {
throw new CompletionException(e);
},
(stream) -> {
val parser = new JsonParser();
val json = parser.parse(new InputStreamReader(stream));
if (!json.isJsonObject()) {
return;
}
response.set(json.getAsJsonObject());
val parser = new JsonParser();
val json = parser.parse(new InputStreamReader(stream));
if (!json.isJsonObject()) {
return;
}
response.set(json.getAsJsonObject());
});
if (response.get() == null) {
return null;
@@ -306,11 +312,10 @@ public final class UpdateCheckerImpl {
if (latestVersions.contains(currentVersion)) {
continue;
}
val updateURL = obj.has("updateURL") &&
obj.get("updateURL").isJsonPrimitive() &&
obj.get("updateURL").getAsJsonPrimitive().isString()
? obj.get("updateURL").getAsString()
: "";
val updateURL = obj.has("updateURL") && obj.get("updateURL").isJsonPrimitive() && obj.get("updateURL")
.getAsJsonPrimitive()
.isString()
? obj.get("updateURL").getAsString() : "";
result.add(new ModUpdateInfo(modid, currentVersion, latestVersions.get(0), updateURL));
}
return result;