67 lines
1.2 KiB
Go
67 lines
1.2 KiB
Go
package markdown
|
|
|
|
import (
|
|
"bufio"
|
|
"errors"
|
|
"io"
|
|
"strings"
|
|
|
|
"github.com/pelletier/go-toml/v2"
|
|
)
|
|
|
|
func isSeparator(line string) bool {
|
|
line = strings.TrimSpace(line)
|
|
for i := 0; i < len(line); i++ {
|
|
if line[i] != '-' {
|
|
return false
|
|
}
|
|
}
|
|
return len(line) > 2
|
|
}
|
|
|
|
// Meta reads from r to extract TOML frontmatter
|
|
func Meta(r io.Reader, out interface{}) error {
|
|
var content strings.Builder
|
|
scanner := bufio.NewScanner(r)
|
|
var seps int
|
|
for scanner.Scan() {
|
|
line := scanner.Text()
|
|
if seps == 0 && content.Len() == 0 && !isSeparator(line) {
|
|
return errors.New("no beginning separator")
|
|
}
|
|
if isSeparator(line) {
|
|
seps++
|
|
if content.Len() == 0 {
|
|
continue
|
|
}
|
|
break
|
|
}
|
|
content.WriteString(line + "\n")
|
|
}
|
|
if seps != 2 {
|
|
return errors.New("no ending separator")
|
|
}
|
|
|
|
if content.Len() > 0 {
|
|
return toml.Unmarshal([]byte(content.String()), out)
|
|
}
|
|
return errors.New("no content")
|
|
}
|
|
|
|
// Content skips meta and returns document content
|
|
func Content(r io.Reader) (string, error) {
|
|
var s strings.Builder
|
|
scanner := bufio.NewScanner(r)
|
|
var seps int
|
|
for scanner.Scan() {
|
|
if seps < 2 && isSeparator(scanner.Text()) {
|
|
seps++
|
|
continue
|
|
}
|
|
if seps >= 2 {
|
|
s.WriteString(scanner.Text() + "\n")
|
|
}
|
|
}
|
|
return s.String(), nil
|
|
}
|