UNPKG

2.38 kBPlain TextView Raw
1import * as fs from 'fs-extra-plus';
2import * as handlebars from 'handlebars';
3import { HelperOptions } from 'handlebars';
4import { userInfo } from 'os';
5import { resolve } from 'path';
6import { findVal, yaml } from './utils';
7
8export async function render(templateString: string, data: any) {
9 const hbs = getHandlebars();
10 const tmpl = hbs.compile(templateString, { noEscape: true });
11 const outContent = tmpl(data);
12 return outContent;
13}
14
15export async function loadTemplatizedYaml(path: string, data?: any) {
16 try {
17 const stringContent = await fs.readFile(path, 'utf8');
18 const content = await render(stringContent, data);
19 return yaml(content);
20 } catch (ex) {
21 console.log(`ERROR - Cannot load ${resolve(path)}\n\tcause ${ex}`);
22 throw ex;
23 }
24
25}
26
27// --------- Handlebars Factory --------- //
28let _handlebars: typeof Handlebars | null = null;
29// Initial
30function getHandlebars() {
31 if (_handlebars) {
32 return _handlebars;
33 }
34
35 // encode64
36 handlebars.registerHelper('encode64', function (this: any, arg1: any, arg2: any) {
37 let val: string;
38 let opts: any;
39 // if we do not have two args, then, it is a regular helper
40 if (arg2 === undefined) {
41 opts = arg1;
42 val = opts.fn(this);
43 }
44 // if we have two args, then, the first is the value
45 else {
46 val = arg1 as string;
47 opts = arg2;
48 }
49 const b64 = Buffer.from(val).toString('base64');
50 return b64;
51 });
52
53 handlebars.registerHelper('username', function () {
54 const username = userInfo().username;
55 return username;
56 });
57
58 // return the absolute dir of the project (where the script is being run) (with an ending '/')
59 handlebars.registerHelper('projectDir', function () {
60 return resolve('./') + '/';
61 });
62
63 handlebars.registerHelper('assign', function (this: any, varName: string, varValue: any, options: HelperOptions) {
64 if (!options.data.root) {
65 options.data.root = {};
66 }
67 options.data.root[varName] = varValue;
68 });
69
70 handlebars.registerHelper('assignJsonValue', function (this: any, varName: string, jsonFile: any, namePath: any, options: HelperOptions) {
71 if (!options.data.root) {
72 options.data.root = {};
73 }
74 // handlebars helper does not support async
75 const obj = fs.readJsonSync(jsonFile);
76 const val = findVal(obj, namePath);
77 options.data.root[varName] = val;
78 });
79
80
81
82 _handlebars = handlebars;
83 return _handlebars;
84}
85// --------- /Handlebars Factory --------- //
86
87