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