forked from Azure/azure-rest-api-specs
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlatest-profile-generator.ts
315 lines (275 loc) · 10.5 KB
/
latest-profile-generator.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
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
314
315
import * as fs from "@ts-common/fs"
import * as process from "process"
import * as Path from "path"
import * as cm from "@ts-common/commonmark-to-markdown"
import * as it from "@ts-common/iterator"
import * as yaml from "js-yaml"
import { values, keys } from '@ts-common/string-map';
type Code = {
readonly "input-file"?: ReadonlyArray<string>|string
}
const main = async (specificationsDirectory: string, profilesDirectory: string) => {
try {
const list = fs.recursiveReaddir(specificationsDirectory);
const specs = [];
let foundMultiApiReadmes = false;
for await (const file of list) {
const f = Path.parse(file);
if (f.base === "readme.enable-multi-api.md") {
foundMultiApiReadmes = true;
const content = (await fs.readFile(file)).toString();
const readMe = cm.parse(content);
const set = new Set<string>();
for (const c of cm.iterate(readMe.markDown)) {
if (
c.type === "code_block" &&
c.info !== null &&
c.info.startsWith("yaml") &&
c.literal !== null
) {
const y = (yaml.load(c.literal) as Code)["input-file"];
if (typeof y === "string") {
set.add(y.replace('$(this-folder)', ''));
} else if (it.isArray(y)) {
for (const i of y) {
let cleanFilePath = i.replace('$(this-folder)', '');
set.add(cleanFilePath);
specs.push(Path.join(f.dir, cleanFilePath));
}
}
}
}
}
}
if (!foundMultiApiReadmes){
throw `Couldn't find any readme.enable-multi-api.md files.`
}
const allPaths = await getPaths(specs);
const crawlResult = getCrawlData(allPaths);
const telemetryDir = Path.join(profilesDirectory, 'crawl-log.json')
fs.writeFile(telemetryDir, JSON.stringify(crawlResult, null, 2));
console.log(`Telemetry written at ${telemetryDir}`);
const latestProfile = getLatestProfile(crawlResult);
const latestProfileMarkDown = cm.markDownExToString(
{
markDown: cm.createNode(
"document",
cm.createNode(
"heading",
cm.createText("Latest Azure Profile")
),
cm.createNode(
"block_quote",
cm.createNode(
"paragraph",
cm.createText("see https://aka.ms/autorest")
)
),
cm.createCodeBlock(
"yaml ",
yaml.dump({ "profiles":{[`latest-${getFormattedDate()}`]: latestProfile} }, { lineWidth: 1000 })
)
)
}
);
const latestProfileDir = Path.join(profilesDirectory, `definitions/`);
const latestProfileLocation = Path.join(latestProfileDir, `latest-${getFormattedDate()}.md`);
fs.writeFile(latestProfileLocation, latestProfileMarkDown);
console.log(`Latest profile written at ${latestProfileLocation}`);
// now get all the profile definitions and generate the readme.
const definitions = fs.recursiveReaddir(latestProfileDir);
const definitionsRelativePaths = [];
for await (const file of definitions){
const f = Path.parse(file);
definitionsRelativePaths.push(`$(this-folder)/definitions/${f.base}`);
}
const profilesReadme = cm.markDownExToString(
{
markDown: cm.createNode(
"document",
cm.createNode(
'heading',
cm.createText("Azure Profiles")
),
cm.createNode(
"block_quote",
cm.createNode(
"paragraph",
cm.createText("see https://aka.ms/autorest")
)
),
cm.createNode(
"block_quote",
cm.createNode(
"paragraph",
cm.createText("The files under this directory are the profile definitions used by autorest.")
)
),
cm.createCodeBlock(
"yaml",
yaml.dump({ "require": definitionsRelativePaths })
)
)
}
);
fs.writeFile(Path.join(profilesDirectory, "readme.md"), profilesReadme);
console.log(`Regenerated profiles readme.md at ${profilesDirectory}`);
console.log('DONE');
} catch (e) {
console.error(e);
}
}
function getFormattedDate(): string {
const today = new Date();
const monthNumber = today.getMonth() + 1;
const dayNumber = today.getDate();
const yyyy = String(today.getFullYear());
const mm = (monthNumber < 10) ? `0${monthNumber}` : String(monthNumber);
const dd = (dayNumber < 10) ? `0${dayNumber}` : String(dayNumber);
return `${yyyy}-${mm}-${dd}`;
}
async function getPaths(specHandles: Array<string>): Promise<Array<PathMetadata>> {
console.log(`Parsing specs`);
const result = new Array<PathMetadata>();
for (const specHandle of specHandles) {
try {
const spec = JSON.parse((await fs.readFile(specHandle)).toString());
if (spec.swagger && spec.info.version) {
for (const path of Object.entries(spec.paths)) {
result.push({endpoint: path[0], apiVersion: spec.info.version, originalLocation: Path.relative(process.cwd(), specHandle).replace(/\\/g, '/')});
}
}
} catch (e) {
console.error(`Couldn't parse ${specHandle} - ${e}`);
}
}
return result;
}
function getCrawlData(paths: Array<PathMetadata>): CrawlResult {
console.log(`Crawling paths for resources and getting telemetry ...`);
const result: CrawlResult = {resources: new Array<Resource>(), operations: {}};
const providerNamePattern = `microsoft\.[a-z]+(?:\.[a-z]+)?`;
const parameterPattern = `\{[a-z0-9]+\}`;
const nonParameterPattern = `[a-z0-9]+`;
const resourcePathRegex = new RegExp(`(.*)(\/providers\/${providerNamePattern}(:?\/${nonParameterPattern}|\/${parameterPattern})+\/?$)`, 'gi');
for (const p of paths) {
if (p.endpoint.match(resourcePathRegex)) {
const resource = { path: p.endpoint, apiVersion: p.apiVersion, providerNamespace: '', name: ''};
// get last /provider/microsoft.<provider>... section. Also, get rid of any possible trailing slash '/'
const scopedProviderSection = resource.path.replace(/\/*$/, '').replace(resourcePathRegex, '$2').split('/');
resource.providerNamespace = scopedProviderSection[2].toLowerCase();
// for now, only provider-namespaces ending with admin are blacklisted
if (resource.providerNamespace.endsWith('admin')){
if (result.blackListedPaths === undefined) {
result.blackListedPaths = [];
}
result.blackListedPaths.push(p);
continue;
}
const resourcesSection = `/${scopedProviderSection.slice(3).join('/')}`;
const resourceRegex = new RegExp(`\/${nonParameterPattern}\/${nonParameterPattern}|\/${nonParameterPattern}\/${parameterPattern}|\/${nonParameterPattern}$`, 'gi');
const resourceMatches = resourcesSection.match(resourceRegex);
if (resourceMatches !== null) {
const resourceNames = resourceMatches.map(each => each.split('/')[1]);
resource.name = resourceNames.join('/');
}
result.resources.push(resource);
} else {
if (result.operations[p.endpoint] === undefined){
result.operations[p.endpoint] = [];
}
result.operations[p.endpoint].push({apiVersion:p.apiVersion, originalLocation: p.originalLocation})
}
}
return result;
}
export function getLatestProfile(crawlData: CrawlResult): Profile {
const latestProfile: Profile = {resources:{}, operations: {}};
const allResources = crawlData.resources;
const allOperations = crawlData.operations;
const compareVersions = require('compare-versions');
console.log('Constructing latest profile ...')
// --- Process Resources ---
crawlData.resources.sort((a, b) => {
try{
return compareVersions(getSemverEquivalent(b.apiVersion), getSemverEquivalent(a.apiVersion));
} catch {
const dummy = '';
console.log(dummy);
}
});
const latestResources: {[uid: string] : Resource } = {};
for (const resource of allResources) {
const resourceUid = `${resource.providerNamespace.toLowerCase()}${resource.name.toLowerCase()}`;
if (latestResources[resourceUid] === undefined) {
latestResources[resourceUid] = { apiVersion: resource.apiVersion, name: resource.name, providerNamespace: resource.providerNamespace.toLowerCase(), path: resource.path };
}
}
for (const resource of values(latestResources)) {
latestProfile.resources[resource.providerNamespace] = latestProfile.resources[resource.providerNamespace] || {};
latestProfile.resources[resource.providerNamespace][resource.apiVersion] = latestProfile.resources[resource.providerNamespace][resource.apiVersion] || [];
latestProfile.resources[resource.providerNamespace][resource.apiVersion].push(resource.name);
}
for (const apiVersion of values(latestProfile.resources)) {
for (const resources of values(apiVersion)) {
resources.sort();
}
}
// --- Process Operations ---
for (const operation of values(allOperations)) {
operation.sort((a, b) => {
return compareVersions(getSemverEquivalent(b.apiVersion), getSemverEquivalent(a.apiVersion));
});
}
for (const operation of keys(allOperations)) {
latestProfile.operations[operation] = allOperations[operation][0].apiVersion;
}
return latestProfile;
}
// azure rest specs mostly uses versioning of the form yyyy-mm-dd
// To take into consideration this we convert to an equivalent of
// semver for comparisons.
function getSemverEquivalent(version: string) {
let result = '';
for (const i of version.split(/[\.\-]/g)) {
if (!result) {
result = i;
continue;
}
result = Number.isNaN(Number.parseInt(i)) ? `${result}-${i}` : `${result}.${Number(i)}`;
}
const semver = require('semver');
return semver.valid(semver.coerce(result));
}
interface Resource {
path: string;
apiVersion: string;
providerNamespace: string;
name: string;
}
interface CrawlResult {
operations: {
[operation:string]: Array<{
apiVersion: string;
originalLocation: string;
}>;
},
resources: Array<Resource>,
blackListedPaths?: Array<PathMetadata>;
}
interface PathMetadata {
endpoint: string;
apiVersion: string;
originalLocation: string;
}
interface Profile {
resources: {
[providerNamespace: string]: {
[apiVersion: string]: Array<string>;
};
},
operations: {
[path: string]: string;
}
}
main(Path.join(process.cwd(), "specification"), Path.join(process.cwd(), "profiles"));