1 | import chalk = require('chalk');
|
2 |
|
3 | import {join} from 'path';
|
4 |
|
5 | import {Files} from '../static';
|
6 | import {OutputOptions} from './options';
|
7 | import {OutputProducer} from './producer';
|
8 | import {OutputException} from '../exception';
|
9 | import {fileFromString, pathFromString} from '../filesystem';
|
10 | import {Snapshot} from '../snapshot';
|
11 | import {log} from './log';
|
12 | import {pathFromUri} from '../route';
|
13 | import {transformInplace} from './transform';
|
14 |
|
15 | export class HtmlOutput implements OutputProducer {
|
16 | constructor(private options: OutputOptions) {}
|
17 |
|
18 | initialize() {
|
19 | if (this.options.output == null) {
|
20 | throw new OutputException('HTML output writer needs a path to write to');
|
21 | }
|
22 |
|
23 | if (this.options.output.exists() === false) {
|
24 | try {
|
25 | this.options.output.mkdir();
|
26 | }
|
27 | catch (exception) {
|
28 | throw new OutputException(`Cannot create output folder: ${this.options.output.toString()}`, exception);
|
29 | }
|
30 |
|
31 | log.info(`Created output path: ${this.options.output.toString()}`);
|
32 | }
|
33 |
|
34 | return Promise.resolve();
|
35 | }
|
36 |
|
37 | async write<V>(snapshot: Snapshot<V>): Promise<void> {
|
38 | const file = fileFromString(join(this.routedPathFromSnapshot(snapshot).toString(), Files.index));
|
39 |
|
40 | transformInplace(file.parent(), snapshot, this.options);
|
41 |
|
42 | log.info(`Rendered route ${pathFromUri(snapshot.uri)} to ${file}`);
|
43 |
|
44 | file.create(snapshot.renderedDocument);
|
45 |
|
46 | return Promise.resolve(void 0);
|
47 | }
|
48 |
|
49 | exception(exception: Error) {
|
50 | log.error(`Fatal exception encountered: ${chalk.red(exception.toString())}`);
|
51 |
|
52 | return Promise.resolve(void 0);
|
53 | }
|
54 |
|
55 | private routedPathFromSnapshot<V>(snapshot: Snapshot<V>) {
|
56 | const routedPath = pathFromString(join(this.options.output.toString(), pathFromUri(snapshot.uri)));
|
57 |
|
58 | routedPath.mkdir();
|
59 |
|
60 | return routedPath;
|
61 | }
|
62 | }
|