diff --git a/internal/edit/jsonarray.go b/internal/edit/jsonarray.go index 2d1ee8ba3..45e54f43e 100644 --- a/internal/edit/jsonarray.go +++ b/internal/edit/jsonarray.go @@ -186,7 +186,10 @@ func findItem(stripped []byte, where map[string]string) (gjson.Result, bool) { func delItem(raw, stripped []byte, r gjson.Result) []byte { a, b := r.Index, r.Index+len(r.Raw) ls := bytes.LastIndexByte(raw[:a], '\n') + 1 - alone := len(bytes.TrimSpace(stripped[ls:a])) == 0 + // a comment before the element on its line is not alone: read from raw, + // where the comment is still there (stripped has it blanked), as + // delJSONBytes does, so the comment stays when the element goes. + alone := len(bytes.TrimSpace(raw[ls:a])) == 0 j := b for j < len(stripped) && isSpace(stripped[j]) { j++ diff --git a/internal/edit/jsonarray_comment_test.go b/internal/edit/jsonarray_comment_test.go new file mode 100644 index 000000000..6a30aca6a --- /dev/null +++ b/internal/edit/jsonarray_comment_test.go @@ -0,0 +1,47 @@ +package edit + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/tidwall/jsonc" +) + +// A comment at the start of the element's line stays when the element is +// taken out, as a member's delete keeps the comment before it: VS Code's +// chatLanguageModels.json carries the user's notes beside their groups. + +func TestDelJSONItemKeepsACommentBeforeTheElement(t *testing.T) { + where := map[string]string{"vendor": "customendpoint", "name": "magpie"} + magpie := `{"name": "magpie", "vendor": "customendpoint"}` + for _, in := range []string{ + // last element, its comment on the line with it + "[\n {\"name\": \"a\", \"vendor\": \"openai\"},\n /* magpie's group */ " + magpie + "\n]\n", + // not the last + "[\n /* magpie's group */ " + magpie + ",\n {\"name\": \"b\", \"vendor\": \"ollama\"}\n]\n", + // on one line, the [ on it too + "[ {\"name\": \"a\", \"vendor\": \"openai\"}, /* magpie's group */ " + magpie + " ]\n", + // a block comment that ends on the element's line + "[\n {\"name\": \"a\", \"vendor\": \"openai\"},\n /* magpie's group\n */ " + magpie + "\n]\n", + } { + p := tmpFile(t, "chatLanguageModels.json", in) + if err := DelJSONItem(p, where); err != nil { + t.Fatal(err) + } + b := read(t, p) + var got []map[string]any + if err := json.Unmarshal(jsonc.ToJSON([]byte(b)), &got); err != nil { + t.Fatalf("%q: not valid JSONC after: %v\n%s", in, err, b) + } + if len(got) != strings.Count(in, "\"vendor\"")-1 { + t.Fatalf("%q: %d elements left:\n%s", in, len(got), b) + } + if _, ok := GetJSONItem(p, where); ok { + t.Fatalf("%q: the element is still there:\n%s", in, b) + } + if !strings.Contains(b, "/* magpie's group") || !strings.Contains(b, "*/") { + t.Fatalf("%q: the comment before the element went with it:\n%s", in, b) + } + } +}