-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
336 lines (277 loc) · 8.1 KB
/
Copy pathmain.go
File metadata and controls
336 lines (277 loc) · 8.1 KB
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
package main
import (
"bytes"
"flag"
"fmt"
"html/template"
"log/slog"
"net/http"
"os"
"strings"
"time"
"github.com/fsnotify/fsnotify"
"github.com/gorilla/websocket"
"github.com/yuin/goldmark"
"github.com/yuin/goldmark-highlighting/v2"
"github.com/yuin/goldmark/extension"
)
type PageData struct {
Content template.HTML
}
var logger *slog.Logger
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
type Hub struct {
clients map[*websocket.Conn]bool
broadcast chan []byte
register chan *websocket.Conn
unregister chan *websocket.Conn
}
func newHub() *Hub {
return &Hub{
clients: make(map[*websocket.Conn]bool),
broadcast: make(chan []byte),
register: make(chan *websocket.Conn),
unregister: make(chan *websocket.Conn),
}
}
func (h *Hub) run() {
for {
select {
case client := <-h.register:
h.clients[client] = true
case client := <-h.unregister:
if _, ok := h.clients[client]; ok {
delete(h.clients, client)
client.Close()
}
case message := <-h.broadcast:
for client := range h.clients {
err := client.WriteMessage(websocket.TextMessage, message)
if err != nil {
logger.Error("error writing to client, removing", "err", err)
client.Close()
delete(h.clients, client)
}
}
}
}
}
func serveWs(hub *Hub, w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
logger.Error("failed to upgrade websocket", "err", err)
return
}
hub.register <- conn
go func(c *websocket.Conn) {
defer func() {
hub.unregister <- c
c.Close()
}()
for {
if _, _, err := c.NextReader(); err != nil {
break
}
}
}(conn)
}
func main() {
handler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{})
logger = slog.New(handler)
// single-generation flags
markdownDocument := flag.String("markdown", "post.md", "the input markdown post file")
templateFile := flag.String("template", "template.html", "the template file for the markdown document")
outputFile := flag.String("output", "output.html", "the output html file")
// live reload flags
watch := flag.Bool("watch", false, "watch for changes and reload the template")
serve := flag.Bool("serve", false, "enable server with live reload")
port := flag.String("port", "8080", "port for the server")
flag.Parse()
if markdownDocument == nil || *markdownDocument == "" {
logger.Error("the markdown document flag must be present")
return
}
if templateFile == nil || *templateFile == "" {
logger.Error("the template file must be present")
return
}
if outputFile == nil || *outputFile == "" {
logger.Error("the output file must be present")
return
}
if *serve {
runServer(markdownDocument, templateFile, outputFile, port)
} else {
runCli(markdownDocument, templateFile, outputFile, watch)
}
}
func runCli(markdownDocument, templateFile, outputFile *string, watch *bool) {
if !*watch {
err := buildDocument(markdownDocument, templateFile, outputFile)
if err != nil {
logger.Error("there was an error building the markdown document")
return
}
logger.Info("the template was successfully rendered", "input", *markdownDocument, "template", *templateFile, "output", *outputFile)
return
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
logger.Error("there was an error creating the file watcher")
return
}
defer watcher.Close()
go startWatcher(watcher, markdownDocument, templateFile, outputFile, nil)
if err := buildDocument(markdownDocument, templateFile, outputFile); err != nil {
logger.Error("error performing initial build", "err", err)
} else {
logger.Info("initial build successful")
}
if err := watcher.Add(*markdownDocument); err != nil {
logger.Error("error adding markdown file to watcher", "err", err)
return
}
if err := watcher.Add(*templateFile); err != nil {
logger.Error("error adding template file to watcher", "err", err)
return
}
logger.Info("watching for changes...")
<-make(chan struct{})
}
func runServer(markdownDocument, templateFile, outputFile, port *string) {
hub := newHub()
go hub.run()
watcher, err := fsnotify.NewWatcher()
if err != nil {
logger.Error("there was an error creating the file watcher")
return
}
defer watcher.Close()
go startWatcher(watcher, markdownDocument, templateFile, outputFile, hub)
if err := buildDocument(markdownDocument, templateFile, outputFile); err != nil {
logger.Error("error performing initial build", "err", err)
} else {
logger.Info("initial build successful")
}
if err := watcher.Add(*markdownDocument); err != nil {
logger.Error("error adding markdown file to watcher", "err", err)
return
}
if err := watcher.Add(*templateFile); err != nil {
logger.Error("error adding template file to watcher", "err", err)
return
}
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
serveWs(hub, w, r)
})
fs := http.FileServer(http.Dir("."))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
html, err := os.ReadFile(*outputFile)
if err != nil {
http.Error(w, "Could not read output file: "+err.Error(), http.StatusInternalServerError)
return
}
script := fmt.Sprintf(`<script>
let socket = new WebSocket("ws://%s/ws");
socket.onmessage = function(event) {
if (event.data === "reload") {
location.reload();
}
};
socket.onclose = function(event) {
console.log("Live reload socket closed. Reloading page to try reconnecting...");
setTimeout(() => location.reload(), 2000);
};
</script>`, r.Host)
injectedHTML := strings.Replace(string(html), "</body>", script+"</body>", 1)
w.Header().Set("Content-Type", "text/html")
w.Write([]byte(injectedHTML))
return
}
fs.ServeHTTP(w, r)
})
logger.Info("starting server, watching for changes...", "address", "http://localhost:"+*port)
if err := http.ListenAndServe(":"+*port, nil); err != nil {
logger.Error("server failed to start", "err", err)
}
}
func startWatcher(watcher *fsnotify.Watcher, markdownDocument, templateFile, outputFile *string, hub *Hub) {
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
if !(event.Has(fsnotify.Write) || event.Has(fsnotify.Rename) || event.Has(fsnotify.Remove)) {
continue
}
if event.Has(fsnotify.Rename) || event.Has(fsnotify.Remove) {
time.Sleep(100 * time.Millisecond)
}
logger.Info("change detected, rebuilding...", "file", event.Name, "op", event.Op.String())
if err := buildDocument(markdownDocument, templateFile, outputFile); err != nil {
if !(event.Has(fsnotify.Rename) || event.Has(fsnotify.Remove)) {
logger.Error("error rebuilding document", "err", err)
}
} else {
logger.Info("rebuild successful")
if hub != nil {
hub.broadcast <- []byte("reload")
}
}
if event.Has(fsnotify.Rename) || event.Has(fsnotify.Remove) {
watcher.Add(*markdownDocument)
watcher.Add(*templateFile)
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
logger.Error("error watching files", "err", err)
}
}
}
func buildDocument(markdownDocument *string, templateFile *string, outputFile *string) error {
markdownContent, err := os.ReadFile(*markdownDocument)
if err != nil {
logger.Error("there was an error parsing the markdown content", "err", err)
return err
}
var buf bytes.Buffer
md := goldmark.New(
goldmark.WithExtensions(
extension.GFM,
highlighting.NewHighlighting(
highlighting.WithStyle("monokai"),
highlighting.WithFormatOptions(),
),
),
)
if err := md.Convert(markdownContent, &buf); err != nil {
logger.Error("error converting markdown into html", "err", err)
return err
}
tmpl, err := template.ParseFiles(*templateFile)
if err != nil {
logger.Error("error parsing template file", "err", err)
return err
}
output, err := os.Create(*outputFile)
if err != nil {
logger.Error("error creating output file", "err", err)
return err
}
defer output.Close()
data := PageData{
Content: template.HTML(buf.String()),
}
if err := tmpl.Execute(output, data); err != nil {
logger.Error("error rendering template with markdown", "err", err)
return err
}
return nil
}