From d9d9a93103eb550baa07377c80d4dc5a205c8085 Mon Sep 17 00:00:00 2001 From: Adil Karim Date: Fri, 6 Nov 2026 06:05:10 +0000 Subject: [PATCH] fix(shell): decode multiline sed append continuations (OPE-98) Remove continuation markers from sed append text while decoding escaped backslashes in a single pass. Cover streaming and in-place edits with two- and three-line payloads. Amp-Thread-ID: https://ampcode.com/threads/T-ed5ce2ce-0dc6-4112-9153-576179f83d14 Co-authored-by: Amp --- pkg/shell/cmds/sed.go | 7 +++++++ pkg/shell/cmds/sed_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/pkg/shell/cmds/sed.go b/pkg/shell/cmds/sed.go index 27c0ba4..dc8ffcb 100644 --- a/pkg/shell/cmds/sed.go +++ b/pkg/shell/cmds/sed.go @@ -521,6 +521,13 @@ func parseSedExpr(expr string) (sedCmd, error) { cmd.text = strings.TrimPrefix(cmd.text, "\\") cmd.text = strings.TrimPrefix(cmd.text, "\r\n") cmd.text = strings.TrimPrefix(cmd.text, "\n") + // Decode pairs in one pass so a literal backslash cannot become + // a continuation marker during a later replacement. + cmd.text = strings.NewReplacer( + `\\`, `\`, + "\\\n", "\n", + "\\\r\n", "\r\n", + ).Replace(cmd.text) } else { cmd.text = strings.TrimLeft(cmd.text, " \t") } diff --git a/pkg/shell/cmds/sed_test.go b/pkg/shell/cmds/sed_test.go index 8da2318..381eec5 100644 --- a/pkg/shell/cmds/sed_test.go +++ b/pkg/shell/cmds/sed_test.go @@ -364,6 +364,37 @@ func TestSedAppendMultilineInPlace(t *testing.T) { } } +func TestSedAppendContinuations(t *testing.T) { + tests := []struct { + name string + expr string + want string + }{ + {"two lines", "1a\\\nx\\\ny", "l1\nx\ny\nl2\nl3\n"}, + {"three lines", "2a\\\n x; keep\\\ny\\\nz", "l1\nl2\n x; keep\ny\nz\nl3\n"}, + {"literal backslash before continuation", "1a\\\nx\\\\\\\ny", "l1\nx\\\ny\nl2\nl3\n"}, + {"literal backslash at end", "1a\\\nx\\\\", "l1\nx\\\nl2\nl3\n"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + fs := testFS() + fs.AddFile("/docs/append.txt", "l1\nl2\nl3\n") + out, errOut, code := execCmd(t, fs, "cat /docs/append.txt | sed '"+tt.expr+"'") + if code != 0 || errOut != "" || out != tt.want { + t.Fatalf("code=%d stdout=%q stderr=%q, want %q", code, out, errOut, tt.want) + } + out, errOut, code = execCmd(t, fs, "sed -i '"+tt.expr+"' /docs/append.txt") + if code != 0 || out != "" || errOut != "" { + t.Fatalf("in-place: code=%d stdout=%q stderr=%q", code, out, errOut) + } + content, err := fs.ReadFile("/docs/append.txt") + if err != nil || string(content) != tt.want { + t.Fatalf("in-place content=%q err=%v, want %q", content, err, tt.want) + } + }) + } +} + func TestSedRejectsUnsupportedCommands(t *testing.T) { tests := []struct { name string