-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
127 lines (113 loc) · 2.48 KB
/
main.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
package main
import (
"fmt"
"html/template"
"io"
"io/ioutil"
"log"
"net/url"
"os"
"path/filepath"
"strings"
)
var (
repoURL = "https://github.com/piotrpersona/sheetmusic"
branch = "main"
directory = "pdf"
readmeFile = "README.md"
ghPagesIndex = "docs/index.md"
readmeTemplate = "templates/README.md.tmpl"
ghPagesTemplate = "templates/index.md.tmpl"
)
type PDF struct {
Name string
DownloadURL string
}
type TemplateData struct {
PDFs []PDF
}
func panicErr(err error) {
if err != nil {
log.Printf("Panic: %v\n", err)
panic(err)
}
}
func listDirectory(rootPath string) (files []string, err error) {
fileInfos, err := ioutil.ReadDir(rootPath)
if err != nil {
return
}
for _, info := range fileInfos {
if info.IsDir() {
continue
}
fileName := info.Name()
if matched, err := filepath.Match("*.pdf", fileName); matched && err == nil {
files = append(files, fileName)
}
}
return
}
func createRawURL(name string) (raw string) {
return fmt.Sprintf("%s/raw/%s/%s/%s", repoURL, branch, directory, name)
}
func constructPDFs(names []string) (pdfs []PDF, err error) {
for _, name := range names {
rawURL := createRawURL(name)
parsedURL, parseErr := url.Parse(rawURL)
if parseErr != nil {
err = parseErr
return
}
pdf := PDF{
Name: name,
DownloadURL: parsedURL.String(),
}
pdfs = append(pdfs, pdf)
}
return
}
func templateDocument(templateFile string, templateData TemplateData, writers ...io.Writer) (err error) {
tmpl, err := template.New(strings.Split(templateFile, "/")[1]).ParseFiles(templateFile)
if err != nil {
return
}
for _, writer := range writers {
err = tmpl.Execute(writer, templateData)
if err != nil {
return
}
}
return
}
func main() {
files, err := listDirectory("pdf")
panicErr(err)
pdfs, err := constructPDFs(files)
panicErr(err)
readmeWriter, err := os.OpenFile(readmeFile, os.O_WRONLY, os.ModeAppend)
panicErr(err)
if readmeWriter != nil {
defer func() {
err = readmeWriter.Close()
panicErr(err)
}()
}
ghPagesWriter, err := os.OpenFile(ghPagesIndex, os.O_WRONLY, os.ModeAppend)
panicErr(err)
if ghPagesWriter != nil {
defer func() {
err = ghPagesWriter.Close()
panicErr(err)
}()
}
templateData := TemplateData{PDFs: pdfs}
templateWriterMap := map[string]io.Writer{
readmeTemplate: readmeWriter,
ghPagesTemplate: ghPagesWriter,
}
for templateFile, writer := range templateWriterMap {
err = templateDocument(templateFile, templateData, writer)
panicErr(err)
}
}