SetJSON splices new lines into the file with \n. In a JSON or JSONC file saved with \r\n (VS Code on Windows does that), a member added to an object or a nested value came back with a bare \n among the \r\n lines. SetJSON of "b" on "{\r\n \"a\": 1\r\n}\r\n" gave "{\n \"b\": 2,\r\n \"a\": 1\r\n}\r\n".
The result is written back through keepCRLF, which turns every line break into \r\n when the original used \r\n for all of them. Untouched lines already carry their \r, so only the added lines change; a file that mixed endings is written as before.
TestSetJSONKeepsCRLF fails on the old code; TestSetJSONKeepsMixedEndings pins that a mixed file is left alone. go vet and go test ./internal/edit pass here and on current main with this merged.
29 lines
1011 B
Go
29 lines
1011 B
Go
package edit
|
|
|
|
import "testing"
|
|
|
|
// A JSON file that uses \r\n for every line break keeps it when a member is
|
|
// added or replaced: the lines an edit adds used to carry a bare \n, so the
|
|
// file ended up with mixed endings.
|
|
|
|
func TestSetJSONKeepsCRLF(t *testing.T) {
|
|
p := tmpFile(t, "settings.json", "{\r\n \"a\": 1,\r\n \"n\": {\r\n \"x\": 1\r\n }\r\n}\r\n")
|
|
if err := SetJSON(p, KV{Path: "b", Value: 2}, KV{Path: "n.y", Value: []string{"p"}}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
want := "{\r\n \"b\": 2,\r\n \"a\": 1,\r\n \"n\": {\r\n \"y\": [\r\n \"p\"\r\n ],\r\n \"x\": 1\r\n }\r\n}\r\n"
|
|
if got := read(t, p); got != want {
|
|
t.Fatalf("got %q, want %q", got, want)
|
|
}
|
|
}
|
|
|
|
func TestSetJSONKeepsMixedEndings(t *testing.T) {
|
|
p := tmpFile(t, "settings.json", "{\r\n \"a\": 1\n}\n")
|
|
if err := SetJSON(p, KV{Path: "b", Value: 2}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got, want := read(t, p), "{\n \"b\": 2,\r\n \"a\": 1\n}\n"; got != want {
|
|
t.Fatalf("got %q, want %q", got, want)
|
|
}
|
|
}
|