1 | import { RenderedAction, RunnerConfig } from './types'
|
2 |
|
3 | const fs = require('fs-extra')
|
4 | const ejs = require('ejs')
|
5 | const fm = require('front-matter')
|
6 | const path = require('path')
|
7 | const walk = require('ignore-walk')
|
8 | const context = require('./context')
|
9 |
|
10 |
|
11 |
|
12 | const map = f => arr => arr.map(f)
|
13 | const filter = f => arr => arr.filter(f)
|
14 |
|
15 | const ignores = [
|
16 | 'prompt.js',
|
17 | 'index.js',
|
18 | '.hygenignore',
|
19 | '.DS_Store',
|
20 | '.Spotlight-V100',
|
21 | '.Trashes',
|
22 | 'ehthumbs.db',
|
23 | 'Thumbs.db',
|
24 | ]
|
25 | const renderTemplate = (tmpl, locals, config) =>
|
26 | typeof tmpl === 'string' ? ejs.render(tmpl, context(locals, config)) : tmpl
|
27 |
|
28 | async function getFiles(dir) {
|
29 | const files = walk
|
30 | .sync({ path: dir, ignoreFiles: ['.hygenignore'] })
|
31 | .map(f => path.join(dir, f))
|
32 | return files
|
33 | }
|
34 |
|
35 | const render = async (
|
36 | args: any,
|
37 | config: RunnerConfig,
|
38 | ): Promise<RenderedAction[]> =>
|
39 | getFiles(args.actionfolder)
|
40 | .then(things => things.sort((a, b) => a.localeCompare(b)))
|
41 | .then(filter(f => !ignores.find(ig => f.endsWith(ig))))
|
42 |
|
43 | .then(filter(file => (args.subaction ? file.match(args.subaction) : true)))
|
44 | .then(
|
45 | map(file =>
|
46 | fs.readFile(file).then(text => ({ file, text: text.toString() })),
|
47 | ),
|
48 | )
|
49 | .then(_ => Promise.all(_))
|
50 | .then(map(({ file, text }) => Object.assign({ file }, fm(text))))
|
51 | .then(
|
52 | map(({ file, attributes, body }) => ({
|
53 | file,
|
54 | attributes: Object.entries(attributes).reduce((obj, [key, value]) => {
|
55 | return {
|
56 | ...obj,
|
57 | [key]: renderTemplate(value, args, config),
|
58 | }
|
59 | }, {}),
|
60 | body: renderTemplate(body, args, config),
|
61 | })),
|
62 | )
|
63 |
|
64 | module.exports = render
|