oav/lib/xMsExampleExtractor.ts

339 строки
12 KiB
TypeScript
Исходник Обычный вид История

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
2020-11-24 06:07:36 +03:00
import * as fs from "fs";
import * as pathlib from "path";
import { URL } from "url";
V2 (#655) * fix bug * fix bug * separate schema def * fix types * remove type & add scenario * fix testResourceLoader * fix jsonpatch * fix schemas * fix schema * fix types * fix schema * fix raw types * save * fix loader * simplify VariableScope in memory * fix * fix testScenarioGenerator * fix * fix runner * fix tslint * restore shareScope * fix bug * requiredVariables * variable type * fix resolve variables * bump js-yaml version * define patternProperties * restore plain structure * implement apiScenaroYamlLoader * expectedResponse & use Example operationId * fix variableEnv bug * support patch * fix bug * implement Patch per ARM RPC * log step name * templateGenerator * update export types * add armTemplate parameters convension * fix bug * fix request schema * cleanUpSteps * error handling when execution * revert * revert cliSuppressExceptions * Update validate-examples-regression-sample.yml for Azure Pipelines * Update azure-pipelines.yml for Azure Pipelines * Revert "Update azure-pipelines.yml for Azure Pipelines" This reverts commit 273b05ef82f9d38327af572a63721464df15b936. * Revert "Update validate-examples-regression-sample.yml for Azure Pipelines" This reverts commit d758018bdbfdab2598743237062ff0dce48e1dbd. * npm install with v6 * Refactor VariableEnv * fix bug * variableEnv * fix outputVariables * revert placeholder * add resolveVariables option and turn off in postmanCollectionRunner * fix pathVariable * use output method to make output variable global * update * fix prettier * rename to apiScenario * rename command * restore folder name * restore fixture * remove fixture from .gitignore * fix * fix test * resove armTemplate * systemData is readOnly * Fix bug * fix VariableEnv * fix resolveString * fix convention for cleanUp steps * apply patch * fix xmsExampleExtract bug * fix xMsExampleExtractor * rename folder and add Changelog Co-authored-by: ruowan <ruowan@microsoft.com>
2021-09-30 06:27:59 +03:00
import {
MutableStringMap,
StringMap,
entries,
mapEntries,
keys,
values,
} from "@azure-tools/openapi-tools-common";
import swaggerParser from "@apidevtools/swagger-parser";
2020-11-24 06:07:36 +03:00
import { log } from "./util/logging";
import { kvPairsToObject } from "./util/utils";
export interface Options {
2020-11-24 06:07:36 +03:00
output?: string;
shouldResolveXmsExamples?: unknown;
matchApiVersion?: unknown;
}
const mkdirRecursiveSync = (dir: string) => {
if (!fs.existsSync(dir)) {
2020-11-24 06:07:36 +03:00
const parent = pathlib.dirname(dir);
if (parent !== dir) {
2020-11-24 06:07:36 +03:00
mkdirRecursiveSync(parent);
}
2020-11-24 06:07:36 +03:00
fs.mkdirSync(dir);
}
2020-11-24 06:07:36 +03:00
};
/**
* @class
*/
2018-05-30 06:30:11 +03:00
export class XMsExampleExtractor {
2020-11-24 06:07:36 +03:00
private readonly specPath: string;
private readonly recordings: string;
private readonly options: Options;
/**
* @constructor
* Initializes a new instance of the xMsExampleExtractor class.
2018-01-27 03:54:11 +03:00
*
* @param {string} specPath the swagger spec path
2018-01-27 03:54:11 +03:00
*
* @param {object} recordings the folder for recordings
2018-01-27 03:54:11 +03:00
*
* @param {object} [options] The options object
2018-01-27 03:54:11 +03:00
*
2018-06-04 16:16:47 +03:00
* @param {object} [options.matchApiVersion] Only generate examples if api-version matches.
* Default: false
2018-01-27 03:54:11 +03:00
*
* @param {object} [options.output] Output folder for the generated examples.
*/
public constructor(specPath: string, recordings: string, options: Options) {
if (
specPath === null ||
specPath === undefined ||
typeof specPath.valueOf() !== "string" ||
!specPath.trim().length
) {
2018-06-04 16:16:47 +03:00
throw new Error(
"specPath is a required property of type string and it cannot be an empty string."
2020-11-24 06:07:36 +03:00
);
}
if (
recordings === null ||
recordings === undefined ||
typeof recordings.valueOf() !== "string" ||
!recordings.trim().length
) {
2018-06-04 16:16:47 +03:00
throw new Error(
"recordings is a required property of type string and it cannot be an empty string."
2020-11-24 06:07:36 +03:00
);
}
2020-11-24 06:07:36 +03:00
this.specPath = specPath;
this.recordings = recordings;
if (!options) {
2020-11-24 06:07:36 +03:00
options = {};
}
if (options.output === null || options.output === undefined) {
2020-11-24 06:07:36 +03:00
options.output = process.cwd() + "/output";
}
if (
options.shouldResolveXmsExamples === null ||
options.shouldResolveXmsExamples === undefined
) {
2020-11-24 06:07:36 +03:00
options.shouldResolveXmsExamples = true;
}
if (options.matchApiVersion === null || options.matchApiVersion === undefined) {
2020-11-24 06:07:36 +03:00
options.matchApiVersion = false;
}
2020-11-24 06:07:36 +03:00
this.options = options;
log.debug(`specPath : ${this.specPath}`);
log.debug(`recordings : ${this.recordings}`);
log.debug(`options.output : ${this.options.output}`);
log.debug(`options.matchApiVersion : ${this.options.matchApiVersion}`);
}
public extractOne(
relativeExamplesPath: string,
outputExamples: string,
2020-11-24 06:07:36 +03:00
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
api: any,
recordingFileName: string
2020-11-24 06:07:36 +03:00
): void {
const recording = JSON.parse(fs.readFileSync(recordingFileName).toString());
const paths = api.paths;
let pathIndex = 0;
let pathParams: MutableStringMap<number> = {};
for (const path of keys(paths)) {
2020-11-24 06:07:36 +03:00
pathIndex++;
const searchResult = path.match(/\/{\w*\}/g);
const pathParts = path.split("/");
let pathToMatch = path;
pathParams = {};
if (searchResult !== null) {
for (const match of searchResult) {
2020-11-24 06:07:36 +03:00
const splitRegEx = /[{}]/;
const pathParam = match.split(splitRegEx)[1];
2020-11-24 06:07:36 +03:00
for (const [part, value] of entries(pathParts)) {
const pathPart = "/" + value;
if (pathPart.localeCompare(match) === 0) {
2020-11-24 06:07:36 +03:00
pathParams[pathParam] = part;
}
}
2020-11-24 06:07:36 +03:00
pathToMatch = pathToMatch.replace(match, "/[^/]+");
}
}
2020-11-24 06:07:36 +03:00
let newPathToMatch = pathToMatch.replace(/\//g, "\\/");
newPathToMatch = newPathToMatch + "$";
// for this API path (and method), try to find it in the recording file, and get
// the data
2020-11-24 06:07:36 +03:00
const recordingEntries: StringMap<any> = recording.Entries;
let entryIndex = 0;
V2 (#655) * fix bug * fix bug * separate schema def * fix types * remove type & add scenario * fix testResourceLoader * fix jsonpatch * fix schemas * fix schema * fix types * fix schema * fix raw types * save * fix loader * simplify VariableScope in memory * fix * fix testScenarioGenerator * fix * fix runner * fix tslint * restore shareScope * fix bug * requiredVariables * variable type * fix resolve variables * bump js-yaml version * define patternProperties * restore plain structure * implement apiScenaroYamlLoader * expectedResponse & use Example operationId * fix variableEnv bug * support patch * fix bug * implement Patch per ARM RPC * log step name * templateGenerator * update export types * add armTemplate parameters convension * fix bug * fix request schema * cleanUpSteps * error handling when execution * revert * revert cliSuppressExceptions * Update validate-examples-regression-sample.yml for Azure Pipelines * Update azure-pipelines.yml for Azure Pipelines * Revert "Update azure-pipelines.yml for Azure Pipelines" This reverts commit 273b05ef82f9d38327af572a63721464df15b936. * Revert "Update validate-examples-regression-sample.yml for Azure Pipelines" This reverts commit d758018bdbfdab2598743237062ff0dce48e1dbd. * npm install with v6 * Refactor VariableEnv * fix bug * variableEnv * fix outputVariables * revert placeholder * add resolveVariables option and turn off in postmanCollectionRunner * fix pathVariable * use output method to make output variable global * update * fix prettier * rename to apiScenario * rename command * restore folder name * restore fixture * remove fixture from .gitignore * fix * fix test * resove armTemplate * systemData is readOnly * Fix bug * fix VariableEnv * fix resolveString * fix convention for cleanUp steps * apply patch * fix xmsExampleExtract bug * fix xMsExampleExtractor * rename folder and add Changelog Co-authored-by: ruowan <ruowan@microsoft.com>
2021-09-30 06:27:59 +03:00
let queryParams: any = {};
for (const recordingEntry of values(recordingEntries)) {
2020-11-24 06:07:36 +03:00
entryIndex++;
const parsedUrl = new URL(recordingEntry.RequestUri, "https://management.azure.com");
V2 (#655) * fix bug * fix bug * separate schema def * fix types * remove type & add scenario * fix testResourceLoader * fix jsonpatch * fix schemas * fix schema * fix types * fix schema * fix raw types * save * fix loader * simplify VariableScope in memory * fix * fix testScenarioGenerator * fix * fix runner * fix tslint * restore shareScope * fix bug * requiredVariables * variable type * fix resolve variables * bump js-yaml version * define patternProperties * restore plain structure * implement apiScenaroYamlLoader * expectedResponse & use Example operationId * fix variableEnv bug * support patch * fix bug * implement Patch per ARM RPC * log step name * templateGenerator * update export types * add armTemplate parameters convension * fix bug * fix request schema * cleanUpSteps * error handling when execution * revert * revert cliSuppressExceptions * Update validate-examples-regression-sample.yml for Azure Pipelines * Update azure-pipelines.yml for Azure Pipelines * Revert "Update azure-pipelines.yml for Azure Pipelines" This reverts commit 273b05ef82f9d38327af572a63721464df15b936. * Revert "Update validate-examples-regression-sample.yml for Azure Pipelines" This reverts commit d758018bdbfdab2598743237062ff0dce48e1dbd. * npm install with v6 * Refactor VariableEnv * fix bug * variableEnv * fix outputVariables * revert placeholder * add resolveVariables option and turn off in postmanCollectionRunner * fix pathVariable * use output method to make output variable global * update * fix prettier * rename to apiScenario * rename command * restore folder name * restore fixture * remove fixture from .gitignore * fix * fix test * resove armTemplate * systemData is readOnly * Fix bug * fix VariableEnv * fix resolveString * fix convention for cleanUp steps * apply patch * fix xmsExampleExtract bug * fix xMsExampleExtractor * rename folder and add Changelog Co-authored-by: ruowan <ruowan@microsoft.com>
2021-09-30 06:27:59 +03:00
let recordingPath = parsedUrl.href || "";
queryParams = kvPairsToObject(parsedUrl.searchParams) || {};
const hostUrl = parsedUrl ? parsedUrl.protocol! + "//" + parsedUrl.hostname! : undefined;
2020-11-24 06:07:36 +03:00
const headerParams = recordingEntry.RequestHeaders;
// if command-line included check for API version, validate api-version from URI in
// recordings matches the api-version of the spec
if (
!this.options.matchApiVersion ||
("api-version" in queryParams && queryParams["api-version"] === api.info.version)
) {
2020-11-24 06:07:36 +03:00
recordingPath = recordingPath.replace(/\?.*/, "");
const recordingPathParts = recordingPath.split("/");
// eslint-disable-next-line @typescript-eslint/prefer-regexp-exec
const match = recordingPath.match(newPathToMatch);
if (match !== null) {
2020-11-24 06:07:36 +03:00
log.silly("path: " + path);
log.silly("recording path: " + recordingPath);
2020-11-24 06:07:36 +03:00
const pathParamsValues: MutableStringMap<unknown> = {};
for (const [p, v] of mapEntries(pathParams)) {
const index = v;
pathParamsValues[p] = recordingPathParts[index];
}
if (hostUrl !== undefined) {
pathParamsValues.url = hostUrl;
}
// found a match in the recording
2020-11-24 06:07:36 +03:00
const requestMethodFromRecording = recordingEntry.RequestMethod;
const infoFromOperation = paths[path][requestMethodFromRecording.toLowerCase()];
if (typeof infoFromOperation !== "undefined") {
// need to consider each method in operation
2020-11-24 06:07:36 +03:00
const fileNameArray = recordingFileName.split("/");
let fileName = fileNameArray[fileNameArray.length - 1];
fileName = fileName.split(".json")[0];
fileName = fileName.replace(/\//g, "-");
const exampleFileName = `${fileName}-${requestMethodFromRecording}-example-${pathIndex}${entryIndex}.json`;
const ref = {
2020-11-24 06:07:36 +03:00
$ref: relativeExamplesPath + exampleFileName,
};
const exampleFriendlyName = `${fileName}${requestMethodFromRecording}${pathIndex}${entryIndex}`;
log.debug(`exampleFriendlyName: ${exampleFriendlyName}`);
if (!("x-ms-examples" in infoFromOperation)) {
2020-11-24 06:07:36 +03:00
infoFromOperation["x-ms-examples"] = {};
}
2020-11-24 06:07:36 +03:00
infoFromOperation["x-ms-examples"][exampleFriendlyName] = ref;
const exampleL: {
2020-11-24 06:07:36 +03:00
parameters: MutableStringMap<unknown>;
responses: MutableStringMap<{
2020-11-24 06:07:36 +03:00
body?: unknown;
}>;
} = {
parameters: {},
2020-11-24 06:07:36 +03:00
responses: {},
};
const paramsToProcess = [
2020-11-24 06:07:36 +03:00
...mapEntries(pathParamsValues),
...mapEntries(queryParams),
...mapEntries(headerParams),
];
for (const paramEntry of paramsToProcess) {
2020-11-24 06:07:36 +03:00
const param = paramEntry[0];
const v = paramEntry[1];
exampleL.parameters[param] = v;
}
2020-11-24 06:07:36 +03:00
const params = infoFromOperation.parameters;
for (const param of keys(infoFromOperation.parameters)) {
if (params[param].in === "body") {
2020-11-24 06:07:36 +03:00
const bodyParamName = params[param].name;
const bodyParamValue = recordingEntry.RequestBody;
const bodyParamExample: MutableStringMap<unknown> = {};
bodyParamExample[bodyParamName] = bodyParamValue;
exampleL.parameters[bodyParamName] =
2020-11-24 06:07:36 +03:00
bodyParamValue !== "" ? JSON.parse(bodyParamValue) : "";
}
}
V2 (#655) * fix bug * fix bug * separate schema def * fix types * remove type & add scenario * fix testResourceLoader * fix jsonpatch * fix schemas * fix schema * fix types * fix schema * fix raw types * save * fix loader * simplify VariableScope in memory * fix * fix testScenarioGenerator * fix * fix runner * fix tslint * restore shareScope * fix bug * requiredVariables * variable type * fix resolve variables * bump js-yaml version * define patternProperties * restore plain structure * implement apiScenaroYamlLoader * expectedResponse & use Example operationId * fix variableEnv bug * support patch * fix bug * implement Patch per ARM RPC * log step name * templateGenerator * update export types * add armTemplate parameters convension * fix bug * fix request schema * cleanUpSteps * error handling when execution * revert * revert cliSuppressExceptions * Update validate-examples-regression-sample.yml for Azure Pipelines * Update azure-pipelines.yml for Azure Pipelines * Revert "Update azure-pipelines.yml for Azure Pipelines" This reverts commit 273b05ef82f9d38327af572a63721464df15b936. * Revert "Update validate-examples-regression-sample.yml for Azure Pipelines" This reverts commit d758018bdbfdab2598743237062ff0dce48e1dbd. * npm install with v6 * Refactor VariableEnv * fix bug * variableEnv * fix outputVariables * revert placeholder * add resolveVariables option and turn off in postmanCollectionRunner * fix pathVariable * use output method to make output variable global * update * fix prettier * rename to apiScenario * rename command * restore folder name * restore fixture * remove fixture from .gitignore * fix * fix test * resove armTemplate * systemData is readOnly * Fix bug * fix VariableEnv * fix resolveString * fix convention for cleanUp steps * apply patch * fix xmsExampleExtract bug * fix xMsExampleExtractor * rename folder and add Changelog Co-authored-by: ruowan <ruowan@microsoft.com>
2021-09-30 06:27:59 +03:00
const parseResponseBody = (body: any) => {
try {
return JSON.parse(body);
} catch (err) {
return body;
}
};
2020-11-24 06:07:36 +03:00
for (const _v of keys(infoFromOperation.responses)) {
const statusCodeFromRecording = recordingEntry.StatusCode;
V2 (#655) * fix bug * fix bug * separate schema def * fix types * remove type & add scenario * fix testResourceLoader * fix jsonpatch * fix schemas * fix schema * fix types * fix schema * fix raw types * save * fix loader * simplify VariableScope in memory * fix * fix testScenarioGenerator * fix * fix runner * fix tslint * restore shareScope * fix bug * requiredVariables * variable type * fix resolve variables * bump js-yaml version * define patternProperties * restore plain structure * implement apiScenaroYamlLoader * expectedResponse & use Example operationId * fix variableEnv bug * support patch * fix bug * implement Patch per ARM RPC * log step name * templateGenerator * update export types * add armTemplate parameters convension * fix bug * fix request schema * cleanUpSteps * error handling when execution * revert * revert cliSuppressExceptions * Update validate-examples-regression-sample.yml for Azure Pipelines * Update azure-pipelines.yml for Azure Pipelines * Revert "Update azure-pipelines.yml for Azure Pipelines" This reverts commit 273b05ef82f9d38327af572a63721464df15b936. * Revert "Update validate-examples-regression-sample.yml for Azure Pipelines" This reverts commit d758018bdbfdab2598743237062ff0dce48e1dbd. * npm install with v6 * Refactor VariableEnv * fix bug * variableEnv * fix outputVariables * revert placeholder * add resolveVariables option and turn off in postmanCollectionRunner * fix pathVariable * use output method to make output variable global * update * fix prettier * rename to apiScenario * rename command * restore folder name * restore fixture * remove fixture from .gitignore * fix * fix test * resove armTemplate * systemData is readOnly * Fix bug * fix VariableEnv * fix resolveString * fix convention for cleanUp steps * apply patch * fix xmsExampleExtract bug * fix xMsExampleExtractor * rename folder and add Changelog Co-authored-by: ruowan <ruowan@microsoft.com>
2021-09-30 06:27:59 +03:00
let responseBody = recordingEntry.ResponseBody;
if (typeof responseBody === "string" && responseBody !== "") {
responseBody = parseResponseBody(responseBody);
}
exampleL.responses[statusCodeFromRecording] = {
V2 (#655) * fix bug * fix bug * separate schema def * fix types * remove type & add scenario * fix testResourceLoader * fix jsonpatch * fix schemas * fix schema * fix types * fix schema * fix raw types * save * fix loader * simplify VariableScope in memory * fix * fix testScenarioGenerator * fix * fix runner * fix tslint * restore shareScope * fix bug * requiredVariables * variable type * fix resolve variables * bump js-yaml version * define patternProperties * restore plain structure * implement apiScenaroYamlLoader * expectedResponse & use Example operationId * fix variableEnv bug * support patch * fix bug * implement Patch per ARM RPC * log step name * templateGenerator * update export types * add armTemplate parameters convension * fix bug * fix request schema * cleanUpSteps * error handling when execution * revert * revert cliSuppressExceptions * Update validate-examples-regression-sample.yml for Azure Pipelines * Update azure-pipelines.yml for Azure Pipelines * Revert "Update azure-pipelines.yml for Azure Pipelines" This reverts commit 273b05ef82f9d38327af572a63721464df15b936. * Revert "Update validate-examples-regression-sample.yml for Azure Pipelines" This reverts commit d758018bdbfdab2598743237062ff0dce48e1dbd. * npm install with v6 * Refactor VariableEnv * fix bug * variableEnv * fix outputVariables * revert placeholder * add resolveVariables option and turn off in postmanCollectionRunner * fix pathVariable * use output method to make output variable global * update * fix prettier * rename to apiScenario * rename command * restore folder name * restore fixture * remove fixture from .gitignore * fix * fix test * resove armTemplate * systemData is readOnly * Fix bug * fix VariableEnv * fix resolveString * fix convention for cleanUp steps * apply patch * fix xmsExampleExtract bug * fix xMsExampleExtractor * rename folder and add Changelog Co-authored-by: ruowan <ruowan@microsoft.com>
2021-09-30 06:27:59 +03:00
body: responseBody,
2020-11-24 06:07:36 +03:00
};
}
log.info(
`Writing x-ms-examples at ${pathlib.resolve(outputExamples, exampleFileName)}`
);
2020-11-24 06:07:36 +03:00
const examplePath = pathlib.join(outputExamples, exampleFileName);
const dir = pathlib.dirname(examplePath);
mkdirRecursiveSync(dir);
fs.writeFileSync(examplePath, JSON.stringify(exampleL, null, 2));
}
}
}
}
}
}
/**
* Extracts x-ms-examples from the recordings
*/
public async extract(): Promise<StringMap<unknown>> {
if (this.options.output === undefined) {
2020-11-24 06:07:36 +03:00
throw new Error("this.options.output === undefined");
}
2020-11-24 06:07:36 +03:00
this.mkdirSync(this.options.output);
this.mkdirSync(this.options.output + "/examples");
this.mkdirSync(this.options.output + "/swagger");
2020-11-24 06:07:36 +03:00
const outputExamples = pathlib.join(this.options.output, "examples");
const relativeExamplesPath = "../examples/";
const specName = this.specPath.split("/");
const outputSwagger = pathlib.join(
this.options.output,
"swagger",
specName[specName.length - 1].split(".")[0] + ".json"
2020-11-24 06:07:36 +03:00
);
2020-11-24 06:07:36 +03:00
const accErrors: MutableStringMap<unknown> = {};
const filesArray: string[] = [];
this.getFileList(this.recordings, filesArray);
2020-11-24 06:07:36 +03:00
const recordingFiles = filesArray;
2018-06-04 16:16:47 +03:00
try {
2020-11-24 06:07:36 +03:00
const api = await swaggerParser.parse(this.specPath);
for (const recordingFileName of recordingFiles) {
2020-11-24 06:07:36 +03:00
log.debug(`Processing recording file: ${recordingFileName}`);
try {
2020-11-24 06:07:36 +03:00
this.extractOne(relativeExamplesPath, outputExamples, api, recordingFileName);
log.info(`Writing updated swagger with x-ms-examples at ${outputSwagger}`);
fs.writeFileSync(outputSwagger, JSON.stringify(api, null, 2));
2018-06-04 16:16:47 +03:00
} catch (err) {
2020-11-24 06:07:36 +03:00
accErrors[recordingFileName] = err.toString();
log.warn(`Error processing recording file: "${recordingFileName}"`);
log.warn(`Error: "${err.toString()} "`);
}
}
2018-06-04 16:16:47 +03:00
if (JSON.stringify(accErrors) !== "{}") {
2020-11-24 06:07:36 +03:00
log.error(`Errors loading/parsing recording files.`);
log.error(`${JSON.stringify(accErrors)}`);
}
2018-06-04 16:16:47 +03:00
} catch (err) {
2020-11-24 06:07:36 +03:00
process.exitCode = 1;
log.error(err);
2018-06-04 16:16:47 +03:00
}
2020-11-24 06:07:36 +03:00
return accErrors;
}
private mkdirSync(dir: string): void {
try {
2020-11-24 06:07:36 +03:00
fs.mkdirSync(dir);
} catch (e) {
if (e.code !== "EEXIST") {
2020-11-24 06:07:36 +03:00
throw e;
}
}
}
2018-06-09 02:35:55 +03:00
private getFileList(dir: string, fileList: string[]): string[] {
2020-11-24 06:07:36 +03:00
const files = fs.readdirSync(dir);
fileList = fileList || [];
files.forEach((file) => {
if (fs.statSync(pathlib.join(dir, file)).isDirectory()) {
2020-11-24 06:07:36 +03:00
fileList = this.getFileList(pathlib.join(dir, file), fileList);
2018-06-04 16:16:47 +03:00
} else {
2020-11-24 06:07:36 +03:00
fileList.push(pathlib.join(dir, file));
}
2020-11-24 06:07:36 +03:00
});
return fileList;
}
}