cheat/internal/sheet/parse.go
Christopher Allen Lane 2d635293c5 refactor(Sheet): create parse method
Move `Frontmatter.Parse` to `Sheet.parse`, and delete the `frontmatter`
package. `Sheet.parse` more accurately describes the parser's behavior.
2022-08-26 13:55:09 -04:00

46 lines
1.1 KiB
Go

package sheet
import (
"fmt"
"runtime"
"strings"
"gopkg.in/yaml.v1"
)
// Parse parses cheatsheet frontmatter
func parse(markdown string) (frontmatter, string, error) {
// determine the appropriate line-break for the platform
linebreak := "\n"
if runtime.GOOS == "windows" {
linebreak = "\r\n"
}
// specify the frontmatter delimiter
delim := fmt.Sprintf("---%s", linebreak)
// initialize a frontmatter struct
var fm frontmatter
// if the markdown does not contain frontmatter, pass it through unmodified
if !strings.HasPrefix(markdown, delim) {
return fm, markdown, nil
}
// otherwise, split the frontmatter and cheatsheet text
parts := strings.SplitN(markdown, delim, 3)
// return an error if the frontmatter parses into the wrong number of parts
if len(parts) != 3 {
return fm, markdown, 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 fm, markdown, fmt.Errorf("failed to unmarshal frontmatter: %v", err)
}
return fm, parts[2], nil
}