-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
256 lines (226 loc) · 6.92 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
import * as yaml from 'js-yaml';
import fs from 'fs';
import * as path from 'path';
import Mustache from 'mustache';
import {LOG_FORMAT, YAML_STRUCTURE} from './util.js';
import * as winston from 'winston';
import * as yamlValidator from 'yaml-validator';
import YamlValidator from 'yaml-validator';
let log = winston.createLogger({
level: 'warn',
format: LOG_FORMAT,
transports: [new winston.transports.Console()]
});
/*
async function template(options): boolean
options: {
workingDirectory: string
directory to be used as working directory and source of manifest.yml files and templates
default: '.' (current directory)
log: winston.Logger
logger to be used for logging
}
*/
export async function template(options) {
if(options.log) {
log = options.log;
}
const workingDirectory = path.resolve(options.workingDirectory || '.');
log.debug(`working directory: ${workingDirectory}`);
const templates = getTemplates(workingDirectory);
let manifest = {};
if(!options.manifestData) {
const manifestFiles = getManifestFiles(workingDirectory, options.manifest);
for(const manifestFile of manifestFiles) {
try {
const doc = yaml.load(fs.readFileSync(manifestFile, 'utf8'));
manifest = mergeDeep(manifest, doc);
}
catch(err) {
log.error(`Error loading manifest file: ${manifestFile}`);
}
}
}
else {
try {
// TODO validate manifestData
manifest = yaml.load(options.manifestData);
}
catch(err) {
log.error(`Error reading manifest data`);
}
}
log.debug(`\n\n-----------------------------------------------------------\n`)
log.debug(JSON.stringify(manifest, null, 2));
log.debug(`\n-----------------------------------------------------------\n\n`)
for(const file of manifest.files) {
let templateMatch = false;
let templateFile = '';
for(const template of templates) {
if(template.endsWith(file.template) || template.endsWith(`${file.template}.mustache`)) {
templateMatch = true;
templateFile = template;
break;
}
}
if(!templateMatch) {
log.error(`template ${file.template} not found`);
throw new Error(`template '${file.template}' not found`);
}
const template = fs.readFileSync(templateFile, 'utf8');
const output = Mustache.render(template, file.values);
const outputFile = path.resolve(path.join(workingDirectory, file.destination));
log.debug(`output file: '${outputFile}'`);
const parentDir = path.dirname(outputFile);
log.debug(`output file parent dir: '${parentDir}'`);
if(!fs.existsSync(parentDir)) {
log.debug(`creating parent dir '${parentDir}'`);
if(!options.dryrun) {
fs.mkdirSync(parentDir, { recursive: true});
}
else {
log.debug(`not creating parent dir due to '--dryrun'`);
}
}
else {
log.debug(`parent dir already exists`);
}
log.debug(`writing file: ${outputFile}`);
if(!options.dryrun) {
fs.writeFileSync(outputFile, output);
}
else {
log.debug(`not writing file due to '--dryrun'`);
}
if(options.console) {
console.log(`# From template '${file.template}'`);
console.log(output);
}
}
}
function getTemplates(workingDirectory) {
const templates = [];
try {
const files = fs.readdirSync(workingDirectory);
for(const file of files) {
const filePath = path.join(workingDirectory, file);
if(!fs.statSync(filePath).isDirectory() && file.endsWith('.mustache')) {
log.debug(`found template: ${filePath}`);
templates.push(filePath);
}
}
}
catch(err) {
log.error(err);
}
return templates;
}
function getManifestFiles(workingDirectory, manifestFile) {
const manifests = [];
const addManifestFile = (file, fail) => {
const valid = validateManifestFile(file);
if(valid) {
log.debug(`found valid manifest file: ${file}`);
manifests.push(file);
}
else {
const exists = fs.existsSync(file);
const message = exists ? `invalid manifest file: ${file}` : `manifest file '${file}' does not exist`;
if(fail) {
log.error(message);
throw new Error(message);
}
else {
log.warn(message);
}
}
}
// check if --manifest is specified in options
const manifestFileGiven = manifestFile && typeof(manifestFile) === 'string' && manifestFile.length > 0;
if(manifestFileGiven) {
const manifestFilePath = path.resolve(manifestFile);
addManifestFile(manifestFilePath, true);
}
// otherwise check for manifest.yml in working directory
else {
const manifestFileDefaults = ['manifest.yml', 'manifest.yaml'];
for(const manifestFileDefault of manifestFileDefaults) {
const manifestFilePath = path.join(workingDirectory, manifestFileDefault);
if(fs.existsSync(manifestFilePath)) {
addManifestFile(manifestFilePath, false);
break;
}
}
}
// otherwise check for any .yml files in working directory
if(manifests.length === 0) {
const files = fs.readdirSync(workingDirectory);
for(const file of files) {
const filePath = path.join(workingDirectory, file);
if(!fs.statSync(filePath).isDirectory() && (file.endsWith('.yml') || file.endsWith('.yaml'))) {
addManifestFile(filePath, false);
}
}
}
if(manifests.length === 0) {
log.error('no valid manifest files available');
throw new Error('no valid manifest files available');
}
return manifests;
}
function validateManifestFile(file) {
if(!fs.existsSync(file)) {
log.error(`manifest file does not exist: ${file}`);
throw new Error(`manifest file does not exist: ${file}`);
}
const options = {
log: true,
structure: YAML_STRUCTURE,
writeJson: false,
onWarning: (warning) => {
log.warn(warning);
}
}
const validator = new YamlValidator(options);
validator.validate([file]);
return validator.report() === 0;
}
function isObject(item) {
return (item && typeof item === 'object' && !Array.isArray(item));
}
function mergeDeep(target, ...sources) {
if (!sources.length) { return target; }
const source = sources.shift();
if (isObject(target) && isObject(source)) {
for (const key in source) {
if (isObject(source[key])) {
if (!target[key]) {
Object.assign(target, { [key]: {} });
}
mergeDeep(target[key], source[key]);
} else {
if(Array.isArray(target[key]) && Array.isArray(source[key])) {
target[key].push(...source[key])
}
else {
Object.assign(target, { [key]: source[key] });
}
}
}
}
return mergeDeep(target, ...sources);
}
/*
try {
const doc = yaml.load(fs.readFileSync('/home/ixti/example.yml', 'utf8'));
console.log(doc);
} catch (e) {
console.log(e);
}
var view = {
title: "Joe",
calc: function () {
return 2 + 4;
}
};
var output = Mustache.render("{{title}} spends {{calc}}", view); */