edit: keep a CRLF file's line endings when JSON members are added or replaced (#830)

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.
This commit is contained in:
Charan Rathore
2026-10-05 04:29:55 +08:00
committed by GitHub
parent 0c38071c63
commit 6b0a44ea7d
2 changed files with 42 additions and 1 deletions
+28
View File
@@ -0,0 +1,28 @@
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)
}
}
+14 -1
View File
@@ -39,13 +39,26 @@ func SetJSON(path string, kvs ...KV) error {
if len(bytes.TrimSpace(raw)) == 0 {
raw = []byte("{}\n")
}
orig := raw
for _, kv := range kvs {
raw, err = setJSONBytes(raw, kv.Path, kv.Value)
if err != nil {
return fmt.Errorf("%s: %w", path, err)
}
}
return WriteAtomic(path, raw)
return WriteAtomic(path, keepCRLF(raw, orig))
}
// keepCRLF is out, an edit of orig, with \r\n at every line break when orig
// used \r\n for all of them: the lines an edit adds are built with \n, and a
// file that mixed endings is left as it was.
func keepCRLF(out, orig []byte) []byte {
n := bytes.Count(orig, []byte("\n"))
if n == 0 || bytes.Count(orig, []byte("\r\n")) != n {
return out
}
out = bytes.ReplaceAll(out, []byte("\r\n"), []byte("\n"))
return bytes.ReplaceAll(out, []byte("\n"), []byte("\r\n"))
}
func setJSONBytes(raw []byte, keyPath string, value any) ([]byte, error) {