toml: Codex's config.toml with a multi-line array (notify = [ … ]) is edited right, and an edit that fails leaves every file as it was (#253 kerwinliu00001: "edited TOML is invalid: line 2, column 1: incomplete number", config.toml left with model_provider gone and [model_providers.magpie] added but no model) — the top-level key edits (GetTOMLTop, SetTOMLTop, DelTOMLTop) went line by line with regexes: a new key went after the last line that looked like key = …, which for notify = [ was inside the array; key = value lines inside a multi-line string were read as keys and a line starting with [ as a table; replacing or deleting a multi-line value touched only its first line. They now locate the top-level keys with the TOML parser, as the table edits already did, each with its value's whole range however many lines it takes (parseTOMLFile, the unnamed root table beside the tables); SetTOMLTop finds all its keys in the file as read and writes once. A file the parser refuses is still read line by line, so a broken config keeps showing its model, and writes to it are refused untouched. And a pick is several writes (Codex: drop model_provider, add magpie's provider table, set openai_base_url and model), each checked, so one failing left the earlier ones on disk: edit.Atomically(fn, paths…) puts each file back to its bytes and mode, or removes one it created, when fn fails, and every field set and Sync of Codex (config.toml and magpie-models.json, so Codex in WSL too), Kimi and Grok goes through it, as do Codex's MCP server writes (putCodex, delCodex). Tested in temp dirs and a temp HOME: the reporter's file read, set and deleted directly and through Codex's model field (signed in, with model_provider and model above the array, with magpie as the provider), the array's text kept and the TOML valid, and back to a Codex model; nested arrays, trailing commas, comments in arrays, [x] and a = b in strings, an inline table in an array; """ and ''' strings holding model = … and [table] lines not read as keys, new keys after their closing quotes, one deleted whole; a forced failure of Codex's last write leaving config.toml byte-identical; TestAtomically. They fail on main (the Codex ones with the reporter's error). go vet ./internal/..., go build -tags nogui (and GOOS=linux, GOOS=windows) and go test -tags nogui ./... pass. Not tried against a real ~/.codex, in WSL or in the GUI; multi-line inline tables (TOML 1.1) are refused by the parser and so left untouched with an error.
This commit is contained in:
@@ -13,6 +13,7 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/proc"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
@@ -275,3 +276,21 @@ func (a *Agent) Spell(key, v string) (string, error) {
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// atomic makes each of an agent's field sets, and its Sync, one edit of the
|
||||
// files at paths: one that fails part way puts them all back as they were,
|
||||
// rather than leaving, say, Codex's config.toml with magpie's provider table
|
||||
// written but its model not (#253).
|
||||
func atomic(a *Agent, paths ...string) *Agent {
|
||||
for i := range a.Fields {
|
||||
if set := a.Fields[i].Set; set != nil {
|
||||
a.Fields[i].Set = func(v string) error {
|
||||
return edit.Atomically(func() error { return set(v) }, paths...)
|
||||
}
|
||||
}
|
||||
}
|
||||
if sync := a.Sync; sync != nil {
|
||||
a.Sync = func() error { return edit.Atomically(sync, paths...) }
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
@@ -246,7 +246,7 @@ func codexIn(at place) *Agent {
|
||||
return settle()
|
||||
}
|
||||
|
||||
return &Agent{
|
||||
return atomic(&Agent{
|
||||
ID: "codex", Name: "Codex", Icon: "codex-color", Bin: "codex", Dir: dir, Path: path,
|
||||
UA: []string{"codex"},
|
||||
Sync: func() error {
|
||||
@@ -413,7 +413,7 @@ func codexIn(at place) *Agent {
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}, path, catalogPath)
|
||||
}
|
||||
|
||||
func contains(xs []string, x string) bool {
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/pelletier/go-toml/v2"
|
||||
)
|
||||
|
||||
// #253: a config.toml with a top-level array over several lines. Picking a
|
||||
// model through magpie put the new top-level keys inside the array, and the
|
||||
// failed write left the provider table appended but no model.
|
||||
const codexNotify = `notify = [
|
||||
"/usr/local/bin/notifier",
|
||||
"turn-ended",
|
||||
]
|
||||
|
||||
[model_providers.example]
|
||||
base_url = "http://127.0.0.1:1/v1"
|
||||
`
|
||||
|
||||
func TestCodexMultilineArray(t *testing.T) {
|
||||
for _, tc := range []struct{ name, auth, config string }{
|
||||
{"signed in", `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`, codexNotify},
|
||||
{"signed in, on a provider of its own", `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`,
|
||||
"model = \"gpt-5.5\"\nmodel_provider = \"example\"\n" + codexNotify},
|
||||
{"as a provider", "", codexNotify},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
home, read := codexHome(t, tc.auth, tc.config)
|
||||
cx := codex(home)
|
||||
if err := cx.Fields[0].Set("fake/m1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var cfg struct {
|
||||
Model string
|
||||
Notify []string
|
||||
ModelProviders map[string]any `toml:"model_providers"`
|
||||
}
|
||||
if err := toml.Unmarshal([]byte(read()), &cfg); err != nil {
|
||||
t.Fatalf("%v\n%s", err, read())
|
||||
}
|
||||
if want := []string{"/usr/local/bin/notifier", "turn-ended"}; cfg.Model != "fake/m1" || !reflect.DeepEqual(cfg.Notify, want) ||
|
||||
cfg.ModelProviders["magpie"] == nil || cfg.ModelProviders["example"] == nil {
|
||||
t.Fatalf("after the pick:\n%s", read())
|
||||
}
|
||||
if !strings.Contains(read(), "notify = [\n \"/usr/local/bin/notifier\",\n \"turn-ended\",\n]\n") {
|
||||
t.Fatalf("the array was rewritten:\n%s", read())
|
||||
}
|
||||
// and back to one of Codex's own
|
||||
if err := cx.Fields[0].Set("gpt-5.4"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := cx.Fields[0].Get(); got != "gpt-5.4" {
|
||||
t.Fatalf("model = %q\n%s", got, read())
|
||||
}
|
||||
if !strings.Contains(read(), "notify = [\n \"/usr/local/bin/notifier\",\n \"turn-ended\",\n]\n") {
|
||||
t.Fatalf("the array was rewritten:\n%s", read())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A pick whose last step can't be written leaves config.toml byte for byte
|
||||
// as it was, rather than with magpie's provider table added and no model:
|
||||
// here a table named openai_base_url makes the key of that name a
|
||||
// conflicting definition, found only once the earlier steps are written.
|
||||
func TestCodexFailedPickLeavesConfig(t *testing.T) {
|
||||
const config = "model = \"gpt-5.5\" # mine\nmodel_provider = \"example\"\n\n[openai_base_url]\nx = 1\n\n[model_providers.example]\nbase_url = \"http://127.0.0.1:1/v1\"\n"
|
||||
home, read := codexHome(t, `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`, config)
|
||||
err := codex(home).Fields[0].Set("fake/m1")
|
||||
if err == nil || !strings.Contains(err.Error(), "edited TOML is invalid") {
|
||||
t.Fatalf("err = %v\n%s", err, read())
|
||||
}
|
||||
if got := read(); got != config {
|
||||
t.Fatalf("config.toml left half-edited:\n%s", got)
|
||||
}
|
||||
}
|
||||
@@ -98,7 +98,7 @@ func grok(home string) *Agent {
|
||||
}
|
||||
return catalog.Efforts(magpieModels("grok"), ref)
|
||||
}
|
||||
return &Agent{
|
||||
return atomic(&Agent{
|
||||
ID: "grok", Name: "Grok Build", Icon: "xai", Aliases: []string{"grok-build", "grok-cli"},
|
||||
UA: []string{"grok-shell", "grok-pager", "xai-grok-build"}, // grok-pager: its terminal front end
|
||||
Dir: dir, Path: path,
|
||||
@@ -210,7 +210,7 @@ func grok(home string) *Agent {
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}, path)
|
||||
}
|
||||
|
||||
// grokOwnOptions are the models Grok Build offers its signed-in account, as
|
||||
|
||||
@@ -93,7 +93,7 @@ func kimi(home string) *Agent {
|
||||
t, err := edit.GetTOMLTable(path, "models."+strconv.Quote(k))
|
||||
return err == nil && t != nil
|
||||
}
|
||||
return &Agent{
|
||||
return atomic(&Agent{
|
||||
ID: "kimi", Name: "Kimi Code", Icon: "kimi", Aliases: []string{"kimi-code", "kimi-cli"},
|
||||
UA: []string{"kimicli"},
|
||||
Bin: "kimi", Dir: dir, Path: path,
|
||||
@@ -161,7 +161,7 @@ func kimi(home string) *Agent {
|
||||
return append(kimiOwnOptions(path, cur["model"]), viaMagpie("kimi", magpieID+"/")...)
|
||||
},
|
||||
}},
|
||||
}
|
||||
}, path)
|
||||
}
|
||||
|
||||
// kimiOwnOptions are the models of the user's own in Kimi's config: its
|
||||
|
||||
@@ -4,7 +4,9 @@
|
||||
package edit
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -56,3 +58,54 @@ func WriteAtomic(path string, data []byte) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Atomically runs fn, which may write the files at paths in several steps,
|
||||
// and puts each of them back as it was — its bytes and mode, or its absence
|
||||
// — when fn fails, so an edit that fails part way leaves no file half made.
|
||||
// A file that can't be read beforehand is left to fn as it is.
|
||||
func Atomically(fn func() error, paths ...string) error {
|
||||
type saved struct {
|
||||
path string
|
||||
data []byte
|
||||
mode fs.FileMode
|
||||
exists bool
|
||||
}
|
||||
var before []saved
|
||||
for _, p := range paths {
|
||||
st, err := os.Stat(p)
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
before = append(before, saved{path: p})
|
||||
continue
|
||||
}
|
||||
if err != nil || !st.Mode().IsRegular() {
|
||||
continue
|
||||
}
|
||||
b, err := os.ReadFile(p)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
before = append(before, saved{p, b, st.Mode().Perm(), true})
|
||||
}
|
||||
err := fn()
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
for _, s := range before {
|
||||
now, rerr := os.ReadFile(s.path)
|
||||
switch {
|
||||
case !s.exists:
|
||||
if !errors.Is(rerr, fs.ErrNotExist) {
|
||||
if e := os.Remove(s.path); e != nil && !errors.Is(e, fs.ErrNotExist) {
|
||||
err = errors.Join(err, fmt.Errorf("put %s back: %w", s.path, e))
|
||||
}
|
||||
}
|
||||
case rerr != nil || !bytes.Equal(now, s.data):
|
||||
if e := WriteAtomic(s.path, s.data); e != nil {
|
||||
err = errors.Join(err, fmt.Errorf("put %s back: %w", s.path, e))
|
||||
} else if e := os.Chmod(s.path, s.mode); e != nil {
|
||||
err = errors.Join(err, fmt.Errorf("put %s back: %w", s.path, e))
|
||||
}
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
+6
-40
@@ -7,54 +7,20 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Top-level TOML and YAML keys are edited line by line. That keeps every
|
||||
// comment and every other line byte-for-byte intact, which a round trip
|
||||
// through a parser would not.
|
||||
// Top-level YAML keys are edited line by line. That keeps every comment and
|
||||
// every other line byte-for-byte intact, which a round trip through a parser
|
||||
// would not. TOML's are located by its parser (see toml.go), since a value
|
||||
// there can run over several lines.
|
||||
|
||||
var (
|
||||
// tomlTable and tomlKV only read a TOML file its parser refuses; see
|
||||
// GetTOMLTop.
|
||||
tomlTable = regexp.MustCompile(`^\s*\[`)
|
||||
tomlKV = regexp.MustCompile(`^\s*([A-Za-z0-9_.-]+|"[^"]*")\s*=\s*(.*?)\s*$`)
|
||||
yamlKV = regexp.MustCompile(`^([A-Za-z0-9_.-]+)\s*:\s*(.*?)\s*$`)
|
||||
yamlPlain = regexp.MustCompile(`^[A-Za-z0-9._/-]+$`)
|
||||
)
|
||||
|
||||
// GetTOMLTop reads a top-level (pre-table) key from a TOML file.
|
||||
func GetTOMLTop(path, key string) (string, bool) {
|
||||
raw, err := Read(path)
|
||||
if err != nil || raw == nil {
|
||||
return "", false
|
||||
}
|
||||
for _, line := range splitLines(string(raw)) {
|
||||
if tomlTable.MatchString(line) {
|
||||
break
|
||||
}
|
||||
if m := tomlKV.FindStringSubmatch(line); m != nil && strings.Trim(m[1], `"`) == key {
|
||||
return tomlValue(m[2]), true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// SetTOMLTop sets top-level keys in a TOML file. Existing lines are replaced
|
||||
// in place; new keys go right after the last existing top-level key.
|
||||
func SetTOMLTop(path string, kvs ...KV) error {
|
||||
raw, err := Read(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
lines := splitLines(string(raw))
|
||||
for _, kv := range kvs {
|
||||
lines = setLine(lines, kv.Path, kv.Path+" = "+strconv.Quote(toString(kv.Value)), tomlTable, func(line string) (string, bool) {
|
||||
m := tomlKV.FindStringSubmatch(line)
|
||||
if m == nil {
|
||||
return "", false
|
||||
}
|
||||
return strings.Trim(m[1], `"`), true
|
||||
})
|
||||
}
|
||||
return writeTOML(path, lines)
|
||||
}
|
||||
|
||||
// GetYAMLTop reads a top-level scalar key from a YAML file.
|
||||
func GetYAMLTop(path, key string) (string, bool) {
|
||||
raw, err := Read(path)
|
||||
|
||||
+157
-31
@@ -195,29 +195,132 @@ func DelTOMLTable(path, name string) error {
|
||||
return writeTOML(path, out)
|
||||
}
|
||||
|
||||
// DelTOMLTop removes top-level (pre-table) keys.
|
||||
// GetTOMLTop reads a top-level (pre-table) key from a TOML file. A string is
|
||||
// decoded; any other value is its text as written, without a trailing
|
||||
// comment, an array or inline table over several lines included. A file
|
||||
// TOML's parser refuses is read line by line, as well as that goes.
|
||||
func GetTOMLTop(path, key string) (string, bool) {
|
||||
doc, err := tomlFileOf(path)
|
||||
if err != nil {
|
||||
return getTOMLTopLines(path, key)
|
||||
}
|
||||
for _, kv := range doc.root.keys {
|
||||
if kv.name == key {
|
||||
if kv.scalar {
|
||||
return kv.value, true
|
||||
}
|
||||
return kv.text, true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// getTOMLTopLines is GetTOMLTop for a file that isn't valid TOML: the first
|
||||
// line that looks like `key = value` before one that looks like a header.
|
||||
func getTOMLTopLines(path, key string) (string, bool) {
|
||||
raw, err := Read(path)
|
||||
if err != nil || raw == nil {
|
||||
return "", false
|
||||
}
|
||||
for _, line := range splitLines(string(raw)) {
|
||||
if tomlTable.MatchString(line) {
|
||||
break
|
||||
}
|
||||
if m := tomlKV.FindStringSubmatch(line); m != nil && strings.Trim(m[1], `"`) == key {
|
||||
return tomlValue(m[2]), true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// SetTOMLTop sets top-level keys in a TOML file, as strings. An existing key
|
||||
// is replaced as a whole, its value's every line with it; new keys go right
|
||||
// after the last existing top-level key's value, or first in the file when
|
||||
// there is none. Every key is located in the file as it was read, so the
|
||||
// edit is one write that either happens entirely or not at all.
|
||||
func SetTOMLTop(path string, kvs ...KV) error {
|
||||
raw, err := Read(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
lines := splitLines(string(raw))
|
||||
doc, err := parseTOMLFile(lines)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s: %w", path, err)
|
||||
}
|
||||
type span struct {
|
||||
to int
|
||||
line string
|
||||
}
|
||||
replace := map[int]span{}
|
||||
var added []string
|
||||
addedAt := map[string]int{}
|
||||
at := 0
|
||||
if n := len(doc.root.keys); n > 0 {
|
||||
at = doc.root.keys[n-1].to
|
||||
}
|
||||
for _, kv := range kvs {
|
||||
line := kv.Path + " = " + strconv.Quote(toString(kv.Value))
|
||||
found := false
|
||||
for _, k := range doc.root.keys {
|
||||
if k.name == kv.Path {
|
||||
replace[k.from] = span{k.to, line}
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
switch i, ok := addedAt[kv.Path]; {
|
||||
case found:
|
||||
case ok:
|
||||
added[i] = line
|
||||
default:
|
||||
addedAt[kv.Path] = len(added)
|
||||
added = append(added, line)
|
||||
}
|
||||
}
|
||||
out := make([]string, 0, len(lines)+len(added))
|
||||
for i := 0; i < len(lines); {
|
||||
if i == at {
|
||||
out = append(out, added...)
|
||||
added = nil
|
||||
}
|
||||
if r, ok := replace[i]; ok {
|
||||
out = append(out, r.line)
|
||||
i = r.to
|
||||
continue
|
||||
}
|
||||
out = append(out, lines[i])
|
||||
i++
|
||||
}
|
||||
out = append(out, added...)
|
||||
return writeTOML(path, out)
|
||||
}
|
||||
|
||||
// DelTOMLTop removes top-level (pre-table) keys, each with every line of its
|
||||
// value.
|
||||
func DelTOMLTop(path string, keys ...string) error {
|
||||
raw, err := Read(path)
|
||||
if err != nil || raw == nil {
|
||||
return err
|
||||
}
|
||||
lines := splitLines(string(raw))
|
||||
doc, err := parseTOMLFile(lines)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s: %w", path, err)
|
||||
}
|
||||
drop := map[string]bool{}
|
||||
for _, k := range keys {
|
||||
drop[k] = true
|
||||
}
|
||||
var out []string
|
||||
header := true
|
||||
for _, line := range splitLines(string(raw)) {
|
||||
if header && tomlTable.MatchString(line) {
|
||||
header = false
|
||||
at := 0
|
||||
for _, kv := range doc.root.keys {
|
||||
if drop[kv.name] {
|
||||
out = append(out, lines[at:kv.from]...)
|
||||
at = kv.to
|
||||
}
|
||||
if header {
|
||||
if m := tomlKV.FindStringSubmatch(line); m != nil && drop[strings.Trim(m[1], `"`)] {
|
||||
continue
|
||||
}
|
||||
}
|
||||
out = append(out, line)
|
||||
}
|
||||
out = append(out, lines[at:]...)
|
||||
return writeTOML(path, out)
|
||||
}
|
||||
|
||||
@@ -233,6 +336,7 @@ type tomlKeySpan struct {
|
||||
from, to int // to is -1 until the next expression or EOF bounds the value.
|
||||
column int // 1-based start of the key.
|
||||
name, value string
|
||||
text string // The value as written, from prefix to suffix.
|
||||
prefix, suffix string // Original text before and after the complete value.
|
||||
comment int // Column of a trailing comment, or -1 when absent.
|
||||
scalar bool
|
||||
@@ -269,31 +373,56 @@ func tomlTableNamed(tables []tomlTableSpan, name string) (tomlTableSpan, bool) {
|
||||
// changes: an agent's config can be large (Codex's lists every project it
|
||||
// was trusted in) and is read field by field. Missing files are (nil, nil).
|
||||
func tomlTablesOf(path string) ([]tomlTableSpan, error) {
|
||||
tables, err := filememo.Read("toml tables", path, func(b []byte) ([]tomlTableSpan, error) {
|
||||
tables, err := parseTOMLTables(splitLines(string(b)))
|
||||
doc, err := tomlFileOf(path)
|
||||
return doc.tables, err
|
||||
}
|
||||
|
||||
// tomlFileOf is parseTOMLFile of a file, kept as tomlTablesOf says. A missing
|
||||
// file is an empty document and no error.
|
||||
func tomlFileOf(path string) (tomlFile, error) {
|
||||
doc, err := filememo.Read("toml file", path, func(b []byte) (tomlFile, error) {
|
||||
doc, err := parseTOMLFile(splitLines(string(b)))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", path, err)
|
||||
return tomlFile{}, fmt.Errorf("%s: %w", path, err)
|
||||
}
|
||||
return tables, nil
|
||||
return doc, nil
|
||||
})
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return nil, nil
|
||||
return tomlFile{}, nil
|
||||
}
|
||||
return tables, err
|
||||
return doc, err
|
||||
}
|
||||
|
||||
// parseTOMLTables finds both ordinary and array-table blocks in one parser pass.
|
||||
// Only top-level expressions delimit edits, so lines inside multiline values
|
||||
// cannot be mistaken for keys, comments, or table headers.
|
||||
func parseTOMLTables(lines []string) ([]tomlTableSpan, error) {
|
||||
doc, err := parseTOMLFile(lines)
|
||||
return doc.tables, err
|
||||
}
|
||||
|
||||
// tomlFile is a file's top-level (pre-table) keys, as the unnamed table root
|
||||
// spanning [0, first header), and its table blocks in file order.
|
||||
type tomlFile struct {
|
||||
root tomlTableSpan
|
||||
tables []tomlTableSpan
|
||||
}
|
||||
|
||||
// parseTOMLFile is parseTOMLTables with the top-level keys too, located the
|
||||
// same way: a key's range covers its whole value, however many lines it takes.
|
||||
func parseTOMLFile(lines []string) (tomlFile, error) {
|
||||
p := unstable.Parser{KeepComments: true}
|
||||
p.Reset([]byte(strings.Join(lines, "\n")))
|
||||
root := tomlTableSpan{to: len(lines)}
|
||||
var tables []tomlTableSpan
|
||||
finishKey := func(to int) error {
|
||||
current := func() *tomlTableSpan {
|
||||
if len(tables) == 0 {
|
||||
return nil
|
||||
return &root
|
||||
}
|
||||
table := &tables[len(tables)-1]
|
||||
return &tables[len(tables)-1]
|
||||
}
|
||||
finishKey := func(to int) error {
|
||||
table := current()
|
||||
if len(table.keys) == 0 {
|
||||
return nil
|
||||
}
|
||||
@@ -319,6 +448,8 @@ func parseTOMLTables(lines []string) ([]tomlTableSpan, error) {
|
||||
// the value. Keep all whitespace between the closing value and comment.
|
||||
end = len(strings.TrimRight(last[:end], " \t\r"))
|
||||
kv.suffix = last[end:]
|
||||
text := strings.Join(lines[kv.from:kv.to], "\n")
|
||||
kv.text = text[len(kv.prefix) : len(text)-len(kv.suffix)]
|
||||
return nil
|
||||
}
|
||||
for p.NextExpression() {
|
||||
@@ -342,23 +473,18 @@ func parseTOMLTables(lines []string) ([]tomlTableSpan, error) {
|
||||
shape := p.Shape(keyRange)
|
||||
i := shape.Start.Line - 1
|
||||
if err := finishKey(i); err != nil {
|
||||
return nil, err
|
||||
return tomlFile{}, err
|
||||
}
|
||||
switch expr.Kind {
|
||||
case unstable.Table, unstable.ArrayTable:
|
||||
if len(tables) > 0 {
|
||||
tables[len(tables)-1].to = i
|
||||
}
|
||||
current().to = i
|
||||
tables = append(tables, tomlTableSpan{
|
||||
from: i, to: len(lines), name: strings.Join(rawParts, "."),
|
||||
column: shape.Start.Column,
|
||||
array: expr.Kind == unstable.ArrayTable,
|
||||
})
|
||||
case unstable.KeyValue:
|
||||
if len(tables) == 0 {
|
||||
continue
|
||||
}
|
||||
table := &tables[len(tables)-1]
|
||||
table := current()
|
||||
value := expr.Value()
|
||||
// Start after the parsed key, which may itself contain '='.
|
||||
_, valueText, _ := strings.Cut(lines[i][shape.End.Column-1:], "=")
|
||||
@@ -376,12 +502,12 @@ func parseTOMLTables(lines []string) ([]tomlTableSpan, error) {
|
||||
}
|
||||
}
|
||||
if err := p.Error(); err != nil {
|
||||
return nil, tomlParseError(&p, err)
|
||||
return tomlFile{}, tomlParseError(&p, err)
|
||||
}
|
||||
if err := finishKey(len(lines)); err != nil {
|
||||
return nil, err
|
||||
return tomlFile{}, err
|
||||
}
|
||||
return tables, nil
|
||||
return tomlFile{root: root, tables: tables}, nil
|
||||
}
|
||||
|
||||
func tomlParseError(p *unstable.Parser, err error) error {
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
package edit
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/pelletier/go-toml/v2"
|
||||
)
|
||||
|
||||
// The config.toml of #253: a top-level array over several lines. A new
|
||||
// top-level key went in right after the array's first line, inside it
|
||||
// ("edited TOML is invalid: line 2, column 1: incomplete number").
|
||||
const issue253 = `notify = [
|
||||
"/usr/local/bin/notifier",
|
||||
"turn-ended",
|
||||
]
|
||||
|
||||
[model_providers.example]
|
||||
base_url = "http://127.0.0.1:1/v1"
|
||||
`
|
||||
|
||||
func TestTOMLTopMultilineArray(t *testing.T) {
|
||||
p := tmpFile(t, "config.toml", issue253)
|
||||
if v, ok := GetTOMLTop(p, "notify"); !ok || v != "[\n \"/usr/local/bin/notifier\",\n \"turn-ended\",\n]" {
|
||||
t.Fatalf("notify = %q %v", v, ok)
|
||||
}
|
||||
if err := SetTOMLTop(p, KV{Path: "model", Value: "gpt-6-luna"}, KV{Path: "model_provider", Value: "magpie"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertTOMLContent(t, p, `notify = [
|
||||
"/usr/local/bin/notifier",
|
||||
"turn-ended",
|
||||
]
|
||||
model = "gpt-6-luna"
|
||||
model_provider = "magpie"
|
||||
|
||||
[model_providers.example]
|
||||
base_url = "http://127.0.0.1:1/v1"
|
||||
`)
|
||||
assertNotify(t, p)
|
||||
// replacing a key before the array, and the array itself
|
||||
if err := SetTOMLTop(p, KV{Path: "model", Value: "gpt-5.5"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertNotify(t, p)
|
||||
if err := DelTOMLTop(p, "model_provider", "notify"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertTOMLContent(t, p, "model = \"gpt-5.5\"\n\n[model_providers.example]\nbase_url = \"http://127.0.0.1:1/v1\"\n")
|
||||
}
|
||||
|
||||
func assertNotify(t *testing.T, p string) {
|
||||
t.Helper()
|
||||
var doc struct{ Notify []string }
|
||||
if err := toml.Unmarshal([]byte(read(t, p)), &doc); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if want := []string{"/usr/local/bin/notifier", "turn-ended"}; !reflect.DeepEqual(doc.Notify, want) {
|
||||
t.Fatalf("notify = %q", doc.Notify)
|
||||
}
|
||||
}
|
||||
|
||||
// Nested arrays, trailing commas, comments inside an array, and brackets
|
||||
// and `key = value` inside its strings: none of it is a key or a header.
|
||||
func TestTOMLTopNestedArrays(t *testing.T) {
|
||||
const input = `model = "old" # the model
|
||||
matrix = [
|
||||
[1, 2,],
|
||||
["[x]", "a = b"], # a comment with [brackets]
|
||||
# model = "not a key"
|
||||
[
|
||||
3,
|
||||
],
|
||||
{ name = "[t]" },
|
||||
]
|
||||
[mcp]
|
||||
x = 1
|
||||
`
|
||||
p := tmpFile(t, "config.toml", input)
|
||||
if v, ok := GetTOMLTop(p, "model"); !ok || v != "old" {
|
||||
t.Fatalf("model = %q %v", v, ok)
|
||||
}
|
||||
if err := SetTOMLTop(p, KV{Path: "model", Value: "new"}, KV{Path: "openai_base_url", Value: "http://127.0.0.1:1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertTOMLContent(t, p, `model = "new"
|
||||
matrix = [
|
||||
[1, 2,],
|
||||
["[x]", "a = b"], # a comment with [brackets]
|
||||
# model = "not a key"
|
||||
[
|
||||
3,
|
||||
],
|
||||
{ name = "[t]" },
|
||||
]
|
||||
openai_base_url = "http://127.0.0.1:1"
|
||||
[mcp]
|
||||
x = 1
|
||||
`)
|
||||
if err := DelTOMLTop(p, "matrix"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertTOMLContent(t, p, "model = \"new\"\nopenai_base_url = \"http://127.0.0.1:1\"\n[mcp]\nx = 1\n")
|
||||
}
|
||||
|
||||
// Multi-line strings, basic and literal, whose lines look like keys and
|
||||
// tables: they are the string's text, not the file's.
|
||||
func TestTOMLTopMultilineStrings(t *testing.T) {
|
||||
const input = `instructions = """
|
||||
model = "inner"
|
||||
[not.a.table]
|
||||
"""
|
||||
raw = '''
|
||||
[another]
|
||||
model_provider = x
|
||||
'''
|
||||
|
||||
[t]
|
||||
x = 1
|
||||
`
|
||||
p := tmpFile(t, "config.toml", input)
|
||||
if v, ok := GetTOMLTop(p, "model"); ok {
|
||||
t.Fatalf("model read from inside a string: %q", v)
|
||||
}
|
||||
if v, _ := GetTOMLTop(p, "raw"); v != "[another]\nmodel_provider = x\n" {
|
||||
t.Fatalf("raw = %q", v)
|
||||
}
|
||||
if got, err := TOMLTables(p); err != nil || !reflect.DeepEqual(got, []string{"t"}) {
|
||||
t.Fatalf("tables = %v, %v", got, err)
|
||||
}
|
||||
if err := SetTOMLTop(p, KV{Path: "model", Value: "m"}, KV{Path: "model_provider", Value: "magpie"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertTOMLContent(t, p, `instructions = """
|
||||
model = "inner"
|
||||
[not.a.table]
|
||||
"""
|
||||
raw = '''
|
||||
[another]
|
||||
model_provider = x
|
||||
'''
|
||||
model = "m"
|
||||
model_provider = "magpie"
|
||||
|
||||
[t]
|
||||
x = 1
|
||||
`)
|
||||
if err := DelTOMLTop(p, "instructions", "model_provider"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertTOMLContent(t, p, "raw = '''\n[another]\nmodel_provider = x\n'''\nmodel = \"m\"\n\n[t]\nx = 1\n")
|
||||
if err := SetTOMLKey(p, "t", "y", "z"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := SetTOMLTable(p, "u", KV{Path: "k", Value: "v"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertTOMLContent(t, p, "raw = '''\n[another]\nmodel_provider = x\n'''\nmodel = \"m\"\n\n[t]\nx = 1\ny = \"z\"\n\n[u]\nk = \"v\"\n")
|
||||
}
|
||||
|
||||
// Atomically puts back every file an edit in several steps touched once a
|
||||
// step fails: changed bytes, mode, and a file that wasn't there.
|
||||
func TestAtomically(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfg := filepath.Join(dir, "config.toml")
|
||||
extra := filepath.Join(dir, "models.json")
|
||||
os.WriteFile(cfg, []byte(issue253), 0o600)
|
||||
fail := errors.New("step two")
|
||||
err := Atomically(func() error {
|
||||
if err := SetTOMLTable(cfg, "model_providers.magpie", KV{Path: "name", Value: "magpie"}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := WriteAtomic(extra, []byte("{}")); err != nil {
|
||||
return err
|
||||
}
|
||||
os.Chmod(cfg, 0o644)
|
||||
return fail
|
||||
}, cfg, extra)
|
||||
if !errors.Is(err, fail) {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
if got := read(t, cfg); got != issue253 {
|
||||
t.Fatalf("config not put back:\n%s", got)
|
||||
}
|
||||
if st, _ := os.Stat(cfg); runtime.GOOS != "windows" && st.Mode().Perm() != 0o600 {
|
||||
t.Fatalf("mode %v", st.Mode().Perm())
|
||||
}
|
||||
if _, err := os.Stat(extra); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("a file made by the failed edit stays: %v", err)
|
||||
}
|
||||
// a successful edit is kept
|
||||
if err := Atomically(func() error { return SetTOMLTop(cfg, KV{Path: "model", Value: "m"}) }, cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if v, _ := GetTOMLTop(cfg, "model"); v != "m" {
|
||||
t.Fatalf("model = %q", v)
|
||||
}
|
||||
}
|
||||
@@ -104,21 +104,23 @@ func TestTOMLWritesRejectDefinitionConflicts(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTOMLTopRejectsBrokenMultilineEdits(t *testing.T) {
|
||||
// A top-level value over several lines is replaced or removed as a whole.
|
||||
func TestTOMLTopMultilineEdits(t *testing.T) {
|
||||
const input = "value = [\n1,\n2\n]\n\n[a]\nkeep = true\n"
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
edit func(string) error
|
||||
name, want string
|
||||
edit func(string) error
|
||||
}{
|
||||
{"replace", func(p string) error { return SetTOMLTop(p, KV{Path: "value", Value: "new"}) }},
|
||||
{"delete", func(p string) error { return DelTOMLTop(p, "value") }},
|
||||
{"replace", "value = \"new\"\n\n[a]\nkeep = true\n", func(p string) error { return SetTOMLTop(p, KV{Path: "value", Value: "new"}) }},
|
||||
{"delete", "\n[a]\nkeep = true\n", func(p string) error { return DelTOMLTop(p, "value") }},
|
||||
{"add", "value = [\n1,\n2\n]\nother = \"x\"\n\n[a]\nkeep = true\n", func(p string) error { return SetTOMLTop(p, KV{Path: "other", Value: "x"}) }},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
p := tmpFile(t, "config.toml", input)
|
||||
if err := tc.edit(p); err == nil {
|
||||
t.Fatal("expected the incomplete multiline edit to be rejected")
|
||||
if err := tc.edit(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertTOMLContent(t, p, input)
|
||||
assertTOMLContent(t, p, tc.want)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
+21
-16
@@ -628,26 +628,31 @@ func (f *mcpFile) del(name string) error {
|
||||
// or only those under it, which putCodex writes inline instead.
|
||||
// Include child array tables (such as env_vars), which would otherwise
|
||||
// implicitly recreate the removed server.
|
||||
// Each is one edit of the file: a step that fails puts it back as it was.
|
||||
func delCodex(path, name string, self bool) error {
|
||||
table := "mcp_servers." + name
|
||||
if err := edit.SetTOMLTables(path, []string{table + "."}, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
if !self {
|
||||
return nil
|
||||
}
|
||||
return edit.DelTOMLTable(path, table)
|
||||
return edit.Atomically(func() error {
|
||||
table := "mcp_servers." + name
|
||||
if err := edit.SetTOMLTables(path, []string{table + "."}, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
if !self {
|
||||
return nil
|
||||
}
|
||||
return edit.DelTOMLTable(path, table)
|
||||
}, path)
|
||||
}
|
||||
|
||||
func putCodex(path, name string, o ordered) error {
|
||||
if err := delCodex(path, name, false); err != nil {
|
||||
return err
|
||||
}
|
||||
var kvs []edit.KV
|
||||
for _, e := range o {
|
||||
kvs = append(kvs, edit.KV{Path: tomlKey(e.k), Value: edit.Raw(tomlValue(e.v))})
|
||||
}
|
||||
return edit.SetTOMLTable(path, "mcp_servers."+name, kvs...)
|
||||
return edit.Atomically(func() error {
|
||||
if err := delCodex(path, name, false); err != nil {
|
||||
return err
|
||||
}
|
||||
var kvs []edit.KV
|
||||
for _, e := range o {
|
||||
kvs = append(kvs, edit.KV{Path: tomlKey(e.k), Value: edit.Raw(tomlValue(e.v))})
|
||||
}
|
||||
return edit.SetTOMLTable(path, "mcp_servers."+name, kvs...)
|
||||
}, path)
|
||||
}
|
||||
|
||||
func tomlString(s string) string {
|
||||
|
||||
Reference in New Issue
Block a user