diff --git a/internal/frontmatter/frontmatter.go b/internal/frontmatter/frontmatter.go index b3e7813..1ad3625 100644 --- a/internal/frontmatter/frontmatter.go +++ b/internal/frontmatter/frontmatter.go @@ -1,6 +1,7 @@ package frontmatter import ( + "fmt" "strings" "gopkg.in/yaml.v1" @@ -28,7 +29,16 @@ func Parse(markdown string) (string, Frontmatter, error) { // otherwise, split the frontmatter and cheatsheet text parts := strings.SplitN(markdown, delim, 3) - err := yaml.Unmarshal([]byte(parts[1]), &fm) - return strings.TrimSpace(parts[2]), fm, err + // return an error if the frontmatter parses into the wrong number of parts + if len(parts) != 3 { + return markdown, fm, fmt.Errorf("failed to delimit frontmatter") + } + + // return an error if the YAML cannot be unmarshalled + if err := yaml.Unmarshal([]byte(parts[1]), &fm); err != nil { + return markdown, fm, fmt.Errorf("failed to unmarshal frontmatter: %v", err) + } + + return strings.TrimSpace(parts[2]), fm, nil } diff --git a/internal/frontmatter/frontmatter_test.go b/internal/frontmatter/frontmatter_test.go index d6c8e32..4a0159a 100644 --- a/internal/frontmatter/frontmatter_test.go +++ b/internal/frontmatter/frontmatter_test.go @@ -69,3 +69,27 @@ func TestHasNoFrontmatter(t *testing.T) { t.Errorf("failed to parse tags: want: len 0, got: len %d", len(fm.Tags)) } } + +// TestHasInvalidFrontmatter asserts that markdown is properly parsed when it +// contains invalid frontmatter +func TestHasInvalidFrontmatter(t *testing.T) { + + // stub our cheatsheet content (with invalid frontmatter) + markdown := `--- +syntax: go +tags: [ test ] +To foo the bar: baz` + + // parse the frontmatter + text, _, err := Parse(markdown) + + // assert that an error was returned + if err == nil { + t.Error("failed to error on invalid frontmatter") + } + + // assert that the "raw" markdown was returned + if text != markdown { + t.Errorf("failed to parse text: want: %s, got: %s", markdown, text) + } +}