Reload Zed schemas and ignore .zed in pack hotload

Also covers modded studios and the editor command
This commit is contained in:
piexel committed 2026-11-14 15:39:12 +01:00
1 parent bbb3833e29
commit ca5cdff5ea
14 files changed
+556 -98

No files matched your search

@@ -24,6 +24,7 @@ import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.studio.map.MapWindow;
import art.arcane.iris.studio.map.PaletteExplorerStart;
import art.arcane.iris.studio.view.GuiHost;
import art.arcane.iris.pack.PackDownloader;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.studio.workspace.IrisProject;
import art.arcane.iris.studio.workspace.IrisCodeWorkspace;
@@ -170,9 +171,15 @@ public class CommandStudio implements DirectorExecutor {
@Director(description = "Open the configured editor for a dimension", descriptionKey = "iris.director.commandstudio.director.open_editor_dimension", aliases = {"vscode", "vsc"})
public void editor(
@Param(defaultValue = "default", description = "The dimension to open the editor for", descriptionKey = "iris.director.commandstudio.param.dimension_open_editor", aliases = "dim", customHandler = DimensionHandler.class)
@Param(defaultValue = "null", description = "The dimension to open the editor for", descriptionKey = "iris.director.commandstudio.param.dimension_open_editor", aliases = "dim", customHandler = NullableDimensionHandler.class)
IrisDimension dimension
) {
StudioSVC studio = Iris.service(StudioSVC.class);
String pack = dimension != null ? dimension.getLoadKey() : packForEditor(studio);
if (!PackDownloader.isPackPresent(studio.getWorkspaceFolder(), pack)) {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_COULD_NOT_RESOLVE_PACK_DIMENSION, MessageArgument.untrusted("value", pack)));
return;
}
StudioEditor editor = StudioEditorLauncher.configuredEditor();
if (editor == StudioEditor.NONE) {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_NO_EDITOR_CONFIGURED));
@@ -183,8 +190,15 @@ public class CommandStudio implements DirectorExecutor {
return;
}
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_EDITOR_PACK,
MessageArgument.untrusted("editor", editor.getDisplayName()), MessageArgument.untrusted("value", dimension.getName())));
Iris.service(StudioSVC.class).openEditor(sender(), dimension.getLoadKey());
MessageArgument.untrusted("editor", editor.getDisplayName()), MessageArgument.untrusted("value", pack)));
studio.openEditor(sender(), pack);
}
private static String packForEditor(StudioSVC studio) {
if (studio.isProjectOpen()) {
return studio.getActiveProject().getName();
}
return IrisSettings.get().getGenerator().getDefaultWorldType();
}
@Director(description = "Close an open studio project", descriptionKey = "iris.director.commandstudio.director.close_open_studio_project", aliases = {"x"}, sync = true)
@@ -27,6 +27,15 @@ public class CommandStudioCreationContractTest {
assertEquals(NullableDimensionHandler.class, template.customHandler());
}
@Test
public void editorDimensionIsOptionalSoTheOpenStudioCanBeUsed() throws NoSuchMethodException {
Method command = CommandStudio.class.getDeclaredMethod("editor", IrisDimension.class);
Param dimension = command.getParameters()[0].getAnnotation(Param.class);
assertEquals("null", dimension.defaultValue());
assertEquals(NullableDimensionHandler.class, dimension.customHandler());
}
@Test
public void openExposesAnOptInForceFlag() throws NoSuchMethodException {
Method command = CommandStudio.class.getDeclaredMethod(
@@ -23,7 +23,8 @@ import art.arcane.iris.pack.loading.ResourceLoader;
import art.arcane.iris.pack.schema.SchemaBuilder;
import art.arcane.iris.pack.schema.annotation.Snippet;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.world.task.J;
import art.arcane.iris.studio.workspace.SchemaFiles;
import art.arcane.iris.studio.workspace.ZedProjectSettings;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.format.Form;
import art.arcane.volmlib.util.io.IO;
@@ -32,6 +33,9 @@ import art.arcane.volmlib.util.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public final class ModdedWorkspaceGenerator {
private ModdedWorkspaceGenerator() {
@@ -42,17 +46,29 @@ public final class ModdedWorkspaceGenerator {
}
public static File writeWorkspace(IrisData data, File folder, boolean immediateSchemas) throws IOException {
JSONObject workspaceConfig = buildWorkspace(data, immediateSchemas);
List<CompletableFuture<String>> schemaWrites = new ArrayList<>();
JSONObject workspaceConfig = buildWorkspace(data, immediateSchemas, schemaWrites);
File workspace = new File(folder, folder.getName() + ".code-workspace");
IO.writeAll(workspace, workspaceConfig.toString(4));
JSONArray schemas = workspaceConfig.getJSONObject("settings").getJSONArray("json.schemas");
writeZedSettings(folder, schemas, schemaWrites);
return workspace;
}
public static JSONObject buildWorkspace(IrisData data) {
return buildWorkspace(data, false);
return buildWorkspace(data, false, new ArrayList<>());
}
private static JSONObject buildWorkspace(IrisData data, boolean immediateSchemas) {
private static void writeZedSettings(File folder, JSONArray schemas, List<CompletableFuture<String>> schemaWrites) {
try {
new ZedProjectSettings(folder).writeIrisSettings(schemas, SchemaFiles.awaitTexts(schemaWrites));
} catch (Throwable e) {
IrisLogging.reportError(e);
IrisLogging.warn("Could not update Zed schema mappings for " + folder.getAbsolutePath() + "; VSCode workspace generation will continue.");
}
}
private static JSONObject buildWorkspace(IrisData data, boolean immediateSchemas, List<CompletableFuture<String>> schemaWrites) {
JSONObject ws = new JSONObject();
JSONArray folders = new JSONArray();
JSONObject folder = new JSONObject();
@@ -82,17 +98,20 @@ public final class ModdedWorkspaceGenerator {
json.put("editor.suggest.insertMode", "replace");
settings.put("[json]", json);
settings.put("json.maxItemsComputed", 30000);
settings.put("json.schemas", buildSchemas(data, immediateSchemas));
settings.put("json.schemas", buildSchemas(data, immediateSchemas, schemaWrites));
ws.put("settings", settings);
return ws;
}
private static JSONArray buildSchemas(IrisData data, boolean immediateSchemas) {
private static JSONArray buildSchemas(IrisData data, boolean immediateSchemas, List<CompletableFuture<String>> schemaWrites) {
JSONArray schemas = new JSONArray();
// The shared instance keeps its file listings across edits, so files added, moved or removed since would be missing.
data.clearLists();
for (ResourceLoader<?> loader : data.getLoaders().v()) {
if (loader.supportsSchemas()) {
schemas.put(immediateSchemas ? loader.buildSchemaImmediately() : loader.buildSchema());
schemas.put(loader.schemaMapping());
schemaWrites.add(loader.writeSchemaFile(immediateSchemas));
}
}
@@ -110,17 +129,7 @@ public final class ModdedWorkspaceGenerator {
entry.put("url", "./.iris/schema/snippet/" + snipType + "-schema.json");
schemas.put(entry);
File schemaFile = new File(data.getDataFolder(), ".iris/schema/snippet/" + snipType + "-schema.json");
if (immediateSchemas) {
IO.writeAll(schemaFile, new SchemaBuilder(snippetClass, data).construct().toString(4));
} else {
J.attemptAsync(() -> {
try {
IO.writeAll(schemaFile, new SchemaBuilder(snippetClass, data).construct().toString(4));
} catch (Throwable e) {
IrisLogging.reportError(e);
}
});
}
schemaWrites.add(SchemaFiles.write(schemaFile, () -> new SchemaBuilder(snippetClass, data).construct().toString(4), immediateSchemas));
} catch (Throwable e) {
if (immediateSchemas) {
throw new IllegalStateException("Could not write snippet schema for " + snippetClass.getName(), e);
@@ -21,6 +21,7 @@ package art.arcane.iris.modded.service;
import art.arcane.iris.modded.ModdedIrisLog;
import art.arcane.iris.studio.view.PregeneratorJob;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.studio.workspace.PackHotloadFolder;
import art.arcane.iris.world.WorldMaintenance;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.world.history.SavedTerrainChunk;
@@ -364,12 +365,10 @@ public final class ModdedStudioHotloadService implements ModdedTickableService,
if (watch.engine != engine) {
watch.close();
watch.engine = engine;
watch.folder = new ReactiveFolder(
watch.folder = PackHotloadFolder.watch(
engine.getData().getDataFolder(),
(KList<File> created, KList<File> changed, KList<File> deleted) -> hotload(dimensionId, engine),
new KList<>(".iob", ".json"),
new KList<>(".iris"),
new KList<>());
(KList<File> created, KList<File> changed, KList<File> deleted) -> hotload(dimensionId, engine));
return;
}
ReactiveFolder folder = watch.folder;
@@ -25,6 +25,7 @@ import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.pack.schema.SchemaBuilder;
import art.arcane.iris.pack.PackValidator;
import art.arcane.iris.studio.workspace.SchemaFiles;
import art.arcane.iris.generation.runtime.PreservationRegistry;
import art.arcane.volmlib.util.cache.AtomicCache;
import art.arcane.iris.generation.runtime.Engine;
@@ -66,8 +67,10 @@ import java.util.Comparator;
import java.util.HashSet;
import java.util.HexFormat;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -75,6 +78,7 @@ import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.GZIPInputStream;
@@ -92,7 +96,7 @@ public class ResourceLoader<T extends IrisRegistrant> implements MeteredCache {
private static final int PREFETCH_KEY_LENGTH_LIMIT = 1_024;
private static final long PREFETCH_FILE_SIZE_LIMIT = 4L * 1_024L * 1_024L;
private static volatile ExecutorService schemaBuildExecutor;
private static final Set<String> schemaBuildQueue = ConcurrentHashMap.newKeySet();
private static final Map<String, CompletableFuture<String>> schemaBuildQueue = new ConcurrentHashMap<>();
protected final AtomicCache<KList<File>> folderCache;
protected volatile KSet<String> firstAccess;
protected File root;
@@ -144,7 +148,7 @@ public class ResourceLoader<T extends IrisRegistrant> implements MeteredCache {
private static synchronized ExecutorService schemaBuildExecutor() {
ExecutorService current = schemaBuildExecutor;
if (current == null || current.isShutdown()) {
schemaBuildQueue.clear();
abandonQueuedSchemaBuilds();
current = Executors.newSingleThreadExecutor(runnable -> {
Thread thread = new Thread(runnable, "Iris-Schema-Builder");
thread.setDaemon(true);
@@ -160,16 +164,12 @@ public class ResourceLoader<T extends IrisRegistrant> implements MeteredCache {
return current;
}
public JSONObject buildSchema() {
return buildSchema(false);
private static void abandonQueuedSchemaBuilds() {
schemaBuildQueue.values().forEach(build -> build.complete(SchemaFiles.FAILED_SCHEMA_TEXT));
schemaBuildQueue.clear();
}
public JSONObject buildSchemaImmediately() {
return buildSchema(true);
}
private JSONObject buildSchema(boolean immediate) {
IrisLogging.debug("Building Schema " + objectClass.getSimpleName() + " " + root.getPath());
public JSONObject schemaMapping() {
JSONObject o = new JSONObject();
KList<String> fm = new KList<>();
@@ -179,39 +179,40 @@ public class ResourceLoader<T extends IrisRegistrant> implements MeteredCache {
o.put("fileMatch", new JSONArray(fm.toArray()));
o.put("url", "./.iris/schema/" + getFolderName() + "-schema.json");
File a = new File(getManager().getDataFolder(), ".iris/schema/" + getFolderName() + "-schema.json");
if (immediate) {
try {
IO.writeAll(a, new SchemaBuilder(objectClass, manager).construct().toString(4));
} catch (IOException e) {
throw new IllegalStateException("Could not write schema " + a.getAbsolutePath(), e);
}
return o;
}
String schemaPath = a.getAbsolutePath();
if (schemaBuildQueue.add(schemaPath)) {
try {
schemaBuildExecutor().execute(() -> {
try {
IO.writeAll(a, new SchemaBuilder(objectClass, manager).construct().toString(4));
} catch (Throwable e) {
IrisLogging.reportError(e);
} finally {
schemaBuildQueue.remove(schemaPath);
}
});
} catch (RejectedExecutionException rejected) {
// Never let a dead pool leak the queue entry or escape into workspace
// generation (which would delete the user's .code-workspace on the way out).
schemaBuildQueue.remove(schemaPath);
IrisLogging.warn("Schema build skipped (executor unavailable): " + schemaPath);
}
}
return o;
}
public CompletableFuture<String> writeSchemaFile(boolean immediate) {
IrisLogging.debug("Building Schema " + objectClass.getSimpleName() + " " + root.getPath());
File schemaFile = new File(getManager().getDataFolder(), ".iris/schema/" + getFolderName() + "-schema.json");
Supplier<String> schemaText = () -> new SchemaBuilder(objectClass, manager).construct().toString(4);
if (immediate) {
return SchemaFiles.write(schemaFile, schemaText, true);
}
String schemaPath = schemaFile.getAbsolutePath();
CompletableFuture<String> build = new CompletableFuture<>();
CompletableFuture<String> queued = schemaBuildQueue.putIfAbsent(schemaPath, build);
if (queued != null) {
return queued;
}
try {
schemaBuildExecutor().execute(() -> {
String text = SchemaFiles.writeReporting(schemaFile, schemaText);
schemaBuildQueue.remove(schemaPath, build);
build.complete(text);
});
} catch (RejectedExecutionException rejected) {
// Never let a dead pool leak the queue entry or escape into workspace
// generation (which would delete the user's .code-workspace on the way out).
schemaBuildQueue.remove(schemaPath, build);
build.complete(SchemaFiles.FAILED_SCHEMA_TEXT);
IrisLogging.warn("Schema build skipped (executor unavailable): " + schemaPath);
}
return build;
}
public File findFile(String name) {
if (name == null || name.trim().isEmpty()) {
return null;
@@ -39,6 +39,7 @@ import art.arcane.iris.studio.object.ObjectStudioLayout;
import art.arcane.iris.studio.jigsaw.JigsawStudioActivation;
import art.arcane.iris.studio.jigsaw.JigsawStudioSession;
import art.arcane.iris.studio.StudioSVC;
import art.arcane.iris.studio.workspace.PackHotloadFolder;
import art.arcane.iris.world.IrisToolbelt;
import art.arcane.iris.generation.runtime.IrisComplex;
import art.arcane.iris.generation.runtime.IrisEngine;
@@ -189,13 +190,7 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun
this.dataLocation = dataLocation;
this.dimensionKey = dimensionKey;
this.generationHistory = generationHistory;
this.folder = new ReactiveFolder(
dataLocation,
(_a, _b, _c) -> hotloadFromWatcher(),
new KList<>(".iob", ".json", ".png"),
new KList<>(".iris"),
new KList<>()
);
this.folder = PackHotloadFolder.watch(dataLocation, new KList<>(".iob", ".json", ".png"), (_a, _b, _c) -> hotloadFromWatcher());
this.initializationFailure = null;
this.jigsawStudioActive = false;
this.validatedDimension = null;
@@ -42,6 +42,7 @@ import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@SuppressWarnings("ALL")
public class IrisCodeWorkspace {
@@ -156,12 +157,14 @@ public class IrisCodeWorkspace {
settings.put("files.associations", associations);
JSONArray schemas = new JSONArray();
List<JSONObject> schemaEntries = new ArrayList<>();
List<CompletableFuture<String>> schemaWrites = new ArrayList<>();
IrisData dm = IrisData.get(project.getPath());
// The shared instance keeps its file listings across edits, so files added, moved or removed since would be missing.
dm.clearLists();
for (ResourceLoader<?> resourceLoader : dm.getLoaders().v()) {
if (resourceLoader.supportsSchemas()) {
schemaEntries.add(immediateSchemas
? resourceLoader.buildSchemaImmediately()
: resourceLoader.buildSchema());
schemaEntries.add(resourceLoader.schemaMapping());
schemaWrites.add(resourceLoader.writeSchemaFile(immediateSchemas));
}
}
@@ -179,18 +182,7 @@ public class IrisCodeWorkspace {
schemaEntry.put("url", "./.iris/schema/snippet/" + snipType + "-schema.json");
schemaEntries.add(schemaEntry);
File schemaFile = new File(dm.getDataFolder(), ".iris/schema/snippet/" + snipType + "-schema.json");
if (immediateSchemas) {
IO.writeAll(schemaFile, new SchemaBuilder(snippetClass, dm).construct().toString(4));
} else {
IrisData snippetData = dm;
J.attemptAsync(() -> {
try {
IO.writeAll(schemaFile, new SchemaBuilder(snippetClass, snippetData).construct().toString(4));
} catch (Throwable e) {
IrisLogging.reportError(e);
}
});
}
schemaWrites.add(SchemaFiles.write(schemaFile, () -> new SchemaBuilder(snippetClass, dm).construct().toString(4), immediateSchemas));
} catch (Throwable e) {
if (immediateSchemas) {
throw new IllegalStateException("Could not write snippet schema for " + snippetClass.getName(), e);
@@ -215,7 +207,7 @@ public class IrisCodeWorkspace {
}
try {
new ZedProjectSettings(project.getPath()).writeIrisSettings(schemas);
new ZedProjectSettings(project.getPath()).writeIrisSettings(schemas, SchemaFiles.awaitTexts(schemaWrites));
} catch (Throwable e) {
IrisLogging.reportError(e);
IrisLogging.warn("Could not update Zed schema mappings for " + project.getPath().getAbsolutePath() + "; VSCode workspace generation will continue.");
@@ -0,0 +1,42 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.workspace;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.function.Consumer3;
import art.arcane.volmlib.util.io.ReactiveFolder;
import java.io.File;
public final class PackHotloadFolder {
private static final String EDITOR_SETTINGS_FOLDER = File.separator + ".zed" + File.separator;
private PackHotloadFolder() {
}
public static ReactiveFolder watch(File packFolder, KList<String> watchedExtensions, Consumer3<KList<File>, KList<File>, KList<File>> hotload) {
return new ReactiveFolder(
packFolder,
hotload,
watchedExtensions,
new KList<>(".iris", EDITOR_SETTINGS_FOLDER),
new KList<>()
);
}
}
@@ -0,0 +1,87 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.workspace;
import art.arcane.iris.generation.concurrent.MultiBurst;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.volmlib.util.io.IO;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
/**
* Writes schema files and hands back the text written, so the editor settings can carry a hash of what is on disk.
*/
public final class SchemaFiles {
public static final String FAILED_SCHEMA_TEXT = "";
private SchemaFiles() {
}
/**
* Builds and writes {@code schemaFile} now, or in the background. A background write that fails is reported and
* completes with an empty text; a write now throws.
*/
public static CompletableFuture<String> write(File schemaFile, Supplier<String> schemaText, boolean immediate) {
if (immediate) {
return CompletableFuture.completedFuture(writeNow(schemaFile, schemaText));
}
return writeAsync(schemaFile, schemaText);
}
public static CompletableFuture<String> writeAsync(File schemaFile, Supplier<String> schemaText) {
return MultiBurst.burst.completeValueAsync(() -> writeReporting(schemaFile, schemaText));
}
public static String writeNow(File schemaFile, Supplier<String> schemaText) {
String text = schemaText.get();
try {
IO.writeAll(schemaFile, text);
} catch (IOException failure) {
throw new UncheckedIOException("Could not write schema " + schemaFile.getAbsolutePath(), failure);
}
return text;
}
public static String writeReporting(File schemaFile, Supplier<String> schemaText) {
try {
return writeNow(schemaFile, schemaText);
} catch (Throwable failure) {
IrisLogging.reportError(failure);
return FAILED_SCHEMA_TEXT;
}
}
public static List<String> awaitTexts(List<CompletableFuture<String>> schemaWrites) {
return schemaWrites.stream().map(SchemaFiles::awaitText).toList();
}
private static String awaitText(CompletableFuture<String> schemaWrite) {
try {
return schemaWrite.join();
} catch (RuntimeException failure) {
IrisLogging.reportError(failure);
return FAILED_SCHEMA_TEXT;
}
}
}
@@ -35,16 +35,24 @@ import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
import java.util.List;
/**
* Keeps the JSON schema mappings in a pack's Zed project settings in sync with the VSCode workspace.
* The file belongs to the user, so Iris only replaces {@code lsp.json-language-server.settings.json.schemas}
* and makes sure {@code file_types.JSONC} contains {@code json}.
* and {@code lsp.json-language-server.settings.irisSchemaHash}, and makes sure {@code file_types.JSONC} contains {@code json}.
*/
final class ZedProjectSettings {
public final class ZedProjectSettings {
private static final List<String> JSON_SERVER_SETTINGS_PATH = List.of("lsp", "json-language-server", "settings");
private static final List<String> SCHEMAS_PARENT_PATH = List.of("lsp", "json-language-server", "settings", "json");
private static final String SCHEMAS_KEY = "schemas";
// Zed's JSON server caches schema files until its configuration changes, and Zed never reports schema file edits.
// Carrying a hash of the schema contents in the configuration makes regenerated schemas reach the editor.
private static final String SCHEMA_HASH_KEY = "irisSchemaHash";
private static final int SCHEMA_HASH_HEX_LENGTH = 16;
private static final List<String> FILE_TYPES_PATH = List.of("file_types");
// Pack files may contain comments; Zed's JSONC language keeps schema support but stops flagging them.
private static final String JSONC_LANGUAGE = "JSONC";
@@ -58,7 +66,7 @@ final class ZedProjectSettings {
private final Path settingsFile;
ZedProjectSettings(File projectRoot) {
public ZedProjectSettings(File projectRoot) {
this.settingsFile = projectRoot.toPath().resolve(".zed").resolve("settings.json");
}
@@ -66,7 +74,7 @@ final class ZedProjectSettings {
return settingsFile;
}
void writeIrisSettings(JSONArray schemas) throws IOException {
public void writeIrisSettings(JSONArray schemas, List<String> schemaTexts) throws IOException {
String existing = Files.isRegularFile(settingsFile) ? Files.readString(settingsFile, StandardCharsets.UTF_8) : null;
JsonObject settings = parseOrNull(existing);
if (settings == null) {
@@ -74,7 +82,7 @@ final class ZedProjectSettings {
return;
}
if (!mergeSchemas(settings, schemas) || !mergeJsoncFileType(settings)) {
if (!mergeSchemas(settings, schemas) || !mergeSchemaHash(settings, schemaTexts) || !mergeJsoncFileType(settings)) {
IrisLogging.warn("Could not merge Iris settings into " + settingsFile + ": " + String.join(".", SCHEMAS_PARENT_PATH)
+ " must be an object and " + String.join(".", FILE_TYPES_PATH) + "." + JSONC_LANGUAGE + " a list; leaving it untouched.");
return;
@@ -104,6 +112,32 @@ final class ZedProjectSettings {
return true;
}
private static boolean mergeSchemaHash(JsonObject settings, List<String> schemaTexts) {
JsonObject jsonServerSettings = findOrCreateObject(settings, JSON_SERVER_SETTINGS_PATH);
if (jsonServerSettings == null) {
return false;
}
jsonServerSettings.addProperty(SCHEMA_HASH_KEY, hashSchemaTexts(schemaTexts));
return true;
}
private static String hashSchemaTexts(List<String> schemaTexts) {
MessageDigest digest = sha256();
for (String schemaText : schemaTexts) {
digest.update(schemaText.getBytes(StandardCharsets.UTF_8));
digest.update((byte) 0);
}
return HexFormat.of().formatHex(digest.digest()).substring(0, SCHEMA_HASH_HEX_LENGTH);
}
private static MessageDigest sha256() {
try {
return MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("Every Java runtime must provide SHA-256", e);
}
}
private static boolean mergeJsoncFileType(JsonObject settings) {
JsonObject fileTypes = findOrCreateObject(settings, FILE_TYPES_PATH);
if (fileTypes == null) {
@@ -22,15 +22,18 @@ import org.mockito.Answers;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.stream.Stream;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -138,6 +141,26 @@ public class IrisCodeWorkspaceTest {
Files.readString(unrelatedWorkspace.toPath(), StandardCharsets.UTF_8));
}
@Test
public void reopeningAfterAFileMoveOffersTheNewKeyAndChangesZedsSchemaHash() throws Exception {
File pack = temporaryFolder.newFolder("moved-biome");
Path biomes = Files.createDirectories(pack.toPath().resolve("biomes"));
Files.writeString(biomes.resolve("before-move.json"), "{}", StandardCharsets.UTF_8);
IrisSettings.get().getStudio().setEditor(StudioEditor.NONE);
IrisCodeWorkspace workspace = new IrisCodeWorkspace(new IrisProject(pack));
workspace.prepareAndOpenEditor();
data = IrisData.get(pack);
String hashBefore = zedSchemaHash(pack);
assertTrue(schemasMention(pack, "before-move"));
Files.move(biomes.resolve("before-move.json"), biomes.resolve("after-move.json"));
workspace.prepareAndOpenEditor();
assertTrue("The refreshed schemas must offer the moved file's new key", schemasMention(pack, "after-move"));
assertFalse("The refreshed schemas must stop offering the old key", schemasMention(pack, "before-move"));
assertNotEquals("Zed must see a settings change so it reloads the schemas", hashBefore, zedSchemaHash(pack));
}
@Test
public void updateWorkspaceMirrorsSchemasIntoZedSettings() throws Exception {
File pack = temporaryFolder.newFolder("zed-pack");
@@ -163,6 +186,26 @@ public class IrisCodeWorkspaceTest {
assertEquals("jsonc", configuration.getJSONObject("settings").getJSONObject("files.associations").getString("*.json"));
}
private static boolean schemasMention(File pack, String key) throws Exception {
try (Stream<Path> schemaFiles = Files.walk(pack.toPath().resolve(".iris/schema"))) {
return schemaFiles.filter(Files::isRegularFile)
.anyMatch(file -> readQuietly(file).contains("\"" + key + "\""));
}
}
private static String readQuietly(Path file) {
try {
return Files.readString(file, StandardCharsets.UTF_8);
} catch (Exception e) {
return "";
}
}
private static String zedSchemaHash(File pack) throws Exception {
JSONObject settings = new JSONObject(Files.readString(pack.toPath().resolve(".zed/settings.json"), StandardCharsets.UTF_8));
return settings.getJSONObject("lsp").getJSONObject("json-language-server").getJSONObject("settings").getString("irisSchemaHash");
}
private static JSONArray assertWorkspaceSchemasMaterialized(File pack, File canonicalWorkspace) throws Exception {
JSONObject configuration = new JSONObject(Files.readString(canonicalWorkspace.toPath(), StandardCharsets.UTF_8));
JSONArray schemas = configuration.getJSONObject("settings").getJSONArray("json.schemas");
@@ -0,0 +1,78 @@
package art.arcane.iris.studio.workspace;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.io.ReactiveFolder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class PackHotloadFolderTest {
private static final long HOTLOAD_DEADLINE_MILLIS = 15_000L;
private static final long CHECK_INTERVAL_MILLIS = 50L;
private static final KList<String> WATCHED_EXTENSIONS = new KList<>(".iob", ".json");
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Test
public void packFileChangeTriggersHotload() throws Exception {
File pack = temp.newFolder("pack");
File dimension = new File(pack, "dimensions/overworld.json");
write(dimension, "{}");
AtomicReference<KList<File>> changed = new AtomicReference<>();
ReactiveFolder folder = PackHotloadFolder.watch(pack, WATCHED_EXTENSIONS, (created, modified, deleted) -> changed.set(modified));
folder.check();
write(dimension, "{\"changed\":true}");
assertNotNull(awaitHotload(folder, changed));
}
@Test
public void editorSettingsAndIrisCacheNeverReachTheHotload() throws Exception {
File pack = temp.newFolder("pack");
File dimension = new File(pack, "dimensions/overworld.json");
File editorSettings = new File(pack, ".zed/settings.json");
File irisCache = new File(pack, ".iris/cache.json");
write(dimension, "{}");
write(editorSettings, "{}");
write(irisCache, "{}");
AtomicReference<KList<File>> changed = new AtomicReference<>();
ReactiveFolder folder = PackHotloadFolder.watch(pack, WATCHED_EXTENSIONS, (created, modified, deleted) -> changed.set(modified));
folder.check();
write(editorSettings, "{\"changed\":true}");
write(irisCache, "{\"changed\":true}");
write(dimension, "{\"changed\":true}");
KList<File> reloaded = awaitHotload(folder, changed);
assertNotNull(reloaded);
assertEquals(1, reloaded.size());
assertTrue(reloaded.get(0).getPath().endsWith("overworld.json"));
}
private static void write(File file, String content) throws IOException {
Files.createDirectories(file.getParentFile().toPath());
Files.writeString(file.toPath(), content);
}
private static KList<File> awaitHotload(ReactiveFolder folder, AtomicReference<KList<File>> changed) throws InterruptedException {
long deadline = System.currentTimeMillis() + HOTLOAD_DEADLINE_MILLIS;
while (System.currentTimeMillis() < deadline) {
if (folder.check()) {
return changed.get();
}
Thread.sleep(CHECK_INTERVAL_MILLIS);
}
return null;
}
}
@@ -0,0 +1,111 @@
package art.arcane.iris.studio.workspace;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.spi.IrisPlatform;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.spi.PlatformRegistries;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.mockito.Answers;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class SchemaFilesTest {
private static final String SCHEMA_TEXT = "{\"type\": \"object\"}";
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
private IrisPlatform previousPlatform;
private IrisSettings previousSettings;
@Before
public void bindPlatform() {
previousPlatform = IrisPlatforms.isBound() ? IrisPlatforms.get() : null;
previousSettings = IrisSettings.settings;
IrisPlatforms.unbind();
IrisPlatform platform = mock(IrisPlatform.class, Answers.CALLS_REAL_METHODS);
when(platform.dataFolder()).thenReturn(temporaryFolder.getRoot());
when(platform.registries()).thenReturn(mock(PlatformRegistries.class));
IrisPlatforms.bind(platform);
IrisSettings.settings = new IrisSettings();
}
@After
public void restorePlatform() {
IrisPlatforms.unbind();
if (previousPlatform != null) {
IrisPlatforms.bind(previousPlatform);
}
IrisSettings.settings = previousSettings;
}
@Test
public void immediateWriteReturnsTheTextItWrote() throws Exception {
File schemaFile = new File(temporaryFolder.getRoot(), ".iris/schema/biome-schema.json");
String text = SchemaFiles.write(schemaFile, () -> SCHEMA_TEXT, true).join();
assertEquals(SCHEMA_TEXT, text);
assertEquals(SCHEMA_TEXT, Files.readString(schemaFile.toPath(), StandardCharsets.UTF_8).stripTrailing());
}
@Test
public void immediateWriteThrowsWhenTheSchemaCannotBeBuilt() {
File schemaFile = new File(temporaryFolder.getRoot(), "broken-schema.json");
assertThrows(IllegalStateException.class, () -> SchemaFiles.write(schemaFile, () -> {
throw new IllegalStateException("broken");
}, true));
assertFalse(schemaFile.exists());
}
@Test
public void backgroundWriteReturnsTheTextItWrote() throws Exception {
File schemaFile = new File(temporaryFolder.getRoot(), "region-schema.json");
String text = SchemaFiles.write(schemaFile, () -> SCHEMA_TEXT, false).join();
assertEquals(SCHEMA_TEXT, text);
assertEquals(SCHEMA_TEXT, Files.readString(schemaFile.toPath(), StandardCharsets.UTF_8).stripTrailing());
}
@Test
public void failedBackgroundWriteHashesAsEmptyText() {
File schemaFile = new File(temporaryFolder.getRoot(), "broken-schema.json");
String text = SchemaFiles.write(schemaFile, () -> {
throw new IllegalStateException("broken");
}, false).join();
assertEquals(SchemaFiles.FAILED_SCHEMA_TEXT, text);
}
@Test
public void awaitTextsKeepsOrderAndMapsFailuresToEmptyText() {
CompletableFuture<String> failed = new CompletableFuture<>();
failed.completeExceptionally(new IllegalStateException("broken"));
List<String> texts = SchemaFiles.awaitTexts(List.of(CompletableFuture.completedFuture("a"), failed, CompletableFuture.completedFuture("c")));
assertEquals(List.of("a", SchemaFiles.FAILED_SCHEMA_TEXT, "c"), texts);
}
}
@@ -14,11 +14,15 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
public class ZedProjectSettingsTest {
private static final String BIOME_SCHEMA_TEXT = "{\"enum\": [\"land/plains\"]}";
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@@ -27,7 +31,7 @@ public class ZedProjectSettingsTest {
File pack = temporaryFolder.newFolder("pack");
ZedProjectSettings zed = new ZedProjectSettings(pack);
zed.writeIrisSettings(biomeSchemas());
zed.writeIrisSettings(biomeSchemas(), List.of(BIOME_SCHEMA_TEXT));
assertTrue("Zed settings must be created", Files.isRegularFile(zed.getSettingsFile()));
JsonObject settings = readSettings(zed.getSettingsFile());
@@ -54,7 +58,7 @@ public class ZedProjectSettingsTest {
}
""", StandardCharsets.UTF_8);
zed.writeIrisSettings(biomeSchemas());
zed.writeIrisSettings(biomeSchemas(), List.of(BIOME_SCHEMA_TEXT));
JsonObject settings = readSettings(zed.getSettingsFile());
assertEquals(JsonParser.parseString("[\"*.jsonc5\", \"json\"]"), jsoncGlobsIn(settings));
@@ -81,7 +85,7 @@ public class ZedProjectSettingsTest {
""";
Files.writeString(zed.getSettingsFile(), jsonc, StandardCharsets.UTF_8);
zed.writeIrisSettings(biomeSchemas());
zed.writeIrisSettings(biomeSchemas(), List.of(BIOME_SCHEMA_TEXT));
assertEquals(jsonc, Files.readString(zed.getSettingsFile(), StandardCharsets.UTF_8));
}
@@ -90,18 +94,58 @@ public class ZedProjectSettingsTest {
public void unchangedSchemasDoNotRewriteTheFile() throws Exception {
File pack = temporaryFolder.newFolder("pack");
ZedProjectSettings zed = new ZedProjectSettings(pack);
zed.writeIrisSettings(biomeSchemas());
zed.writeIrisSettings(biomeSchemas(), List.of(BIOME_SCHEMA_TEXT));
Path file = zed.getSettingsFile();
String first = Files.readString(file, StandardCharsets.UTF_8);
FileTime stamp = FileTime.fromMillis(Files.getLastModifiedTime(file).toMillis() - 60_000L);
Files.setLastModifiedTime(file, stamp);
zed.writeIrisSettings(biomeSchemas());
zed.writeIrisSettings(biomeSchemas(), List.of(BIOME_SCHEMA_TEXT));
assertEquals(first, Files.readString(file, StandardCharsets.UTF_8));
assertEquals("Unchanged Zed settings must not be rewritten", stamp.toMillis(), Files.getLastModifiedTime(file).toMillis());
}
@Test
public void changedSchemaContentChangesTheSchemaHash() throws Exception {
ZedProjectSettings zed = new ZedProjectSettings(temporaryFolder.newFolder("pack"));
zed.writeIrisSettings(biomeSchemas(), List.of(BIOME_SCHEMA_TEXT));
String firstHash = schemaHashIn(readSettings(zed.getSettingsFile()));
zed.writeIrisSettings(biomeSchemas(), List.of(BIOME_SCHEMA_TEXT.replace("land/plains", "land/meadow")));
String secondHash = schemaHashIn(readSettings(zed.getSettingsFile()));
assertNotEquals("A regenerated schema must change Zed's JSON server configuration", firstHash, secondHash);
}
@Test
public void schemaHashIsAStableSixteenDigitHexOfTheTexts() throws Exception {
ZedProjectSettings zed = new ZedProjectSettings(temporaryFolder.newFolder("pack"));
zed.writeIrisSettings(biomeSchemas(), List.of("a", "b"));
String hash = schemaHashIn(readSettings(zed.getSettingsFile()));
zed.writeIrisSettings(biomeSchemas(), List.of("a", "b"));
assertTrue(hash.matches("[0-9a-f]{16}"));
assertEquals(hash, schemaHashIn(readSettings(zed.getSettingsFile())));
}
@Test
public void textBoundariesChangeTheSchemaHash() throws Exception {
ZedProjectSettings zed = new ZedProjectSettings(temporaryFolder.newFolder("pack"));
zed.writeIrisSettings(biomeSchemas(), List.of("ab", "c"));
String firstHash = schemaHashIn(readSettings(zed.getSettingsFile()));
zed.writeIrisSettings(biomeSchemas(), List.of("a", "bc"));
assertNotEquals(firstHash, schemaHashIn(readSettings(zed.getSettingsFile())));
}
private static String schemaHashIn(JsonObject settings) {
return settings.getAsJsonObject("lsp").getAsJsonObject("json-language-server")
.getAsJsonObject("settings").get("irisSchemaHash").getAsString();
}
private static JSONArray biomeSchemas() {
JSONObject entry = new JSONObject();
entry.put("fileMatch", new JSONArray(new Object[]{"/biomes/*.json", "/biomes/*/*.json"}));