Generate index page with reports

This commit is contained in:
Matt Baer 2016-03-07 16:03:32 -05:00
parent 38a2c39509
commit 917025c260
3 changed files with 50 additions and 2 deletions

19
index.tmpl Normal file
View File

@ -0,0 +1,19 @@
<!DOCTYPE html>
<html>
<head>
<title>life reports.</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<div id="wrap">
<h1>life reports</h1>
<ul>
{{range .}}
<li><a href="{{.File}}">No. {{.Num}}: {{.Month}} {{.Year}}</a></li>
{{end}}
</ul>
<hr />
</div>
</body>
</html>

View File

@ -16,6 +16,7 @@ type (
// various areas of a given person's life for the given time period -- // various areas of a given person's life for the given time period --
// in this case, a month. // in this case, a month.
Report struct { Report struct {
File string
Num int Num int
Month string Month string
Year int `json:"year"` Year int `json:"year"`
@ -50,8 +51,8 @@ func ParseReport(f *os.File) (*Report, error) {
// Determine report number and month from filename in the format // Determine report number and month from filename in the format
// NNN-month.json // NNN-month.json
baseName := path.Base(f.Name()) r.File = path.Base(f.Name())
fd := strings.Split(baseName[:strings.Index(baseName, ".json")], "-") fd := strings.Split(r.File[:strings.Index(r.File, ".json")], "-")
if len(fd) >= 2 { if len(fd) >= 2 {
r.Num, err = strconv.Atoi(fd[0]) r.Num, err = strconv.Atoi(fd[0])
if err != nil { if err != nil {
@ -66,3 +67,10 @@ func ParseReport(f *os.File) (*Report, error) {
return &r, nil return &r, nil
} }
// ByNum implements sort.Interface for []Report based on the Num field.
type ByNum []Report
func (n ByNum) Len() int { return len(n) }
func (n ByNum) Swap(i, j int) { n[i], n[j] = n[j], n[i] }
func (n ByNum) Less(i, j int) bool { return n[i].Num < n[j].Num }

View File

@ -6,6 +6,7 @@ import (
"io/ioutil" "io/ioutil"
"os" "os"
"path" "path"
"sort"
"strings" "strings"
report "github.com/thebaer/life-report" report "github.com/thebaer/life-report"
@ -32,6 +33,8 @@ func main() {
return return
} }
var reports []report.Report
for _, file := range files { for _, file := range files {
if file.Name() == "template.json" || !strings.HasSuffix(file.Name(), ".json") { if file.Name() == "template.json" || !strings.HasSuffix(file.Name(), ".json") {
continue continue
@ -64,5 +67,23 @@ func main() {
t.Execute(o, r) t.Execute(o, r)
o.Close() o.Close()
r.File = outName
reports = append(reports, *r)
} }
// Create index file
i, err := os.Create(path.Join(dir, "index.html"))
if err != nil {
fmt.Fprintf(os.Stdout, "Unable to write index: %v\n", err)
return
}
it, err := template.ParseFiles("../index.tmpl")
if err != nil {
fmt.Printf("Unable to parse index template: %v\n", err)
return
}
sort.Sort(sort.Reverse(report.ByNum(reports)))
it.Execute(i, reports)
i.Close()
} }