-
Notifications
You must be signed in to change notification settings - Fork 175
Expand file tree
/
Copy pathcommands.js
More file actions
313 lines (284 loc) · 11.7 KB
/
commands.js
File metadata and controls
313 lines (284 loc) · 11.7 KB
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
const Logger = require('@accordproject/concerto-util').Logger;
const FileWriter = require('@accordproject/concerto-util').FileWriter;
const Template = require('@accordproject/cicero-core').Template;
const { CodeGen } = require('@accordproject/concerto-codegen');
/**
* Utility class that implements the commands exposed by the Cicero CLI.
* @class
* @memberof module:cicero-cli
*/
class Commands {
/**
* Whether the template path is to a file (template archive)
* @param {string} templatePath - path to the template directory or archive
* @return {boolean} true if the path is to a file, false otherwise
*/
static isTemplateArchive(templatePath) {
return fs.lstatSync(templatePath).isFile();
}
/**
* Return a promise to a template from either a directory or an archive file
* @param {string} templatePath - path to the template directory or archive
* @param {Object} [options] - an optional set of options
* @return {Promise<Template>} a Promise to the instantiated template
*/
static loadTemplate(templatePath, options) {
if (Commands.isTemplateArchive(templatePath)) {
const buffer = fs.readFileSync(templatePath);
return Template.fromArchive(buffer, options);
} else {
return Template.fromDirectory(templatePath, options);
}
}
/**
* Common default params before we create an archive using a template
*
* @param {object} argv - the inbound argument values object
* @returns {object} a modfied argument object
*/
static validateCommonArgs(argv) {
// the user typed 'cicero [command] [template]'
if(argv._.length === 2){
argv.template = argv._[1];
}
if(!argv.template){
Logger.info('Using current directory as template folder');
argv.template = '.';
}
argv.template = path.resolve(argv.template);
if (!Commands.isTemplateArchive(argv.template)) {
const packageJsonExists = fs.existsSync(path.resolve(argv.template,'package.json'));
let isAPTemplate = false;
if(packageJsonExists){
let packageJsonContents = JSON.parse(fs.readFileSync(path.resolve(argv.template,'package.json')),'utf8');
isAPTemplate = packageJsonContents.accordproject;
}
if(!packageJsonExists || !isAPTemplate){
throw new Error(`${argv.template} is not a valid cicero template. Make sure that package.json exists and that it has a cicero entry.`);
}
}
return argv;
}
/**
* Set default params before we create an archive using a template
*
* @param {object} argv the inbound argument values object
* @returns {object} a modfied argument object
*/
static validateArchiveArgs(argv) {
return Commands.validateCommonArgs(argv);
}
/**
* Create an archive using a template
*
* @param {string} templatePath - path to the template directory or archive
* @param {string} target - target language for the archive
* @param {string} outputPath - to the archive file
* @param {Object} [options] - an optional set of options
* @returns {object} Promise to the code creating an archive
*/
static archive(templatePath, target, outputPath, options) {
return Commands.loadTemplate(templatePath, options)
.then(async (template) => {
let keystore = null;
if (options.keystore) {
const p12File = fs.readFileSync(options.keystore.path, { encoding: 'base64' });
const inputKeystore = {
p12File: p12File,
passphrase: options.keystore.passphrase
};
keystore = inputKeystore;
}
const archive = await template.toArchive(target, {keystore}, options);
let file;
if (outputPath) {
file = outputPath;
}
else {
const templateName = template.getMetadata().getName();
const templateVersion = template.getMetadata().getVersion();
file = `${templateName}@${templateVersion}.cta`;
}
Logger.info('Creating archive: ' + file);
fs.writeFileSync(file, archive);
return true;
});
}
/**
* Set default params before we verify signatures of template author/developer
*
* @param {object} argv the inbound argument values object
* @returns {object} a modfied argument object
*/
static validateVerifyArgs(argv) {
argv = Commands.validateCommonArgs(argv);
return argv;
}
/**
* Verify the template developer/author's signatures
*
* @param {string} templatePath - path to the template directory or archive
* @param {Object} [options] - an optional set of options
* @returns {object} returns true if signature is valid else false
*/
static verify(templatePath, options) {
return Commands.loadTemplate(templatePath, options)
.then((template) => {
return template.verifyTemplateSignature();
});
}
/**
* Set default params before we compile a template
*
* @param {object} argv the inbound argument values object
* @returns {object} a modfied argument object
*/
static validateCompileArgs(argv) {
argv = Commands.validateCommonArgs(argv);
if(argv.verbose) {
Logger.info(`compile using a template ${argv.template}`);
}
return argv;
}
/**
* Compile the template to a given target
*
* @param {string} templatePath - path to the template directory or archive
* @param {string} target - the target format
* @param {string} outputPath - the output directory
* @param {Object} [options] - an optional set of options
* @returns {object} Promise to the result of code generation
*/
static compile(templatePath, target, outputPath, options) {
return Commands.loadTemplate(templatePath, options)
.then((template) => {
const VisitorClass = CodeGen.formats[target];
if(!VisitorClass) {
throw new Error ('Unrecognized code generator: ' + target);
}
const visitor = new VisitorClass();
console.log('generating code...');
let parameters = {};
parameters.fileWriter = new FileWriter(outputPath);
template.getModelManager().accept(visitor, parameters);
})
.catch((err) => {
Logger.error(err);
});
}
/**
* Set default params before we download external dependencies
*
* @param {object} argv the inbound argument values object
* @returns {object} a modfied argument object
*/
static validateGetArgs(argv) {
argv = Commands.validateCommonArgs(argv);
if (!argv.output) {
if (Commands.isTemplateArchive(argv.template)) {
argv.output = './model';
} else {
argv.output = path.resolve(argv.template,'model');
}
}
return argv;
}
/**
* Set default params before we list vocabularies
*
* @param {object} argv the inbound argument values object
* @returns {object} a modfied argument object
*/
static validateVocabularyArgs(argv) {
return Commands.validateCommonArgs(argv);
}
/**
* List or query vocabulary terms for a template
*
* @param {string} templatePath - path to the template directory or archive
* @param {string} locale - the BCP-47 locale to query
* @param {Object} [options] - an optional set of options
* @returns {object} Promise to the vocabulary information
*/
static vocabulary(templatePath, locale, options) {
return Commands.loadTemplate(templatePath, options)
.then((template) => {
const vocManager = template.getVocabularyManager();
const vocFiles = template.getVocFiles();
const defaultLocale = template.getMetadata().getDefaultLocale();
if (vocFiles.length === 0) {
Logger.info('No vocabulary files found in this template.');
return {};
}
Logger.info(`Found ${vocFiles.length} vocabulary file(s). Default locale: ${defaultLocale || 'not set'}`);
if (locale) {
// Query terms for a specific locale
const modelFiles = template.getModelManager().getModelFiles().filter(mf => !mf.isSystemModelFile?.());
const results = {};
modelFiles.forEach(mf => {
const ns = mf.getNamespace();
const voc = template.getVocabulary(ns, locale);
if (voc) {
Logger.info(`\nVocabulary for ${ns} (locale: ${voc.getLocale()}):`);
const terms = voc.getTerms();
terms.forEach(decl => {
const declName = Object.keys(decl)[0];
Logger.info(` ${declName}: ${decl[declName]}`);
if (decl.properties) {
decl.properties.forEach(prop => {
const propName = Object.keys(prop)[0];
Logger.info(` ${propName}: ${prop[propName]}`);
});
}
});
results[ns] = terms;
} else {
Logger.info(`\nNo vocabulary found for ${ns} in locale: ${locale}`);
}
});
return results;
} else {
// List available vocabularies
vocFiles.forEach(file => {
Logger.info(` - ${file.name}`);
});
return { files: vocFiles.map(f => f.name), defaultLocale };
}
});
}
/**
* Fetches all external for a set of models dependencies and
* saves all the models to a target directory
*
* @param {string} templatePath the system model
* @param {string} output the output directory
* @return {string} message
*/
static async get(templatePath, output) {
return Commands.loadTemplate(templatePath, {})
.then((template) => {
const modelManager = template.getModelManager();
mkdirp.sync(output);
modelManager.writeModelsToFileSystem(output);
return `Loaded external models in '${output}'.`;
});
}
}
module.exports = Commands;