UNPKG

2.46 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const handlebars = require("handlebars");
4const os_1 = require("os");
5const path_1 = require("path");
6const utils_1 = require("./utils");
7const fs = require("fs-extra-plus");
8async function render(templateString, data) {
9 const hbs = getHandlebars();
10 const tmpl = handlebars.compile(templateString, { noEscape: true });
11 const outContent = tmpl(data);
12 return outContent;
13}
14exports.render = render;
15async function loadTemplatizedYaml(path, data) {
16 const stringContent = await fs.readFile(path, 'utf8');
17 const content = await render(stringContent, data);
18 return utils_1.yaml(content);
19}
20exports.loadTemplatizedYaml = loadTemplatizedYaml;
21// --------- Handlebars Factory --------- //
22let _handlebars = null;
23// Initial
24function getHandlebars() {
25 if (_handlebars) {
26 return _handlebars;
27 }
28 // encode64
29 handlebars.registerHelper('encode64', function (arg1, arg2) {
30 let val;
31 let opts;
32 // if we do not have two args, then, it is a regular helper
33 if (arg2 === undefined) {
34 opts = arg1;
35 val = opts.fn(this);
36 }
37 // if we have two args, then, the first is the value
38 else {
39 val = arg1;
40 opts = arg2;
41 }
42 const b64 = Buffer.from(val).toString('base64');
43 return b64;
44 });
45 handlebars.registerHelper('username', function () {
46 const username = os_1.userInfo().username;
47 return username;
48 });
49 // return the absolute dir of the project (where the script is being run) (with an ending '/')
50 handlebars.registerHelper('projectDir', function () {
51 return path_1.resolve('./') + '/';
52 });
53 handlebars.registerHelper('assign', function (varName, varValue, options) {
54 if (!options.data.root) {
55 options.data.root = {};
56 }
57 options.data.root[varName] = varValue;
58 });
59 handlebars.registerHelper('assignJsonValue', function (varName, jsonFile, namePath, options) {
60 if (!options.data.root) {
61 options.data.root = {};
62 }
63 // handlebars helper does not support async
64 const obj = fs.readJsonSync(jsonFile);
65 const val = utils_1.findVal(obj, namePath);
66 options.data.root[varName] = val;
67 });
68 _handlebars = handlebars;
69 return _handlebars;
70}
71// --------- /Handlebars Factory --------- //