apeman-tmpl
Version:
Template manager for apeman.
92 lines (83 loc) • 2.32 kB
JavaScript
/**
* Get templates from Apemanfile.
* @function getTemplates
* @param {object} apemanfile
* @param {string} pattern to filter.
* @returns {object[]} - Array of bud.
*/
const path = require('path')
const arrayfilter = require('arrayfilter')
const arrayreduce = require('arrayreduce')
const minimatch = require('minimatch')
let rejectEmpty = arrayfilter.emptyReject()
let concatArray = arrayreduce.arrayConcat()
/** @lends getTemplates */
function getTemplates (configuration, names) {
let $tmpls = configuration.get('$tmpls') || {}
return Object.keys($tmpls)
.filter((filename) => {
let hasFilter = names && names.length > 0
if (!hasFilter) {
return true
}
for (let i = 0, len = names.length; i < len; i++) {
let hit = minimatch(filename, names[ i ])
if (hit) {
return true
}
}
return false
})
.map((filename) => {
let tmpl = $tmpls[ filename ]
return [].concat(tmpl)
.reduce(concatArray, [])
.filter(rejectEmpty)
.map((tmpl) => {
if (typeof tmpl === 'string') {
tmpl = _textTmpl(tmpl)
}
return tmpl
})
.filter((tmpl) => {
return Object.keys(tmpl).length > 0
})
.map((tmpl) => {
return Object.assign({
path: filename,
mkdirp: true
}, tmpl)
})
})
.reduce(concatArray, [])
.filter(rejectEmpty)
.sort((a, b) => a.path.localeCompare(b.path))
}
function _textTmpl (text) {
return {
data: { text: text },
tmpl (data) {
return String(data.text)
}
}
}
getTemplates.childTmpls = function (configuration, names) {
let $children = configuration.get('$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))
}
let relativeNames = names && names.map((name) => {
return path.relative($child.$cwd, name)
})
result[ name ] = getTemplates($child, relativeNames).map((tmpl) => {
tmpl.path = path.resolve($child.$cwd, tmpl.path)
return tmpl
})
})
return result
}
module.exports = getTemplates