Skip to content

Commit

Permalink
add default title setting based on h1
Browse files Browse the repository at this point in the history
  • Loading branch information
jtarchie committed Mar 31, 2023
1 parent 35b3e58 commit b5e7e7b
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 7 deletions.
21 changes: 21 additions & 0 deletions builder_suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,27 @@ var _ = Describe("Builder", func() {
})
})

When("rendering documents without frontmatter", func() {
It("errors on no title", func() {
createLayout()
createFile("index.md", "some text")

err := cli.Run(logger)
Expect(err).To(HaveOccurred())
})

It("uses H1 for the title", func() {
createLayout()
createFile("index.md", "# some title")

err := cli.Run(logger)
Expect(err).NotTo(HaveOccurred())

contents := readFile("index.html")
Expect(contents).To(ContainSubstring("<title>some title</title>"))
})
})

When("rendering a file with template functions", func() {
BeforeEach(func() {
createLayout()
Expand Down
23 changes: 16 additions & 7 deletions markdown_doc.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
htmlTemplate "html/template"
"os"
"path/filepath"
"regexp"
"strings"

"github.com/yuin/goldmark"
Expand Down Expand Up @@ -40,6 +41,8 @@ func NewMarkdownDoc(
}
}

var titleFromHeader = regexp.MustCompile(`(?m)^#\s+(.*)$`)

func (m *markdownDoc) Write(
layout *htmlTemplate.Template,
converter goldmark.Markdown,
Expand Down Expand Up @@ -89,15 +92,21 @@ func (m *markdownDoc) Write(
return fmt.Errorf("could not create file (%s): %w", newPath, err)
}

d := frontmatter.Get(ctx)
if d == nil {
return fmt.Errorf("frontmatter required (%s)", m.filename)
}

meta := &metadataPayload{}
d := frontmatter.Get(ctx)

if err := d.Decode(meta); err != nil {
return fmt.Errorf("could not decode front matter (%s): %w", m.filename, err)
switch {
case d == nil:
matches := titleFromHeader.FindAllStringSubmatch(evaluated.String(), 1)
if len(matches) == 0 {
return fmt.Errorf("frontmatter required with (%s)", m.filename)
}

meta.Title = matches[0][1]
default:
if err := d.Decode(meta); err != nil {
return fmt.Errorf("could not decode front matter (%s): %w", m.filename, err)
}
}

err = layout.Execute(file, map[string]any{
Expand Down

0 comments on commit b5e7e7b

Please sign in to comment.