-
-
Notifications
You must be signed in to change notification settings - Fork 192
/
Copy pathoptimize.ts
185 lines (168 loc) · 7.07 KB
/
optimize.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
import { Flags } from '@oclif/core';
import { Optimizer, Output, Report, ReportElement } from '@asyncapi/optimizer';
import Command from '../base';
import { ValidationError } from '../errors/validation-error';
import { load, Specification } from '../models/SpecificationFile';
import * as inquirer from 'inquirer';
import chalk from 'chalk';
import { promises } from 'fs';
import { Example } from '@oclif/core/lib/interfaces';
const { writeFile } = promises;
export enum Optimizations {
REMOVE_COMPONENTS='remove-components',
REUSE_COMPONENTS='reuse-components',
MOVE_TO_COMPONETS='move-to-components'
}
export enum Outputs {
TERMINAL='terminal',
NEW_FILE='new-file',
OVERWRITE='overwrite'
}
export default class Optimize extends Command {
static description = 'optimize asyncapi specification file';
isInteractive = false;
optimizations?: Optimizations[];
outputMethod?: Outputs;
static examples: Example[] = [
'asyncapi optimize ./asyncapi.yaml',
'asyncapi optimize ./asyncapi.yaml --no-tty',
'asyncapi optimize ./asyncapi.yaml --optimization=remove-components,reuse-components,move-to-components --no-tty',
'asyncapi optimize ./asyncapi.yaml --optimization=remove-components,reuse-components,move-to-components --output=terminal --no-tty',
];
static flags = {
help: Flags.help({ char: 'h' }),
optimization: Flags.string({char: 'p', default: Object.values(Optimizations), options: Object.values(Optimizations), multiple: true, description: 'select the type of optimizations that you want to apply.'}),
output: Flags.string({char: 'o', default: Outputs.TERMINAL, options: Object.values(Outputs), description: 'select where you want the output.'}),
'no-tty': Flags.boolean({ description: 'do not use an interactive terminal', default: false }),
};
static args = [
{ name: 'spec-file', description: 'spec path, url, or context-name', required: false },
];
async run() {
const { args, flags } = await this.parse(Optimize); //NOSONAR
const filePath = args['spec-file'];
let specFile: Specification;
try {
specFile = await load(filePath);
} catch (err) {
this.error(
new ValidationError({
type: 'invalid-file',
filepath: filePath,
})
);
}
if (specFile.isAsyncAPI3()) {
this.error('Optimize command does not support AsyncAPI v3 yet, please checkout https://github.com/asyncapi/optimizer/issues/168');
}
let optimizer: Optimizer;
let report: Report;
try {
optimizer = new Optimizer(specFile.text());
report = await optimizer.getReport();
} catch (err) {
this.error(
new ValidationError({
type: 'invalid-file',
filepath: filePath,
})
);
}
this.isInteractive = !flags['no-tty'];
this.optimizations = flags.optimization as Optimizations[];
this.outputMethod = flags.output as Outputs;
if (!(report.moveToComponents?.length || report.removeComponents?.length || report.reuseComponents?.length)) {
this.log(`No optimization has been applied since ${specFile.getFilePath() ?? specFile.getFileURL()} looks optimized!`);
return;
}
const isTTY = process.stdout.isTTY;
if (this.isInteractive && isTTY) {
await this.interactiveRun(report);
}
try {
const optimizedDocument = optimizer.getOptimizedDocument({rules: {
moveToComponents: this.optimizations.includes(Optimizations.MOVE_TO_COMPONETS),
removeComponents: this.optimizations.includes(Optimizations.REMOVE_COMPONENTS),
reuseComponents: this.optimizations.includes(Optimizations.REUSE_COMPONENTS)
}, output: Output.YAML});
const specPath = specFile.getFilePath();
let newPath = '';
if (specPath) {
const pos = specPath.lastIndexOf('.');
newPath = `${specPath.substring(0,pos) }_optimized.${ specPath.substring(pos+1)}`;
} else {
newPath = 'optimized-asyncapi.yaml';
}
if (this.outputMethod === Outputs.TERMINAL) {
this.log(optimizedDocument);
} else if (this.outputMethod === Outputs.NEW_FILE) {
await writeFile(newPath, optimizedDocument, { encoding: 'utf8' });
this.log(`Created file ${newPath}...`);
} else if (this.outputMethod === Outputs.OVERWRITE) {
await writeFile(specPath ?? 'asyncapi.yaml', optimizedDocument, { encoding: 'utf8' });
this.log(`Created file ${newPath}...`);
}
} catch (error) {
throw new ValidationError({
type: 'parser-error',
err: error
});
}
}
private showOptimizations(elements: ReportElement[] | undefined) {
if (!elements) {
return;
}
for (let i = 0; i < elements.length; i++) {
const element = elements[+i];
if (element.action==='move') {
this.log(`${chalk.green('move')} ${element.path} to ${element.target} and reference it.`);
} else if (element.action==='reuse') {
this.log(`${chalk.green('reuse')} ${element.target} in ${element.path}.`);
} else if (element.action === 'remove') {
this.log(`${chalk.red('remove')} ${element.path}.`);
}
}
this.log('\n');
}
private async interactiveRun(report: Report) {
const canMove = report.moveToComponents?.length;
const canRemove = report.removeComponents?.length;
const canReuse = report.reuseComponents?.length;
const choices = [];
if (canMove) {
const totalMove = report.moveToComponents?.filter((e: ReportElement) => e.action === 'move').length;
this.log(`\n${chalk.green(totalMove)} components can be moved to the components sections.\nthe following changes will be made:`);
this.showOptimizations(report.moveToComponents);
choices.push({name: 'move to components section', value: Optimizations.MOVE_TO_COMPONETS});
}
if (canRemove) {
const totalMove = report.removeComponents?.length;
this.log(`${chalk.green(totalMove)} unused components can be removed.\nthe following changes will be made:`);
this.showOptimizations(report.removeComponents);
choices.push({name: 'remove components', value: Optimizations.REMOVE_COMPONENTS});
}
if (canReuse) {
const totalMove = report.reuseComponents?.length;
this.log(`${chalk.green(totalMove)} components can be reused.\nthe following changes will be made:`);
this.showOptimizations(report.reuseComponents);
choices.push({name: 'reuse components', value: Optimizations.REUSE_COMPONENTS});
}
const optimizationRes = await inquirer.prompt([{
name: 'optimization',
message: 'select the type of optimization that you want to apply:',
type: 'checkbox',
default: 'all',
choices
}]);
this.optimizations = optimizationRes.optimization;
const outputRes = await inquirer.prompt([{
name: 'output',
message: 'where do you want to save the result:',
type: 'list',
default: 'log to terminal',
choices: [{name: 'log to terminal',value: Outputs.TERMINAL}, {name: 'create new file', value: Outputs.NEW_FILE}, {name: 'update original', value: Outputs.OVERWRITE}]
}]);
this.outputMethod = outputRes.output;
}
}