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
|
package main
import (
"flag"
"fmt"
"os"
"path/filepath"
"github.com/pelletier/go-toml/v2"
"go.jolheiser.com/blog"
"gopkg.in/yaml.v3"
)
type args struct {
ArticleDir string `yaml:"article-dir" toml:"article-dir"`
TemplateDir string `yaml:"template-dir" toml:"template-dir"`
OutDir string `yaml:"out-dir" toml:"out-dir"`
Author blog.Author `yaml:"author" toml:"author"`
}
func main() {
if err := maine(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func maine() error {
var args args
fs := flag.NewFlagSet("blog", flag.ExitOnError)
configFlag := fs.String("config", "", "Configuration, TOML or YAML")
fs.StringVar(configFlag, "c", *configFlag, "--config")
articlesFlag := fs.String("articles", "", "Path to articles")
fs.StringVar(articlesFlag, "a", *articlesFlag, "--articles")
templatesFlag := fs.String("templates", "", "Path to templates")
fs.StringVar(templatesFlag, "t", *templatesFlag, "--templates")
outFlag := fs.String("out", "", "Path to output")
fs.StringVar(outFlag, "o", *outFlag, "--out")
if err := fs.Parse(os.Args[1:]); err != nil {
return err
}
if *configFlag != "" {
data, err := os.ReadFile(*configFlag)
if err != nil {
return err
}
switch ext := filepath.Ext(*configFlag); ext {
case ".yaml", ".yml":
if err := yaml.Unmarshal(data, &args); err != nil {
return err
}
case ".toml":
if err := toml.Unmarshal(data, &args); err != nil {
return err
}
default:
return fmt.Errorf("could not determine config type %q", ext)
}
}
if *articlesFlag != "" {
args.ArticleDir = *articlesFlag
}
if args.ArticleDir == "" {
args.ArticleDir = "articles"
}
if *templatesFlag != "" {
args.TemplateDir = *templatesFlag
}
if args.TemplateDir == "" {
args.TemplateDir = "templates"
}
if *outFlag != "" {
args.OutDir = *outFlag
}
if args.OutDir == "" {
args.OutDir = "out"
}
if err := os.MkdirAll(args.OutDir, os.ModePerm); err != nil {
return err
}
blog, err := blog.NewBlog(args.ArticleDir, args.TemplateDir, args.Author)
if err != nil {
return err
}
indexFile, err := os.Create(filepath.Join(args.OutDir, "index.html"))
if err != nil {
return err
}
defer indexFile.Close()
if err := blog.Index(indexFile); err != nil {
return err
}
for _, article := range blog.Articles {
if err := func() error {
articleFile, err := os.Create(filepath.Join(args.OutDir, article.Filename+".html"))
if err != nil {
return err
}
defer articleFile.Close()
return blog.Article(articleFile, article)
}(); err != nil {
return err
}
}
return nil
}
|