Skip to content

Commit

Permalink
TIL-7 Tags into pages
Browse files Browse the repository at this point in the history
Signed-off-by: Chris Cummer <chriscummer@me.com>
  • Loading branch information
senorprogrammer committed Aug 1, 2021
1 parent 91ac7f6 commit ec7a35b
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
12 changes: 12 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,11 +112,23 @@ func main() {

func buildContent() {
pages := loadPages()
buildContentPages(pages)
tagMap := buildTagPages(pages)

buildIndexPage(pages, tagMap)
}

// buildContentPages loops through all the pages and tells them to save themselves
// to disk. This process writes any auto-generated content into the pages
func buildContentPages(pages []*pages.Page) {
for _, page := range pages {
if page.IsContentPage() {
page.AppendTagsToContent()
page.Save()
}
}
}

// buildIndexPage creates the main index.md page that is the root of the site
func buildIndexPage(pageSet []*pages.Page, tagMap *pages.TagMap) {
src.Info(statusIdxBuild)
Expand Down
42 changes: 42 additions & 0 deletions pages/page.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"io/ioutil"
"os/exec"
"path/filepath"
"regexp"
"strings"
"time"

Expand Down Expand Up @@ -50,6 +51,47 @@ func NewPage(title string, targetDir string) *Page {
return page
}

// AppendTagsToContent programatically modifies the page content to save auto-included
// content like the tag list
func (page *Page) AppendTagsToContent() bool {
if len(page.Tags()) == 0 {
return true
}

tagLinks := []string{}
for _, tag := range page.Tags() {
if tag.Link() != "" {
tagLinks = append(tagLinks, tag.Link())
}
}

tagList := strings.Join(tagLinks, ", ")

// Tags
tagsStartStr := "<!-- TAGS:START -->"
tagsEndStr := "<!-- TAGS:END -->"

re := fmt.Sprintf("`%s\n.*\n%s`", tagsStartStr, tagsEndStr)
rg := regexp.MustCompile(re)

newContent := rg.ReplaceAllString(page.Content, tagList)

if page.Content != newContent {
// Swap the old content with the new content
page.Content = newContent
} else {
// Append the tag list to the end of the page
page.Content += fmt.Sprintf(
"\n%s\n%s\n%s\n",
tagsStartStr,
tagList,
tagsEndStr,
)
}

return true
}

// PageFromFilePath creates and returns a Page instance from a file path
func PageFromFilePath(filePath string) *Page {
page := new(Page)
Expand Down

0 comments on commit ec7a35b

Please sign in to comment.