1 | import * as fs from 'fs-extra';
|
2 | import * as handlebars from 'handlebars';
|
3 | import { HelperOptions } from 'handlebars';
|
4 | import { userInfo } from 'os';
|
5 | import { resolve } from 'path';
|
6 | import { findVal, yaml } from './utils';
|
7 |
|
8 | export 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 |
|
15 | export 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 |
|
28 | let _handlebars: typeof Handlebars | null = null;
|
29 |
|
30 | function getHandlebars() {
|
31 | if (_handlebars) {
|
32 | return _handlebars;
|
33 | }
|
34 |
|
35 |
|
36 | handlebars.registerHelper('encode64', function (this: any, arg1: any, arg2: any) {
|
37 | let val: string;
|
38 | let opts: any;
|
39 |
|
40 | if (arg2 === undefined) {
|
41 | opts = arg1;
|
42 | val = opts.fn(this);
|
43 | }
|
44 |
|
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 |
|
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 |
|
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 |
|
86 |
|
87 |
|