UNPKG

boats

Version:

Beautiful Open / Async Template System - Write less yaml with BOATS and Nunjucks.

68 lines (67 loc) 2.65 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const nunjucks_1 = tslib_1.__importStar(require("nunjucks")); const fs_extra_1 = tslib_1.__importDefault(require("fs-extra")); const upath_1 = tslib_1.__importDefault(require("upath")); const SnippetsFetch_1 = tslib_1.__importDefault(require("./SnippetsFetch")); const dirListFilesSync_1 = require("./utils/dirListFilesSync"); class Snippets { constructor(input) { this.nunjucksSetup(); this.copySnippet(input.injectSnippet, input.subSnippetPath, input.relativeTargetPath, input.targetName).then((target) => { this.renderPlacedSnippet(target, input) .then(() => { console.log('Done'); }) .catch((e) => { console.error(e); }); }).catch((e) => { console.error(e); }); } nunjucksSetup() { nunjucks_1.default.configure({ tags: { blockStart: '~~%', blockEnd: '%~~', variableStart: '~~$', variableEnd: '$~~', commentStart: '~~#', commentEnd: '#~~' } }); } async copySnippet(snippetName, subSnippetPath = '', relativeTargetPath, name) { let localSnippetPath = await SnippetsFetch_1.default.resolve(snippetName); if (subSnippetPath !== '') { localSnippetPath = upath_1.default.join(localSnippetPath, subSnippetPath); } const targetPath = upath_1.default.join(process.cwd(), relativeTargetPath, name); fs_extra_1.default.ensureDirSync(targetPath); const filter = (src) => { // do not return true for .git paths return src.indexOf('.git') === -1; }; fs_extra_1.default.copySync(localSnippetPath, targetPath, { filter }); return targetPath; } renderPlacedSnippet(targetPath, data) { return new Promise((resolve, reject) => { const files = (0, dirListFilesSync_1.dirListFilesSync)(targetPath); files.forEach((file) => { try { const rendered = (0, nunjucks_1.renderString)(fs_extra_1.default.readFileSync(file, 'utf8'), data); fs_extra_1.default.outputFileSync(file, rendered); } catch (e) { console.error(`Error parsing nunjucks file ${file}: `); return reject(e); } }); resolve(); }); } } exports.default = Snippets;