UNPKG

1.88 kBPlain TextView Raw
1import { RenderedAction, RunnerConfig } from './types'
2
3const fs = require('fs-extra')
4const ejs = require('ejs')
5const fm = require('front-matter')
6const path = require('path')
7const walk = require('ignore-walk')
8const context = require('./context')
9
10// for some reason lodash/fp takes 90ms to load.
11// inline what we use here with the regular lodash.
12const map = f => arr => arr.map(f)
13const filter = f => arr => arr.filter(f)
14
15const ignores = [
16 'prompt.js',
17 'index.js',
18 '.hygenignore',
19 '.DS_Store',
20 '.Spotlight-V100',
21 '.Trashes',
22 'ehthumbs.db',
23 'Thumbs.db',
24]
25const renderTemplate = (tmpl, locals, config) =>
26 typeof tmpl === 'string' ? ejs.render(tmpl, context(locals, config)) : tmpl
27
28async 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
35const 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))) // TODO: add a test to verify this sort
41 .then(filter(f => !ignores.find(ig => f.endsWith(ig)))) // TODO: add a
42 // test for ignoring prompt.js and index.js
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
64module.exports = render