Parse parses cheatsheet frontmatter
(markdown string)
| 9 | |
| 10 | // Parse parses cheatsheet frontmatter |
| 11 | func parse(markdown string) (frontmatter, string, error) { |
| 12 | |
| 13 | // detect the line-break style used in the content |
| 14 | linebreak := "\n" |
| 15 | if strings.Contains(markdown, "\r\n") { |
| 16 | linebreak = "\r\n" |
| 17 | } |
| 18 | |
| 19 | // specify the frontmatter delimiter |
| 20 | delim := fmt.Sprintf("---%s", linebreak) |
| 21 | |
| 22 | // initialize a frontmatter struct |
| 23 | var fm frontmatter |
| 24 | |
| 25 | // if the markdown does not contain frontmatter, pass it through unmodified |
| 26 | if !strings.HasPrefix(markdown, delim) { |
| 27 | return fm, markdown, nil |
| 28 | } |
| 29 | |
| 30 | // otherwise, split the frontmatter and cheatsheet text |
| 31 | parts := strings.SplitN(markdown, delim, 3) |
| 32 | |
| 33 | // return an error if the frontmatter parses into the wrong number of parts |
| 34 | if len(parts) != 3 { |
| 35 | return fm, markdown, fmt.Errorf("failed to delimit frontmatter") |
| 36 | } |
| 37 | |
| 38 | // return an error if the YAML cannot be unmarshalled |
| 39 | if err := yaml.Unmarshal([]byte(parts[1]), &fm); err != nil { |
| 40 | return fm, markdown, fmt.Errorf("failed to unmarshal frontmatter: %v", err) |
| 41 | } |
| 42 | |
| 43 | return fm, parts[2], nil |
| 44 | } |
no outgoing calls