-
Notifications
You must be signed in to change notification settings - Fork 13
/
index.ts
210 lines (195 loc) · 7.08 KB
/
index.ts
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
/*!
* Copyright (c) 2019 Ville de Montreal. All rights reserved.
* Licensed under the MIT license.
* See LICENSE file in the project root for full license information.
*/
import * as colors from 'colors/safe';
import * as fs from 'fs';
import * as path from 'path';
import * as prompt from 'prompt';
import * as shell from 'shelljs';
import { Project, SyntaxKind } from 'ts-morph';
import { symbols } from '../../../configs/constants/symbols';
// Set prompt as green
prompt.message = colors.green('Replace');
const localPath = process.cwd();
/*
* Command function
*/
export const task = async (args, options, logger) => {
const language = options.lang;
const workflowPath = options.file;
const template = args.template;
// tslint:disable: no-console
// console.log(options);
// console.log(args);
if (!template || template !== 'default') {
throw new Error(`Invalid template ${template}`);
}
if (!language || language !== 'node') {
throw new Error(`This language is not supported ${language}`);
}
const templatePath = `${__dirname}/templates/${language}/${template}`.replace(
'workit-cli/lib/command',
'workit-cli/src/command'
);
const contentFile = fs.readFileSync(`${templatePath}/src/task`);
/*
* File variables
*/
const variables = require(`${templatePath}/_variables`);
// Remove variables file from the current directory
// since it only is needed on the template directory
if (fs.existsSync(`${localPath}/_variables.js`)) {
shell.rm(`${localPath}/_variables.js`);
}
if (workflowPath) {
if (!fs.existsSync(workflowPath)) {
throw new Error("Le fichier n'a pas été trouvé");
}
const tasks = getExternalTasks(workflowPath);
// tslint:disable-next-line: variable-name
const ProgressBar = require('progress');
const bar = new ProgressBar(' generating tasks [:bar] :percent :etas', {
complete: '=',
incomplete: ' ',
width: 30,
total: tasks.size
});
for (const currentTask of tasks) {
await processHandler(currentTask, contentFile, true);
bar.tick(1);
}
logger.info(`\n${symbols.ok} Success!`);
} else {
logger.info('Please fill the following values…');
prompt.start().get(variables, (err, result) => {
if (err || !result || !result.className) {
return;
}
processHandler(result.className, contentFile)
.then(() => logger.info(`${symbols.ok} Success!`))
.catch((error: any) => logger.error(`${symbols.err} Fail!\n${error.message}`));
});
}
};
async function processHandler(className, contentFile, isBpmn = false) {
const camelCase = require('camelcase');
const classNameWithMaj = camelCase(className, { pascalCase: true });
const classNameSanitized = camelCase(className);
const project = new Project({
// Optionally specify compiler options, tsconfig.json, virtual file system, and more here.
// If you initialize with a tsconfig.json, then it will automatically populate the project
// with the associated source files.
// Read more: https://dsherret.github.io/ts-morph/setup/
});
if (fs.existsSync(`${localPath}/src/tasks/${classNameSanitized}.ts`)) {
return Promise.resolve();
}
fs.writeFileSync(
`${localPath}/src/tasks/${classNameSanitized}.ts`,
contentFile.toString().replace('[CLASSNAME]', classNameWithMaj)
);
// tslint:disable: no-console
const filePath = path.resolve(`${localPath}/src/config/ioc.ts`);
project.addExistingSourceFiles(filePath);
const file = project.getSourceFile(filePath);
if (file) {
let iocFound = false;
let j = 0;
const statements = file.getDescendantsOfKind(SyntaxKind.ExpressionStatement);
const imports = file.getDescendantsOfKind(SyntaxKind.ImportDeclaration);
while (!iocFound && j < statements.length) {
const exp = statements[j];
const ex = exp.getDescendantsOfKind(SyntaxKind.PropertyAccessExpression);
let i = 0;
while (!iocFound && i < ex.length) {
const prop = ex[i];
const node = prop.compilerNode;
if ((node.expression as any).escapedText === 'IoC') {
iocFound = true;
const firstImport = imports[0];
firstImport.replaceWithText(
`import { ${classNameWithMaj} } from "../tasks/${classNameSanitized}";\n${firstImport.getText()}`
);
exp.replaceWithText(
`IoC.bindTo(${classNameWithMaj}, '${isBpmn ? className : '<ACTIVITY_ID>'}');\n${exp.getText()}`
);
}
i++;
}
j++;
}
// improve this with a pattern
if (!iocFound) {
if (imports.length === 0) {
file.addImportDeclaration({
moduleSpecifier: `../tasks/${classNameSanitized}`,
namedImports: [{ name: classNameWithMaj }]
});
file.addImportDeclaration({
moduleSpecifier: `workit-camunda`,
namedImports: [{ name: 'IoC' }]
});
} else {
const firstImport = imports[0];
firstImport.replaceWithText(
`import { ${classNameWithMaj} } from "../tasks/${classNameSanitized}";\n${firstImport.getText()}`
);
}
if (statements.length === 0) {
file.addStatements(writer =>
writer.newLine().writeLine(`IoC.bindTo(${classNameWithMaj}, '${isBpmn ? className : '<ACTIVITY_ID>'}');`)
);
} else {
const statement = statements[0];
statement.replaceWithText(
`\nIoC.bindTo(${classNameWithMaj}, '${isBpmn ? className : '<ACTIVITY_ID>'}');\n${statement.getText()}`
);
}
}
file.organizeImports();
await project.save();
}
}
function getExternalTasks(pathToFile: string): Set<string> {
const parser = require('fast-xml-parser');
const he = require('he');
const options = {
attributeNamePrefix: '',
attrNodeName: '', // default is false
textNodeName: '#text',
ignoreAttributes: false,
cdataTagName: '__cdata', // default is false
cdataPositionChar: '\\c',
format: false,
indentBy: ' ',
supressEmptyNode: false,
tagValueProcessor: a => he.encode(a, { useNamedReferences: true }), // default is a=>a
attrValueProcessor: a => he.encode(a, { isAttributeValue: true, useNamedReferences: true }) // default is a=>a
};
const xmlData = fs.readFileSync(pathToFile).toString();
const externalTasks = new Set<string>();
if (!parser.validate(xmlData)) {
throw new Error('Your bpmn file cannot be parsed as xml file.');
}
const bpmn = parser.parse(xmlData, options);
const bpmnDef = bpmn['bpmn:definitions'];
const bpmnProc = bpmnDef['bpmn:process'];
let serviceTasks = bpmnProc['bpmn:serviceTask'];
if (!Array.isArray(serviceTasks)) {
serviceTasks = [serviceTasks];
}
serviceTasks.forEach((_task: any) => {
if (_task['camunda:type'] === 'external' || _task['bpmn:extensionElements']['zeebe:taskDefinition']) {
// const className = camelCase(task.id, { pascalCase: true });
// this.fs.copyTpl(
// this.templatePath('task.ts'),
// this.destinationPath(`src/tasks/${ camelCase(task.id) }`),
// { className }
// );
externalTasks.add(_task.id);
}
});
return externalTasks;
}