Make frontmatter splitting work with CRLF files

This commit is contained in:
Sasha Koshka 2024-12-07 16:25:34 -05:00
parent bc08186d30
commit b66b64a327
2 changed files with 44 additions and 2 deletions

View File

@ -12,10 +12,15 @@ type FrontMatter = map[string] string
// representing it along with the rest of the input as a string. If there is no
// front matter, an empty map will be returned.
func SplitFrontMatter (input string) (FrontMatter, string, error) {
// i hate crlf!!!!! uwehhh!!!
input = strings.ReplaceAll(input, "\r\n", "\n")
// stop if there is no front matter
if !strings.HasPrefix(input, frontMatterRule + "\n") {
// no front matter at all
return FrontMatter { }, input, nil
}
// get the start and the end of the front matter
input = strings.TrimPrefix(input, frontMatterRule)
index := strings.Index(input, "\n" + frontMatterRule + "\n")
if index < 0 {
@ -24,6 +29,8 @@ func SplitFrontMatter (input string) (FrontMatter, string, error) {
frontMatterRaw := input[:index]
body := input[index + len(frontMatterRule) + 2:]
frontMatter := make(FrontMatter)
// iterate over the lines
for _, line := range strings.Split(frontMatterRaw, "\n") {
line = strings.TrimSpace(line)
if line == "" { continue }

View File

@ -1,10 +1,11 @@
package step
import "strings"
import "testing"
const quickBrownFox = "The quick brown fox jumped over the lazy dog."
func TestSplitFrontMatter (test *testing.T) {
func TestSplitFrontMatterLF (test *testing.T) {
correctBody :=
`this is some sample text
---
@ -50,3 +51,37 @@ Sentence: ` + quickBrownFox + `
if value3 != "that" { test.Fatal("value is not correct") }
if value4 != quickBrownFox { test.Fatal("value is not correct") }
}
func TestSplitFrontMatterCRLF (test *testing.T) {
correctBody := "this is some sample text\r\n---\r\ntheres another hr that shouldnt\r\nbreak anything\r\nbreak: anything\r\n"
frontMatter, body, err := SplitFrontMatter(
"---\r\nFOO: baR\r\n fOoo: Bar\r\nShouldn't break anything: ---\r\n\r\nthis : that\r\nSentence: " + quickBrownFox + "\r\n---\r\n" + correctBody)
if err != nil {
test.Fatal(err)
}
test.Log("BODY:")
test.Log(body)
correctBody = strings.ReplaceAll(correctBody, "\r\n", "\n")
if body != correctBody {
test.Fatal("body is not correct")
}
test.Log("FRONT MATTER:")
test.Log(frontMatter)
value0, ok := frontMatter["foo"]
if !ok { test.Fatal("missing key") }
value1, ok := frontMatter["fooo"]
if !ok { test.Fatal("missing key") }
value2, ok := frontMatter["shouldn't break anything"]
if !ok { test.Fatal("missing key") }
value3, ok := frontMatter["this"]
if !ok { test.Fatal("missing key") }
value4, ok := frontMatter["sentence"]
if !ok { test.Fatal("missing key") }
if value0 != "baR" { test.Fatal("value is not correct") }
if value1 != "Bar" { test.Fatal("value is not correct") }
if value2 != "---" { test.Fatal("value is not correct") }
if value3 != "that" { test.Fatal("value is not correct") }
if value4 != quickBrownFox { test.Fatal("value is not correct") }
}