1 | 'use strict';
|
2 |
|
3 | const fs = require('hexo-fs');
|
4 | const Promise = require('bluebird');
|
5 | const pathFn = require('path');
|
6 | const chalk = require('chalk');
|
7 |
|
8 | function assetGenerator(locals) {
|
9 | const self = this;
|
10 |
|
11 | function process(name) {
|
12 | return Promise.filter(self.model(name).toArray(), asset => fs.exists(asset.source).then(exist => {
|
13 | if (exist) return exist;
|
14 | return asset.remove().thenReturn(exist);
|
15 | })).map(asset => {
|
16 | const source = asset.source;
|
17 | let path = asset.path;
|
18 | const data = {
|
19 | modified: asset.modified
|
20 | };
|
21 |
|
22 | if (asset.renderable && self.render.isRenderable(path)) {
|
23 |
|
24 | const extname = pathFn.extname(path);
|
25 | const filename = path.substring(0, path.length - extname.length);
|
26 |
|
27 | path = `${filename}.${self.render.getOutput(path)}`;
|
28 |
|
29 | data.data = () => self.render.render({
|
30 | path: source,
|
31 | toString: true
|
32 | }).catch(err => {
|
33 | self.log.error({err}, 'Asset render failed: %s', chalk.magenta(path));
|
34 | });
|
35 | } else {
|
36 | data.data = () => fs.createReadStream(source);
|
37 | }
|
38 |
|
39 | return {
|
40 | path,
|
41 | data
|
42 | };
|
43 | });
|
44 | }
|
45 |
|
46 | return Promise.all([
|
47 | process('Asset'),
|
48 | process('PostAsset')
|
49 | ]).then(data => Array.prototype.concat.apply([], data));
|
50 | }
|
51 |
|
52 | module.exports = assetGenerator;
|