hswg: take output path for the index as argument

This commit is contained in:
Přemysl Eric Janouch 2021-06-22 02:34:24 +02:00
parent d763ce619d
commit 49a685c32e
Signed by: p
GPG Key ID: A0420B94F92B9493
1 changed files with 29 additions and 19 deletions

View File

@ -284,7 +284,8 @@ func finalizeEntries(entries *map[string]*Entry) {
} }
} }
func writeIndex(t *template.Template, entries *map[string]*Entry) error { func writeIndex(path string, t *template.Template,
entries *map[string]*Entry) error {
// Reorder entries reversely, primarily by date, secondarily by filename. // Reorder entries reversely, primarily by date, secondarily by filename.
ordered := []*Entry{} ordered := []*Entry{}
for _, e := range *entries { for _, e := range *entries {
@ -309,8 +310,13 @@ func writeIndex(t *template.Template, entries *map[string]*Entry) error {
return p2.Before(*p1) return p2.Before(*p1)
}) })
f, err := os.Create(path)
if err != nil {
return err
}
// TODO(p): Splitting content to categories would be nice. // TODO(p): Splitting content to categories would be nice.
return t.Execute(os.Stdout, ordered) return t.Execute(f, ordered)
} }
func singleFile() { func singleFile() {
@ -330,43 +336,47 @@ func main() {
singleFile() singleFile()
return return
} }
if len(os.Args) < 3 { if len(os.Args) < 4 {
log.Fatalf("usage: %s TEMPLATE GLOB...\n", os.Args[0]) log.Fatalf("usage: %s TEMPLATE INDEX GLOB...\n", os.Args[0])
} }
// Read the common page header. argTemplate, argIndex, argGlobs := os.Args[1], os.Args[2], os.Args[3:]
header, err := ioutil.ReadFile(os.Args[1])
// Read a template for entries.
header, err := ioutil.ReadFile(argTemplate)
if err != nil { if err != nil {
log.Fatalln(err) log.Fatalln(err)
} }
t, err := template.New("page").Parse(string(header)) tmplEntry, err := template.New("entry").Parse(string(header))
if err != nil {
log.Fatalln(err)
}
// Read a template for the index from the standard input.
index, err := ioutil.ReadAll(os.Stdin)
if err != nil {
log.Fatalln(err)
}
tmplIndex, err := template.New("index").Parse(string(index))
if err != nil { if err != nil {
log.Fatalln(err) log.Fatalln(err)
} }
// Process all entries. // Process all entries.
entries, err := loadEntries(os.Args[2:]) entries, err := loadEntries(argGlobs)
if err != nil { if err != nil {
log.Fatalln(err) log.Fatalln(err)
} }
finalizeEntries(&entries) finalizeEntries(&entries)
for _, e := range entries { for _, e := range entries {
if err := writeEntry(e, t, &entries); err != nil { if err := writeEntry(e, tmplEntry, &entries); err != nil {
log.Fatalln(err) log.Fatalln(err)
} }
} }
// Read a template from the standard input, write an index. // Write an index.
var input []byte if err := writeIndex(argIndex, tmplIndex, &entries); err != nil {
if input, err = ioutil.ReadAll(os.Stdin); err != nil {
log.Fatalln(err)
}
t, err = template.New("-").Parse(string(input))
if err != nil {
log.Fatalln(err)
}
if err := writeIndex(t, &entries); err != nil {
log.Fatalln(err) log.Fatalln(err)
} }
} }