edit: validate nested YAML input and output (#591)

Reject duplicate keys and multiple documents instead of silently editing
them. Validate rendered output before writing so edits cannot leave
dangling aliases or introduce duplicate keys. Errors leave files untouched.
Apply the same validation to YAMLText.

JSONToYAML now rejects duplicate keys without creating or replacing the
target, including omp's models.json conversion. Treat a document containing
only --- as empty, matching the top-level YAML editor.

Add regression tests for document loss, dangling aliases and duplicate
keys, alongside existing-behavior coverage for malformed input.
This commit is contained in:
Zhizhen He
2026-10-03 01:15:14 +08:00
committed by GitHub
parent 8efd7d8027
commit 6d7bd11d07
4 changed files with 447 additions and 48 deletions
+99 -15
View File
@@ -3,6 +3,7 @@ package edit
import (
"bytes"
"fmt"
"io"
"strings"
"github.com/tidwall/jsonc"
@@ -87,27 +88,33 @@ func GetYAMLText(path, keyPath string) (string, bool) {
type YAMLText string
// EditYAMLTextStrings is EditYAMLStrings on YAML text (a YAMLText) rather
// than a file: fn's answers in place of every string in it.
// than a file: fn's answers in place of every string in it. Invalid input
// or output returns the original text and an error.
func EditYAMLTextStrings(text YAMLText, fn func(string) string) (YAMLText, error) {
var doc yaml.Node
if err := yaml.Unmarshal([]byte(text), &doc); err != nil || len(doc.Content) == 0 {
root, err := parseYAMLDocument([]byte(text))
if err != nil || root == nil {
return text, err
}
if !mapStrings(doc.Content[0], fn) {
if !mapStrings(root, fn) {
return text, nil
}
b, err := yaml.Marshal(doc.Content[0])
b, err := yaml.Marshal(root)
if err != nil {
return text, err
}
if _, err := parseYAMLDocument(b); err != nil {
return text, err
}
return YAMLText(strings.TrimSuffix(string(b), "\n")), nil
}
// SetYAML sets key paths in a YAML file; a value may be a scalar, a map,
// a slice, a struct with yaml tags or YAMLText. Missing files and parents
// are created.
// are created. Only the first mapping document can be edited, with empty or
// null trailing documents allowed; invalid input or output leaves the file
// untouched.
func SetYAML(path string, kvs ...KV) error {
root, err := loadYAML(path)
root, err := loadYAMLForEdit(path)
if err != nil {
return err
}
@@ -117,11 +124,14 @@ func SetYAML(path string, kvs ...KV) error {
for _, kv := range kvs {
var v yaml.Node
if t, ok := kv.Value.(YAMLText); ok {
var doc yaml.Node
if err := yaml.Unmarshal([]byte(t), &doc); err != nil || len(doc.Content) == 0 {
n, err := parseYAMLDocument([]byte(t))
if err != nil {
return fmt.Errorf("%s: %s: %w", path, kv.Path, err)
}
if n == nil {
return fmt.Errorf("%s: %s: not YAML: %q", path, kv.Path, string(t))
}
v = *doc.Content[0]
v = *n
} else if err := v.Encode(kv.Value); err != nil {
return fmt.Errorf("%s: %w", path, err)
}
@@ -132,7 +142,7 @@ func SetYAML(path string, kvs ...KV) error {
// DelYAML removes key paths from a YAML file. A missing file stays missing.
func DelYAML(path string, keyPaths ...string) error {
root, err := loadYAML(path)
root, err := loadYAMLForEdit(path)
if err != nil || root == nil {
return err
}
@@ -166,7 +176,7 @@ func DelYAML(path string, keyPaths ...string) error {
// its place, comments and quoting kept. The file is written only when an
// answer differs, so an fn that answers what it is given only reads.
func EditYAMLStrings(path string, keyPaths []string, fn func(string) string) error {
root, err := loadYAML(path)
root, err := loadYAMLForEdit(path)
if err != nil || root == nil {
return err
}
@@ -219,7 +229,9 @@ func JSONToYAML(src, dst string) error {
return writeYAML(dst, root)
}
// loadYAML returns the top-level mapping, or nil for a missing or empty file.
// loadYAML reads the first document's mapping without decoding its values.
// Unrelated duplicate keys, complex keys or invalid tags must not hide a
// readable model setting. Writers use loadYAMLForEdit to validate the whole file.
func loadYAML(path string) (*yaml.Node, error) {
raw, err := Read(path)
if err != nil || len(bytes.TrimSpace(raw)) == 0 {
@@ -236,13 +248,80 @@ func loadYAML(path string) (*yaml.Node, error) {
if root.Kind != yaml.MappingNode {
return nil, fmt.Errorf("%s: top level is not a YAML mapping", path)
}
// comments above the first key belong to the document
if doc.HeadComment != "" && root.HeadComment == "" {
root.HeadComment = doc.HeadComment
}
return root, nil
}
// loadYAMLForEdit validates input even when the requested key is unchanged
// or missing.
func loadYAMLForEdit(path string) (*yaml.Node, error) {
raw, err := Read(path)
if err != nil {
return nil, err
}
root, _, err := parseYAMLTop(raw)
if err != nil {
return nil, fmt.Errorf("%s: %w", path, err)
}
return root, nil
}
// parseYAMLDocument validates the first document and any empty/null trailing ones.
func parseYAMLDocument(raw []byte) (*yaml.Node, error) {
root, _, err := parseYAMLDocuments(raw)
return root, err
}
// Decode as well as parse: yaml.Node alone accepts duplicate mapping keys.
// Only empty or null trailing documents can be discarded safely. nextLine
// bounds the first document for line edits; it is zero when no other follows.
func parseYAMLDocuments(raw []byte) (root *yaml.Node, nextLine int, err error) {
dec := yaml.NewDecoder(bytes.NewReader(raw))
var doc yaml.Node
if err := dec.Decode(&doc); err == io.EOF {
return nil, 0, nil
} else if err != nil {
return nil, 0, err
}
for {
var extra yaml.Node
if err := dec.Decode(&extra); err == io.EOF {
break
} else if err != nil {
return nil, 0, err
}
if nextLine == 0 {
nextLine = extra.Line
}
if len(extra.Content) == 0 {
continue
}
n := extra.Content[0]
if n.Kind != yaml.ScalarNode || n.ShortTag() != "!!null" {
return nil, 0, fmt.Errorf("expected a single YAML document")
}
var null any
if err := n.Decode(&null); err != nil {
return nil, 0, err
}
}
if len(doc.Content) == 0 {
return nil, nextLine, nil
}
root = doc.Content[0]
var decoded any
if err := root.Decode(&decoded); err != nil {
return nil, 0, err
}
// comments above the first key belong to the document
if doc.HeadComment != "" && root.HeadComment == "" {
root.HeadComment = doc.HeadComment
}
return root, nextLine, nil
}
func writeYAML(path string, root *yaml.Node) error {
var buf bytes.Buffer
enc := yaml.NewEncoder(&buf)
@@ -251,7 +330,12 @@ func writeYAML(path string, root *yaml.Node) error {
return fmt.Errorf("%s: %w", path, err)
}
if err := enc.Close(); err != nil {
return err
return fmt.Errorf("%s: %w", path, err)
}
// Reparse the rendered text: replacing or removing a node can leave a
// dangling alias even though the original node tree was valid.
if _, err := parseYAMLDocument(buf.Bytes()); err != nil {
return fmt.Errorf("%s: %w", path, err)
}
return WriteAtomic(path, buf.Bytes())
}
+12
View File
@@ -40,6 +40,18 @@ func TestYAMLTopAfterBlockEntry(t *testing.T) {
{"document end comment",
"---\nextensions: {}\n...\t # end\n# footer\n",
"---\nextensions: {}\nGOOSE_THINKING_EFFORT: off\n...\t # end\n# footer\n"},
{"empty trailing document",
"extensions: {}\n---\n",
"extensions: {}\nGOOSE_THINKING_EFFORT: off\n---\n"},
{"null trailing document",
"extensions: {}\n---\nnull\n",
"extensions: {}\nGOOSE_THINKING_EFFORT: off\n---\nnull\n"},
{"several null trailing documents",
"extensions: {}\n---\nnull\n---\n~\n",
"extensions: {}\nGOOSE_THINKING_EFFORT: off\n---\nnull\n---\n~\n"},
{"terminated before empty trailing document",
"extensions: {}\n... # end\n# before empty\n---\n# empty\n",
"extensions: {}\nGOOSE_THINKING_EFFORT: off\n... # end\n# before empty\n---\n# empty\n"},
{"indented root",
" GOOSE_MODEL: m\n extensions: {}\n",
" GOOSE_MODEL: m\n extensions: {}\n GOOSE_THINKING_EFFORT: off\n"},
+18 -33
View File
@@ -1,9 +1,7 @@
package edit
import (
"bytes"
"fmt"
"io"
"regexp"
"sort"
"strconv"
@@ -19,7 +17,7 @@ func GetYAMLTop(path, key string) (string, bool) {
if err != nil {
return "", false
}
root, err := parseYAMLTop(raw)
root, _, err := parseYAMLTop(raw)
if err != nil || root == nil {
return "", false
}
@@ -31,8 +29,9 @@ func GetYAMLTop(path, key string) (string, bool) {
}
// SetYAMLTop sets top-level scalar keys without reformatting other entries.
// Only a single block mapping can be edited; invalid input or output leaves
// the file untouched. Missing files are created.
// Only the first block mapping can be edited, with empty or null trailing
// documents allowed; invalid input or output leaves the file untouched.
// Missing files are created.
func SetYAMLTop(path string, kvs ...KV) error {
raw, err := Read(path)
if err != nil {
@@ -101,37 +100,20 @@ func yamlTopLiteral(value any) string {
return v
}
// Decode as well as parse: yaml.Node alone accepts duplicate mapping keys.
// A second document must not silently disappear from the editor's view.
func parseYAMLTop(raw []byte) (*yaml.Node, error) {
dec := yaml.NewDecoder(bytes.NewReader(raw))
var doc, extra yaml.Node
if err := dec.Decode(&doc); err == io.EOF {
return nil, nil
} else if err != nil {
return nil, err
// parseYAMLTop requires a mapping root, treating an empty null document as empty.
// nextLine is the first trailing document's line, or zero when none follows.
func parseYAMLTop(raw []byte) (root *yaml.Node, nextLine int, err error) {
root, nextLine, err = parseYAMLDocuments(raw)
if err != nil || root == nil {
return nil, nextLine, err
}
if err := dec.Decode(&extra); err != io.EOF {
if err == nil {
err = fmt.Errorf("expected a single YAML document")
}
return nil, err
}
if len(doc.Content) == 0 {
return nil, nil
}
root := doc.Content[0]
if root.Kind == yaml.ScalarNode && root.Tag == "!!null" && root.Value == "" {
return nil, nil
return nil, nextLine, nil
}
if root.Kind != yaml.MappingNode {
return nil, fmt.Errorf("line %d: top level is not a YAML mapping", root.Line)
return nil, 0, fmt.Errorf("line %d: top level is not a YAML mapping", root.Line)
}
var decoded any
if err := root.Decode(&decoded); err != nil {
return nil, err
}
return root, nil
return root, nextLine, nil
}
type yamlTopEntry struct {
@@ -142,7 +124,7 @@ type yamlTopEntry struct {
// The next parsed key bounds an entry, even when its value contains key-like
// lines or a flow collection whose closing bracket is at column zero.
func yamlTopEntries(lines []string) ([]yamlTopEntry, int, string, error) {
root, err := parseYAMLTop([]byte(strings.Join(lines, "\n")))
root, nextLine, err := parseYAMLTop([]byte(strings.Join(lines, "\n")))
if err != nil {
return nil, 0, "", err
}
@@ -150,6 +132,9 @@ func yamlTopEntries(lines []string) ([]yamlTopEntry, int, string, error) {
if lines[end-1] == "" {
end-- // splitLines' final empty element is not another physical line.
}
if nextLine > 0 {
end = nextLine - 1 // Edits belong before the empty/null trailing documents.
}
// Keep an explicit document terminator and the comments following it.
for i := end - 1; i >= 0; i-- {
line := strings.TrimSpace(lines[i])
@@ -233,7 +218,7 @@ func sameYAMLValue(a, b *yaml.Node) bool {
func writeYAMLTop(path string, lines []string) error {
raw := []byte(joinLines(lines))
if _, err := parseYAMLTop(raw); err != nil {
if _, _, err := parseYAMLTop(raw); err != nil {
return fmt.Errorf("%s: %w", path, err)
}
return WriteAtomic(path, raw)
+318
View File
@@ -0,0 +1,318 @@
package edit
import (
"os"
"path/filepath"
"strings"
"testing"
"gopkg.in/yaml.v3"
)
func TestYAMLNestedRejectsInvalidInput(t *testing.T) {
for _, c := range []struct{ name, in string }{
{"malformed first document", "model:\n default: [\n"},
{"multiple documents", "model:\n default: old\n---\nimportant: keep-me\n"},
{"malformed second document", "model:\n default: old\n---\nimportant: [\n"},
{"nonempty third document", "model:\n default: old\n---\nnull\n---\nimportant: keep-me\n"},
{"malformed third document", "model:\n default: old\n---\nnull\n---\nimportant: [\n"},
{"invalid null tag", "model:\n default: old\n---\n!!null invalid\n"},
{"duplicate root key", "model: {default: old}\nmodel: {default: other}\n"},
{"duplicate nested key", "model:\n default: old\n \"default\": other\n"},
{"undefined alias", "model:\n default: *missing\n"},
{"sequence root", "- model: {default: old}\n"},
} {
t.Run(c.name, func(t *testing.T) {
for _, op := range []struct {
name string
fn func(string) error
}{
{"set", func(p string) error { return SetYAML(p, KV{"model.default", "new"}) }},
{"delete", func(p string) error { return DelYAML(p, "model.default") }},
{"edit strings", func(p string) error {
return EditYAMLStrings(p, []string{"model"}, func(s string) string {
return strings.ReplaceAll(s, "old", "new")
})
}},
} {
t.Run(op.name, func(t *testing.T) {
p := tmpFile(t, "config.yaml", c.in)
if err := op.fn(p); err == nil || !strings.Contains(err.Error(), p) {
t.Fatalf("error = %v, want an error with the file path", err)
}
if got := read(t, p); got != c.in {
t.Fatalf("failed edit changed file: %q", got)
}
})
}
})
}
}
func TestYAMLNestedReadsStayLenient(t *testing.T) {
// Parsing nodes need not expand aliases, even when decoding values would
// exceed yaml.v3's expansion limit.
const aliases = "a: &a [0,0,0,0,0,0,0,0,0]\n" +
"b: &b [*a,*a,*a,*a,*a,*a,*a,*a,*a]\n" +
"c: &c [*b,*b,*b,*b,*b,*b,*b,*b,*b]\n" +
"d: &d [*c,*c,*c,*c,*c,*c,*c,*c,*c]\n" +
"e: &e [*d,*d,*d,*d,*d,*d,*d,*d,*d]\n" +
"f: &f [*e,*e,*e,*e,*e,*e,*e,*e,*e]\n" +
"g: &g [*f,*f,*f,*f,*f,*f,*f,*f,*f]\n" +
"h: &h [*g,*g,*g,*g,*g,*g,*g,*g,*g]\n" +
"i: &i [*h,*h,*h,*h,*h,*h,*h,*h,*h]\n"
for _, c := range []struct{ name, extra string }{
{"duplicate unrelated key", "other:\n key: first\n key: second\n"},
{"sequence key", "? [a, b]\n: other\n"},
{"mapping key", "? {a: b}\n: other\n"},
{"invalid tagged scalar", "other: !!int abc\n"},
{"heavy aliases", aliases},
{"multiple documents", "---\nother: keep-me\n"},
} {
t.Run(c.name, func(t *testing.T) {
in := "model:\n default: old\nmodels: [old, fallback]\n" + c.extra
p := tmpFile(t, "config.yaml", in)
if got, ok := GetYAML(p, "model.default"); !ok || got != "old" {
t.Errorf("GetYAML = %q, %v", got, ok)
}
if got := GetYAMLMap(p, "model"); len(got) != 1 || got["default"] != "old" {
t.Errorf("GetYAMLMap = %#v", got)
}
if got := GetYAMLList(p, "models"); len(got) != 2 || got[0] != "old" || got[1] != "fallback" {
t.Errorf("GetYAMLList = %#v", got)
}
if got, ok := GetYAMLText(p, "models"); !ok || got != "[old, fallback]" {
t.Errorf("GetYAMLText = %q, %v", got, ok)
}
// Read compatibility must not let an unsafe file be edited.
for _, op := range []struct {
name string
fn func(string) error
}{
{"set", func(p string) error { return SetYAML(p, KV{"model.default", "new"}) }},
{"delete", func(p string) error { return DelYAML(p, "model.default") }},
{"edit strings", func(p string) error {
return EditYAMLStrings(p, []string{"model"}, func(s string) string {
return strings.ReplaceAll(s, "old", "new")
})
}},
} {
if err := op.fn(p); err == nil || !strings.Contains(err.Error(), p) {
t.Fatalf("%s: error = %v, want an error with the file path", op.name, err)
}
if got := read(t, p); got != in {
t.Fatalf("%s: failed edit changed file: %q", op.name, got)
}
}
})
}
}
func TestYAMLNestedAcceptsNullTrailingDocuments(t *testing.T) {
for _, c := range []struct{ name, tail string }{
{"empty", "---\n"},
{"comment only", "---\n# empty\n...\n"},
{"null", "---\nnull\n"},
{"tilde", "---\n~\n"},
{"uppercase null", "---\nNULL\n"},
{"several", "---\n---\nnull\n---\n~\n"},
{"explicit end", "...\n---\nnull\n...\n"},
} {
t.Run(c.name, func(t *testing.T) {
for _, op := range []struct {
name, want string
fn func(string) error
}{
{"set", "model:\n default: new\nother: keep\n", func(p string) error {
return SetYAML(p, KV{"model.default", "new"})
}},
{"delete", "model: {}\nother: keep\n", func(p string) error {
return DelYAML(p, "model.default")
}},
{"edit strings", "model:\n default: new\nother: keep\n", func(p string) error {
return EditYAMLStrings(p, []string{"model"}, func(s string) string {
return strings.ReplaceAll(s, "old", "new")
})
}},
} {
t.Run(op.name, func(t *testing.T) {
p := tmpFile(t, "config.yaml", "model:\n default: old\nother: keep\n"+c.tail)
if err := op.fn(p); err != nil {
t.Fatal(err)
}
if got := read(t, p); got != op.want {
t.Fatalf("got %q, want %q", got, op.want)
}
})
}
})
}
}
func TestYAMLNestedValidatesBeforeWriting(t *testing.T) {
for _, c := range []struct {
name, in string
fn func(string) error
}{
{"replace anchor", "model:\n default: &chosen old\nother: *chosen\n", func(p string) error {
return SetYAML(p, KV{"model.default", "new"})
}},
{"delete anchor", "model:\n default: &chosen old\nother: *chosen\n", func(p string) error {
return DelYAML(p, "model.default")
}},
{"replace anchor parent", "model:\n default: &chosen old\nother: *chosen\n", func(p string) error {
return SetYAML(p, KV{"model", "new"})
}},
{"duplicate edited key", "model:\n default: old\n other: keep\n", func(p string) error {
return EditYAMLStrings(p, []string{"model"}, func(s string) string {
if s == "other" {
return "default"
}
return s
})
}},
} {
t.Run(c.name, func(t *testing.T) {
p := tmpFile(t, "config.yaml", c.in)
if err := c.fn(p); err == nil || !strings.Contains(err.Error(), p) {
t.Fatalf("error = %v, want an error with the file path", err)
}
if got := read(t, p); got != c.in {
t.Fatalf("failed edit changed file: %q", got)
}
})
}
}
func TestYAMLNestedValidEditsWithAliases(t *testing.T) {
p := tmpFile(t, "config.yaml", "# models\nmodel:\n default: &chosen old # pinned\nother: *chosen\n")
if err := SetYAML(p, KV{"model.effort", "high"}); err != nil {
t.Fatal(err)
}
if err := EditYAMLStrings(p, []string{"model.default"}, func(string) string { return "new" }); err != nil {
t.Fatal(err)
}
var got map[string]any
if err := yaml.Unmarshal([]byte(read(t, p)), &got); err != nil {
t.Fatal(err)
}
model := got["model"].(map[string]any)
if model["default"] != "new" || model["effort"] != "high" || got["other"] != "new" {
t.Fatalf("values or aliases changed: %#v", got)
}
for _, comment := range []string{"# models", "# pinned"} {
if !strings.Contains(read(t, p), comment) {
t.Fatalf("lost comment %q", comment)
}
}
// Removing an anchor and all its uses in one edit leaves valid YAML.
if err := DelYAML(p, "model.default", "other"); err != nil {
t.Fatal(err)
}
if content := read(t, p); content != "# models\nmodel:\n effort: high\n" {
t.Fatalf("after deleting anchor and alias: %q", content)
}
}
func TestYAMLNestedAcceptsFlowRoot(t *testing.T) {
p := tmpFile(t, "config.yaml", "{model: {default: old}, other: keep}\n")
if err := SetYAML(p, KV{"model.default", "new"}); err != nil {
t.Fatal(err)
}
if got := read(t, p); got != "{model: {default: new}, other: keep}\n" {
t.Fatalf("flow mapping changed: %q", got)
}
}
func TestYAMLTextRejectsInvalidInput(t *testing.T) {
for _, c := range []struct{ name, text string }{
{"multiple documents", "old\n---\nkeep-me\n"},
{"duplicate key", "default: old\n\"default\": other\n"},
{"undefined alias", "*missing\n"},
} {
t.Run(c.name, func(t *testing.T) {
const in = "model:\n default: old\n"
p := tmpFile(t, "config.yaml", in)
if err := SetYAML(p, KV{"model.default", YAMLText(c.text)}); err == nil ||
!strings.Contains(err.Error(), p) || !strings.Contains(err.Error(), "model.default") {
t.Fatalf("error = %v, want an error with the file and key paths", err)
}
if got := read(t, p); got != in {
t.Fatalf("failed edit changed file: %q", got)
}
text, err := EditYAMLTextStrings(YAMLText(c.text), func(s string) string {
return strings.ReplaceAll(s, "old", "new")
})
if err == nil || text != YAMLText(c.text) {
t.Fatalf("edited invalid YAML: %q, error = %v", text, err)
}
})
}
}
func TestYAMLTextValidatesEditedOutput(t *testing.T) {
const in YAMLText = "default: old\nother: keep\n"
got, err := EditYAMLTextStrings(in, func(s string) string {
if s == "other" {
return "default"
}
return s
})
if err == nil || got != in {
t.Fatalf("edited YAML has duplicate keys: %q, error = %v", got, err)
}
}
func TestYAMLTextAcceptsStructuredValues(t *testing.T) {
p := tmpFile(t, "config.yaml", "model:\n existing: keep\n")
text, err := EditYAMLTextStrings("[old, fallback]", func(s string) string {
return strings.ReplaceAll(s, "old", "new")
})
if err != nil {
t.Fatal(err)
}
if err := SetYAML(p, KV{"model.default", text}, KV{"model.effort", YAMLText("high")}); err != nil {
t.Fatal(err)
}
if got := read(t, p); got != "model:\n existing: keep\n default: [new, fallback]\n effort: high\n" {
t.Fatalf("structured values changed: %q", got)
}
}
func TestJSONToYAMLRejectsDuplicateKeys(t *testing.T) {
for _, c := range []struct{ name, in string }{
{"root", `{"model": "old", "model": "other"}`},
{"nested", `{"providers": {"mine": {"baseUrl": "old", "baseUrl": "other"}}}`},
} {
t.Run(c.name, func(t *testing.T) {
for _, target := range []struct {
name string
exists bool
}{
{"missing target", false},
{"existing target", true},
} {
t.Run(target.name, func(t *testing.T) {
src := tmpFile(t, "models.json", c.in)
dst := filepath.Join(filepath.Dir(src), "models.yml")
const before = "model: keep\n"
if target.exists {
if err := os.WriteFile(dst, []byte(before), 0o600); err != nil {
t.Fatal(err)
}
}
if err := JSONToYAML(src, dst); err == nil || !strings.Contains(err.Error(), dst) {
t.Fatalf("error = %v, want an error with the target path", err)
}
if target.exists {
if got := read(t, dst); got != before {
t.Fatalf("failed conversion changed target: %q", got)
}
} else if _, err := os.Stat(dst); !os.IsNotExist(err) {
t.Fatalf("failed conversion created target: %v", err)
}
})
}
})
}
}