Skip to content

Commit

Permalink
replacer: {file.*} global placeholder strips trailing newline (cadd…
Browse files Browse the repository at this point in the history
…yserver#6411)

Co-authored-by: Kanashimia <[email protected]>
  • Loading branch information
steffenbusch and kanashimia authored Aug 7, 2024
1 parent 59cbb2c commit b85b6c6
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
foo

Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
foo
3 changes: 3 additions & 0 deletions replacer.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package caddy

import (
"bytes"
"fmt"
"io"
"net/http"
Expand Down Expand Up @@ -354,6 +355,8 @@ func (f fileReplacementProvider) replace(key string) (any, bool) {
zap.Error(err))
return nil, true
}
body = bytes.TrimSuffix(body, []byte("\n"))
body = bytes.TrimSuffix(body, []byte("\r"))
return string(body), true
}

Expand Down
15 changes: 15 additions & 0 deletions replacer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +431,14 @@ func TestReplacerNew(t *testing.T) {
variable: "file.caddytest/integration/testdata/foo.txt",
value: "foo",
},
{
variable: "file.caddytest/integration/testdata/foo_with_trailing_newline.txt",
value: "foo",
},
{
variable: "file.caddytest/integration/testdata/foo_with_multiple_trailing_newlines.txt",
value: "foo" + getEOL(),
},
} {
if val, ok := repl.providers[1].replace(tc.variable); ok {
if val != tc.value {
Expand All @@ -442,6 +450,13 @@ func TestReplacerNew(t *testing.T) {
}
}

func getEOL() string {
if os.PathSeparator == '\\' {
return "\r\n" // Windows EOL
}
return "\n" // Unix and modern macOS EOL
}

func TestReplacerNewWithoutFile(t *testing.T) {
repl := NewReplacer().WithoutFile()

Expand Down

0 comments on commit b85b6c6

Please sign in to comment.