-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.ts
More file actions
286 lines (265 loc) · 8.49 KB
/
main.ts
File metadata and controls
286 lines (265 loc) · 8.49 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
import {
Goldsmith,
GoldsmithPlugin,
goldsmithJSONMetadata,
goldsmithFrontMatter,
goldsmithExcludeDrafts,
goldsmithFileMetadata,
goldsmithIndex,
goldsmithCollections,
goldsmithInjectFiles,
goldsmithMarkdown,
goldsmithRootPaths,
goldsmithLayout,
goldsmithLayoutLiteralHTML,
goldsmithWatch,
goldsmithServe,
goldsmithFeed,
goldsmithLinkChecker,
validatePostMetadata,
validateSiteMetadata,
version as md2blogVersion,
} from "./deps.ts";
import { processFlags } from "https://deno.land/x/flags_usage@1.0.1/mod.ts";
import { templates, generateCSS } from "./templates.ts";
// @deno-types="./deps/highlightjs-11.3.1.d.ts"
import highlightJS from "./deps/highlightjs-11.3.1.js";
import copyrightNotice from "./LICENSE.ts";
// Command line arguments
const { clean, drafts, execute, input, output, serve, watch, version, copyright } = processFlags(Deno.args, {
description: {
clean: "Clean output directory before processing",
drafts: "Include drafts in output",
serve: "Serve web site, with automatic reloading",
watch: "Watch for changes and rebuild automatically",
input: "Input directory",
output: "Output directory",
execute: "Command to run on build completion",
copyright: "Display open source software copyright notices",
version: "Display md2blog version information",
},
argument: {
execute: "command",
input: "dir",
output: "dir",
},
string: [
"execute",
"input",
"output",
],
boolean: [
"clean",
"drafts",
"serve",
"watch",
"copyright",
"version",
],
alias: {
clean: "c",
drafts: "d",
execute: "x",
input: "i",
output: "o",
serve: "s",
watch: "w",
},
default: {
input: "content",
output: "out",
},
});
if (copyright) {
console.log(copyrightNotice);
Deno.exit(0);
}
if (version) {
console.log(md2blogVersion);
Deno.exit(0);
}
// Path format for posts: posts/(:category/)postName.md
// Groups: |-- 2 --|
const postPathPattern = /^posts(\/([^/]+))?\/[^/]+.md$/;
function replaceLink(link: string) {
return link.replace(/^([^/][^:]*)\.md(#[^#]+)?$/, "$1.html$2")
}
function capitalize(str: string): string {
if (str.length > 0) {
return str[0].toLocaleUpperCase() + str.substring(1);
}
return str;
}
function executeCallback(): void {
if (execute) {
Deno.run({ cmd: execute.split(" ") });
}
}
// Cache the results of syntax highlighting since that process is somewhat slow
const highlightCache: { [language: string]: { [code: string]: string } } = {};
function highlight(code: string, language?: string): string {
const key = language ?? "undefined";
let cache = highlightCache[key];
if (cache) {
const result = cache[code];
if (result) {
return result;
}
} else {
const newCache = {};
highlightCache[key] = newCache;
cache = newCache;
}
const result = (language && highlightJS.getLanguage(language))
? highlightJS.highlight(code, { language }).value
: highlightJS.highlightAuto(code).value;
cache[code] = result;
return result;
}
const noop: GoldsmithPlugin = (_files, _goldsmith) => {};
const watching = serve || watch; // --serve implies --watch
await Goldsmith({ lineEndings: "auto" })
.source(input)
.destination(output)
.clean(clean)
.use(goldsmithJSONMetadata({ "site.json": "site" }))
.use((_files, goldsmith) => {
// Validate site.json
try {
validateSiteMetadata(goldsmith.metadata().site)
} catch (error) {
console.log("Error validating site.json:");
throw error;
}
})
.use(goldsmithFrontMatter())
.use(drafts ? noop : goldsmithExcludeDrafts())
.use(goldsmithFileMetadata({
pattern: /\.html$/,
metadata: { layout: false }, // Opt raw HTML files out of layouts so they're copied verbatim
}))
.use(goldsmithFileMetadata({
pattern: postPathPattern,
metadata: (file, matches) => {
// Verify post metadata
try {
validatePostMetadata(file);
} catch (error) {
console.log(`Error validating ${matches[0]}:`);
throw error;
}
return {};
},
}))
.use(goldsmithFileMetadata({
pattern: postPathPattern,
metadata: (_file, matches) => ({ category: matches[2] ?? "misc" }),
}))
.use(goldsmithFileMetadata({
pattern: postPathPattern,
metadata: (file) => ({
layout: "post",
// Set "tags" to be [ category, ...keywords ] (with duplicates removed)
tags: [...new Set([ file.category!, ...(file.keywords ?? []) ])],
}),
}))
.use(goldsmithIndex({
pattern: postPathPattern,
property: "tags",
createTermIndexPath: term => `posts/${term}/index.html`,
}))
.use(goldsmithFileMetadata({
pattern: /^posts\/[^/]+?\/index.html$/,
metadata: (file, _matches, metadata) => ({
tag: file.term,
layout: "tagIndex",
isTagIndex: true,
postsWithTag: metadata.indexes!.tags[file.term!].sort((a, b) => (b.date!.valueOf() - a.date!.valueOf())), // Note: Sorts the array in place!
}),
}))
.use(goldsmithCollections({
posts: {
pattern: postPathPattern,
sortBy: "date",
reverse: true,
},
postsRecent: {
pattern: postPathPattern,
sortBy: "date",
reverse: true,
limit: 5,
},
nonPosts: {
pattern: /^[^/]+\.(html|md)$/,
sortBy: "title",
},
}))
.use((_files, goldsmith) => {
// Create index and archive tag lists
const metadata = goldsmith.metadata();
// Sort "all tags" list alphabetically
metadata.tagsAll = Object.keys(metadata.indexes!.tags).sort((a, b) => (a < b ? -1 : 1));
// Sort "top tags" list by most posts, and then most recent post if there's a tie
metadata.tagsTop = Object.keys(metadata.indexes!.tags).sort((a, b) => {
const postsA = metadata.indexes!.tags[a];
const postsB = metadata.indexes!.tags[b];
return (postsB.length - postsA.length) || (postsB[0].date!.getDate() - postsA[0].date!.getDate());
}).slice(0, 4);
})
.use(goldsmithInjectFiles({
"index.html": { layout: "index" },
"posts/index.html": { layout: "archive" },
"404.html": { layout: "404" },
}))
.use(goldsmithInjectFiles({
"css/style.css": {
data: (metadata) => generateCSS(metadata.site?.colors ?? {}),
},
}))
.use(goldsmithMarkdown({
replaceLinks: link => replaceLink(link),
highlight,
cache: watching,
}))
.use(goldsmithRootPaths())
.use(goldsmithFeed({ getCollection: (metadata) => metadata.collections!.postsRecent! }))
.use((_files, goldsmith) => {
// Set header defaults
const metadata = goldsmith.metadata();
const site = metadata.site!;
const text = site.header?.text ?? site.description;
let links = site.header?.links;
if (!links) {
links = {};
for (const file of metadata.collections!.nonPosts) {
const pathFromRoot = file.pathFromRoot!;
if (pathFromRoot !== "index.html") {
const name = capitalize(
pathFromRoot
.replace(/\.[^.]*$/, "")
.replace("-", " ")
);
links[name] = pathFromRoot;
}
}
}
for (const [name, link] of Object.entries(links)) {
links[name] = replaceLink(link);
}
site.header = {
text,
links,
};
})
.use(goldsmithLayout({
pattern: /\.html$/,
layout: goldsmithLayoutLiteralHTML({
templates,
defaultTemplate: "default",
})
}))
.use(goldsmithLinkChecker({ background: serve })) // Link-check asynchronously when serving
.use(watching ? goldsmithWatch({ onRebuildCompleted: executeCallback, delayMS: 10 }) : noop)
.use(serve ? goldsmithServe() : noop)
.build();
executeCallback();