UNPKG

apeman-tmpl

Version:
80 lines (72 loc) 2.19 kB
/** * Get templates from Apemanfile. * @function getTemplates * @param {object} apemanfile * @param {string} pattern to filter. * @returns {object[]} - Array of bud. */ "use strict"; const extend = require('extend'), path = require('path'), arrayfilter = require('arrayfilter'), minimatch = require('minimatch'); /** @lends getTemplates */ function getTemplates(apemanfile, pattern) { let results = []; let $tmpls = apemanfile.$tmpls || {}; let emptyReject = arrayfilter.emptyReject(); Object.keys($tmpls).forEach((filename) => { let rejected = pattern && !minimatch(filename, pattern); if (rejected) { return; } let tmpl = $tmpls[filename]; [].concat(tmpl).filter(emptyReject) .map((tmpl) => { if (typeof tmpl === 'string') { tmpl = _textTmpl(tmpl); } return tmpl; }) .filter((tmpl) => { return Object.keys(tmpl).length > 0; }) .forEach((tmpl) => { tmpl = extend({ path: filename, mkdirp: true }, tmpl); results.push(tmpl); }); }); return results.sort((a, b) => { let pathA = a.path, pathB = b.path; return pathA.localeCompare(pathB); }); } function _textTmpl(text) { return { data: {text: text}, tmpl: function (data) { return String(data.text); } }; } getTemplates.childTmpls = function (apemanfile, pattern) { let $cwd = apemanfile.$cwd || process.cwd(); let $children = apemanfile.$children || {}; let result = {}; Object.keys($children).forEach((name) => { let $child = $children[name]; if (!$child.$cwd) { throw new Error('$cwd not found with apemanfile: ' + JSON.stirngify($child)); } result[name] = getTemplates($child, pattern).map((tmpl) => { tmpl.path = path.resolve($child.$cwd, tmpl.path); return tmpl; }); }); return result; }; module.exports = getTemplates;