Skip to content

Commit b85b6c6

Browse files
replacer: {file.*} global placeholder strips trailing newline (#6411)
Co-authored-by: Kanashimia <[email protected]>
1 parent 59cbb2c commit b85b6c6

File tree

4 files changed

+21
-0
lines changed

4 files changed

+21
-0
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
foo
2+
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
foo

replacer.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
package caddy
1616

1717
import (
18+
"bytes"
1819
"fmt"
1920
"io"
2021
"net/http"
@@ -354,6 +355,8 @@ func (f fileReplacementProvider) replace(key string) (any, bool) {
354355
zap.Error(err))
355356
return nil, true
356357
}
358+
body = bytes.TrimSuffix(body, []byte("\n"))
359+
body = bytes.TrimSuffix(body, []byte("\r"))
357360
return string(body), true
358361
}
359362

replacer_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -431,6 +431,14 @@ func TestReplacerNew(t *testing.T) {
431431
variable: "file.caddytest/integration/testdata/foo.txt",
432432
value: "foo",
433433
},
434+
{
435+
variable: "file.caddytest/integration/testdata/foo_with_trailing_newline.txt",
436+
value: "foo",
437+
},
438+
{
439+
variable: "file.caddytest/integration/testdata/foo_with_multiple_trailing_newlines.txt",
440+
value: "foo" + getEOL(),
441+
},
434442
} {
435443
if val, ok := repl.providers[1].replace(tc.variable); ok {
436444
if val != tc.value {
@@ -442,6 +450,13 @@ func TestReplacerNew(t *testing.T) {
442450
}
443451
}
444452

453+
func getEOL() string {
454+
if os.PathSeparator == '\\' {
455+
return "\r\n" // Windows EOL
456+
}
457+
return "\n" // Unix and modern macOS EOL
458+
}
459+
445460
func TestReplacerNewWithoutFile(t *testing.T) {
446461
repl := NewReplacer().WithoutFile()
447462

0 commit comments

Comments
 (0)