-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli.go
99 lines (81 loc) · 2.51 KB
/
cli.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
package builder
import (
"fmt"
"log"
"log/slog"
"path/filepath"
"github.com/bmatcuk/doublestar/v4"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
type CLI struct {
AssetsPath string `help:"path to static assets (default with be source-path/public)"`
BaseURL string `help:"the URL which the contents will be served from, this is only used for generating feeds"`
BuildPath string `help:"where generated content should go" required:"" type:"path"`
FeedGlob string `help:"glob patterns for documents to feature in feeds"`
LayoutFilename string `default:"layout.html" help:"layout file to render" required:""`
Serve bool `help:"serve when done building"`
SourcePath string `help:"source of all files" required:"" type:"path"`
}
func (c *CLI) Run() error {
if c.AssetsPath == "" {
c.AssetsPath = filepath.Join(c.SourcePath, "public")
}
renderer := NewRender(
filepath.Join(c.SourcePath, c.LayoutFilename),
c.SourcePath,
c.AssetsPath,
c.BuildPath,
c.BaseURL,
)
markdownGlob := filepath.Join(c.SourcePath, "**", "*.md")
if c.FeedGlob == "" {
c.FeedGlob = markdownGlob
} else {
c.FeedGlob = filepath.Join(c.SourcePath, c.FeedGlob)
}
err := renderer.Execute(
markdownGlob,
c.FeedGlob,
)
if err != nil {
return fmt.Errorf("could not execute render: %w", err)
}
if c.Serve {
watcher := NewWatcher(c.SourcePath)
go c.startWatcher(watcher, renderer, markdownGlob, c.FeedGlob)
e := echo.New()
e.Use(middleware.Logger())
e.Static("/", c.BuildPath)
err = e.Start(":8080")
if err != nil {
return fmt.Errorf("could not start serving: %w", err)
}
}
return nil
}
func (c *CLI) startWatcher(
watcher *Watcher,
renderer *Render,
markdownGlob string,
feedGlob string,
) {
allGlob := filepath.Join(c.SourcePath, "**", "{*.md,*.html,*.js,*.css}")
err := watcher.Execute(func(filename string) error {
matched, _ := doublestar.Match(allGlob, filename)
if matched {
slog.Info("rebuilding markdown files", slog.String("filename", filename))
err := renderer.Execute(
markdownGlob,
feedGlob,
)
if err != nil {
slog.Error("could not rebuild markdown files", slog.String("error", err.Error()))
}
}
return nil
})
if err != nil {
log.Fatalf("could not run watcher: %s", err)
}
}