Files
magpie/internal/edit/crlf_yaml_test.go
T
Charan Rathore 05295e5ab9 edit: keep a CRLF file's line endings when SetYAML, DelYAML and EditYAMLStrings rewrite it (#831)
* edit: keep a CRLF file's line endings when JSON members are added or replaced

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.

* edit: keep a CRLF file's line endings when SetYAML, DelYAML and EditYAMLStrings rewrite it

writeYAML renders the whole document with the YAML encoder, which writes \n. A YAML file saved with \r\n (the usual case for one edited on Windows) came back entirely LF after any SetYAML, DelYAML or EditYAMLStrings, so an edit of one key rewrote every line of the file and showed up as a full-file diff.

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. A LF or mixed file is written as before.

TestSetYAMLKeepsCRLF fails on the old code; TestSetYAMLKeepsLF pins that an LF file is unchanged. This builds on the keepCRLF added for SetJSON in the previous commit (#830). go vet and go test ./internal/edit ./internal/agent ./internal/library ./internal/settings pass.
2026-10-05 04:30:23 +08:00

34 lines
1021 B
Go

package edit
import "testing"
// A YAML file that uses \r\n for every line break keeps it when SetYAML,
// DelYAML or EditYAMLStrings rewrite it: the encoder writes \n, which turned
// the whole file into LF.
func TestSetYAMLKeepsCRLF(t *testing.T) {
p := tmpFile(t, "config.yaml", "a: 1\r\nb:\r\n c: 2\r\n")
if err := SetYAML(p, KV{Path: "b.c", Value: 3}, KV{Path: "d", Value: "4"}); err != nil {
t.Fatal(err)
}
if got, want := read(t, p), "a: 1\r\nb:\r\n c: 3\r\nd: \"4\"\r\n"; got != want {
t.Fatalf("got %q, want %q", got, want)
}
if err := DelYAML(p, "a"); err != nil {
t.Fatal(err)
}
if got, want := read(t, p), "b:\r\n c: 3\r\nd: \"4\"\r\n"; got != want {
t.Fatalf("after delete got %q, want %q", got, want)
}
}
func TestSetYAMLKeepsLF(t *testing.T) {
p := tmpFile(t, "config.yaml", "a: 1\nb: 2\n")
if err := SetYAML(p, KV{Path: "c", Value: 3}); err != nil {
t.Fatal(err)
}
if got, want := read(t, p), "a: 1\nb: 2\nc: 3\n"; got != want {
t.Fatalf("got %q, want %q", got, want)
}
}