Merge pull request #545 from chrisallenlane/issue-544

fix(frontmatter): resolve #544
This commit is contained in:
Chris Allen Lane 2020-03-11 19:03:06 -04:00 committed by GitHub
commit 521f83377c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 44 additions and 5 deletions

View File

@ -17,7 +17,7 @@ import (
"github.com/cheat/cheat/internal/installer"
)
const version = "3.7.0"
const version = "3.7.1"
func main() {

View File

@ -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
}

View File

@ -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)
}
}

View File

@ -33,7 +33,7 @@ func Load(cheatpaths []cp.Cheatpath) ([]map[string]sheet.Sheet, error) {
// fail if an error occurred while walking the directory
if err != nil {
return fmt.Errorf("error walking path: %v", err)
return fmt.Errorf("failed to walk path: %v", err)
}
// don't register directories as cheatsheets
@ -61,7 +61,12 @@ func Load(cheatpaths []cp.Cheatpath) ([]map[string]sheet.Sheet, error) {
// parse the cheatsheet file into a `sheet` struct
s, err := sheet.New(title, path, cheatpath.Tags, cheatpath.ReadOnly)
if err != nil {
return fmt.Errorf("could not create sheet: %v", err)
return fmt.Errorf(
"failed to load sheet: %s, path: %s, err: %v",
title,
path,
err,
)
}
// register the cheatsheet on its cheatpath, keyed by its title