Accept JSONC comments in pack files and editors

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

No files matched your search

@@ -25,6 +25,7 @@ import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.Strictness;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
@@ -954,6 +955,7 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
File f = new File(getDataFolder(), r + ".json");
if (f.exists()) {
try (JsonReader snippetReader = new JsonReader(new FileReader(f))){
snippetReader.setStrictness(Strictness.LENIENT);
return adapter.read(snippetReader);
} catch (IrisEngineStreamType.UnknownStreamException unknownStream) {
throw unknownStream;
@@ -168,6 +168,9 @@ public class IrisCodeWorkspace {
jc.put("editor.suggest.insertMode", "replace");
settings.put("[json]", jc);
settings.put("json.maxItemsComputed", 30000);
JSONObject associations = new JSONObject();
associations.put("*.json", "jsonc");
settings.put("files.associations", associations);
JSONArray schemas = new JSONArray();
List<JSONObject> schemaEntries = new ArrayList<>();
IrisData dm = IrisData.get(project.getPath());
@@ -229,7 +232,7 @@ public class IrisCodeWorkspace {
}
try {
new ZedProjectSettings(project.getPath()).writeJsonSchemas(schemas);
new ZedProjectSettings(project.getPath()).writeIrisSettings(schemas);
} catch (Throwable e) {
IrisLogging.reportError(e);
IrisLogging.warn("Could not update Zed schema mappings for " + project.getPath().getAbsolutePath() + "; VSCode workspace generation will continue.");
@@ -22,10 +22,12 @@ 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.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.google.gson.Strictness;
import java.io.File;
@@ -37,11 +39,16 @@ 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.
* 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}.
*/
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";
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";
private static final String JSON_EXTENSION = "json";
// 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)
@@ -59,7 +66,7 @@ final class ZedProjectSettings {
return settingsFile;
}
void writeJsonSchemas(JSONArray schemas) throws IOException {
void writeIrisSettings(JSONArray schemas) throws IOException {
String existing = Files.isRegularFile(settingsFile) ? Files.readString(settingsFile, StandardCharsets.UTF_8) : null;
JsonObject settings = parseOrNull(existing);
if (settings == null) {
@@ -67,13 +74,12 @@ final class ZedProjectSettings {
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.");
if (!mergeSchemas(settings, schemas) || !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;
}
schemasParent.add(SCHEMAS_KEY, JsonParser.parseString(schemas.toString()));
writeIfChanged(STRICT_GSON.toJson(settings) + "\n", existing);
}
@@ -89,9 +95,38 @@ final class ZedProjectSettings {
}
}
private static JsonObject findOrCreateSchemasParent(JsonObject settings) {
private static boolean mergeSchemas(JsonObject settings, JSONArray schemas) {
JsonObject schemasParent = findOrCreateObject(settings, SCHEMAS_PARENT_PATH);
if (schemasParent == null) {
return false;
}
schemasParent.add(SCHEMAS_KEY, JsonParser.parseString(schemas.toString()));
return true;
}
private static boolean mergeJsoncFileType(JsonObject settings) {
JsonObject fileTypes = findOrCreateObject(settings, FILE_TYPES_PATH);
if (fileTypes == null) {
return false;
}
JsonElement jsoncGlobs = fileTypes.get(JSONC_LANGUAGE);
if (jsoncGlobs == null || jsoncGlobs.isJsonNull()) {
jsoncGlobs = new JsonArray();
fileTypes.add(JSONC_LANGUAGE, jsoncGlobs);
}
if (!jsoncGlobs.isJsonArray()) {
return false;
}
JsonPrimitive jsonExtension = new JsonPrimitive(JSON_EXTENSION);
if (!jsoncGlobs.getAsJsonArray().contains(jsonExtension)) {
jsoncGlobs.getAsJsonArray().add(jsonExtension);
}
return true;
}
private static JsonObject findOrCreateObject(JsonObject settings, List<String> path) {
JsonObject current = settings;
for (String key : SCHEMAS_PARENT_PATH) {
for (String key : path) {
JsonElement child = current.get(key);
if (child == null || child.isJsonNull()) {
child = new JsonObject();
@@ -0,0 +1,123 @@
package art.arcane.iris.pack.loading;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.biome.IrisBiomeGeneratorLink;
import art.arcane.iris.generation.runtime.MeteredCache;
import art.arcane.iris.generation.runtime.PreservationRegistry;
import art.arcane.iris.spi.IrisPlatform;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.spi.IrisServices;
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.nio.file.Path;
import java.util.concurrent.ExecutorService;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class CommentedPackJsonTest {
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
private IrisPlatform previousPlatform;
private IrisSettings previousSettings;
private IrisData data;
@Before
public void bindPlatform() {
previousPlatform = IrisPlatforms.isBound() ? IrisPlatforms.get() : null;
previousSettings = IrisSettings.settings;
IrisPlatforms.unbind();
IrisPlatform platform = mock(IrisPlatform.class, Answers.CALLS_REAL_METHODS);
PlatformRegistries registries = mock(PlatformRegistries.class);
when(platform.dataFolder()).thenReturn(temporaryFolder.getRoot());
when(platform.registries()).thenReturn(registries);
IrisPlatforms.bind(platform);
IrisSettings.settings = new IrisSettings();
IrisServices.register(PreservationRegistry.class, new NoOpPreservationRegistry());
}
@After
public void restorePlatform() {
if (data != null) {
data.close();
data = null;
}
IrisServices.remove(PreservationRegistry.class);
IrisPlatforms.unbind();
if (previousPlatform != null) {
IrisPlatforms.bind(previousPlatform);
}
IrisSettings.settings = previousSettings;
}
@Test
public void biomeAndReferencedSnippetWithJsoncCommentsLoad() throws Exception {
File pack = temporaryFolder.newFolder("commented-pack");
write(pack.toPath().resolve("biomes/commented.json"), """
// Biome authored with JSONC comments
{
/* shown in studio */
"name": "Commented Biome", // trailing note
"generators": ["snippet/generator-layer/commented-flat"]
}
""");
write(pack.toPath().resolve("snippet/generator-layer/commented-flat.json"), """
{
// snippet note
"generator": "flat",
"min": 2, /* inline */ "max": 5
}
""");
data = IrisData.get(pack);
IrisBiome biome = data.getBiomeLoader().load("commented");
assertNotNull("A biome with comments must load", biome);
assertEquals("Commented Biome", biome.getName());
IrisBiomeGeneratorLink link = biome.getGenerators().get(0);
assertEquals("flat", link.getGenerator());
assertEquals(2, link.getMin());
assertEquals(5, link.getMax());
}
private static void write(Path file, String content) throws Exception {
Files.createDirectories(file.getParent());
Files.writeString(file, content, StandardCharsets.UTF_8);
}
private static final class NoOpPreservationRegistry implements PreservationRegistry {
@Override
public void register(Thread thread) {
}
@Override
public void register(ExecutorService service) {
}
@Override
public void registerCache(MeteredCache cache) {
}
@Override
public void dereference() {
}
}
}
@@ -154,6 +154,15 @@ public class IrisCodeWorkspaceTest {
assertTrue("Zed settings must carry the workspace schemas", zedSchemas.similar(workspaceSchemas));
}
@Test
public void workspaceOpensPackJsonAsJsoncSoCommentsAreNotFlagged() throws Exception {
File pack = temporaryFolder.newFolder("jsonc-pack");
JSONObject configuration = new IrisCodeWorkspace(new IrisProject(pack)).createCodeWorkspaceConfig();
data = IrisData.get(pack);
assertEquals("jsonc", configuration.getJSONObject("settings").getJSONObject("files.associations").getString("*.json"));
}
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");
@@ -27,10 +27,12 @@ public class ZedProjectSettingsTest {
File pack = temporaryFolder.newFolder("pack");
ZedProjectSettings zed = new ZedProjectSettings(pack);
zed.writeJsonSchemas(biomeSchemas());
zed.writeIrisSettings(biomeSchemas());
assertTrue("Zed settings must be created", Files.isRegularFile(zed.getSettingsFile()));
assertEquals(JsonParser.parseString(biomeSchemas().toString()), schemasIn(readSettings(zed.getSettingsFile())));
JsonObject settings = readSettings(zed.getSettingsFile());
assertEquals(JsonParser.parseString(biomeSchemas().toString()), schemasIn(settings));
assertEquals(JsonParser.parseString("[\"json\"]"), jsoncGlobsIn(settings));
}
@Test
@@ -41,6 +43,7 @@ public class ZedProjectSettingsTest {
Files.writeString(zed.getSettingsFile(), """
{
"tab_size": 2,
"file_types": { "JSONC": ["*.jsonc5"], "Rust": ["rs.in"] },
"lsp": {
"rust-analyzer": { "initialization_options": { "check": { "command": "clippy" } } },
"json-language-server": {
@@ -51,9 +54,11 @@ public class ZedProjectSettingsTest {
}
""", StandardCharsets.UTF_8);
zed.writeJsonSchemas(biomeSchemas());
zed.writeIrisSettings(biomeSchemas());
JsonObject settings = readSettings(zed.getSettingsFile());
assertEquals(JsonParser.parseString("[\"*.jsonc5\", \"json\"]"), jsoncGlobsIn(settings));
assertEquals("rs.in", settings.getAsJsonObject("file_types").getAsJsonArray("Rust").get(0).getAsString());
JsonObject jsonServer = settings.getAsJsonObject("lsp").getAsJsonObject("json-language-server");
assertEquals(2, settings.get("tab_size").getAsInt());
assertEquals("clippy", settings.getAsJsonObject("lsp").getAsJsonObject("rust-analyzer")
@@ -76,7 +81,7 @@ public class ZedProjectSettingsTest {
""";
Files.writeString(zed.getSettingsFile(), jsonc, StandardCharsets.UTF_8);
zed.writeJsonSchemas(biomeSchemas());
zed.writeIrisSettings(biomeSchemas());
assertEquals(jsonc, Files.readString(zed.getSettingsFile(), StandardCharsets.UTF_8));
}
@@ -85,13 +90,13 @@ public class ZedProjectSettingsTest {
public void unchangedSchemasDoNotRewriteTheFile() throws Exception {
File pack = temporaryFolder.newFolder("pack");
ZedProjectSettings zed = new ZedProjectSettings(pack);
zed.writeJsonSchemas(biomeSchemas());
zed.writeIrisSettings(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());
zed.writeIrisSettings(biomeSchemas());
assertEquals(first, Files.readString(file, StandardCharsets.UTF_8));
assertEquals("Unchanged Zed settings must not be rewritten", stamp.toMillis(), Files.getLastModifiedTime(file).toMillis());
@@ -110,6 +115,10 @@ public class ZedProjectSettingsTest {
return JsonParser.parseString(Files.readString(file, StandardCharsets.UTF_8)).getAsJsonObject();
}
private static JsonElement jsoncGlobsIn(JsonObject settings) {
return settings.getAsJsonObject("file_types").get("JSONC");
}
private static JsonElement schemasIn(JsonObject settings) {
return settings.getAsJsonObject("lsp").getAsJsonObject("json-language-server")
.getAsJsonObject("settings").getAsJsonObject("json").get("schemas");