template.go - staticgit - A git static site generator in GO with HTML output!
(HTM) git clone git://jay.scot/staticgit
(DIR) Log
(DIR) Files
(DIR) Refs
(DIR) README
---
template.go (2004B)
---
1 package template
2
3 import (
4 "embed"
5 "fmt"
6 "html/template"
7 "io"
8 "log"
9 "os"
10 "path/filepath"
11 "sort"
12
13 "staticgit/internal/repo"
14 )
15
16 //go:embed templates/*
17 var templateFS embed.FS
18
19 var (
20 templates = map[string]*template.Template{}
21 )
22
23 func init() {
24 for _, name := range []string{"index", "detail"} {
25 baseContent, err := templateFS.ReadFile("templates/base.html")
26 if err != nil {
27 log.Fatalf("Failed to read base.html: %v", err)
28 }
29
30 contentFile := fmt.Sprintf("templates/%s.html", name)
31 contentContent, err := templateFS.ReadFile(contentFile)
32 if err != nil {
33 log.Fatalf("Failed to read %s: %v", contentFile, err)
34 }
35
36 t, err := template.New(name).Parse(string(baseContent) + string(contentContent))
37 if err != nil {
38 log.Fatalf("Failed to parse %s template: %v", name, err)
39 }
40
41 templates[name] = t
42 }
43 }
44
45 func GenerateIndex(outDir string, repos []*repo.Repo) error {
46 sort.Slice(repos, func(i, j int) bool {
47 return repos[i].LastMod.After(repos[j].LastMod)
48 })
49
50 path := filepath.Join(outDir, "index.html")
51
52 f, err := os.Create(path)
53 if err != nil {
54 return fmt.Errorf("create index HTML: %w", err)
55 }
56 defer f.Close()
57
58 return executeTemplate("index", f, struct {
59 Title string
60 Repos []*repo.Repo
61 }{
62 Title: "Repos for days!",
63 Repos: repos,
64 })
65 }
66
67 func GenerateRepoPage(name, readmeContent string, commits []repo.Commit, files []string, outPath string) error {
68 f, err := os.Create(outPath)
69 if err != nil {
70 return fmt.Errorf("create details HTML: %w", err)
71 }
72 defer f.Close()
73
74 return executeTemplate("detail", f, struct {
75 Title string
76 ReadmeContent string
77 Files []string
78 Commits []repo.Commit
79 }{
80 Title: "git clone git://jay.scot/" + name,
81 ReadmeContent: readmeContent,
82 Files: files,
83 Commits: commits,
84 })
85 }
86
87 func executeTemplate(name string, w io.Writer, data interface{}) error {
88 t, ok := templates[name]
89 if !ok {
90 return fmt.Errorf("template %s not found", name)
91 }
92
93 return t.Execute(w, data)
94 }