hugo-micropub/post.go

107 lines
2.6 KiB
Go
Raw Normal View History

2019-11-07 10:00:24 +00:00
package main
import (
"bytes"
2019-11-14 17:46:49 +00:00
"errors"
"gopkg.in/yaml.v2"
"strings"
2019-11-07 10:00:24 +00:00
"time"
)
func writeFrontMatter(entry *Entry) string {
var buff bytes.Buffer
t := time.Now().Format(time.RFC3339)
buff.WriteString("---\n")
if len(entry.title) > 0 {
buff.WriteString("title: \"" + entry.title + "\"\n")
2019-11-07 10:00:24 +00:00
}
buff.WriteString("date: " + t + "\n")
buff.WriteString("tags:\n")
for _, tag := range entry.tags {
2019-11-07 10:00:24 +00:00
buff.WriteString("- " + tag + "\n")
}
if len(entry.link) > 0 {
buff.WriteString("externalURL: " + entry.link + "\n")
}
2019-11-07 10:00:24 +00:00
buff.WriteString("indieweb:\n")
if len(entry.replyLink) > 0 {
buff.WriteString(" reply:\n link: " + entry.replyLink + "\n")
if len(entry.replyTitle) > 0 {
buff.WriteString(" title: " + entry.replyTitle + "\n")
}
2019-11-07 10:00:24 +00:00
}
if len(entry.likeLink) > 0 {
buff.WriteString(" like:\n link: " + entry.likeLink + "\n")
if len(entry.likeTitle) > 0 {
buff.WriteString(" title: " + entry.likeTitle + "\n")
}
}
2019-11-07 10:00:24 +00:00
buff.WriteString("---\n")
return buff.String()
}
func WriteHugoPost(entry *Entry) string {
var buff bytes.Buffer
buff.WriteString(writeFrontMatter(entry))
if len(entry.content) > 0 {
buff.WriteString(entry.content)
2019-11-07 10:00:24 +00:00
}
return buff.String()
}
2019-11-14 17:46:49 +00:00
func readFrontMatter(frontmatter string, entry *Entry) (err error) {
parsedFrontmatter := &struct {
Title string
Date string
Lastmod string
Tags []string
ExternalURL string `yaml:"externalURL"`
Indieweb struct {
Reply struct {
Link string
Title string
}
}
}{}
err = yaml.Unmarshal([]byte(frontmatter), &parsedFrontmatter)
if err != nil {
err = errors.New("failed parsing frontmatter")
}
if len(parsedFrontmatter.Title) > 0 {
entry.title = parsedFrontmatter.Title
}
if len(parsedFrontmatter.Date) > 0 {
entry.date = parsedFrontmatter.Date
}
if len(parsedFrontmatter.Lastmod) > 0 {
entry.lastmod = parsedFrontmatter.Lastmod
}
if len(parsedFrontmatter.Tags) > 0 {
entry.tags = parsedFrontmatter.Tags
}
if len(parsedFrontmatter.ExternalURL) > 0 {
entry.link = parsedFrontmatter.ExternalURL
}
if len(parsedFrontmatter.Indieweb.Reply.Link) > 0 {
entry.replyLink = parsedFrontmatter.Indieweb.Reply.Link
}
if len(parsedFrontmatter.Indieweb.Reply.Title) > 0 {
entry.replyTitle = parsedFrontmatter.Indieweb.Reply.Title
}
return
}
func ReadHugoPost(fileContent string) (entry *Entry, err error) {
parts := strings.Split(fileContent, "---\n")
if len(parts) != 3 {
err = errors.New("empty frontmatter or content")
return
}
entry = new(Entry)
err = readFrontMatter(parts[1], entry)
if err != nil {
return
}
entry.content = strings.TrimSuffix(parts[2], "\n")
return
}