forked from maaslalani/slides
-
Notifications
You must be signed in to change notification settings - Fork 0
/
meta.go
131 lines (112 loc) · 2.46 KB
/
meta.go
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
// Package meta implements markdown frontmatter parsing for simple
// slides configuration
package meta
import (
"os"
"os/user"
"strings"
"time"
"gopkg.in/yaml.v2"
)
// Temporary structure to differentiate values not present in the YAML header
// from values set to empty strings in the YAML header. We replace values not
// set by defaults values when parsing a header.
type parsedMeta struct {
Theme *string `yaml:"theme"`
Author *string `yaml:"author"`
Date *string `yaml:"date"`
Paging *string `yaml:"paging"`
}
// Meta contains all of the data to be parsed
// out of a markdown file's header section
type Meta struct {
Theme string
Author string
Date string
Paging string
}
// New creates a new instance of the
// slideshow meta header object
func New() *Meta {
return &Meta{}
}
// Parse parses metadata from a slideshows header slide
// including theme information
//
// If no front matter is provided, it will fallback to the default theme and
// return false to acknowledge that there is no front matter in this slide
func (m *Meta) Parse(header string) (*Meta, bool) {
fallback := &Meta{
Theme: defaultTheme(),
Author: defaultAuthor(),
Date: defaultDate(),
Paging: defaultPaging(),
}
var tmp parsedMeta
err := yaml.Unmarshal([]byte(header), &tmp)
if err != nil {
return fallback, false
}
if tmp.Theme != nil {
m.Theme = *tmp.Theme
} else {
m.Theme = fallback.Theme
}
if tmp.Author != nil {
m.Author = *tmp.Author
} else {
m.Author = fallback.Author
}
if tmp.Date != nil {
parsedDate := parseDate(*tmp.Date)
if parsedDate == *tmp.Date {
m.Date = *tmp.Date
} else {
m.Date = time.Now().Format(parsedDate)
}
} else {
m.Date = fallback.Date
}
if tmp.Paging != nil {
m.Paging = *tmp.Paging
} else {
m.Paging = fallback.Paging
}
return m, true
}
func defaultTheme() string {
theme := os.Getenv("GLAMOUR_STYLE")
if theme == "" {
return "default"
}
return theme
}
func defaultAuthor() string {
user, err := user.Current()
if err != nil {
return ""
}
return user.Name
}
func defaultDate() string {
return time.Now().Format(parseDate("YYYY-MM-DD"))
}
func defaultPaging() string {
return "Slide %d / %d"
}
func parseDate(value string) string {
pairs := [][]string{
{"YYYY", "2006"},
{"YY", "06"},
{"MMMM", "January"},
{"MMM", "Jan"},
{"MM", "01"},
{"mm", "1"},
{"DD", "02"},
{"dd", "2"},
}
for _, p := range pairs {
value = strings.ReplaceAll(value, p[0], p[1])
}
return value
}