Public: anyone can read this; the crew can change it.

A YAML value changed in the form is written over its own bytes #17720

opened this

Merged 10h 19m ago, live in production

sold/leaf-editor-1 → main 0 commits 5 threads · 5 unresolved

  • Merged. sold/leaf-editor-1 was merged into main as 423c8d4.

Review

Sign in to review this change.
5 files changed +320 −16
docs/features/config-form.md +19 −10
@@ -46,22 +46,31 @@ signed in. A private repository's file is a 404 to anyone who cannot read it.
4646 Both read into the same form as JSON and use the same schema lookup. The
4747 difference is the save: they are patched, not rewritten.
4848
49 - **YAML** goes through the `yaml` package's Document API. Comments, anchors,
50 quoting, key order and every line you did not change are written as they
51 were. A file you did not change is returned byte for byte. A file of several
52 documents (`---`) is one fieldset per document ("Document 1", …), and only
53 a document you changed is rewritten. An alias shows as the value it points
54 at; a change that only an alias holds is refused, with the reason, rather
55 than guessed. A key that is not text, or an alias that fans out to over
56 2,000 values, sends the file to its source view.
49 - **YAML**: a changed value is written over its own bytes, in its own quoting,
50 and every other byte of the file stays (`src/web/render/yaml-splice.ts`, in
51 the web form and the terminal's). Text that a YAML 1.1 reader, as many game
52 plugins have, would take for something else (`yes`, `22:22`, `010`) is
53 quoted. Some changes go through the `yaml` package's Document API instead:
54 adding or removing a key or an item, a block text (`|`, `>`) whose new words
55 do not fit its header, a value with an explicit tag (`!!str 5`), and an
56 empty value behind an anchor, in a flow collection or as a list item. That
outdated

Rewrap this paragraph; the line runs past the width of the rest of the file.

57 keeps comments, anchors, quoting and key order, but lays the document's
58 spacing out again. One such change takes the whole save that way, its plain
59 changes too. A file you did not change is returned byte for byte. A file of
60 several documents (`---`) is one fieldset per document ("Document 1", …),
61 and only a document you changed is rewritten. An alias shows as the value it
62 points at; a change that only an alias holds is refused, with the reason,
63 rather than guessed. A key that is not text, or an alias that fans out to
64 over 2,000 values, sends the file to its source view.
5765 - **TOML** goes through `@decimalturn/toml-patch`, which keeps comments and
5866 layout and rewrites only the values that differ. Dates and times show as the
5967 text they were written as. TOML has no null, so a form that would write one
6068 is refused. A table is a fieldset and an array of tables is a list of cards.
outdated

Rewrap this line to the file's width, and say it once more simply.

6169 - After either writes, the result is read back and must equal what the form
6270 held; if it does not, nothing is committed.
63 - One limit: YAML sequences are indented the way most of the file does it,
64 so a file that mixes both styles has its changed document re-indented.
71 - When a YAML document is laid out again, all its lists get one indent: the
72 one most of the file uses. A file that mixes two indents loses the rarer one
73 in that document.
6574
6675 ### The two vendored libraries
6776
src/web/render/vendor/yaml.d.mts +8
@@ -10,6 +10,10 @@ export interface Node {
1010 export interface Scalar extends Node {
1111 value: unknown;
1212 source?: string;
13 /** How it is written: PLAIN, QUOTE_DOUBLE, QUOTE_SINGLE, BLOCK_LITERAL or BLOCK_FOLDED. */
14 type?: string;
15 /** Its tag, when the file writes one (`!!str`). */
16 tag?: string;
1317 }
1418 export interface Pair {
1519 key: unknown;
@@ -17,9 +21,13 @@ export interface Pair {
1721 }
1822 export interface YAMLMap extends Node {
1923 items: Pair[];
24 /** Written in braces. */
25 flow?: boolean;
2026 }
2127 export interface YAMLSeq extends Node {
2228 items: unknown[];
29 /** Written in brackets. */
30 flow?: boolean;
2331 }
2432 export interface Alias extends Node {
2533 resolve(doc: Document): unknown;
src/web/render/yaml-config.ts +16 −6
@@ -1,8 +1,9 @@
11 /**
22 * YAML as the config form holds it (#7337): the `yaml` package's Document
3 * API reads it into a `Json`, and a save edits that same Document, so
4 * comments, anchors, quoting and key order survive and an untouched line is
5 * written byte for byte as it was.
3 * API reads it into a `Json`. A save that only changes values writes each over
4 * its own bytes (`yaml-splice.ts`), so the rest of the file stays as it was. A
5 * save that adds or removes something edits the Document and prints it: its
6 * comments, anchors, quoting and key order survive, its spacing may not.
67 *
78 * A file of several documents (`---`) reads as one object whose keys are
89 * "Document 1", "Document 2" …, so the form draws one fieldset each. An
@@ -13,7 +14,8 @@
1314 import { isAlias, isMap, isScalar, isSeq, parseAllDocuments, type Document } from "./vendor/yaml.mjs";
1415 import { editsBetween, plainOf, type Path } from "./config-diff.ts";
1516 import { MAX_FIELDS } from "./config-form.ts";
16 import type { Json, ParseError } from "./json-doc.ts";
17 import { sameDoc, type Json, type ParseError } from "./json-doc.ts";
18 import { spliceYaml, type DocEdit } from "./yaml-splice.ts";
1719
1820 export type YamlParsed =
1921 | { readonly ok: true; readonly value: Json }
@@ -220,6 +222,7 @@ export function writeYaml(original: string, before: Json, after: Json): YamlWrit
220222 const edits = editsBetween(before, after);
221223 if (edits.length === 0) return { ok: true, text: original };
222224 const changed = new Set<number>();
225 const own: DocEdit[] = [];
223226 try {
224227 for (const edit of edits) {
225228 let path: Path = edit.path;
@@ -230,10 +233,17 @@ export function writeYaml(original: string, before: Json, after: Json): YamlWrit
230233 if (!(index >= 0 && index < docs.length) || rest.length === 0) throw new Unsupported("a whole document");
231234 path = rest;
232235 } else if (path.length === 0) throw new Unsupported("the whole file");
233 const doc = docs[index]!;
236 own.push({ doc: docs[index]!, edit: { ...edit, path } });
237 changed.add(index);
238 }
239 const spliced = spliceYaml(original, own);
240 // A splice that does not read back as what was asked is dropped, never saved.
241 const back = spliced === undefined ? undefined : parseYaml(spliced);
242 if (spliced !== undefined && back?.ok === true && sameDoc(back.value, after)) return { ok: true, text: spliced };
243 for (const { doc, edit } of own) {
244 const { path } = edit;
234245 if (edit.op === "remove") doc.deleteIn(path);
235246 else doc.setIn(path, plainOf(edit.value));
236 changed.add(index);
237247 }
238248 } catch (e) {
239249 const why = e instanceof Unsupported ? e.message : "a value that comes from an alias or an unusual node";
src/web/render/yaml-splice.ts added +138
@@ -0,0 +1,138 @@
1 /**
2 * Changed YAML values written over their own bytes. The parser says where each value stands in the
3 * text, so a change replaces that range and nothing else: comments, spacing, blank lines, folding
4 * and line endings stay as their author wrote them. Printing the parsed document again keeps the
5 * values but lays the file out anew.
6 *
7 * Only a value put over a value is spliced. An added or removed key, a list that grew or shrank, a
8 * value behind an alias and a block text that needs another header are not: the answer is undefined
9 * and the caller writes the document as before.
10 */
11
12 import type { Edit, Path } from "./config-diff.ts";
13 import { plainOf } from "./config-diff.ts";
14 import { isMap, isScalar, isSeq, parseAllDocuments, type Document, type Scalar } from "./vendor/yaml.mjs";
15
16 /** One edit, in the document it belongs to (its path starts at that document's root). */
17 export interface DocEdit {
18 readonly doc: Document;
19 readonly edit: Edit;
20 }
21
22 /** Text a YAML 1.1 reader (SnakeYAML, in many game plugins) takes for something else when it is plain. */
23 const NOT_TEXT_IN_1_1 =
24 /^(?:y|n|yes|no|on|off|true|false|null|~|[-+]?(?:0b[01_]+|0x[\da-f_]+|0o[0-7_]+|[\d_]+(?::[0-5]?\d)+(?:\.[\d_]*)?|[\d_]*\.?[\d_]*(?:e[-+]?\d+)?|\.(?:inf|nan))|\d{4}-\d\d?-\d\d?.*)$/i;
25
26 /** Characters that are never written as they are: control characters, line separators, a byte order mark. */
27 const UNPRINTABLE = /[\x00-\x1f\x7f-\x9f\u2028\u2029\ufeff]/;
28 const quoted = (v: string): string =>
29 JSON.stringify(v).replace(/[\x7f-\x9f\u2028\u2029\ufeff]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
30
31 /** The scalar node at `path` and the end of its key, walked through the document's own maps and lists; an alias ends the walk. */
32 function scalarAt(doc: Document, path: Path): { node: Scalar; flow: boolean; keyEnd: number | undefined } | undefined {
33 let at: unknown = doc.contents;
34 let keyEnd: number | undefined;
35 let flow = false;
36 for (const key of path) {
37 if (isMap(at)) {
38 flow ||= at.flow === true;
39 const pair = at.items.find((p) => isScalar(p.key) && p.key.value === key);
40 keyEnd = isScalar(pair?.key) ? pair.key.range?.[1] : undefined;
41 at = pair?.value;
42 } else if (isSeq(at) && typeof key === "number") {
43 flow ||= at.flow === true;
44 keyEnd = undefined;
45 at = at.items[key];
46 } else return undefined;
47 }
48 return isScalar(at) && at.tag === undefined ? { node: at, flow, keyEnd } : undefined;
49 }
50
51 /** The longest text tried without quotes: the patterns and the parser below see no more than this. */
52 const MAX_PLAIN = 1_000;
53
54 /** Whether `v`, unquoted on one line here, is read back as exactly that text. */
55 function isPlain(v: string, flow: boolean): boolean {
56 if (v.length > MAX_PLAIN || NOT_TEXT_IN_1_1.test(v) || UNPRINTABLE.test(v)) return false;
57 if (/^[[{]/.test(v) || (flow && /[[\]{},]/.test(v))) return false;
58 const [doc] = parseAllDocuments(flow ? `[${v}]` : `k: ${v}`);
59 if (doc === undefined || doc.errors.length > 0) return false;
60 const node = doc.getIn([flow ? 0 : "k"], true);
61 return isScalar(node) && node.type === "PLAIN" && node.value === v;
62 }
63
64 const HEADER = /^([|>])([-+]?)([ \t]*(?:#[^\r\n]*)?\r?\n)/;
65 const unended = (line: string): string => line.replace(/\r?\n$/, "");
66
67 /**
68 * A block text (`|`, or `>` of one paragraph) saying `v`: its header and its untouched lines as they
69 * were. Undefined when `v` does not fit the header (`+`, an indent digit, text led by a space).
70 */
71 function blockOf(source: string, v: string, eol: string): string | undefined {
72 const head = HEADER.exec(source);
73 if (head === null || head[2] === "+") return undefined;
74 const ends = v.endsWith("\n");
75 const text = ends ? v.slice(0, -1) : v;
76 if (/^\s|\n$|\r/.test(text) || text.trim() === "") return undefined;
77 const body = source.slice(head[0].length);
78 const was = body.match(/[^\n]*\n|[^\n]+$/g) ?? [];
79 // Blank lines after the text belong to the file's layout, not to the text.
80 let tail = "";
81 while (was.length > 0 && was[was.length - 1]!.trim() === "") tail = was.pop()! + tail;
82 const indent = /^ */.exec(was.find((l) => l.trim() !== "") ?? "")![0];
83 if (indent === "") return undefined;
84 const header = head[1]! + (ends ? "" : "-") + head[3]!;
85 const line = (l: string): string => (l === "" ? "" : indent + l) + eol;
86 const closed = (s: string): string => (/\n$/.test(body) ? s : unended(s)) + tail;
87 if (head[1] === ">") return text.includes("\n") ? undefined : header + closed(line(text));
88 const now = text.split("\n");
89 const said = was.map((l) => unended(l).slice(indent.length));
90 let top = 0;
91 while (top < now.length && top < said.length && now[top] === said[top]) top++;
92 let foot = 0;
93 while (foot < now.length - top && foot < said.length - top && now[now.length - 1 - foot] === said[said.length - 1 - foot]) foot++;
94 const kept = (l: string): string => (/\n$/.test(l) ? l : l + eol);
95 return (
96 header +
97 closed([...was.slice(0, top).map(kept), ...now.slice(top, now.length - foot).map(line), ...was.slice(was.length - foot).map(kept)].join(""))
98 );
99 }
100
101 /** What stands in the text for `value` where `source` stood, in the same quoting. */
102 function written(node: Scalar, source: string, value: unknown, flow: boolean, eol: string): string | undefined {
103 if (node.type === "BLOCK_LITERAL" || node.type === "BLOCK_FOLDED") return typeof value === "string" ? blockOf(source, value, eol) : undefined;
104 if (typeof value !== "string") return String(value);
105 if (node.type === "QUOTE_SINGLE" && !UNPRINTABLE.test(value)) return `'${value.replace(/'/g, "''")}'`;
106 return node.type === "PLAIN" && isPlain(value, flow) ? value : quoted(value);
107 }
108
109 /** `original` with every edit written over its value's bytes, or undefined when one has none of its own. */
110 export function spliceYaml(original: string, edits: readonly DocEdit[]): string | undefined {
111 const eol = original.includes("\r\n") ? "\r\n" : "\n";
112 const cuts: { from: number; to: number; text: string }[] = [];
113 for (const { doc, edit } of edits) {
114 if (edit.op !== "set" || edit.value.t === "object" || edit.value.t === "array") return undefined;
115 const found = scalarAt(doc, edit.path);
116 const range = found?.node.range;
117 if (found === undefined || range === null || range === undefined) return undefined;
118 const [from, to] = range;
119 const text = written(found.node, original.slice(from, to), plainOf(edit.value), found.flow, eol);
120 if (text === undefined) return undefined;
121 if (from < to) cuts.push({ from, to, text });
122 else {
123 // `key:` with nothing after it but a comment: the value goes one space after the colon.
124 const { keyEnd } = found;
125 const colon = found.flow || keyEnd === undefined ? null : /^[ \t]*:(?=(?:[ \t\r]*(?:#[^\n]*)?\n)*[ \t\r]*(?:#[^\n]*)?$)/.exec(original.slice(keyEnd, from));
126 if (keyEnd === undefined || colon === null) return undefined;
127 cuts.push({ from: keyEnd + colon[0].length, to: keyEnd + colon[0].length, text: ` ${text}` });
128 }
129 }
130 cuts.sort((a, b) => a.from - b.from);
131 let out = "";
132 let at = 0;
133 for (const c of cuts) {
134 out += original.slice(at, c.from) + c.text;
135 at = c.to;
136 }
137 return out + original.slice(at);
138 }
test/yaml-splice.test.ts added +139
@@ -0,0 +1,139 @@
1 /**
2 * A changed YAML value is written over its own bytes: every other byte of the file, its comments,
3 * spacing and line endings, stays as its author wrote it.
4 */
5
6 import { describe, expect, test } from "bun:test";
7 import { settleConfig } from "../src/web/render/config-save.ts";
8 import { parseConfig, writeConfig } from "../src/web/render/config-format.ts";
9 import { updateAt, type Json } from "../src/web/render/json-doc.ts";
10
11 const read = (text: string): Json => {
12 const p = parseConfig("a.yml", text);
13 if (!p.ok) throw new Error(p.error.message);
14 return p.value;
15 };
16
17 /** `text` with the values at these pointers changed, saved as the form saves it. */
18 function save(text: string, changes: Readonly<Record<string, string | number | boolean | null>>): string {
19 const before = read(text);
20 let after = before;
21 for (const [at, v] of Object.entries(changes)) {
22 const to: Json = v === null ? { t: "null" } : typeof v === "string" ? { t: "string", v } : typeof v === "number" ? { t: "number", v: String(v) } : { t: "boolean", v };
23 after = updateAt(after, at, () => to);
24 }
25 const s = settleConfig("a.yml", text, before, after);
26 if (s.kind !== "text") throw new Error(s.kind === "refused" ? s.message : s.kind);
27 return s.after;
28 }
29
30 const COMPOSE = `# top
31
32 services:
33 mc: # the server
34 image: "example/server" # pinned
35 ports: [ "25565:25565", '1:1' ]
36
37
38 environment:
39 MOTD: hi
40 A: "x"
41 LIST:
42 - a
43 - b
44 DEEP:
45 - c
46 long: >-
47 one two
48 three
49 text: | # kept
50 first
51
52 last
53
54 empty: # nothing yet
55 base: &base
56 retries: 3
57 child:
58 <<: *base
59 `;
60
61 describe("a changed value changes its own bytes and no others", () => {
62 const at = "/services/mc/environment";
63 const cases: readonly [string, string, string, string, string][] = [
64 ["double quoted", `${at}/A`, 'y "z"', 'A: "x"', 'A: "y \\"z\\""'],
65 ["plain, aligned", `${at}/MOTD`, "hello there", "MOTD: hi", "MOTD: hello there"],
66 ["single quoted, in a flow list", "/services/mc/ports/1", "2'2", "'1:1'", "'2''2'"],
67 ["with a comment after it", "/services/mc/image", "example/other", '"example/server" #', '"example/other" #'],
68 ["a list item", `${at}/LIST/1`, "c", "- b", "- c"],
69 ["folded text, one paragraph", `${at}/long`, "one two four", "one two\n three", "one two four"],
70 ["one line of a block", `${at}/text`, "first\n\nnext\n", " last\n", " next\n"],
71 ["a block that loses its last line end", `${at}/text`, "first\n\nlast", "text: | # kept", "text: |- # kept"],
72 ["an empty value", "/services/mc/empty", "now", "empty: #", "empty: now #"],
73 ];
74 for (const eol of ["\n", "\r\n"])
75 for (const [name, where, to, from, into] of cases)
76 test(`${name} (${eol === "\n" ? "LF" : "CRLF"})`, () => {
77 const crlf = (s: string): string => s.replace(/\n/g, eol);
78 expect(save(crlf(COMPOSE), { [where]: to })).toBe(crlf(COMPOSE.replace(from, () => into)));
79 });
80
81 test("several values at once", () => {
82 const out = save(COMPOSE, { "/services/mc/image": "z", [`${at}/A`]: "", [`${at}/LIST/0`]: "longer than it was" });
83 expect(out).toBe(COMPOSE.replace('"example/server"', '"z"').replace('A: "x"', 'A: ""').replace("- a\n", "- longer than it was\n"));
84 });
85
86 test("a byte order mark, no last line end, and a second document stay", () => {
87 expect(save("a: 1 # x\nb: 2", { "/a": 10 })).toBe("a: 10 # x\nb: 2");
88 const two = "a: 1 # x\n---\nb: [ 1, 2 ] # y\nc: 'q'\n";
89 expect(save(two, { "/Document 2/b/1": 3 })).toBe("a: 1 # x\n---\nb: [ 1, 3 ] # y\nc: 'q'\n");
90 });
91 });
92
93 describe("a plain value stays plain only where every reader takes it as text", () => {
94 // SnakeYAML (a game plugin's) reads YAML 1.1: yes is true there, 22:22 is 1342, 010 is 8.
95 for (const v of ["yes", "Off", "n", "22:22", "010", "0x1f", "1_000", "1e3", ".5", "2026-12-02", "~", "null", "true", "", " pad ", "a: b", "a #b", "- a", "*a", "@x", "a\nb", "\u0007"])
96 test(JSON.stringify(v), () => {
97 expect(save("k: word # c\nz: 1\n", { "/k": v })).toBe(`k: ${JSON.stringify(v)} # c\nz: 1\n`);
98 });
99 for (const v of ["1.21.6", "25565:25565", "http://x/y#z", "a b", "ünï", "it's"])
100 test(v, () => {
101 expect(save("k: word # c\nz: 1\n", { "/k": v })).toBe(`k: ${v} # c\nz: 1\n`);
102 });
103 test("in a flow collection a comma or bracket is quoted", () => {
104 expect(save("k: [ a, b ] # c\n", { "/k/0": "x, y" })).toBe('k: [ "x, y", b ] # c\n');
105 expect(save("k: { a: b, c: d }\n", { "/k/a": "x]" })).toBe('k: { a: "x]", c: d }\n');
106 });
107 });
108
109 describe("what has no bytes of its own to write over", () => {
110 test("a value only an alias holds is still refused", () => {
111 const before = read(COMPOSE);
112 const after = updateAt(before, "/child/<</retries", () => ({ t: "number", v: "9" }));
113 expect(writeConfig("a.yml", COMPOSE, before, after).ok).toBe(false);
114 });
115
116 test("an added key is still written, by the document", () => {
117 const before = read("a: 1 # x\n");
118 const after = updateAt(before, "", (v) => (v.t === "object" ? { t: "object", entries: [...v.entries, ["b", { t: "number", v: "2" }]] } : v));
119 expect(writeConfig("a.yml", "a: 1 # x\n", before, after)).toEqual({ ok: true, text: "a: 1 # x\nb: 2\n" });
120 });
121
122 test("an empty value behind an anchor, and a hostile comment run, cost nothing and break nothing", () => {
123 const text = `a: ${"# ".repeat(5_000)}\n &x\nc: w\n`;
124 expect(read(save(text, { "/a": "v" }))).toEqual(updateAt(read(text), "/a", () => ({ t: "string", v: "v" })));
125 expect(save(text, { "/c": "9".repeat(20_000) })).toBe(text.replace("c: w", `c: "${"9".repeat(20_000)}"`));
126 expect(save("k: w\n", { "/k": "[".repeat(900) })).toBe(`k: "${"[".repeat(900)}"\n`);
127 });
128
129 test("a block whose new text needs another header is written whole or refused, never wrong", () => {
130 const at = "/services/mc/environment/text";
131 const before = read(COMPOSE);
132 for (const v of [" led by spaces\n", "two ends\n\n", ""]) {
133 const after = updateAt(before, at, () => ({ t: "string", v }));
134 const s = settleConfig("a.yml", COMPOSE, before, after);
135 if (s.kind === "text") expect(read(s.after)).toEqual(after);
136 else expect(s.kind).toBe("refused");
137 }
138 });
139 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs