Mirror pack schemas into Zed project settings

This commit is contained in:
piexel committed 2026-11-14 15:36:30 +01:00
1 parent 832070cd69
commit f0b7b14db7
4 files changed
+255

No files matched your search

@@ -228,6 +228,13 @@ public class IrisCodeWorkspace {
IrisLogging.warn("Could not update IntelliJ schema mappings for " + project.getPath().getAbsolutePath() + "; VSCode workspace generation will continue.");
}
try {
new ZedProjectSettings(project.getPath()).writeJsonSchemas(schemas);
} catch (Throwable e) {
IrisLogging.reportError(e);
IrisLogging.warn("Could not update Zed schema mappings for " + project.getPath().getAbsolutePath() + "; VSCode workspace generation will continue.");
}
return ws;
}
@@ -0,0 +1,115 @@
/*
* 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.spi.IrisLogging;
import art.arcane.volmlib.util.json.JSONArray;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import com.google.gson.Strictness;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
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 only {@code lsp.json-language-server.settings.json.schemas} is replaced.
*/
final class ZedProjectSettings {
private static final List<String> SCHEMAS_PARENT_PATH = List.of("lsp", "json-language-server", "settings", "json");
private static final String SCHEMAS_KEY = "schemas";
// Strict parsing rejects JSONC comments and trailing commas instead of silently dropping them on rewrite.
private static final Gson STRICT_GSON = new GsonBuilder()
.setStrictness(Strictness.STRICT)
.disableHtmlEscaping()
.setPrettyPrinting()
.create();
private final Path settingsFile;
ZedProjectSettings(File projectRoot) {
this.settingsFile = projectRoot.toPath().resolve(".zed").resolve("settings.json");
}
Path getSettingsFile() {
return settingsFile;
}
void writeJsonSchemas(JSONArray schemas) throws IOException {
String existing = Files.isRegularFile(settingsFile) ? Files.readString(settingsFile, StandardCharsets.UTF_8) : null;
JsonObject settings = parseOrNull(existing);
if (settings == null) {
IrisLogging.warn("Could not parse " + settingsFile + " as strict JSON (comments or trailing commas?); leaving it untouched.");
return;
}
JsonObject schemasParent = findOrCreateSchemasParent(settings);
if (schemasParent == null) {
IrisLogging.warn("Could not merge JSON schemas into " + settingsFile + ": an entry on the path " + String.join(".", SCHEMAS_PARENT_PATH) + " is not an object; leaving it untouched.");
return;
}
schemasParent.add(SCHEMAS_KEY, JsonParser.parseString(schemas.toString()));
writeIfChanged(STRICT_GSON.toJson(settings) + "\n", existing);
}
private static JsonObject parseOrNull(String existing) {
if (existing == null || existing.isBlank()) {
return new JsonObject();
}
try {
JsonElement parsed = STRICT_GSON.fromJson(existing, JsonElement.class);
return parsed != null && parsed.isJsonObject() ? parsed.getAsJsonObject() : null;
} catch (JsonParseException e) {
return null;
}
}
private static JsonObject findOrCreateSchemasParent(JsonObject settings) {
JsonObject current = settings;
for (String key : SCHEMAS_PARENT_PATH) {
JsonElement child = current.get(key);
if (child == null || child.isJsonNull()) {
child = new JsonObject();
current.add(key, child);
}
if (!child.isJsonObject()) {
return null;
}
current = child.getAsJsonObject();
}
return current;
}
private void writeIfChanged(String rendered, String existing) throws IOException {
if (rendered.equals(existing)) {
return;
}
Files.createDirectories(settingsFile.getParent());
Files.writeString(settingsFile, rendered, StandardCharsets.UTF_8);
}
}
@@ -138,6 +138,22 @@ public class IrisCodeWorkspaceTest {
Files.readString(unrelatedWorkspace.toPath(), StandardCharsets.UTF_8));
}
@Test
public void updateWorkspaceMirrorsSchemasIntoZedSettings() throws Exception {
File pack = temporaryFolder.newFolder("zed-pack");
IrisCodeWorkspace workspace = new IrisCodeWorkspace(new IrisProject(pack));
assertTrue(workspace.updateWorkspace());
data = IrisData.get(pack);
JSONArray workspaceSchemas = new JSONObject(Files.readString(workspace.getCodeWorkspaceFile().toPath(), StandardCharsets.UTF_8))
.getJSONObject("settings").getJSONArray("json.schemas");
JSONArray zedSchemas = new JSONObject(Files.readString(new File(pack, ".zed/settings.json").toPath(), StandardCharsets.UTF_8))
.getJSONObject("lsp").getJSONObject("json-language-server").getJSONObject("settings")
.getJSONObject("json").getJSONArray("schemas");
assertTrue("Zed settings must carry the workspace schemas", zedSchemas.similar(workspaceSchemas));
}
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,117 @@
package art.arcane.iris.studio.workspace;
import art.arcane.volmlib.util.json.JSONArray;
import art.arcane.volmlib.util.json.JSONObject;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
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 static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ZedProjectSettingsTest {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Test
public void createsSettingsFileWithSchemasWhenMissing() throws Exception {
File pack = temporaryFolder.newFolder("pack");
ZedProjectSettings zed = new ZedProjectSettings(pack);
zed.writeJsonSchemas(biomeSchemas());
assertTrue("Zed settings must be created", Files.isRegularFile(zed.getSettingsFile()));
assertEquals(JsonParser.parseString(biomeSchemas().toString()), schemasIn(readSettings(zed.getSettingsFile())));
}
@Test
public void mergeReplacesSchemasAndPreservesForeignKeys() throws Exception {
File pack = temporaryFolder.newFolder("pack");
ZedProjectSettings zed = new ZedProjectSettings(pack);
Files.createDirectories(zed.getSettingsFile().getParent());
Files.writeString(zed.getSettingsFile(), """
{
"tab_size": 2,
"lsp": {
"rust-analyzer": { "initialization_options": { "check": { "command": "clippy" } } },
"json-language-server": {
"binary": { "path": "/opt/json-ls" },
"settings": { "json": { "format": { "enable": true }, "schemas": [{ "fileMatch": ["/stale/*.json"], "url": "./stale.json" }] } }
}
}
}
""", StandardCharsets.UTF_8);
zed.writeJsonSchemas(biomeSchemas());
JsonObject settings = readSettings(zed.getSettingsFile());
JsonObject jsonServer = settings.getAsJsonObject("lsp").getAsJsonObject("json-language-server");
assertEquals(2, settings.get("tab_size").getAsInt());
assertEquals("clippy", settings.getAsJsonObject("lsp").getAsJsonObject("rust-analyzer")
.getAsJsonObject("initialization_options").getAsJsonObject("check").get("command").getAsString());
assertEquals("/opt/json-ls", jsonServer.getAsJsonObject("binary").get("path").getAsString());
assertTrue(jsonServer.getAsJsonObject("settings").getAsJsonObject("json").getAsJsonObject("format").get("enable").getAsBoolean());
assertEquals(JsonParser.parseString(biomeSchemas().toString()), schemasIn(settings));
}
@Test
public void unparseableSettingsFileIsLeftUntouched() throws Exception {
File pack = temporaryFolder.newFolder("pack");
ZedProjectSettings zed = new ZedProjectSettings(pack);
Files.createDirectories(zed.getSettingsFile().getParent());
String jsonc = """
// Folder-specific settings
{
"tab_size": 2,
}
""";
Files.writeString(zed.getSettingsFile(), jsonc, StandardCharsets.UTF_8);
zed.writeJsonSchemas(biomeSchemas());
assertEquals(jsonc, Files.readString(zed.getSettingsFile(), StandardCharsets.UTF_8));
}
@Test
public void unchangedSchemasDoNotRewriteTheFile() throws Exception {
File pack = temporaryFolder.newFolder("pack");
ZedProjectSettings zed = new ZedProjectSettings(pack);
zed.writeJsonSchemas(biomeSchemas());
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.writeJsonSchemas(biomeSchemas());
assertEquals(first, Files.readString(file, StandardCharsets.UTF_8));
assertEquals("Unchanged Zed settings must not be rewritten", stamp.toMillis(), Files.getLastModifiedTime(file).toMillis());
}
private static JSONArray biomeSchemas() {
JSONObject entry = new JSONObject();
entry.put("fileMatch", new JSONArray(new Object[]{"/biomes/*.json", "/biomes/*/*.json"}));
entry.put("url", "./.iris/schema/biomes-schema.json");
JSONArray schemas = new JSONArray();
schemas.put(entry);
return schemas;
}
private static JsonObject readSettings(Path file) throws Exception {
return JsonParser.parseString(Files.readString(file, StandardCharsets.UTF_8)).getAsJsonObject();
}
private static JsonElement schemasIn(JsonObject settings) {
return settings.getAsJsonObject("lsp").getAsJsonObject("json-language-server")
.getAsJsonObject("settings").getAsJsonObject("json").get("schemas");
}
}