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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
|
const std = @import("std");
const fs = @import("fs.zig");
const exe = @import("exe.zig");
const Context = @import("main.zig").Context;
const log = std.log.scoped(.gen);
pub fn fixMtimes(ctx: *Context) !void {
ctx.progress_start("Fix mtimes");
defer ctx.progress_end();
const Counter = std.atomic.Value(usize);
var counter = Counter.init(0);
const worker = struct {
fn func(wctx: *Context, wp: []const u8, wcounter: *Counter) !void {
var buf: [2 * std.os.linux.PATH_MAX]u8 = undefined;
var fba = std.heap.FixedBufferAllocator.init(&buf);
wctx.progress_start(wp);
defer wctx.progress_end();
const path = fs.joinPathAndFilename(fba.allocator(), &.{Context.params.PAGE_PATH}, &.{wp}) catch unreachable;
const mdpath = fs.replaceExtension(fba.allocator(), path, "md") catch unreachable;
std.fs.cwd().access(mdpath, .{}) catch {
// only set mtime from git if no markdown source is used
const ts = fs.getGitTime(path) catch return;
fs.setMtime(path, ts) catch unreachable;
_ = wcounter.fetchAdd(1, .monotonic);
};
}
};
try exe.WaitPool(
[]const u8,
worker.func,
).work(ctx, ctx.pages.items, .{&counter});
log.info("Retimed {d} pages.", .{counter.raw});
}
pub fn generate(ctx: *Context) !void {
ctx.progress_start("generate");
defer ctx.progress_end();
try genIndex(ctx);
log.info("Generated index.", .{});
try genSite(ctx);
log.info("Generated {d} files.", .{ctx.generated});
log.info("Generated {d} tildes.", .{ctx.tilde});
}
fn genIndex(ctx: *Context) !void {
ctx.progress_start("index.htm");
defer ctx.progress_end();
const srcpathIndex = try fs.joinPathAndFilename(ctx.allocator(), &.{Context.params.PAGE_PATH}, &.{"index.htm"});
defer ctx.allocator().free(srcpathIndex);
const f = try fs.FileSwapper.createAt(ctx.allocator(), srcpathIndex);
defer f.close();
var buffer: [1024]u8 = undefined;
var w = f.writer(&buffer);
try w.interface.writeAll(
\\<ul class="col2 captial">
\\
);
// alphanum ascii sort
std.mem.sort(
[]const u8,
ctx.pages.items,
{},
struct {
fn lessthan(_: void, a: []const u8, b: []const u8) bool {
return std.ascii.lessThanIgnoreCase(a, b);
}
}.lessthan,
);
for (ctx.pages.items) |p| {
if (std.mem.startsWith(u8, p, "meta.")) continue;
const dstname = try fs.stripExtension(p);
const dstpath = try fs.joinPathAndFilename(ctx.allocator(), &.{Context.params.SITE_PATH}, &.{ dstname, ".html" });
defer ctx.allocator().free(dstpath);
try w.interface.print(
\\<li><a href="/{[LINK]s}">{[NAME]s}</a></li>
\\
, .{
.LINK = dstpath,
.NAME = dstname,
});
}
try w.interface.writeAll(
\\</ul>
\\
);
try w.interface.flush();
if (!try f.diff()) try f.undo();
}
fn genSite(ctx: *Context) !void {
for (ctx.pages.items) |p| {
const pname = std.fs.path.basename(p);
ctx.progress_start(pname);
defer ctx.progress_end();
if (std.mem.startsWith(u8, pname, "meta.")) {
try meta(ctx, p);
continue;
}
const dstname = try fs.stripExtension(p);
const srcpath = try fs.joinPathAndFilename(ctx.allocator(), &.{Context.params.PAGE_PATH}, &.{ dstname, ".htm" });
defer ctx.allocator().free(srcpath);
const dstpath = try fs.joinPathAndFilename(ctx.allocator(), &.{Context.params.SITE_PATH}, &.{ dstname, ".html" });
defer ctx.allocator().free(dstpath);
const rel_dstpath = try std.fs.path.relative(ctx.allocator(), Context.params.SITE_PATH, dstpath);
defer ctx.allocator().free(rel_dstpath);
log.debug("generating {s} at {s}", .{ p, rel_dstpath });
if (std.fs.path.dirname(rel_dstpath)) |d| {
const dstdir = try fs.joinPathAndFilename(ctx.allocator(), &.{Context.params.SITE_PATH}, &.{d});
defer ctx.allocator().free(dstdir);
try std.fs.cwd().makePath(dstdir);
}
const f = try fs.FileSwapper.createAt(ctx.allocator(), dstpath);
defer f.close();
var buffer: [1024]u8 = undefined;
var w = f.writer(&buffer);
const page_name = try std.mem.replaceOwned(u8, ctx.allocator(), dstname, "_", " ");
defer ctx.allocator().free(page_name);
try build(ctx.allocator(), &w.interface, page_name, srcpath);
ctx.generated += 1;
}
}
// build a single html file
fn build(allocator: std.mem.Allocator, w: *std.Io.Writer, page_name: []const u8, srcpath: []const u8) !void {
const mtime = try fs.getMtime(srcpath);
const mtime_str = try fs.formatTimespec(allocator, mtime, "%F");
defer allocator.free(mtime_str);
// HEAD
try w.print(
\\<!-- Generated file, do not edit, you may edit and discard {[SOURCE]s} :) -->
\\<!DOCTYPE html>
\\<html lang="en">
\\<head>
\\<meta charset="utf-8">
\\<meta name="thumbnail" content="/media/services/thumbnail.jpg">
\\<meta name="viewport" content="width=device-width,initial-scale=1">
\\<link rel="preload" href="/media/interface/logo.svg" as="image">
\\<link rel="alternate" type="application/rss+xml" title="RSS Feed" href="/links/rss.xml">
\\<link rel="stylesheet" type="text/css" href="/links/main.css">
\\<link rel="shortcut icon" type="image/png" href="/media/services/icon.png">
\\<link rel="license" href="{[LICENSE_URL]s}">
\\<title>{[SITE_NAME]s} — {[PAGE_NAME]s}</title>
\\</head>
\\<body>
\\<header>
\\<a href="/"><img src="/media/interface/logo.svg" alt="{[SITE_NAME]s}"></a>
\\
, .{
.SOURCE = srcpath,
.LICENSE_URL = Context.params.LICENSE_URL,
.PAGE_NAME = page_name,
.SITE_NAME = Context.params.SITE_NAME,
});
// NAV
try w.writeAll(
\\<nav>
\\
);
portal(allocator, w, "meta.nav", false) catch {}; // ignore error
try w.writeAll(
\\</nav>
\\</header>
\\
);
// MAIN
try w.print(
\\<main>
\\
, .{});
try inject(allocator, w, srcpath);
try w.writeAll(
\\</main>
\\
);
// FOOTER
try w.print(
\\<footer>
\\Edited on {[MTIME]s} <a href="{[SOURCE_URL]s}/{[PATH]s}" target="_blank">[src]</a>
\\<a href="mailto:{[PUBLIC_INBOX]s}">[comments]</a>
\\<br>
\\<b>{[LICENSE_HOLDER]s}</b>
\\© {[LICENSE_YEAR]s}
\\—
\\<a href="{[LICENSE_URL]s}" target="_blank">{[LICENSE_NAME]s}</a>
\\</footer>
\\
, .{
.LICENSE_HOLDER = Context.params.LICENSE_HOLDER,
.LICENSE_NAME = Context.params.LICENSE_NAME,
.LICENSE_URL = Context.params.LICENSE_URL,
.LICENSE_YEAR = Context.params.LICENSE_YEAR,
.MTIME = mtime_str,
.PATH = srcpath,
.PUBLIC_INBOX = Context.params.PUBLIC_INBOX,
.SOURCE_URL = Context.params.SOURCE_URL,
});
try w.writeAll(
\\<a href="#top">[⏶]</a>
\\
);
try w.writeAll(
\\</body>
\\</html>
\\
);
try w.flush();
}
// build a virtual html file, currently either:
// - meta.nav: used for populating the global navigation menu
// - meta.tilde: used to create ~foobar files
fn meta(ctx: *Context, p: []const u8) !void {
ctx.meta += 1;
if (std.mem.startsWith(u8, p, "meta.nav.")) return;
if (std.mem.startsWith(u8, p, "meta.tilde.")) {
const dot = std.mem.indexOfPosLinear(u8, p, 11, ".");
const dstname = p[11..dot.?];
const srcpath = try fs.joinPathAndFilename(ctx.allocator(), &.{Context.params.PAGE_PATH}, &.{p});
defer ctx.allocator().free(srcpath);
const dstpath = try fs.joinPathAndFilename(ctx.allocator(), &.{Context.params.LINK_PATH}, &.{ "~", dstname });
defer ctx.allocator().free(dstpath);
const link = blk: {
const f = try std.fs.cwd().openFile(srcpath, .{ .mode = .read_only });
defer f.close();
const content = try f.readToEndAlloc(ctx.allocator(), std.os.linux.PATH_MAX);
defer ctx.allocator().free(content);
const trimmed = std.mem.trim(u8, content, " \n\t\r");
break :blk try ctx.allocator().dupe(u8, trimmed);
};
defer ctx.allocator().free(link);
const f = try fs.FileSwapper.createAt(ctx.allocator(), dstpath);
defer f.close();
var buffer: [1024]u8 = undefined;
var w = f.writer(&buffer);
try w.interface.print(
\\<!DOCTYPE html>
\\<html lang="en">
\\<head>
\\<meta charset="utf-8">
\\<meta http-equiv="refresh" content="0; url={[LINK]s}">
\\<meta name="fediverse:creator" content="@robertgzr@toot.berlin">
\\<link rel="stylesheet" type="text/css" href="links/main.css">
\\</head>
\\<body>
\\<noscript>Continue to <a href="{[LINK]s}">{[LINK]s}</a>.</noscript>
\\<script>
\\'use strict'
\\window.location.replace("{[LINK]s}")
\\</script>
\\</body>
\\</html>
\\
, .{
.LINK = link,
});
try w.interface.flush();
ctx.tilde += 1;
return;
}
return error.unknownMeta;
}
// parses srcpath, resolves refs and portals and writes everything to w
fn inject(allocator: std.mem.Allocator, w: *std.Io.Writer, srcpath: []const u8) !void {
var arena = std.heap.ArenaAllocator.init(allocator);
defer arena.deinit();
const inc = std.fs.cwd().openFile(srcpath, .{ .mode = .read_only }) catch |err| {
if (err == error.FileNotFound)
log.warn("Missing {s} include.", .{srcpath});
return err;
};
defer inc.close();
var buffer: [1024]u8 = undefined;
var r = inc.readerStreaming(&buffer);
var chunkw = std.Io.Writer.Allocating.init(arena.allocator());
defer chunkw.deinit();
while (true) {
defer chunkw.clearRetainingCapacity(); // reset chunk
_ = r.interface.streamDelimiter(&chunkw.writer, '\n') catch |err|
if (err == error.EndOfStream) break
else return err;
_ = r.interface.toss(1); // skip newline delimiter
var chunk = chunkw.written();
templating: while (true) {
if (std.mem.indexOfPosLinear(u8, chunk, 0, "{")) |start| {
if (std.mem.indexOfPosLinear(u8, chunk, start + 1, "}")) |end| {
try w.writeAll(chunk[0..start]);
template(allocator, w, chunk[start + 1 .. end]) catch |err| switch (err) {
error.FileNotFound => {
// log.warn("ref {s} not found", .{chunk[start + 1 .. end]});
// trim already written chunk and exit templating
chunk = chunk[start..];
break :templating;
},
else => @panic("Failed to resolve template"),
};
chunk = chunk[end + 1 ..];
} else break :templating;
} else break :templating;
}
try w.writeAll(chunk);
try w.writeByte('\n');
try w.flush();
}
try w.flush();
}
// implements various reference types that can be used in .htm templates
fn template(allocator: std.mem.Allocator, w: *std.Io.Writer, refname: []const u8) anyerror!void {
switch (refname[0]) {
'/' => return try portal(allocator, w, refname[1..], false),
'$' => return try ref_link(allocator, w, refname[1..]),
'+' => return try ref_name(allocator, w, refname[1..]),
else => return try ref(allocator, w, refname),
}
}
const Page = struct {
arena: std.heap.ArenaAllocator,
ref: []const u8,
name: []const u8,
html: []const u8,
htm: []const u8,
anchor: []const u8,
fn from_ref(allocator: std.mem.Allocator, refname: []const u8) !Page {
var arena = std.heap.ArenaAllocator.init(allocator);
const endofref = std.mem.lastIndexOf(u8, refname, "#") orelse refname.len;
const basename = try std.mem.replaceOwned(u8, arena.allocator(), refname[0..endofref], " ", "_");
const html = try fs.joinPathAndFilename(arena.allocator(), &.{Context.params.SITE_PATH}, &.{ basename, ".html" });
const htm = try fs.joinPathAndFilename(arena.allocator(), &.{Context.params.PAGE_PATH}, &.{ basename, ".htm" });
try std.fs.cwd().access(htm, .{ .mode = .read_only });
return .{
.arena = arena,
.ref = refname[0..endofref],
.name = basename,
.html = html,
.htm = htm,
.anchor = if (endofref < refname.len) refname[endofref..] else "",
};
}
fn deinit(self: Page) void {
self.arena.deinit();
}
};
fn portal(allocator: std.mem.Allocator, w: *std.Io.Writer, refname: []const u8, insert_heading: bool) anyerror!void {
const page = try Page.from_ref(allocator, refname);
defer page.deinit();
if (insert_heading)
try w.print(
\\<h2 id="{[ID]s}"><a href="/{[PATH]s}">{[NAME]s}</a></2>
\\
, .{
.ID = page.ref,
.NAME = page.name,
.PATH = page.html,
});
try inject(allocator, w, page.htm);
// XXX: track ref count?
}
fn ref(allocator: std.mem.Allocator, w: *std.Io.Writer, refname: []const u8) anyerror!void {
const page = try Page.from_ref(allocator, refname);
defer page.deinit();
try w.print(
\\<a href="/{[PATH]s}{[ANCHOR]s}">{[NAME]s}</a>
, .{
.NAME = page.name,
.PATH = page.html,
.ANCHOR = page.anchor,
});
// XXX: track ref count?
}
fn ref_link(allocator: std.mem.Allocator, w: *std.Io.Writer, refname: []const u8) anyerror!void {
const page = try Page.from_ref(allocator, refname);
defer page.deinit();
try w.print("/{s}{s}", .{ page.html, page.anchor });
}
fn ref_name(allocator: std.mem.Allocator, w: *std.Io.Writer, refname: []const u8) anyerror!void {
const page = try Page.from_ref(allocator, refname);
defer page.deinit();
try w.print("{s}", .{page.ref});
}
|