fix(toml): various edge case fixes for toml.stringify (#3403)

This commit is contained in:
Un Known 2023-05-30 19:51:04 -04:00 committed by GitHub
parent 6ab64b1907
commit 3458e6b20a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 57 additions and 5 deletions

View File

@ -8,7 +8,9 @@ function joinKeys(keys: string[]): string {
// This allows for grouping similar properties together:
return keys
.map((str: string): string => {
return str.match(/[^A-Za-z0-9_-]/) ? JSON.stringify(str) : str;
return str.length === 0 || str.match(/[^A-Za-z0-9_-]/)
? JSON.stringify(str)
: str;
})
.join(".");
}
@ -145,8 +147,9 @@ class Dumper {
throw new Error("should never reach");
}
const str = Object.keys(value).map((key) => {
// deno-lint-ignore no-explicit-any
return `${key} = ${this.#printAsInlineValue((value as any)[key])}`;
return `${joinKeys([key])} = ${
// deno-lint-ignore no-explicit-any
this.#printAsInlineValue((value as any)[key])}`;
}).join(",");
return `{${str}}`;
}
@ -221,8 +224,11 @@ class Dumper {
const l = this.output[i];
// we keep empty entry for array of objects
if (l[0] === "[" && l[1] !== "[") {
// empty object
if (this.output[i + 1] === "") {
// non-empty object with only subobjects as properties
if (
this.output[i + 1] === "" &&
this.output[i + 2]?.slice(0, l.length) === l.slice(0, -1) + "."
) {
i += 1;
continue;
}

View File

@ -711,3 +711,49 @@ aaaaa = 1
assertEquals(actual, expected);
},
});
Deno.test({
name: "[TOML] stringify empty key",
fn() {
const src = {
"": "a",
"b": { "": "c" },
};
const actual = stringify(src);
const expected = `"" = "a"
[b]
"" = "c"
`;
assertEquals(actual, expected);
},
});
Deno.test({
name: "[TOML] stringify empty object",
fn() {
const src = {
"a": {},
"b": { "c": {} },
};
const actual = stringify(src);
const expected = `
[a]
[b.c]
`;
assertEquals(actual, expected);
},
});
Deno.test({
name: "[TOML] stringify special keys in inline object",
fn() {
const src = {
"a": [{ "/": "b" }, "c"],
};
const actual = stringify(src);
const expected = 'a = [{"/" = "b"},"c"]\n';
assertEquals(actual, expected);
},
});