-
Notifications
You must be signed in to change notification settings - Fork 0
/
bin.ts
457 lines (398 loc) · 12.4 KB
/
bin.ts
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
import { exists } from "https://deno.land/std/fs/exists.ts";
import { ensureDir } from "https://deno.land/std/fs/ensure_dir.ts";
import * as path from "https://deno.land/std/path/mod.ts";
import * as yaml from "https://deno.land/std/encoding/yaml.ts";
import { Marked } from "https://deno.land/x/markdown/mod.ts";
import {Template} from "./template.ts"
const fs = { exists, ensureDir };
const srcFolder = "./src";
const buildFolder = "./build";
var encoder = new TextEncoder();
var decoder = new TextDecoder();
interface SrcEntry {
path: string;
}
interface DestEntry {
path: string;
content: string;
}
/**
* Simple object check.
* @param item
* @returns {boolean}
*/
export function isObject(item: any) {
return (item && typeof item === 'object' && !Array.isArray(item));
}
/**
* Deep merge two objects.
* @param target
* @param ...sources
*/
export function mergeDeep(target: any, ...sources: any): any {
if (!sources.length) return target;
const source = sources.shift();
if (isObject(target) && isObject(source)) {
for (const key in source) {
if (isObject(source[key])) {
if (!target[key]) Object.assign(target, { [key]: {} });
mergeDeep(target[key], source[key]);
} else {
Object.assign(target, { [key]: source[key] });
}
}
}
return mergeDeep(target, ...sources);
}
async function addDefaultYaml(ymlStart: any, input: GenInput, dirPath: string) {
let curDir : string | null = path.dirname(dirPath)
let recYaml = [ymlStart]
while (curDir) {
try {
let extraYml = path.join(curDir, "default.yml")
let ymlInfo = yaml.parse(decoder.decode( await input.readFile(extraYml)))
recYaml.push(ymlInfo)
} catch (er) {
//ignore TODO: we need stat
//console.log(er)
}
if (curDir === ".") {
curDir = null
} else {
curDir = path.dirname(curDir)
}
}
recYaml.reverse()
let yamlContent = {}
for(const ymlCt of recYaml) {
yamlContent = mergeDeep(yamlContent,ymlCt)
}
return yamlContent
}
const jsFileProxy = {
get: function (target: any, property: any): any { //do not understand this conditional type shit yet, i would like to have string | Symbol
if (typeof property === 'symbol') {
return target[property];
}
if (property === "@path" || property === "@input") {
return target[property]
}
var newPath = path.join(target['@path'], property)
return asJs(target['@input'], newPath)
}
}
function contentOf(fileAsJs: any): string {
return fileAsJs[Symbol.toPrimitive]('string')
}
// later support iteration
class AsJsObj {
readonly "@input": GenInput
readonly "@path": string
constructor(input: GenInput, path: string) {
this["@input"] = input
this["@path"] = path
}
[Symbol.toPrimitive] (hint: string) {
var filePath = this["@path"].split('\\')
if (filePath.length > 1) {
const fileName = filePath[filePath.length -2] + "." + filePath[filePath.length -1]
filePath.pop()
filePath[filePath.length-1] = fileName
}
const fPath = filePath.join('\\')
let content = null
try {
content = this["@input"].readFileSync(fPath)
}
catch(er) {
throw new Error(`Can not read file ${fPath}: ${er.message}`)
}
return decoder.decode(content)
}
}
function asJs(input: GenInput, path: string=".") {
return new Proxy(new AsJsObj(input, path), jsFileProxy)
}
//we could allow it to access the full source
interface RenderType {
selector(entry: SrcEntry): boolean;
render(input: GenInput, output: GenOutput, entry: SrcEntry): Promise<void>;
}
class MarkdownRender implements RenderType {
selector(entry: SrcEntry): boolean {
if (path.extname(entry.path) === ".md") {
return true;
}
return false;
}
async render(
input: GenInput,
output: GenOutput,
entry: SrcEntry,
): Promise<void> {
//strip header
let markdownFc = decoder.decode(
await input.readFile(entry.path),
);
let yamlContent: any = null
yamlContent = { template: "" };
try {
let yamlBegin = markdownFc.indexOf("---");
if (yamlBegin !== -1) {
let yamlEnd = markdownFc.indexOf("---", yamlBegin + 1);
if (yamlEnd === -1) {
throw new Error("yaml begin marker --- not matched");
}
let yamlRaw = markdownFc.substring(yamlBegin + 3, yamlEnd)
yamlContent = yaml.parse(yamlRaw);
markdownFc = markdownFc.substring(yamlEnd);
}
} catch (er) {
throw new Error(`Failed to read yaml header of file ${entry.path} (error: ${er.message})`)
}
yamlContent = await addDefaultYaml(yamlContent, input, entry.path)
// parse markdown
let markup = Marked.parse(markdownFc);
if (yamlContent && yamlContent.title) {
markup = `<h1>${yamlContent.title}</h1>` + markup
}
// check what template to apply
let template = yamlContent ? yamlContent.template : null;
let curDir = path.dirname(entry.path);
let templStr = "";
if (template) {
templStr = decoder.decode(await input.readFile(template));
}
while (!templStr && curDir != ".") {
try {
template = path.join(curDir, "default.tt")
templStr = decoder.decode( await input.readFile(template))
} catch (er) {
//ignore TODO: we need stat
//console.log(er)
}
curDir = path.dirname(curDir);
}
if (!templStr) {
throw new Error(`can not find a single template, provide a default.tt in one of the parent directory of file ${entry.path}`)
}
var templ = new Template(templStr);
var renderedOut = null
try {
renderedOut = templ.render({ content: markup, static: asJs(input,"./static") , ...yamlContent});
}
catch(er) {
throw new Error(`Could not render template ${template}: ${er.message}`)
}
let outPath = entry.path.slice(0, -2) + "html";
await output.WriteFile(outPath, encoder.encode(renderedOut));
}
}
class JsonRender implements RenderType {
selector(entry: SrcEntry): boolean {
return path.extname(entry.path) === ".json";
}
async render(
input: GenInput,
output: GenOutput,
entry: SrcEntry,
): Promise<void> {
let json = null
try {
json = JSON.parse(decoder.decode(await input.readFile(entry.path)));
}
catch (er) {
throw new Error(`Error in file: ${entry.path}, message: ${er.message}`)
}
if (json.template) {
//we need to do template things
try {
let templStr = decoder.decode(await input.readFile(json.template));
var templ = new Template(templStr);
var content = "";
if (json.source === "film-focus") {
content = await this.renderFilmFocus(input);
} else if (json.source === "webshop") {
content = await this.renderWebshop(input);
}
//
let curDir
let ymlContent = await addDefaultYaml(json, input, entry.path)
var renderedOut = templ.render({ content: content, static: asJs(input,"./static"), ...ymlContent });
let outPath = entry.path.slice(0, -4) + "html";
await output.WriteFile(outPath, encoder.encode(renderedOut));
} catch (er) {
throw new Error(`Could not isntantiate template ${json.template} for file ${entry.path} (reason: ${er.message})`)
}
}
}
async renderFilmFocus(input: GenInput) {
function getFilm(film: string, title: string) {
return `
<div class="column">
<div class="image-fit" onclick="window.location.href = '/film-focus/${film}/' ">
<img class="ui image" src="/film-focus/${film}/front.jpg" />
<div class="image-overlay" >
<div class="image-text" >${title}</div>
</div>
</div>
</div>`;
}
let content = "";
for await (let entry of input.readDir("film-focus")) {
let mdfilePath = `/film-focus/${entry.path}/index.md`
let markdownFc = decoder.decode(
await input.readFile(mdfilePath),
);
let yamlContent: any = null
yamlContent = { template: "" };
try {
let yamlBegin = markdownFc.indexOf("---");
if (yamlBegin !== -1) {
let yamlEnd = markdownFc.indexOf("---", yamlBegin + 1);
if (yamlEnd === -1) {
throw new Error("yaml begin marker --- not matched");
}
let yamlRaw = markdownFc.substring(yamlBegin + 3, yamlEnd)
yamlContent = yaml.parse(yamlRaw);
markdownFc = markdownFc.substring(yamlEnd);
}
} catch (er) {
throw new Error(`Failed to read yaml header of file ${entry.path} (error: ${er.message})`)
}
yamlContent = await addDefaultYaml(yamlContent, input, entry.path)
content += getFilm(entry.path,yamlContent.title);
}
return content;
}
async renderWebshop(input: GenInput) {
function getArticle(article: string) {
return `
<div class="column">
<div class="image-fit" onclick="window.location.href = '/webshop/${article}/' ">
<img class="ui image" src="/webshop/${article}/front.jpg" />
</div>
</div>`;
}
let content = "";
for await (let entry of input.readDir("webshop")) {
content += getArticle(entry.path);
}
return content;
}
}
class CopyRender implements RenderType {
includedExt: string[] = [];
constructor(extToCopy: string[]) {
this.includedExt = extToCopy;
}
selector(entry: SrcEntry): boolean {
if (this.includedExt.indexOf(path.extname(entry.path)) !== -1) {
return true;
}
return false;
}
async render(
input: GenInput,
output: GenOutput,
entry: SrcEntry,
): Promise<void> {
let content = await input.readFile(entry.path);
await output.WriteFile(entry.path, content);
}
}
class GenInput {
basePath: string;
constructor(inputPath: string) {
this.basePath = inputPath;
}
async readFile(filePath: string) {
//cool checks if relative path is not breaking out of root
var fullPath = path.join(this.basePath, filePath);
return Deno.readFile(fullPath);
}
readFileSync(filePath: string) {
//cool checks if relative path is not breaking out of root
var fullPath = path.join(this.basePath, filePath);
return Deno.readFileSync(fullPath)
}
async *readDir(dirPath: string): AsyncIterable<SrcEntry> {
for await (
const dirEntry of Deno.readDir(path.join(this.basePath, dirPath))
) {
if (dirEntry.isDirectory) {
yield { path: dirEntry.name };
}
}
}
async visitFiles(visitor: (entry: SrcEntry) => Promise<void>): Promise<void> {
await visitFiles(this.basePath, "", visitor);
}
}
async function visitFiles(
baseDir: string,
subDir: string,
visitor: (entry: SrcEntry) => Promise<void>,
) {
var dirToCheck = path.join(baseDir, subDir);
for await (const dirEntry of Deno.readDir(dirToCheck)) {
if (dirEntry.isDirectory) {
await visitFiles(baseDir, path.join(subDir, dirEntry.name), visitor);
} else if (dirEntry.isFile) {
await visitor({ path: path.join(subDir, dirEntry.name) });
}
}
}
class GenOutput {
basePath: string = ".";
constructor(iPath: string) {
this.basePath = iPath;
}
async WriteFile(filePath: string, data: Uint8Array) {
//cool checks if relative path is not breaking out of root
//cool check if we do not override exising file
var fullPath = path.join(this.basePath, filePath);
await fs.ensureDir(path.dirname(fullPath));
return Deno.writeFile(fullPath, data);
}
}
async function transformWithFilters(
input: GenInput,
output: GenOutput,
filters: RenderType[],
): Promise<void> {
let results: DestEntry[] = [];
await input.visitFiles(async (entry) => {
//if (entry.path === 'missie\\index.md') {
for (let filter of filters) {
if (filter.selector({ path: entry.path })) {
await filter.render(input, output, { path: entry.path });
}
}
//}
});
}
// clean up
if (await fs.exists(buildFolder)) {
await Deno.remove(buildFolder, { recursive: true });
}
//combine all render types
let renderTypes: RenderType[] = [
new MarkdownRender(),
new CopyRender([".jpg", ".html",".pdf",".mp3", ".m4v",".js"]),
new JsonRender(),
];
// scan files old style
//await copySrc(srcFolder, buildFolder);
//let files: SrcEntry[] = [];
//await scanfiles(srcFolder, "", files);
//first stage
await transformWithFilters(
new GenInput(srcFolder),
new GenOutput(buildFolder),
renderTypes
);
console.log(
"done"
)
Deno.exit()