UNPKG

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