Skip to content

Commit

Permalink
templates: trim windows whitespace in SplitFrontMatter; fix #3386 (#3387
Browse files Browse the repository at this point in the history
)

* add test case for SplitFrontMatter showing issue with windows newline

* fix issue with windows newline when using SplitFrontMatter

* Update modules/caddyhttp/templates/frontmatter.go

Co-authored-by: Francis Lavoie <lavofr@gmail.com>

* make it mere explicit what is trimmed from firstLine

* Update modules/caddyhttp/templates/frontmatter.go

Co-authored-by: Francis Lavoie <lavofr@gmail.com>
Co-authored-by: Matt Holt <mholt@users.noreply.github.com>
  • Loading branch information
3 people authored May 18, 2020
1 parent 41a682d commit 483e31b
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
3 changes: 3 additions & 0 deletions modules/caddyhttp/templates/frontmatter.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ func extractFrontMatter(input string) (map[string]interface{}, string, error) {
}
firstLine := input[firstLineStart:firstLineEnd]

// ensure residue windows carriage return byte is removed
firstLine = strings.TrimSpace(firstLine)

// see what kind of front matter there is, if any
var closingFence string
var fmParser func([]byte) (map[string]interface{}, error)
Expand Down
45 changes: 45 additions & 0 deletions modules/caddyhttp/templates/tplcontext_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,51 @@ func TestFileListing(t *testing.T) {
}
}

func TestSplitFrontMatter(t *testing.T) {
context := getContextOrFail(t)

for i, test := range []struct {
input string
expect string
}{
{
// yaml with windows newline
input: "---\r\ntitle: Welcome\r\n---\r\n# Test\\r\\n",
expect: `Welcome`,
},
{
// yaml
input: `---
title: Welcome
---
### Test`,
expect: `Welcome`,
},
{
// toml
input: `+++
title = "Welcome"
+++
### Test`,
expect: `Welcome`,
},
{
// json
input: `{
"title": "Welcome"
}
### Test`,
expect: `Welcome`,
},
} {
result, _ := context.funcSplitFrontMatter(test.input)
if result.Meta["title"] != test.expect {
t.Errorf("Test %d: Expected %s, found %s. Input was SplitFrontMatter(%s)", i, test.expect, result.Meta["title"], test.input)
}
}

}

func getContextOrFail(t *testing.T) templateContext {
context, err := initTestContext()
if err != nil {
Expand Down

0 comments on commit 483e31b

Please sign in to comment.