mirror of https://github.com/cheat/cheat.git
fix(frontmatter): resolve issue #544
- Fix error in `frontmatter.Parse` which would cause a `panic` when encountering malformed frontmatter - Add a unit-test to cover the above
This commit is contained in:
parent
bddbee4158
commit
5288bd0c1c
|
@ -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
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue