aboutsummaryrefslogtreecommitdiff
path: root/page/index.go
blob: 7dd736e701a5d27109a241ff0b14690fbd6a0a1c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package page

import (
	"io/fs"
	"path/filepath"
	"strings"
	"sync"
	"time"
)

var (
	index   map[string]PageList
	indexMu sync.RWMutex
)

// RebuildIndex can be called in order to rebuild the entire website
// index.
func (p *Page) RebuildIndex() error {
	indexMu.Lock()
	index = nil
	indexMu.Unlock()

	_, err := p.Index()

	return err
}

// Index returns a map of all pages in the current directory separated into
// their respective tags If a Page has multiple tags it will be listed under
// each.
// Pages are located by their Suffix, default being ".md".
func (p *Page) Index() (map[string]PageList, error) {
	indexMu.RLock()
	if index != nil && CacheIndex {
		indexMu.RUnlock()

		return index, nil
	}
	indexMu.RUnlock()
	Logger.Println("Rebuilding index...")

	out := make(map[string]PageList)

	_ = filepath.Walk(".",
		func(path string, info fs.FileInfo, err error) error {
			if err != nil {
				return err
			}

			if !info.IsDir() && strings.HasSuffix(info.Name(), Suffix) {
				if path == BaseTemplate { // Plain template, not a page
					return nil
				}
				p2 := NewPage(strings.ReplaceAll(path, Suffix, ""))
				err = p2.Read()

				if err != nil {
					Logger.Printf("Error encountered: %s: %s\n",
						path, err)

					return err
				}

				for tag := range p2.Tags {
					if _, ok := out[tag]; !ok {
						out[tag] = []*Page{p2}
					} else {
						out[tag] = append(out[tag], p2)
					}
				}
			}

			return nil
		})

	indexMu.Lock()
	index = out
	indexMu.Unlock()

	return out, nil
}

// Time fetches the time.Time from the Date field.
func (p *Page) Time() time.Time {
	return p.Date.Time
}