Enable and fix lint (#73)
* Enable and fix lint * fix return Co-authored-by: xichen <xichen@microsoft.com>
This commit is contained in:
Родитель
f10b0f8f88
Коммит
d4489616dd
|
@ -0,0 +1,37 @@
|
|||
{
|
||||
"env": {
|
||||
"es2020": true,
|
||||
"node": true
|
||||
},
|
||||
"extends": [
|
||||
"eslint:recommended",
|
||||
"plugin:@typescript-eslint/recommended"
|
||||
],
|
||||
"parser": "@typescript-eslint/parser",
|
||||
"parserOptions": {
|
||||
"ecmaVersion": 11,
|
||||
"sourceType": "module"
|
||||
},
|
||||
"plugins": [
|
||||
"@typescript-eslint"
|
||||
],
|
||||
"rules": {
|
||||
"semi": ["error", "always"],
|
||||
"indent": ["error", 4, {
|
||||
"SwitchCase": 1,
|
||||
"VariableDeclarator": 1,
|
||||
"outerIIFEBody": 1,
|
||||
"MemberExpression": 1,
|
||||
"FunctionDeclaration": { "parameters": 1, "body": 1 },
|
||||
"FunctionExpression": { "parameters": 1, "body": 1 },
|
||||
"CallExpression": { "arguments": 1 },
|
||||
"ArrayExpression": 1,
|
||||
"ObjectExpression": 1,
|
||||
"ImportDeclaration": 1,
|
||||
"flatTernaryExpressions": false,
|
||||
"ignoreComments": false,
|
||||
"ignoredNodes": ["TemplateLiteral *"]
|
||||
}],
|
||||
"space-before-function-paren": ["error", "never"]
|
||||
}
|
||||
}
|
14
package.json
14
package.json
|
@ -9,8 +9,7 @@
|
|||
"scripts": {
|
||||
"start": "node dist/src/index.js",
|
||||
"debug": "node --max_old_space_size=4096 --inspect-brk --inspect-port=9997 ./dist/src/index.js",
|
||||
"eslint-fix": "eslint . --fix --ext .ts",
|
||||
"eslint": "eslint . --ext .ts",
|
||||
"eslint": "node_modules\\.bin\\eslint src/**/*.*",
|
||||
"build": "tsc -p .",
|
||||
"start-testserver": "./node_modules/.bin/start-autorest-testserver",
|
||||
"stop-testserver": "./node_modules/.bin/stop-autorest-testserver",
|
||||
|
@ -38,8 +37,17 @@
|
|||
"@types/mocha": "^7.0.2",
|
||||
"@types/node": "10.17.0",
|
||||
"@types/should": "^13.0.0",
|
||||
"@typescript-eslint/eslint-plugin": "^3.3.0",
|
||||
"@typescript-eslint/parser": "^3.3.0",
|
||||
"babel-eslint": "^10.1.0",
|
||||
"chai": "^4.2.0",
|
||||
"eslint": "~5.4.0",
|
||||
"eslint": "^7.2.0",
|
||||
"eslint-config-standard": "^14.1.1",
|
||||
"eslint-plugin-babel": "^5.3.0",
|
||||
"eslint-plugin-import": "^2.21.2",
|
||||
"eslint-plugin-node": "^11.1.0",
|
||||
"eslint-plugin-promise": "^4.2.1",
|
||||
"eslint-plugin-standard": "^4.0.1",
|
||||
"mocha": "^7.1.0",
|
||||
"node-yaml": "^3.2.0",
|
||||
"nyc": "^15.0.0",
|
||||
|
|
|
@ -1,8 +1,7 @@
|
|||
import { Request, Parameter, Operation, Schema } from "@azure-tools/codemodel";
|
||||
import { isNullOrUndefined } from "util";
|
||||
import { Request, Parameter, Operation, Schema } from '@azure-tools/codemodel';
|
||||
import { isNullOrUndefined } from 'util';
|
||||
|
||||
export class CopyHelper {
|
||||
|
||||
public static copyOperation(source: Operation, globalParameters?: Parameter[], customizedReqCopy?: (req: Request) => Request, customizedParamCopy?: (srcParam: Parameter) => Parameter): Operation {
|
||||
const copy = new Operation(source.language.default.name, '', source);
|
||||
copy.language = CopyHelper.deepCopy(source.language);
|
||||
|
@ -13,7 +12,7 @@ export class CopyHelper {
|
|||
} else if (customizedParamCopy) {
|
||||
return customizedParamCopy(op);
|
||||
} else {
|
||||
return CopyHelper.copyParameter(op)
|
||||
return CopyHelper.copyParameter(op);
|
||||
}
|
||||
});
|
||||
copy.requests = source.requests?.map((req) => customizedReqCopy == null ? CopyHelper.copyRequest(req) : customizedReqCopy(req));
|
||||
|
@ -35,7 +34,7 @@ export class CopyHelper {
|
|||
implementation: source.implementation,
|
||||
extensions: {},
|
||||
language: CopyHelper.deepCopy(source.language),
|
||||
protocol: source.protocol,
|
||||
protocol: source.protocol
|
||||
});
|
||||
for (const property in source) {
|
||||
if (isNullOrUndefined(copy[property])) {
|
||||
|
|
|
@ -1,27 +1,32 @@
|
|||
import { Host, Session, startSession } from "@azure-tools/autorest-extension-base";
|
||||
import { serialize } from "@azure-tools/codegen";
|
||||
import { CodeModel, codeModelSchema, Metadata, ObjectSchema, isObjectSchema, Property, Extensions, Scheme, Info } from "@azure-tools/codemodel";
|
||||
import { Helper } from "./helper";
|
||||
import { isNull, isNullOrUndefined } from "util";
|
||||
import { Host, Session } from '@azure-tools/autorest-extension-base';
|
||||
import { serialize } from '@azure-tools/codegen';
|
||||
import { CodeModel, Info } from '@azure-tools/codemodel';
|
||||
import { Helper } from './helper';
|
||||
import { isNullOrUndefined } from 'util';
|
||||
|
||||
export class Dumper {
|
||||
readonly INDEX_KEY = 'cli-dump-index';
|
||||
debugEnabled: boolean = false;
|
||||
debugIndexIncrease: number = 10;
|
||||
debugEnabled = false;
|
||||
debugIndexIncrease = 10;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
dumpDebug: any = {};
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
dumpOther: any = {};
|
||||
info: Info;
|
||||
|
||||
constructor(private host: Host, private session: Session<CodeModel>) {
|
||||
}
|
||||
|
||||
public async init() {
|
||||
public async init(): Promise<Dumper> {
|
||||
this.debugEnabled = await this.session.getValue('debug', false);
|
||||
this.info = this.session.model.info;
|
||||
if (isNullOrUndefined(this.info.extensions))
|
||||
if (isNullOrUndefined(this.info.extensions)) {
|
||||
this.info.extensions = {};
|
||||
if (isNullOrUndefined(this.info.extensions[this.INDEX_KEY]))
|
||||
}
|
||||
if (isNullOrUndefined(this.info.extensions[this.INDEX_KEY])) {
|
||||
this.info.extensions[this.INDEX_KEY] = 10;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
|
@ -29,11 +34,11 @@ export class Dumper {
|
|||
return this.info.extensions[this.INDEX_KEY];
|
||||
}
|
||||
|
||||
private increaseDumpIndex() {
|
||||
private increaseDumpIndex(): void {
|
||||
this.info.extensions[this.INDEX_KEY] += 10;
|
||||
}
|
||||
|
||||
public dumpCodeModel(name: string) {
|
||||
public dumpCodeModel(name: string): void {
|
||||
if (this.debugEnabled) {
|
||||
this.dumpDebug[`clicommon-${this.dumpIndex.toString().padStart(6, '0')}-${name}.yaml`] = serialize(this.session.model);
|
||||
this.dumpDebug[`clicommon-${this.dumpIndex.toString().padStart(6, '0')}-${name}-simplified.yaml`] = Helper.toYamlSimplified(this.session.model);
|
||||
|
@ -41,19 +46,23 @@ export class Dumper {
|
|||
}
|
||||
}
|
||||
|
||||
public dump(name: string, content: string, debugOnly: boolean) {
|
||||
if (debugOnly)
|
||||
public dump(name: string, content: string, debugOnly: boolean): void {
|
||||
if (debugOnly) {
|
||||
this.dumpDebug[name] = content;
|
||||
else
|
||||
}
|
||||
else {
|
||||
this.dumpOther[name] = content;
|
||||
}
|
||||
}
|
||||
|
||||
public async persistAsync() {
|
||||
public async persistAsync(): Promise<void> {
|
||||
if (this.debugEnabled) {
|
||||
for (let key in this.dumpDebug)
|
||||
for (const key in this.dumpDebug) {
|
||||
this.host.WriteFile(key, this.dumpDebug[key], null);
|
||||
}
|
||||
}
|
||||
for (let key in this.dumpOther)
|
||||
for (const key in this.dumpOther) {
|
||||
this.host.WriteFile(key, this.dumpOther[key], null);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,11 +1,11 @@
|
|||
import { getAllProperties, ImplementationLocation, ObjectSchema, Parameter, Property, Request, VirtualParameter } from "@azure-tools/codemodel";
|
||||
import { values } from "@azure-tools/linq";
|
||||
import { isNullOrUndefined } from "util";
|
||||
import { NodeHelper, NodeExtensionHelper, NodeCliHelper } from "./nodeHelper";
|
||||
import { NodeExtensionHelper, NodeCliHelper } from "./nodeHelper";
|
||||
|
||||
export class FlattenHelper {
|
||||
|
||||
public static flattenParameter(req: Request, param: Parameter, path: Property[], prefix: string) {
|
||||
public static flattenParameter(req: Request, param: Parameter, path: Property[], prefix: string): void {
|
||||
if (!(param.schema instanceof ObjectSchema))
|
||||
throw Error(`Try to flatten non-object schema: param = '${param.language.default.name}', schema= '${param.schema.language.default.name}'`);
|
||||
|
||||
|
@ -33,9 +33,13 @@ export class FlattenHelper {
|
|||
targetProperty: property,
|
||||
pathToProperty: path
|
||||
});
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
delete (<any>vp).serializedName;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
delete (<any>vp).readOnly;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
delete (<any>vp).isDiscriminator;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
delete (<any>vp).flattenedNames;
|
||||
|
||||
vp.language = JSON.parse(JSON.stringify(vp.language));
|
||||
|
@ -53,7 +57,8 @@ export class FlattenHelper {
|
|||
NodeExtensionHelper.setCliFlattened(parameter, true);
|
||||
|
||||
// we need this for the further flatten be recognized by python codegen
|
||||
let protocal: any = {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const protocal: any = {
|
||||
http: {
|
||||
in: 'body'
|
||||
},
|
||||
|
@ -61,7 +66,7 @@ export class FlattenHelper {
|
|||
};
|
||||
parameter.protocol = protocal;
|
||||
|
||||
let arr: Parameter[] = [];
|
||||
const arr: Parameter[] = [];
|
||||
for (const property of values(getAllProperties(schema))) {
|
||||
if (property.readOnly) {
|
||||
// skip read-only properties
|
||||
|
@ -76,11 +81,11 @@ export class FlattenHelper {
|
|||
}
|
||||
}
|
||||
|
||||
let arr2: Parameter[] = [];
|
||||
let hash: Set<string> = new Set<string>();
|
||||
const arr2: Parameter[] = [];
|
||||
const hash: Set<string> = new Set<string>();
|
||||
// base class's property is before the subclass's
|
||||
for (let i = 0; i < arr.length; i++) {
|
||||
let cur = arr[i];
|
||||
const cur = arr[i];
|
||||
if (!hash.has(cur.language.default.name)) {
|
||||
arr2.push(cur);
|
||||
hash.add(cur.language.default.name);
|
||||
|
|
134
src/helper.ts
134
src/helper.ts
|
@ -1,10 +1,9 @@
|
|||
import { codeModelSchema, ChoiceSchema, ChoiceValue, Extensions, CodeModel, ObjectSchema, Operation, OperationGroup, Parameter, Property, SealedChoiceSchema, Schema, ConstantSchema, SchemaType, StringSchema, Metadata, Language } from "@azure-tools/codemodel";
|
||||
import { codeModelSchema, ChoiceSchema, ChoiceValue, CodeModel, ObjectSchema, Operation, OperationGroup, Parameter, Property, SealedChoiceSchema, Schema, ConstantSchema, SchemaType, StringSchema } from "@azure-tools/codemodel";
|
||||
import { keys, values } from "@azure-tools/linq";
|
||||
import { isArray, isNull, isNullOrUndefined, isObject, isString, isUndefined } from "util";
|
||||
import { CliConst, M4Node, M4NodeType, NamingType, CliCommonSchema } from "./schema";
|
||||
import { pascalCase, EnglishPluralizationService, guid } from '@azure-tools/codegen';
|
||||
import { EnglishPluralizationService, guid } from '@azure-tools/codegen';
|
||||
import { Session, Host, startSession } from "@azure-tools/autorest-extension-base";
|
||||
import { PreNamer } from "./plugins/prenamer";
|
||||
import { serialize } from "@azure-tools/codegen";
|
||||
import { NodeHelper, NodeCliHelper, NodeExtensionHelper } from "./nodeHelper";
|
||||
import { Dumper } from "./dumper";
|
||||
|
@ -14,12 +13,14 @@ export class Helper {
|
|||
private static session: Session<CodeModel>;
|
||||
private static host: Host;
|
||||
private static _dumper: Dumper;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
private static modelerfourOptions: any;
|
||||
|
||||
public static async init(host: Host) {
|
||||
Helper.session = await startSession<CodeModel>(host, {}, codeModelSchema);;
|
||||
public static async init(host: Host): Promise<Session<CodeModel>> {
|
||||
Helper.session = await startSession<CodeModel>(host, {}, codeModelSchema);
|
||||
Helper.host = host;
|
||||
Helper._dumper = await (new Dumper(host, Helper.session)).init();
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
Helper.modelerfourOptions = <any>await Helper.session.getValue('modelerfour', {});
|
||||
return Helper.session;
|
||||
}
|
||||
|
@ -30,25 +31,25 @@ export class Helper {
|
|||
return Helper._dumper;
|
||||
}
|
||||
|
||||
public static logDebug(msg: string) {
|
||||
public static logDebug(msg: string): void {
|
||||
if (isNullOrUndefined(Helper.session))
|
||||
throw Error("Helper not init yet, please call Helper.init() to init the Helper");
|
||||
Helper.session.debug(msg, []);
|
||||
}
|
||||
|
||||
public static logWarning(msg: string) {
|
||||
public static logWarning(msg: string): void {
|
||||
if (isNullOrUndefined(Helper.session))
|
||||
throw Error("Helper not init yet, please call Helper.init() to init the Helper");
|
||||
Helper.session.warning(msg, []);
|
||||
}
|
||||
|
||||
public static logError(msg: string) {
|
||||
public static logError(msg: string): void {
|
||||
if (isNullOrUndefined(Helper.session))
|
||||
throw Error("Helper not init yet, please call Helper.init() to init the Helper");
|
||||
Helper.session.error(msg, []);
|
||||
}
|
||||
|
||||
public static outputToModelerfour() {
|
||||
public static outputToModelerfour(): void {
|
||||
if (isNullOrUndefined(Helper.session))
|
||||
throw Error("Helper not init yet, please call Helper.init() to init the Helper");
|
||||
if (isNullOrUndefined(Helper.host))
|
||||
|
@ -64,7 +65,7 @@ export class Helper {
|
|||
}
|
||||
}
|
||||
|
||||
public static isEmptyString(str): boolean {
|
||||
public static isEmptyString(str: string): boolean {
|
||||
return isNullOrUndefined(str) || str.length === 0;
|
||||
}
|
||||
|
||||
|
@ -101,8 +102,8 @@ export class Helper {
|
|||
* set to 'true' to return MatchAll regex when str is null/undefined/string.empty
|
||||
* set to 'false' to return null when str is null/undefined/string.empty
|
||||
*/
|
||||
public static createRegex(str: string, emptyAsMatchAll: boolean = false): RegExp {
|
||||
let MATCH_ALL = /^.*$/g;
|
||||
public static createRegex(str: string, emptyAsMatchAll = false): RegExp {
|
||||
const MATCH_ALL = /^.*$/g;
|
||||
if (isNullOrUndefined(str) || str.length === 0) {
|
||||
if (emptyAsMatchAll)
|
||||
return MATCH_ALL;
|
||||
|
@ -116,11 +117,6 @@ export class Helper {
|
|||
return new RegExp(`^${str}$`, "gi");
|
||||
}
|
||||
|
||||
public static validateNullOrUndefined(obj: any, name: string): void {
|
||||
if (isNullOrUndefined(obj))
|
||||
throw Error(`Validation failed: '${name}' is null or undefined`)
|
||||
}
|
||||
|
||||
public static ToNamingType(node: M4Node): NamingType | null {
|
||||
|
||||
if (node instanceof OperationGroup)
|
||||
|
@ -171,7 +167,7 @@ export class Helper {
|
|||
}
|
||||
|
||||
public static singularize(settings: CliCommonSchema.NamingConvention, word: string): string {
|
||||
let low = word.toLowerCase();
|
||||
const low = word.toLowerCase();
|
||||
if (settings.glossary.findIndex(v => v === low) >= 0)
|
||||
return word;
|
||||
|
||||
|
@ -183,7 +179,7 @@ export class Helper {
|
|||
return eps.singularize(word);
|
||||
}
|
||||
|
||||
public static normalizeNamingSettings(settings: CliCommonSchema.NamingConvention) {
|
||||
public static normalizeNamingSettings(settings: CliCommonSchema.NamingConvention): CliCommonSchema.NamingConvention {
|
||||
if (isNullOrUndefined(settings.singularize))
|
||||
settings.singularize = [];
|
||||
if (isNullOrUndefined(settings.glossary))
|
||||
|
@ -193,7 +189,7 @@ export class Helper {
|
|||
if (isNullOrUndefined(settings.override))
|
||||
settings.override = {};
|
||||
else {
|
||||
for (let key in settings.override)
|
||||
for (const key in settings.override)
|
||||
settings.override[key.toLowerCase()] = settings.override[key];
|
||||
}
|
||||
if (isNullOrUndefined(settings.appliedTo)) {
|
||||
|
@ -210,58 +206,58 @@ export class Helper {
|
|||
* @param node
|
||||
* @param languageKey
|
||||
*/
|
||||
public static applyNamingConvention(settings: CliCommonSchema.NamingConvention, node: M4Node, languageKey: string) {
|
||||
public static applyNamingConvention(settings: CliCommonSchema.NamingConvention, node: M4Node, languageKey: string): void {
|
||||
if (isNullOrUndefined(node.language[languageKey]))
|
||||
return;
|
||||
|
||||
let namingType = Helper.ToNamingType(node);
|
||||
const namingType = Helper.ToNamingType(node);
|
||||
if (isNullOrUndefined(namingType)) {
|
||||
// unsupported modelerfour node for naming type, ignore it for now
|
||||
return;
|
||||
}
|
||||
|
||||
let style = settings[namingType];
|
||||
let single = settings.singularize.includes(namingType) === true;
|
||||
const style = settings[namingType];
|
||||
const single = settings.singularize.includes(namingType) === true;
|
||||
|
||||
if (Helper.isEmptyString(style)) {
|
||||
// Only process when naming convention is set
|
||||
return;
|
||||
}
|
||||
|
||||
let up1 = (n: string) => Helper.isEmptyString(n) ? n : n.length == 1 ? n.toUpperCase() : n[0].toUpperCase().concat(n.substr(1).toLowerCase());
|
||||
let op = {};
|
||||
const up1 = (n: string) => Helper.isEmptyString(n) ? n : n.length == 1 ? n.toUpperCase() : n[0].toUpperCase().concat(n.substr(1).toLowerCase());
|
||||
const op = {};
|
||||
op[CliConst.NamingStyle.camel] = {
|
||||
wording: (v: string, i: number) => i === 0 ? v.toLowerCase() : up1(v),
|
||||
sep: '',
|
||||
};
|
||||
op[CliConst.NamingStyle.pascal] = {
|
||||
wording: (v: string, i: number) => up1(v),
|
||||
wording: (v: string) => up1(v),
|
||||
sep: '',
|
||||
};
|
||||
op[CliConst.NamingStyle.kebab] = {
|
||||
wording: (v: string, i: number) => v.toLowerCase(),
|
||||
wording: (v: string) => v.toLowerCase(),
|
||||
sep: '-',
|
||||
};
|
||||
op[CliConst.NamingStyle.snake] = {
|
||||
wording: (v: string, i: number) => v.toLowerCase(),
|
||||
wording: (v: string) => v.toLowerCase(),
|
||||
sep: '_',
|
||||
};
|
||||
op[CliConst.NamingStyle.space] = {
|
||||
wording: (v: string, i: number) => v.toLowerCase(),
|
||||
wording: (v: string) => v.toLowerCase(),
|
||||
sep: ' ',
|
||||
};
|
||||
op[CliConst.NamingStyle.upper] = {
|
||||
wording: (v: string, i: number) => v.toUpperCase(),
|
||||
wording: (v: string) => v.toUpperCase(),
|
||||
sep: '_',
|
||||
};
|
||||
|
||||
let convert = (oldName) => {
|
||||
const convert = (oldName) => {
|
||||
if (Helper.isEmptyString(oldName))
|
||||
return oldName;
|
||||
|
||||
// the oldName should be in snake_naming_convention
|
||||
const SEP = '_';
|
||||
let newName = oldName.split(SEP).map((v, i) =>
|
||||
const newName = oldName.split(SEP).map((v, i) =>
|
||||
Helper.isEmptyString(v) ? '_' :
|
||||
(!isNullOrUndefined(settings.override[v.toLowerCase()]))
|
||||
? settings.override[v.toLowerCase()]
|
||||
|
@ -272,7 +268,7 @@ export class Helper {
|
|||
|
||||
|
||||
settings.appliedTo.forEach(field => {
|
||||
let v = node.language[languageKey][field];
|
||||
const v = node.language[languageKey][field];
|
||||
if (isNullOrUndefined(v))
|
||||
return;
|
||||
else if (isString(v)) {
|
||||
|
@ -291,9 +287,10 @@ export class Helper {
|
|||
public static toYamlSimplified(codeModel: CodeModel): string {
|
||||
const INDENT = ' ';
|
||||
const NEW_LINE = '\n';
|
||||
let initialIndent = 1;
|
||||
let tab = (extra: number = 0) => INDENT.repeat(initialIndent + extra);
|
||||
let formatValue = (o: any, i: number) => {
|
||||
const initialIndent = 1;
|
||||
const tab = (extra = 0) => INDENT.repeat(initialIndent + extra);
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const formatValue = (o: any, i: number) => {
|
||||
if (isString(o))
|
||||
return o;
|
||||
else if (isArray(o))
|
||||
|
@ -308,34 +305,37 @@ export class Helper {
|
|||
return isUndefined(o) ? '{undefined}' : isNull(o) ? '{null}' : o.toString();
|
||||
};
|
||||
|
||||
let generateCliValue = (o: any, i: number) => o.language.default.name + `${isNullOrUndefined(o.schema) ? '' : ('(' + o.schema.language.default.name + '^' + o.schema.type + ')')}` +
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const generateCliValue = (o: any, i: number) => o.language.default.name + `${isNullOrUndefined(o.schema) ? '' : ('(' + o.schema.language.default.name + '^' + o.schema.type + ')')}` +
|
||||
(isNullOrUndefined(o.language.cli) ? '' : Object.getOwnPropertyNames(o.language.cli)
|
||||
.filter(key => o.language.cli[key] !== o.language.default[key])
|
||||
.reduce((pv, cv, ci) => pv.concat((ci === 0 ? (NEW_LINE + tab(i) + 'cli:') : '') +
|
||||
NEW_LINE + tab(i + 1) + `${cv}: ${formatValue(o.language.cli[cv], i + 2)}`), ''));
|
||||
|
||||
let generatePropertyFlattenValue = (o: any, i: number) => {
|
||||
let v = NodeExtensionHelper.getFlattenedValue(o);
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const generatePropertyFlattenValue = (o: any, i: number) => {
|
||||
const v = NodeExtensionHelper.getFlattenedValue(o);
|
||||
return (isNullOrUndefined(v)) ? '' : NEW_LINE + tab(i) + NodeExtensionHelper.FLATTEN_FLAG + ': ' + v;
|
||||
};
|
||||
|
||||
let generatePropertyReadonlyValue = (o: any, i: number) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const generatePropertyReadonlyValue = (o: any, i: number) => {
|
||||
return (o['readOnly'] === true) ? (NEW_LINE + tab(i) + 'readOnly: true') : '';
|
||||
};
|
||||
|
||||
let generateDiscriminatorValueForSchema = (o: Schema, i: number) => {
|
||||
const generateDiscriminatorValueForSchema = (o: Schema, i: number) => {
|
||||
if (o instanceof ObjectSchema) {
|
||||
let v = NodeHelper.HasSubClass(o);
|
||||
const v = NodeHelper.HasSubClass(o);
|
||||
return v ? NEW_LINE + tab(i) + NodeHelper.DISCRIMINATOR_FLAG + ': true' : '';
|
||||
}
|
||||
else {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let generateDiscriminatorValueForParam = (o: Parameter, i: number) => {
|
||||
const generateDiscriminatorValueForParam = (o: Parameter, i: number) => {
|
||||
return generateDiscriminatorValueForSchema(o.schema, i);
|
||||
}
|
||||
};
|
||||
|
||||
let s = '';
|
||||
s = s + `operationGroups:${NEW_LINE}` +
|
||||
|
@ -378,6 +378,7 @@ export class Helper {
|
|||
.join(''));
|
||||
s = s + `${tab()}choices:${NEW_LINE}` +
|
||||
`${tab(1)}all:${NEW_LINE}`.concat(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
[codeModel.schemas.choices ?? [], codeModel.schemas.sealedChoices ?? []].map((arr: any[]) => arr.map(
|
||||
v => `${tab(2)}- choiceName: ${generateCliValue(v, 3)}` +
|
||||
`${NEW_LINE}${tab(3)}choiceValues:${NEW_LINE}`.concat(
|
||||
|
@ -386,7 +387,8 @@ export class Helper {
|
|||
return s;
|
||||
}
|
||||
|
||||
public static getDefaultValue(schema: Schema) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
public static getDefaultValue(schema: Schema): any {
|
||||
switch (schema.type) {
|
||||
case SchemaType.Array:
|
||||
return [];
|
||||
|
@ -406,7 +408,7 @@ export class Helper {
|
|||
return Date.now();
|
||||
case SchemaType.ByteArray:
|
||||
case SchemaType.Binary:
|
||||
return 'BinaryData'
|
||||
return 'BinaryData';
|
||||
case SchemaType.Char:
|
||||
return ' ';
|
||||
case SchemaType.Date:
|
||||
|
@ -443,7 +445,7 @@ export class Helper {
|
|||
case SchemaType.Group:
|
||||
return 'group';
|
||||
default:
|
||||
return 'unknown'
|
||||
return 'unknown';
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -452,11 +454,11 @@ export class Helper {
|
|||
}
|
||||
|
||||
public static createPolyOperationCliKey(baseOperation: Operation, discriminatorValue: string): string {
|
||||
return `${NodeCliHelper.getCliKey(baseOperation, baseOperation.language.default.name)}#${discriminatorValue}`
|
||||
return `${NodeCliHelper.getCliKey(baseOperation, baseOperation.language.default.name)}#${discriminatorValue}`;
|
||||
}
|
||||
|
||||
public static createPolyOperationCliName(baseOperation: Operation, discriminatorValue: string): string {
|
||||
return `${NodeCliHelper.getCliName(baseOperation, baseOperation.language.default.name)}#${discriminatorValue}`
|
||||
return `${NodeCliHelper.getCliName(baseOperation, baseOperation.language.default.name)}#${discriminatorValue}`;
|
||||
}
|
||||
|
||||
public static createSplitOperationCliKey(baseOperation: Operation, splitName: string): string {
|
||||
|
@ -479,9 +481,9 @@ export class Helper {
|
|||
* @param codeModel
|
||||
* @param action
|
||||
*/
|
||||
public static enumerateCodeModel(codeModel: CodeModel, action: (nodeDescriptor: CliCommonSchema.CodeModel.NodeDescriptor) => void, flag: CliCommonSchema.CodeModel.NodeTypeFlag = null) {
|
||||
public static enumerateCodeModel(codeModel: CodeModel, action: (nodeDescriptor: CliCommonSchema.CodeModel.NodeDescriptor) => void, flag: CliCommonSchema.CodeModel.NodeTypeFlag = null): void {
|
||||
if (isNullOrUndefined(action)) {
|
||||
throw Error("empty action for going through code model")
|
||||
throw Error("empty action for going through code model");
|
||||
}
|
||||
|
||||
// choice/sealedChoice/choiceValue
|
||||
|
@ -501,7 +503,7 @@ export class Helper {
|
|||
}
|
||||
}
|
||||
|
||||
public static enumerateChoices(choices: ChoiceSchema<StringSchema>[] | SealedChoiceSchema<StringSchema>[], action: (nodeDescriptor: CliCommonSchema.CodeModel.NodeDescriptor) => void, flag: CliCommonSchema.CodeModel.NodeTypeFlag) {
|
||||
public static enumerateChoices(choices: ChoiceSchema<StringSchema>[] | SealedChoiceSchema<StringSchema>[], action: (nodeDescriptor: CliCommonSchema.CodeModel.NodeDescriptor) => void, flag: CliCommonSchema.CodeModel.NodeTypeFlag): void {
|
||||
const enumSchema = isNullOrUndefined(flag) || ((flag & CliCommonSchema.CodeModel.NodeTypeFlag.choiceSchema) > 0);
|
||||
const cliKeyMissing = '<clikey-missing>';
|
||||
|
||||
|
@ -520,7 +522,7 @@ export class Helper {
|
|||
}
|
||||
}
|
||||
|
||||
public static enumerateChoiceValues(choice: ChoiceSchema<StringSchema> | SealedChoiceSchema<StringSchema>, action: (nodeDescriptor: CliCommonSchema.CodeModel.NodeDescriptor) => void, flag: CliCommonSchema.CodeModel.NodeTypeFlag) {
|
||||
public static enumerateChoiceValues(choice: ChoiceSchema<StringSchema> | SealedChoiceSchema<StringSchema>, action: (nodeDescriptor: CliCommonSchema.CodeModel.NodeDescriptor) => void, flag: CliCommonSchema.CodeModel.NodeTypeFlag): void {
|
||||
const enumValue = isNullOrUndefined(flag) || ((flag & CliCommonSchema.CodeModel.NodeTypeFlag.choiceValue) > 0);
|
||||
const cliKeyMissing = '<clikey-missing>';
|
||||
|
||||
|
@ -538,7 +540,7 @@ export class Helper {
|
|||
}
|
||||
}
|
||||
|
||||
public static enumrateSchemas(schemas: ObjectSchema[], action: (nodeDescriptor: CliCommonSchema.CodeModel.NodeDescriptor) => void, flag: CliCommonSchema.CodeModel.NodeTypeFlag) {
|
||||
public static enumrateSchemas(schemas: ObjectSchema[], action: (nodeDescriptor: CliCommonSchema.CodeModel.NodeDescriptor) => void, flag: CliCommonSchema.CodeModel.NodeTypeFlag): void {
|
||||
const enumObjectSchema = isNullOrUndefined(flag) || ((flag & CliCommonSchema.CodeModel.NodeTypeFlag.objectSchema) > 0);
|
||||
const cliKeyMissing = '<clikey-missing>';
|
||||
|
||||
|
@ -556,7 +558,7 @@ export class Helper {
|
|||
}
|
||||
}
|
||||
|
||||
public static enumrateSchemaProperties(schema: ObjectSchema, action: (nodeDescriptor: CliCommonSchema.CodeModel.NodeDescriptor) => void, flag: CliCommonSchema.CodeModel.NodeTypeFlag) {
|
||||
public static enumrateSchemaProperties(schema: ObjectSchema, action: (nodeDescriptor: CliCommonSchema.CodeModel.NodeDescriptor) => void, flag: CliCommonSchema.CodeModel.NodeTypeFlag): void {
|
||||
const enumProperty = isNullOrUndefined(flag) || ((flag & CliCommonSchema.CodeModel.NodeTypeFlag.property) > 0);
|
||||
if (isNullOrUndefined(schema.properties)) {
|
||||
return;
|
||||
|
@ -571,12 +573,12 @@ export class Helper {
|
|||
parent: schema.properties,
|
||||
target: prop,
|
||||
targetIndex: j
|
||||
})
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static enumrateOperationGroups(groups: OperationGroup[], action: (nodeDescriptor: CliCommonSchema.CodeModel.NodeDescriptor) => void, flag: CliCommonSchema.CodeModel.NodeTypeFlag) {
|
||||
public static enumrateOperationGroups(groups: OperationGroup[], action: (nodeDescriptor: CliCommonSchema.CodeModel.NodeDescriptor) => void, flag: CliCommonSchema.CodeModel.NodeTypeFlag): void {
|
||||
const enumGroup = isNullOrUndefined(flag) || ((flag & CliCommonSchema.CodeModel.NodeTypeFlag.operationGroup) > 0);
|
||||
const cliKeyMissing = '<clikey-missing>';
|
||||
|
||||
|
@ -588,13 +590,13 @@ export class Helper {
|
|||
parent: groups,
|
||||
target: group,
|
||||
targetIndex: i,
|
||||
})
|
||||
});
|
||||
}
|
||||
Helper.enumrateOperations(group, action, flag);
|
||||
}
|
||||
}
|
||||
|
||||
public static enumrateOperations(group: OperationGroup, action: (nodeDescriptor: CliCommonSchema.CodeModel.NodeDescriptor) => void, flag: CliCommonSchema.CodeModel.NodeTypeFlag) {
|
||||
public static enumrateOperations(group: OperationGroup, action: (nodeDescriptor: CliCommonSchema.CodeModel.NodeDescriptor) => void, flag: CliCommonSchema.CodeModel.NodeTypeFlag): void {
|
||||
const enumOperation = isNullOrUndefined(flag) || ((flag & CliCommonSchema.CodeModel.NodeTypeFlag.operation) > 0);
|
||||
const cliKeyMissing = '<clikey-missing>';
|
||||
|
||||
|
@ -610,7 +612,7 @@ export class Helper {
|
|||
operations.push(...cliOps);
|
||||
|
||||
for (let j = operations.length - 1; j >= 0; j--) {
|
||||
let op = operations[j];
|
||||
const op = operations[j];
|
||||
if (enumOperation) {
|
||||
action({
|
||||
operationGroupCliKey: NodeCliHelper.getCliKey(group, cliKeyMissing),
|
||||
|
@ -618,13 +620,13 @@ export class Helper {
|
|||
parent: group.operations,
|
||||
target: op,
|
||||
targetIndex: j,
|
||||
})
|
||||
});
|
||||
}
|
||||
Helper.enumrateParameters(group, op, action, flag);
|
||||
}
|
||||
}
|
||||
|
||||
public static enumrateParameters(group: OperationGroup, op: Operation, action: (nodeDescriptor: CliCommonSchema.CodeModel.NodeDescriptor) => void, flag: CliCommonSchema.CodeModel.NodeTypeFlag) {
|
||||
public static enumrateParameters(group: OperationGroup, op: Operation, action: (nodeDescriptor: CliCommonSchema.CodeModel.NodeDescriptor) => void, flag: CliCommonSchema.CodeModel.NodeTypeFlag): void {
|
||||
const enumParam = isNullOrUndefined(flag) || ((flag & CliCommonSchema.CodeModel.NodeTypeFlag.parameter) > 0);
|
||||
const cliKeyMissing = '<clikey-missing>';
|
||||
|
||||
|
@ -639,7 +641,7 @@ export class Helper {
|
|||
parent: op.parameters,
|
||||
target: param,
|
||||
targetIndex: k,
|
||||
})
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -658,7 +660,7 @@ export class Helper {
|
|||
parent: op.requests[m].parameters,
|
||||
target: param,
|
||||
targetIndex: k,
|
||||
})
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
import { AutoRestExtension, startSession } from '@azure-tools/autorest-extension-base';
|
||||
import { AutoRestExtension } from '@azure-tools/autorest-extension-base';
|
||||
import { Helper } from './helper';
|
||||
import { Modifier } from './plugins/modifier/modifier';
|
||||
import { CommonNamer } from './plugins/namer';
|
||||
|
@ -20,7 +20,7 @@ extension.Add("clicommon", async host => {
|
|||
|
||||
Helper.dumper.dumpCodeModel("modifier-pre");
|
||||
|
||||
let arr = await session.getValue(CliConst.CLI_DIRECTIVE_KEY, null);
|
||||
const arr = await session.getValue(CliConst.CLI_DIRECTIVE_KEY, null);
|
||||
const modifier = await new Modifier(session).init(arr);
|
||||
let result = modifier.process();
|
||||
|
||||
|
@ -32,7 +32,7 @@ extension.Add("clicommon", async host => {
|
|||
Helper.dumper.dumpCodeModel("namer-post");
|
||||
|
||||
// add test scenario from common settings
|
||||
let cliCommonSettings = await host.GetValue("cli");
|
||||
const cliCommonSettings = await host.GetValue("cli");
|
||||
if (cliCommonSettings) {
|
||||
result["test-scenario"] = cliCommonSettings['test-scenario'] || cliCommonSettings['test-setup'];
|
||||
}
|
||||
|
@ -49,5 +49,5 @@ extension.Add("cli-poly-as-resource-modifier", polyAsResourceModifier);
|
|||
extension.Add("cli-flatten-modifier", flattenModifier);
|
||||
extension.Add("cli-poly-as-param-modifier", polyAsParamModifier);
|
||||
extension.Add("cli-complex-marker", complexMarker);
|
||||
extension.Add("cli-visibility-cleaner", visibilityCleaner)
|
||||
extension.Add("cli-visibility-cleaner", visibilityCleaner);
|
||||
extension.Run();
|
|
@ -29,11 +29,11 @@ export class NodeCliHelper {
|
|||
|
||||
private static readonly FLATTENED_NAMES = 'flattenedNames';
|
||||
|
||||
public static setCliDiscriminatorValue(node: ObjectSchema, value: string) {
|
||||
return NodeCliHelper.setCliProperty(node, this.CLI_DISCRIMINATOR_VALUE, value);
|
||||
public static setCliDiscriminatorValue(node: ObjectSchema, value: string): void {
|
||||
NodeCliHelper.setCliProperty(node, this.CLI_DISCRIMINATOR_VALUE, value);
|
||||
}
|
||||
|
||||
public static getCliDiscriminatorValue(node: ObjectSchema) {
|
||||
public static getCliDiscriminatorValue(node: ObjectSchema): string {
|
||||
return NodeCliHelper.getCliProperty(node, this.CLI_DISCRIMINATOR_VALUE, () => node.discriminatorValue);
|
||||
}
|
||||
|
||||
|
@ -42,7 +42,7 @@ export class NodeCliHelper {
|
|||
* @param node
|
||||
* @param value
|
||||
*/
|
||||
public static setCliKey(node: M4Node, value: string) {
|
||||
public static setCliKey(node: M4Node, value: string): void {
|
||||
NodeCliHelper.setCliProperty(node, NodeCliHelper.CLI_KEY, value);
|
||||
}
|
||||
|
||||
|
@ -50,43 +50,39 @@ export class NodeCliHelper {
|
|||
* get node.language.cli.cliKey
|
||||
* @param node
|
||||
*/
|
||||
public static getCliKey(node: M4Node, defaultValue: string) {
|
||||
public static getCliKey(node: M4Node, defaultValue: string): string {
|
||||
return isNullOrUndefined(node?.language[NodeCliHelper.CLI]) ? defaultValue : node.language[NodeCliHelper.CLI][NodeCliHelper.CLI_KEY];
|
||||
}
|
||||
|
||||
public static setCliName(node: M4Node, value: string) {
|
||||
public static setCliName(node: M4Node, value: string): void {
|
||||
NodeCliHelper.setCliProperty(node, NodeCliHelper.NAME, value);
|
||||
}
|
||||
|
||||
public static getCliName(node: M4Node, defaultValue: string) {
|
||||
public static getCliName(node: M4Node, defaultValue: string): string {
|
||||
return isNullOrUndefined(node?.language[NodeCliHelper.CLI]) ? defaultValue : node.language[NodeCliHelper.CLI][NodeCliHelper.NAME];
|
||||
}
|
||||
|
||||
public static getDefaultNameWithType(node: ObjectSchema | DictionarySchema | ArraySchema) {
|
||||
return `${node.language.default.name}(${node instanceof ObjectSchema ? node.type : node instanceof DictionarySchema ? (node.elementType.language.default.name + '^dictionary') : (node.elementType.language.default.name + '^array')})`;
|
||||
}
|
||||
|
||||
public static setHidden(node: M4Node, value: boolean) {
|
||||
public static setHidden(node: M4Node, value: boolean): void {
|
||||
NodeCliHelper.setCliProperty(node, NodeCliHelper.CLI_HIDDEN, value);
|
||||
}
|
||||
|
||||
public static getHidden(node: M4Node, defaultValue: boolean) {
|
||||
public static getHidden(node: M4Node, defaultValue: boolean): boolean {
|
||||
return NodeCliHelper.getCliProperty(node, NodeCliHelper.CLI_HIDDEN, () => defaultValue);
|
||||
}
|
||||
|
||||
public static setRemoved(node: M4Node, value: boolean) {
|
||||
public static setRemoved(node: M4Node, value: boolean): void {
|
||||
NodeCliHelper.setCliProperty(node, NodeCliHelper.CLI_REMOVED, value);
|
||||
}
|
||||
|
||||
public static getRemoved(node: M4Node, defaultValue: boolean) {
|
||||
public static getRemoved(node: M4Node): boolean {
|
||||
return NodeCliHelper.getCliProperty(node, NodeCliHelper.CLI_REMOVED, () => false);
|
||||
}
|
||||
|
||||
public static getCliDescription(node: M4Node) {
|
||||
public static getCliDescription(node: M4Node): string {
|
||||
return isNullOrUndefined(node.language[NodeCliHelper.CLI]) ? '' : node.language[NodeCliHelper.CLI][NodeCliHelper.DESCRIPTION];
|
||||
}
|
||||
|
||||
public static setCliOperationSplitted(op: Operation, value: boolean) {
|
||||
public static setCliOperationSplitted(op: Operation, value: boolean): void {
|
||||
NodeCliHelper.setCliProperty(op, NodeCliHelper.CLI_OPERATION_SPLITTED, value);
|
||||
}
|
||||
|
||||
|
@ -98,7 +94,7 @@ export class NodeCliHelper {
|
|||
return NodeCliHelper.getCliProperty(node, NodeCliHelper.SPLIT_OPERATION_NAMES, () => null);
|
||||
}
|
||||
|
||||
public static clearCliSplitOperationNames(node: Operation) {
|
||||
public static clearCliSplitOperationNames(node: Operation): void {
|
||||
NodeCliHelper.clearCliProperty(node, NodeCliHelper.SPLIT_OPERATION_NAMES);
|
||||
}
|
||||
|
||||
|
@ -110,11 +106,11 @@ export class NodeCliHelper {
|
|||
return NodeCliHelper.getCliProperty(param, NodeCliHelper.FLATTENED_NAMES, () => []);
|
||||
}
|
||||
|
||||
public static setCliFlattenedNames(param: Parameter, flattenedNames: string[]) {
|
||||
public static setCliFlattenedNames(param: Parameter, flattenedNames: string[]): void {
|
||||
NodeCliHelper.setCliProperty(param, NodeCliHelper.FLATTENED_NAMES, flattenedNames);
|
||||
}
|
||||
|
||||
public static setPolyAsResource(node: Parameter, value: boolean) {
|
||||
public static setPolyAsResource(node: Parameter, value: boolean): void {
|
||||
NodeCliHelper.setCliProperty(node, NodeCliHelper.POLY_RESOURCE, value);
|
||||
}
|
||||
|
||||
|
@ -122,7 +118,7 @@ export class NodeCliHelper {
|
|||
return NodeCliHelper.getCliProperty(node, NodeCliHelper.POLY_RESOURCE, () => false);
|
||||
}
|
||||
|
||||
public static setPolyAsParamExpanded(param: Parameter, value: boolean) {
|
||||
public static setPolyAsParamExpanded(param: Parameter, value: boolean): void {
|
||||
NodeCliHelper.setCliProperty(param, NodeCliHelper.POLY_AS_PARAM_EXPANDED, value);
|
||||
}
|
||||
|
||||
|
@ -135,7 +131,7 @@ export class NodeCliHelper {
|
|||
return complexity;
|
||||
}
|
||||
|
||||
public static clearComplex(node: M4Node) {
|
||||
public static clearComplex(node: M4Node): void {
|
||||
NodeCliHelper.clearCliProperty(node, NodeCliHelper.CLI_COMPLEXITY);
|
||||
}
|
||||
|
||||
|
@ -143,7 +139,7 @@ export class NodeCliHelper {
|
|||
return NodeCliHelper.getCliProperty(node, NodeCliHelper.CLI_COMPLEXITY, () => undefined);
|
||||
}
|
||||
|
||||
public static setIsVisibleFlag(node: M4Node, visiblity: CliCommonSchema.CodeModel.Visibility) {
|
||||
public static setIsVisibleFlag(node: M4Node, visiblity: CliCommonSchema.CodeModel.Visibility): void {
|
||||
NodeCliHelper.setCliProperty(node, NodeCliHelper.CLI_IS_VISIBLE, visiblity);
|
||||
}
|
||||
|
||||
|
@ -157,6 +153,7 @@ export class NodeCliHelper {
|
|||
* @param key
|
||||
* @param value
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any
|
||||
public static setCliProperty(node: M4Node, key: string, value: any): void {
|
||||
if (isNullOrUndefined(node.language[NodeCliHelper.CLI]))
|
||||
node.language[NodeCliHelper.CLI] = {};
|
||||
|
@ -168,6 +165,7 @@ export class NodeCliHelper {
|
|||
delete node.language[NodeCliHelper.CLI][key];
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
public static getCliProperty(node: M4Node, propertyName: string, defaultWhenNotExist: () => any): any {
|
||||
if (isNullOrUndefined(node.language[NodeCliHelper.CLI])) {
|
||||
if (isNullOrUndefined(defaultWhenNotExist))
|
||||
|
@ -193,8 +191,8 @@ export class NodeCliHelper {
|
|||
return NodeCliHelper.getCliProperty(schema, NodeCliHelper.CLI_SIMPLIFIER_INDICATOR, () => undefined);
|
||||
}
|
||||
|
||||
public static clearSimplifyIndicator(schema: ObjectSchema) {
|
||||
return NodeCliHelper.clearCliProperty(schema, NodeCliHelper.CLI_SIMPLIFIER_INDICATOR);
|
||||
public static clearSimplifyIndicator(schema: ObjectSchema): void {
|
||||
NodeCliHelper.clearCliProperty(schema, NodeCliHelper.CLI_SIMPLIFIER_INDICATOR);
|
||||
}
|
||||
|
||||
public static setInCircle(schema: ObjectSchema | ArraySchema | DictionarySchema, inCircle: boolean): boolean {
|
||||
|
@ -206,8 +204,8 @@ export class NodeCliHelper {
|
|||
return NodeCliHelper.getCliProperty(schema, NodeCliHelper.CLI_IN_CIRCLE, () => undefined);
|
||||
}
|
||||
|
||||
public static clearInCircle(schema: ObjectSchema | ArraySchema | DictionarySchema) {
|
||||
return NodeCliHelper.clearCliProperty(schema, NodeCliHelper.CLI_IN_CIRCLE);
|
||||
public static clearInCircle(schema: ObjectSchema | ArraySchema | DictionarySchema): void {
|
||||
NodeCliHelper.clearCliProperty(schema, NodeCliHelper.CLI_IN_CIRCLE);
|
||||
}
|
||||
|
||||
|
||||
|
@ -220,7 +218,7 @@ export class NodeCliHelper {
|
|||
return NodeCliHelper.getCliProperty(node, NodeCliHelper.CLI_MARK, () => undefined);
|
||||
}
|
||||
|
||||
public static clearMark(node: M4Node) {
|
||||
public static clearMark(node: M4Node): void {
|
||||
NodeCliHelper.clearCliProperty(node, NodeCliHelper.CLI_MARK);
|
||||
}
|
||||
}
|
||||
|
@ -249,7 +247,7 @@ export class NodeExtensionHelper {
|
|||
* @param isFlatten
|
||||
* @param overwrite
|
||||
*/
|
||||
public static setFlatten(node: Extensions, isFlatten: boolean, overwrite: boolean) {
|
||||
public static setFlatten(node: Extensions, isFlatten: boolean, overwrite: boolean): void {
|
||||
if (isNullOrUndefined(node.extensions))
|
||||
node.extensions = {};
|
||||
if (isNullOrUndefined(node.extensions[NodeExtensionHelper.FLATTEN_FLAG]) || overwrite) {
|
||||
|
@ -261,8 +259,8 @@ export class NodeExtensionHelper {
|
|||
* check node.extensions['x-ms-client-flatten']
|
||||
* @param p
|
||||
*/
|
||||
public static isFlattened(p: Extensions) {
|
||||
return !isNullOrUndefined(p.extensions) && p.extensions[NodeExtensionHelper.FLATTEN_FLAG] == true;
|
||||
public static isFlattened(p: Extensions): boolean {
|
||||
return !isNullOrUndefined(p.extensions) && p.extensions[NodeExtensionHelper.FLATTEN_FLAG] === true;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -270,13 +268,13 @@ export class NodeExtensionHelper {
|
|||
* possible value: true | false | undefined
|
||||
* @param p
|
||||
*/
|
||||
public static getFlattenedValue(p: Extensions) {
|
||||
public static getFlattenedValue(p: Extensions): boolean | undefined {
|
||||
if (isNullOrUndefined(p.extensions) || isNullOrUndefined(p.extensions[NodeExtensionHelper.FLATTEN_FLAG]))
|
||||
return undefined;
|
||||
return p.extensions[NodeExtensionHelper.FLATTEN_FLAG];
|
||||
}
|
||||
|
||||
public static setCliFlattenOrigin(node: M4Node, ori: M4Node) {
|
||||
public static setCliFlattenOrigin(node: M4Node, ori: M4Node): void {
|
||||
NodeExtensionHelper.setExtensionsProperty(node, NodeExtensionHelper.CLI_FLATTEN_ORIGIN, ori);
|
||||
}
|
||||
|
||||
|
@ -284,7 +282,7 @@ export class NodeExtensionHelper {
|
|||
return NodeExtensionHelper.getExtensionsProperty(node, NodeExtensionHelper.CLI_FLATTEN_ORIGIN, () => null);
|
||||
}
|
||||
|
||||
public static setCliFlattenPrefix(node: M4Node, value: string) {
|
||||
public static setCliFlattenPrefix(node: M4Node, value: string): void {
|
||||
NodeExtensionHelper.setExtensionsProperty(node, NodeExtensionHelper.CLI_FLATTEN_PREFIX, value);
|
||||
}
|
||||
|
||||
|
@ -292,7 +290,7 @@ export class NodeExtensionHelper {
|
|||
return NodeExtensionHelper.getExtensionsProperty(param, NodeExtensionHelper.CLI_FLATTEN_PREFIX, () => null);
|
||||
}
|
||||
|
||||
public static setPolyAsResourceParam(op: Operation, polyParam: Parameter) {
|
||||
public static setPolyAsResourceParam(op: Operation, polyParam: Parameter): void {
|
||||
NodeExtensionHelper.setExtensionsProperty(op, NodeExtensionHelper.POLY_AS_RESOURCE_SUBCLASS_PARAM, polyParam);
|
||||
}
|
||||
|
||||
|
@ -300,7 +298,7 @@ export class NodeExtensionHelper {
|
|||
return NodeExtensionHelper.getExtensionsProperty(op, NodeExtensionHelper.POLY_AS_RESOURCE_SUBCLASS_PARAM, null);
|
||||
}
|
||||
|
||||
public static setPolyAsResourceBaseSchema(param: Parameter, base: Schema) {
|
||||
public static setPolyAsResourceBaseSchema(param: Parameter, base: Schema): void {
|
||||
NodeExtensionHelper.setExtensionsProperty(param, NodeExtensionHelper.POLY_AS_RESOURCE_BASE_SCHEMA, base);
|
||||
}
|
||||
|
||||
|
@ -308,7 +306,7 @@ export class NodeExtensionHelper {
|
|||
return NodeExtensionHelper.getExtensionsProperty(param, NodeExtensionHelper.POLY_AS_RESOURCE_BASE_SCHEMA, null);
|
||||
}
|
||||
|
||||
public static setPolyAsResourceOriginalOperation(op: Operation, ori: Operation) {
|
||||
public static setPolyAsResourceOriginalOperation(op: Operation, ori: Operation): void {
|
||||
NodeExtensionHelper.setExtensionsProperty(op, NodeExtensionHelper.POLY_AS_RESOURCE_ORIGINAL_OPERATION, ori);
|
||||
}
|
||||
|
||||
|
@ -316,7 +314,7 @@ export class NodeExtensionHelper {
|
|||
return NodeExtensionHelper.getExtensionsProperty(op, NodeExtensionHelper.POLY_AS_RESOURCE_ORIGINAL_OPERATION, null);
|
||||
}
|
||||
|
||||
public static setPolyAsResourceDiscriminatorValue(op: Operation, value: string) {
|
||||
public static setPolyAsResourceDiscriminatorValue(op: Operation, value: string): void {
|
||||
NodeExtensionHelper.setExtensionsProperty(op, NodeExtensionHelper.POLY_AS_RESOURCE_DISCRIMINATOR_VALUE, value);
|
||||
}
|
||||
|
||||
|
@ -324,7 +322,7 @@ export class NodeExtensionHelper {
|
|||
return NodeExtensionHelper.getExtensionsProperty(op, NodeExtensionHelper.POLY_AS_RESOURCE_DISCRIMINATOR_VALUE, null);
|
||||
}
|
||||
|
||||
public static setSplitOperationOriginalOperation(op: Operation, ori: Operation) {
|
||||
public static setSplitOperationOriginalOperation(op: Operation, ori: Operation): void {
|
||||
NodeExtensionHelper.setExtensionsProperty(op, NodeExtensionHelper.SPLIT_OPERATION_ORIGINAL_OPERATION, ori);
|
||||
}
|
||||
|
||||
|
@ -332,7 +330,7 @@ export class NodeExtensionHelper {
|
|||
return NodeExtensionHelper.getExtensionsProperty(op, NodeExtensionHelper.SPLIT_OPERATION_ORIGINAL_OPERATION, null);
|
||||
}
|
||||
|
||||
public static setPolyAsParamBaseSchema(param: Parameter, base: Schema) {
|
||||
public static setPolyAsParamBaseSchema(param: Parameter, base: Schema): void {
|
||||
NodeExtensionHelper.setExtensionsProperty(param, NodeExtensionHelper.POLY_AS_PARAM_BASE_SCHEMA, base);
|
||||
}
|
||||
|
||||
|
@ -340,7 +338,7 @@ export class NodeExtensionHelper {
|
|||
return NodeExtensionHelper.getExtensionsProperty(param, NodeExtensionHelper.POLY_AS_PARAM_BASE_SCHEMA, null);
|
||||
}
|
||||
|
||||
public static setPolyAsParamOriginalParam(param: Parameter, ori: Parameter) {
|
||||
public static setPolyAsParamOriginalParam(param: Parameter, ori: Parameter): void {
|
||||
NodeExtensionHelper.setExtensionsProperty(param, NodeExtensionHelper.POLY_AS_PARAM_ORIGINIAL_PARAMETER, ori);
|
||||
}
|
||||
|
||||
|
@ -348,7 +346,7 @@ export class NodeExtensionHelper {
|
|||
return NodeExtensionHelper.getExtensionsProperty(param, NodeExtensionHelper.POLY_AS_PARAM_ORIGINIAL_PARAMETER, null);
|
||||
}
|
||||
|
||||
public static setCliFlattened(node: M4Node, value: boolean) {
|
||||
public static setCliFlattened(node: M4Node, value: boolean): void {
|
||||
NodeExtensionHelper.setExtensionsProperty(node, NodeExtensionHelper.CLI_FLATTENED, value);
|
||||
}
|
||||
|
||||
|
@ -356,22 +354,24 @@ export class NodeExtensionHelper {
|
|||
return NodeExtensionHelper.getExtensionsProperty(node, NodeExtensionHelper.CLI_FLATTENED, () => false);
|
||||
}
|
||||
|
||||
public static addCliOperation(originalOperation: Operation, cliOperation: Operation) {
|
||||
let v: Operation[] = NodeExtensionHelper.getExtensionsProperty(originalOperation, NodeExtensionHelper.CLI_OPERATIONS, () => []);
|
||||
public static addCliOperation(originalOperation: Operation, cliOperation: Operation): void {
|
||||
const v: Operation[] = NodeExtensionHelper.getExtensionsProperty(originalOperation, NodeExtensionHelper.CLI_OPERATIONS, () => []);
|
||||
v.push(cliOperation);
|
||||
NodeExtensionHelper.setExtensionsProperty(originalOperation, NodeExtensionHelper.CLI_OPERATIONS, v);
|
||||
}
|
||||
|
||||
public static getCliOperation(originalOperation: Operation, defaultValue: () => any): Operation[] {
|
||||
public static getCliOperation(originalOperation: Operation, defaultValue: () => Operation[]): Operation[] {
|
||||
return NodeExtensionHelper.getExtensionsProperty(originalOperation, NodeExtensionHelper.CLI_OPERATIONS, defaultValue);
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any
|
||||
public static setExtensionsProperty(node: M4Node, key: string, value: any): void {
|
||||
if (isNullOrUndefined(node.extensions))
|
||||
node.extensions = {};
|
||||
node.extensions[key] = value;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any
|
||||
public static getExtensionsProperty(node: M4Node, propertyName: string, defaultWhenNotExist: () => any): any {
|
||||
if (isNullOrUndefined(node.extensions)) {
|
||||
if (isNullOrUndefined(defaultWhenNotExist))
|
||||
|
@ -398,18 +398,18 @@ export class NodeHelper {
|
|||
* Check whether the obj has discriminator property
|
||||
* @param o
|
||||
*/
|
||||
public static HasSubClass(node: ObjectSchema) {
|
||||
public static HasSubClass(node: ObjectSchema): boolean {
|
||||
return !isNullOrUndefined(node.discriminator);
|
||||
}
|
||||
|
||||
public static *getSubClasses(baseSchema: ObjectSchema, leafOnly: boolean) {
|
||||
public static *getSubClasses(baseSchema: ObjectSchema, leafOnly: boolean): Generator<ObjectSchema, ObjectSchema[], unknown> {
|
||||
|
||||
let allSubs = baseSchema.discriminator?.all;
|
||||
const allSubs = baseSchema.discriminator?.all;
|
||||
if (isNullOrUndefined(allSubs))
|
||||
return [];
|
||||
|
||||
for (let key in allSubs) {
|
||||
let subClass = allSubs[key];
|
||||
for (const key in allSubs) {
|
||||
const subClass = allSubs[key];
|
||||
if (!(subClass instanceof ObjectSchema)) {
|
||||
Helper.logWarning("subclass is not ObjectSchema: " + subClass.language.default.name);
|
||||
continue;
|
||||
|
@ -422,7 +422,7 @@ export class NodeHelper {
|
|||
}
|
||||
}
|
||||
|
||||
public static setJson(node: M4Node, isJson: boolean, modifyFlatten: boolean) {
|
||||
public static setJson(node: M4Node, isJson: boolean, modifyFlatten: boolean): void {
|
||||
|
||||
if (modifyFlatten && isJson) {
|
||||
NodeExtensionHelper.setFlatten(node, false /*flatten*/, true /*overwrite flag*/);
|
||||
|
@ -430,11 +430,11 @@ export class NodeHelper {
|
|||
NodeCliHelper.setCliProperty(node, NodeHelper.JSON, isJson);
|
||||
}
|
||||
|
||||
public static getJson(node: M4Node) {
|
||||
public static getJson(node: M4Node): boolean {
|
||||
return NodeCliHelper.getCliProperty(node, NodeHelper.JSON, () => false);
|
||||
}
|
||||
|
||||
public static getDefaultNameWithType(node: ObjectSchema | DictionarySchema | ArraySchema) {
|
||||
public static getDefaultNameWithType(node: ObjectSchema | DictionarySchema | ArraySchema): string {
|
||||
return `${node.language.default.name}(${node instanceof ObjectSchema ? node.type : node instanceof DictionarySchema ? (node.elementType.language.default.name + '^dictionary') : (node.elementType.language.default.name + '^array')})`;
|
||||
}
|
||||
|
||||
|
|
|
@ -1,48 +1,44 @@
|
|||
import { Host, Session, startSession } from "@azure-tools/autorest-extension-base";
|
||||
import { CodeModel, Request, codeModelSchema, Metadata, ObjectSchema, isObjectSchema, Property, Extensions, Scheme, ComplexSchema, Operation, OperationGroup, Parameter, VirtualParameter, ImplementationLocation, ArraySchema, DictionarySchema, AnySchema, ConstantSchema, getAllProperties } from "@azure-tools/codemodel";
|
||||
import { isNullOrUndefined, isArray, isNull } from "util";
|
||||
import { Host, Session } from "@azure-tools/autorest-extension-base";
|
||||
import { CodeModel, isObjectSchema, ArraySchema, DictionarySchema, AnySchema, ConstantSchema, getAllProperties, ObjectSchema } from "@azure-tools/codemodel";
|
||||
import { isNullOrUndefined } from "util";
|
||||
import { Helper } from "../helper";
|
||||
import { CliConst, M4Node, CliCommonSchema } from "../schema";
|
||||
import { Dumper } from "../dumper";
|
||||
import { values } from '@azure-tools/linq';
|
||||
import { CliCommonSchema } from "../schema";
|
||||
import { NodeHelper, NodeCliHelper } from "../nodeHelper";
|
||||
import { FlattenHelper } from "../flattenHelper";
|
||||
|
||||
class ComplexMarker {
|
||||
constructor(private session: Session<CodeModel>) {
|
||||
}
|
||||
|
||||
private calculateDict(dict: DictionarySchema) {
|
||||
let complexity = NodeCliHelper.getComplexity(dict);
|
||||
const complexity = NodeCliHelper.getComplexity(dict);
|
||||
if (!isNullOrUndefined(complexity)) {
|
||||
if (complexity === CliCommonSchema.CodeModel.Complexity.unknown) {
|
||||
// we have been here before, a circle found
|
||||
NodeCliHelper.setComplex(dict, CliCommonSchema.CodeModel.Complexity.dictionary_complex)
|
||||
NodeCliHelper.setComplex(dict, CliCommonSchema.CodeModel.Complexity.dictionary_complex);
|
||||
return CliCommonSchema.CodeModel.Complexity.dictionary_complex;
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
return complexity;
|
||||
}
|
||||
}
|
||||
NodeCliHelper.setComplex(dict, CliCommonSchema.CodeModel.Complexity.unknown);
|
||||
|
||||
if (dict.elementType instanceof ObjectSchema ||
|
||||
dict.elementType instanceof ArraySchema ||
|
||||
dict.elementType instanceof DictionarySchema ||
|
||||
dict.elementType instanceof AnySchema) {
|
||||
NodeCliHelper.setComplex(dict, CliCommonSchema.CodeModel.Complexity.dictionary_complex);
|
||||
return CliCommonSchema.CodeModel.Complexity.dictionary_complex;
|
||||
dict.elementType instanceof ArraySchema ||
|
||||
dict.elementType instanceof DictionarySchema ||
|
||||
dict.elementType instanceof AnySchema) {
|
||||
NodeCliHelper.setComplex(dict, CliCommonSchema.CodeModel.Complexity.dictionary_complex);
|
||||
return CliCommonSchema.CodeModel.Complexity.dictionary_complex;
|
||||
}
|
||||
NodeCliHelper.setComplex(dict, CliCommonSchema.CodeModel.Complexity.dictionary_simple);
|
||||
return CliCommonSchema.CodeModel.Complexity.dictionary_simple;
|
||||
}
|
||||
|
||||
private calculateArray(arr: ArraySchema) {
|
||||
let complexity = NodeCliHelper.getComplexity(arr);
|
||||
const complexity = NodeCliHelper.getComplexity(arr);
|
||||
if (!isNullOrUndefined(complexity)) {
|
||||
if (complexity === CliCommonSchema.CodeModel.Complexity.unknown) {
|
||||
// we have been here before, a circle found
|
||||
NodeCliHelper.setComplex(arr, CliCommonSchema.CodeModel.Complexity.array_complex)
|
||||
NodeCliHelper.setComplex(arr, CliCommonSchema.CodeModel.Complexity.array_complex);
|
||||
return CliCommonSchema.CodeModel.Complexity.array_complex;
|
||||
}
|
||||
else {
|
||||
|
@ -52,10 +48,10 @@ class ComplexMarker {
|
|||
NodeCliHelper.setComplex(arr, CliCommonSchema.CodeModel.Complexity.unknown);
|
||||
|
||||
if (arr.elementType instanceof ObjectSchema ||
|
||||
arr.elementType instanceof ArraySchema ||
|
||||
arr.elementType instanceof DictionarySchema ||
|
||||
arr.elementType instanceof AnySchema) {
|
||||
NodeCliHelper.setComplex(arr, CliCommonSchema.CodeModel.Complexity.array_complex);
|
||||
arr.elementType instanceof ArraySchema ||
|
||||
arr.elementType instanceof DictionarySchema ||
|
||||
arr.elementType instanceof AnySchema) {
|
||||
NodeCliHelper.setComplex(arr, CliCommonSchema.CodeModel.Complexity.array_complex);
|
||||
return CliCommonSchema.CodeModel.Complexity.array_complex;
|
||||
}
|
||||
NodeCliHelper.setComplex(arr, CliCommonSchema.CodeModel.Complexity.array_simple);
|
||||
|
@ -68,7 +64,7 @@ class ComplexMarker {
|
|||
if (!isNullOrUndefined(complexity)) {
|
||||
if (complexity === CliCommonSchema.CodeModel.Complexity.unknown) {
|
||||
// we have been here before, a circle found
|
||||
NodeCliHelper.setComplex(obj, CliCommonSchema.CodeModel.Complexity.object_complex)
|
||||
NodeCliHelper.setComplex(obj, CliCommonSchema.CodeModel.Complexity.object_complex);
|
||||
return CliCommonSchema.CodeModel.Complexity.object_complex;
|
||||
}
|
||||
else {
|
||||
|
@ -79,18 +75,18 @@ class ComplexMarker {
|
|||
if (NodeHelper.HasSubClass(obj))
|
||||
return NodeCliHelper.setComplex(obj, CliCommonSchema.CodeModel.Complexity.object_complex);
|
||||
|
||||
NodeCliHelper.setComplex(obj, CliCommonSchema.CodeModel.Complexity.unknown);
|
||||
NodeCliHelper.setComplex(obj, CliCommonSchema.CodeModel.Complexity.unknown);
|
||||
|
||||
complexity = CliCommonSchema.CodeModel.Complexity.object_simple;
|
||||
if (obj.properties && obj.properties.length > 0) {
|
||||
for (let prop of obj.properties) {
|
||||
for (const prop of obj.properties) {
|
||||
if (isObjectSchema(prop.schema)) {
|
||||
this.calculateObject(prop.schema);
|
||||
return NodeCliHelper.setComplex(obj, CliCommonSchema.CodeModel.Complexity.object_complex);
|
||||
}
|
||||
else if (prop.schema instanceof ArraySchema) {
|
||||
let c = this.calculateArray(prop.schema);
|
||||
if (c == CliCommonSchema.CodeModel.Complexity.array_complex) {
|
||||
const c = this.calculateArray(prop.schema);
|
||||
if (c === CliCommonSchema.CodeModel.Complexity.array_complex) {
|
||||
return NodeCliHelper.setComplex(obj, CliCommonSchema.CodeModel.Complexity.object_complex);
|
||||
}
|
||||
}
|
||||
|
@ -107,24 +103,24 @@ class ComplexMarker {
|
|||
}
|
||||
|
||||
private setSimplifyIndicator(schema: ObjectSchema) {
|
||||
let indicator: CliCommonSchema.CodeModel.SimplifyIndicator = {
|
||||
const indicator: CliCommonSchema.CodeModel.SimplifyIndicator = {
|
||||
simplifiable: true,
|
||||
propertyCountIfSimplify: 0,
|
||||
propertyCountIfSimplifyWithoutSimpleObject: 0,
|
||||
};
|
||||
let impossible: CliCommonSchema.CodeModel.SimplifyIndicator = {
|
||||
const impossible: CliCommonSchema.CodeModel.SimplifyIndicator = {
|
||||
simplifiable: false,
|
||||
propertyCountIfSimplify: 10000,
|
||||
propertyCountIfSimplifyWithoutSimpleObject: 10000,
|
||||
};
|
||||
let flag: CliCommonSchema.CodeModel.SimplifyIndicator = {
|
||||
const flag: CliCommonSchema.CodeModel.SimplifyIndicator = {
|
||||
simplifiable: false,
|
||||
propertyCountIfSimplify: -1,
|
||||
propertyCountIfSimplifyWithoutSimpleObject: -1,
|
||||
|
||||
};
|
||||
|
||||
let pre = NodeCliHelper.getSimplifyIndicator(schema);
|
||||
const pre = NodeCliHelper.getSimplifyIndicator(schema);
|
||||
if (!isNullOrUndefined(pre) && pre.propertyCountIfSimplify === -1) {
|
||||
// circle found
|
||||
return NodeCliHelper.setSimplifyIndicator(schema, impossible);
|
||||
|
@ -132,7 +128,7 @@ class ComplexMarker {
|
|||
|
||||
NodeCliHelper.setSimplifyIndicator(schema, flag);
|
||||
|
||||
for (let p of getAllProperties(schema)) {
|
||||
for (const p of getAllProperties(schema)) {
|
||||
if (p.readOnly)
|
||||
continue;
|
||||
if (p.schema instanceof ConstantSchema)
|
||||
|
@ -146,12 +142,12 @@ class ComplexMarker {
|
|||
if (NodeHelper.HasSubClass(p.schema)) {
|
||||
return NodeCliHelper.setSimplifyIndicator(schema, impossible);
|
||||
}
|
||||
let pi = this.setSimplifyIndicator(p.schema);
|
||||
const pi = this.setSimplifyIndicator(p.schema);
|
||||
if (pi.simplifiable === true) {
|
||||
if (NodeCliHelper.getComplexity(p.schema) === CliCommonSchema.CodeModel.Complexity.object_simple)
|
||||
indicator.propertyCountIfSimplifyWithoutSimpleObject++;
|
||||
else
|
||||
indicator.propertyCountIfSimplifyWithoutSimpleObject += (pi.propertyCountIfSimplifyWithoutSimpleObject)
|
||||
indicator.propertyCountIfSimplifyWithoutSimpleObject += (pi.propertyCountIfSimplifyWithoutSimpleObject);
|
||||
indicator.propertyCountIfSimplify += (pi.propertyCountIfSimplify);
|
||||
}
|
||||
else {
|
||||
|
@ -167,9 +163,9 @@ class ComplexMarker {
|
|||
return NodeCliHelper.setSimplifyIndicator(schema, indicator);
|
||||
}
|
||||
|
||||
public setInCircle(schema: ObjectSchema | DictionarySchema | ArraySchema, stack: (ObjectSchema | DictionarySchema | ArraySchema)[], tag: string) {
|
||||
public setInCircle(schema: ObjectSchema | DictionarySchema | ArraySchema, stack: (ObjectSchema | DictionarySchema | ArraySchema)[], tag: string): void {
|
||||
|
||||
let flag = NodeCliHelper.getMark(schema);
|
||||
const flag = NodeCliHelper.getMark(schema);
|
||||
if (!isNullOrUndefined(flag)) {
|
||||
if (flag === tag) {
|
||||
// we find a circle
|
||||
|
@ -199,7 +195,7 @@ class ComplexMarker {
|
|||
}
|
||||
}
|
||||
else if (schema instanceof ObjectSchema) {
|
||||
for (let prop of getAllProperties(schema)) {
|
||||
for (const prop of getAllProperties(schema)) {
|
||||
if (prop.schema instanceof ObjectSchema ||
|
||||
prop.schema instanceof DictionarySchema ||
|
||||
prop.schema instanceof ArraySchema) {
|
||||
|
@ -213,7 +209,7 @@ class ComplexMarker {
|
|||
NodeCliHelper.setMark(schema, "checked");
|
||||
}
|
||||
|
||||
public process() {
|
||||
public process(): void {
|
||||
|
||||
this.session.model.schemas.objects.forEach(obj => {
|
||||
NodeCliHelper.clearComplex(obj);
|
||||
|
@ -229,7 +225,7 @@ class ComplexMarker {
|
|||
this.session.model.schemas.arrays?.forEach(arr => {
|
||||
NodeCliHelper.clearComplex(arr);
|
||||
NodeCliHelper.clearMark(arr);
|
||||
})
|
||||
});
|
||||
|
||||
let tag = 1;
|
||||
this.session.model.schemas.objects.forEach(obj => {
|
||||
|
@ -243,7 +239,7 @@ class ComplexMarker {
|
|||
this.session.model.schemas.arrays?.forEach(arr => {
|
||||
this.calculateArray(arr);
|
||||
tag++;
|
||||
})
|
||||
});
|
||||
|
||||
this.session.model.schemas.objects.forEach(obj => {
|
||||
this.setSimplifyIndicator(obj);
|
||||
|
@ -261,17 +257,17 @@ class ComplexMarker {
|
|||
this.session.model.schemas.arrays?.forEach(arr => {
|
||||
this.setInCircle(arr, [], tag.toString());
|
||||
tag++;
|
||||
})
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export async function processRequest(host: Host) {
|
||||
export async function processRequest(host: Host): Promise<void> {
|
||||
|
||||
const session = await Helper.init(host);
|
||||
|
||||
Helper.dumper.dumpCodeModel('complex-marker-pre');
|
||||
|
||||
let cm = new ComplexMarker(session);
|
||||
const cm = new ComplexMarker(session);
|
||||
cm.process();
|
||||
|
||||
Helper.dumper.dumpCodeModel('complex-marker-post');
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
import { Host, Session } from "@azure-tools/autorest-extension-base";
|
||||
import { CodeModel, Operation, Request, ObjectSchema, Parameter } from "@azure-tools/codemodel";
|
||||
import { CodeModel, Operation, Request, ObjectSchema } from "@azure-tools/codemodel";
|
||||
import { Helper } from "../helper";
|
||||
import { CliConst, CliCommonSchema } from "../schema";
|
||||
import { NodeHelper, NodeCliHelper, NodeExtensionHelper } from "../nodeHelper";
|
||||
|
@ -13,7 +13,7 @@ export class FlattenModifier {
|
|||
constructor(protected session: Session<CodeModel>){
|
||||
}
|
||||
|
||||
public async process(flattenEnabled: boolean, polyEnabled: boolean) {
|
||||
public async process(flattenEnabled: boolean, polyEnabled: boolean): Promise<void> {
|
||||
await this.modifier();
|
||||
|
||||
if (!flattenEnabled && !polyEnabled) {
|
||||
|
@ -27,9 +27,9 @@ export class FlattenModifier {
|
|||
}
|
||||
}
|
||||
|
||||
private async modifier() {
|
||||
let directives = await this.session.getValue(CliConst.CLI_FLATTEN_DIRECTIVE_KEY, []);
|
||||
let cliDirectives = await this.session.getValue(CliConst.CLI_DIRECTIVE_KEY, []);
|
||||
private async modifier(): Promise<void> {
|
||||
const directives = await this.session.getValue(CliConst.CLI_FLATTEN_DIRECTIVE_KEY, []);
|
||||
const cliDirectives = await this.session.getValue(CliConst.CLI_DIRECTIVE_KEY, []);
|
||||
|
||||
const flattenDirectives = [...directives, ...cliDirectives]
|
||||
.filter((dir) => dir[NodeCliHelper.CLI_FLATTEN])
|
||||
|
@ -48,7 +48,7 @@ export class FlattenModifier {
|
|||
const copy: CliCommonSchema.CliDirective.Directive = {
|
||||
select: src.select,
|
||||
where: CopyHelper.deepCopy(src.where),
|
||||
}
|
||||
};
|
||||
copy[NodeCliHelper.CLI_FLATTEN] = src[NodeCliHelper.CLI_FLATTEN];
|
||||
return copy;
|
||||
}
|
||||
|
@ -119,7 +119,7 @@ export class FlattenModifier {
|
|||
const clonedParam = CopyHelper.copyParameter(parameter);
|
||||
request.parameters[index] = clonedParam;
|
||||
|
||||
let path = isNullOrUndefined(clonedParam['targetProperty']) ? [] : [clonedParam['targetProperty']];
|
||||
const path = isNullOrUndefined(clonedParam['targetProperty']) ? [] : [clonedParam['targetProperty']];
|
||||
// Use parameter's default name as perfix
|
||||
FlattenHelper.flattenParameter(request, clonedParam, path, `${clonedParam.language.default.name}`);
|
||||
|
||||
|
@ -128,13 +128,13 @@ export class FlattenModifier {
|
|||
return false;
|
||||
}
|
||||
|
||||
private isCliOperation(desc: CliCommonSchema.CodeModel.NodeDescriptor) {
|
||||
private isCliOperation(desc: CliCommonSchema.CodeModel.NodeDescriptor): boolean {
|
||||
// CliOperation is not in group.operations. So its index is equal or bigger than operation array(desc.parent)'s length
|
||||
return desc.targetIndex >= desc.parent.length;
|
||||
}
|
||||
}
|
||||
|
||||
export async function processRequest(host: Host) {
|
||||
export async function processRequest(host: Host): Promise<void> {
|
||||
|
||||
const session = await Helper.init(host);
|
||||
Helper.dumper.dumpCodeModel("flatten-pre");
|
||||
|
|
|
@ -1,21 +1,18 @@
|
|||
import { Host, Session, startSession } from "@azure-tools/autorest-extension-base";
|
||||
import { serialize } from "@azure-tools/codegen";
|
||||
import { CodeModel, codeModelSchema, Metadata, ObjectSchema, isObjectSchema, Property, Extensions, getAllProperties, Parameter, DictionarySchema, Schema, ArraySchema, ConstantSchema, AnySchema } from "@azure-tools/codemodel";
|
||||
import { Host, Session } from "@azure-tools/autorest-extension-base";
|
||||
import { CodeModel, ObjectSchema, isObjectSchema, getAllProperties, Parameter, DictionarySchema, Schema, ArraySchema, ConstantSchema, AnySchema } from "@azure-tools/codemodel";
|
||||
import { isNullOrUndefined, isArray } from "util";
|
||||
import { DESTRUCTION } from "dns";
|
||||
import { Helper } from "../../helper";
|
||||
import { NodeHelper, NodeCliHelper, NodeExtensionHelper } from "../../nodeHelper"
|
||||
import { NodeHelper, NodeCliHelper, NodeExtensionHelper } from "../../nodeHelper";
|
||||
import { CliConst, CliCommonSchema } from "../../schema";
|
||||
import { CliDirectiveManager } from "../modifier/cliDirective";
|
||||
import { Modifier } from "../modifier/modifier";
|
||||
import { FlattenValidator } from "./flattenValidator";
|
||||
import { values, Dictionary } from "@azure-tools/linq";
|
||||
import { Z_DEFLATED } from "zlib";
|
||||
import { values } from "@azure-tools/linq";
|
||||
import { ActionHitCount } from "../modifier/cliDirectiveAction";
|
||||
|
||||
class flattenInfo {
|
||||
public constructor(public propCount: number = 0, public complexity: number = 0) { }
|
||||
};
|
||||
}
|
||||
|
||||
interface FlattenConfig {
|
||||
maxComplexity: number;
|
||||
|
@ -43,6 +40,7 @@ function cloneFlattenConfig(config: FlattenConfig): FlattenConfig {
|
|||
|
||||
export class FlattenSetter {
|
||||
codeModel: CodeModel;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
cliConfig: any;
|
||||
manager: CliDirectiveManager;
|
||||
|
||||
|
@ -53,7 +51,7 @@ export class FlattenSetter {
|
|||
|
||||
private canArrayObjectSimplified(schema: Schema, maxArrayObjProp: number) {
|
||||
if (schema instanceof ObjectSchema && !NodeHelper.HasSubClass(schema)) {
|
||||
let sim = NodeCliHelper.getSimplifyIndicator(schema);
|
||||
const sim = NodeCliHelper.getSimplifyIndicator(schema);
|
||||
return ((!isNullOrUndefined(sim)) && sim.simplifiable === true && sim.propertyCountIfSimplify <= maxArrayObjProp);
|
||||
}
|
||||
return false;
|
||||
|
@ -61,7 +59,7 @@ export class FlattenSetter {
|
|||
|
||||
private canSubclassSimplified(schema: Schema, flattenConfig: FlattenConfig, isPolyAsResource: boolean) {
|
||||
if (schema instanceof ObjectSchema && !isNullOrUndefined(schema.discriminatorValue) && !NodeHelper.HasSubClass(schema)) {
|
||||
let sim = NodeCliHelper.getSimplifyIndicator(schema);
|
||||
const sim = NodeCliHelper.getSimplifyIndicator(schema);
|
||||
if (isPolyAsResource)
|
||||
return ((!isNullOrUndefined(sim)) && sim.simplifiable === true && sim.propertyCountIfSimplifyWithoutSimpleObject <= flattenConfig.maxPolyAsResourcePropCount);
|
||||
else
|
||||
|
@ -78,14 +76,14 @@ export class FlattenSetter {
|
|||
*/
|
||||
private calcSchemaForPayloadFlatten(schema: Schema, info: flattenInfo[], level: number, required: boolean, flattenConfig: FlattenConfig): number {
|
||||
|
||||
let weight = required ? 1 : 0.5;
|
||||
const weight = required ? 1 : 0.5;
|
||||
|
||||
let increasePropCount = () => {
|
||||
const increasePropCount = () => {
|
||||
for (let i = level; i < info.length; i++)
|
||||
info[i].propCount++;
|
||||
};
|
||||
|
||||
let increaseComplexity = () => {
|
||||
const increaseComplexity = () => {
|
||||
for (let i = level; i < info.length; i++)
|
||||
info[i].complexity = +weight;
|
||||
};
|
||||
|
@ -108,6 +106,7 @@ export class FlattenSetter {
|
|||
increasePropCount();
|
||||
increaseComplexity();
|
||||
}
|
||||
// eslint-disable-next-line no-empty
|
||||
else if (schema instanceof ConstantSchema) {
|
||||
}
|
||||
else if (schema instanceof ObjectSchema) {
|
||||
|
@ -121,7 +120,7 @@ export class FlattenSetter {
|
|||
else {
|
||||
info[level].propCount++;
|
||||
info[level].complexity += weight;
|
||||
for (let prop of getAllProperties(schema)) {
|
||||
for (const prop of getAllProperties(schema)) {
|
||||
if (prop.readOnly)
|
||||
continue;
|
||||
if (level + 1 < info.length) {
|
||||
|
@ -137,18 +136,18 @@ export class FlattenSetter {
|
|||
}
|
||||
|
||||
private calcPayloadFlatten(paramSchema: Schema, flattenConfig: FlattenConfig): number {
|
||||
let defaultLevel = 1;
|
||||
let info: flattenInfo[] = [];
|
||||
let maxLevel = flattenConfig.maxLevel;
|
||||
let maxComplexity = flattenConfig.maxComplexity;
|
||||
let maxPropCount = flattenConfig.maxPropCount;
|
||||
const defaultLevel = 1;
|
||||
const info: flattenInfo[] = [];
|
||||
const maxLevel = flattenConfig.maxLevel;
|
||||
const maxComplexity = flattenConfig.maxComplexity;
|
||||
const maxPropCount = flattenConfig.maxPropCount;
|
||||
for (let i = maxLevel; i >= 0; i--)
|
||||
info.push(new flattenInfo());
|
||||
|
||||
let r = this.calcSchemaForPayloadFlatten(paramSchema, info, 0, true, flattenConfig);
|
||||
const r = this.calcSchemaForPayloadFlatten(paramSchema, info, 0, true, flattenConfig);
|
||||
|
||||
for (let i = 0; i <= r; i++) {
|
||||
Helper.logDebug(`Level-${i}: propCount=${info[i].propCount}, complexity=${info[i].complexity}`)
|
||||
Helper.logDebug(`Level-${i}: propCount=${info[i].propCount}, complexity=${info[i].complexity}`);
|
||||
}
|
||||
|
||||
for (let i = r; i >= 0; i--) {
|
||||
|
@ -170,20 +169,20 @@ export class FlattenSetter {
|
|||
private isPolyAsResource(schema: Schema, paramName: string, flattenConfig: FlattenConfig): boolean {
|
||||
|
||||
ActionHitCount.hitCount = 0;
|
||||
let desc = flattenConfig.nodeDescripter;
|
||||
const desc = flattenConfig.nodeDescripter;
|
||||
desc.parameterCliKey = paramName;
|
||||
this.manager.process(desc);
|
||||
return (ActionHitCount.hitCount > 0);
|
||||
}
|
||||
|
||||
private flattenPolySchema(baseSchema: ObjectSchema, paramName: string, curLevel: number, flattenSimpleObject: boolean, flattenConfig: FlattenConfig) {
|
||||
private flattenPolySchema(baseSchema: ObjectSchema, paramName: string, curLevel: number, flattenSimpleObject: boolean, flattenConfig: FlattenConfig): void {
|
||||
if (NodeHelper.HasSubClass(baseSchema)) {
|
||||
let isPolyAsResource: boolean = this.isPolyAsResource(baseSchema, paramName, flattenConfig);
|
||||
for (let subClass of NodeHelper.getSubClasses(baseSchema, true)) {
|
||||
const isPolyAsResource: boolean = this.isPolyAsResource(baseSchema, paramName, flattenConfig);
|
||||
for (const subClass of NodeHelper.getSubClasses(baseSchema, true)) {
|
||||
if (this.canSubclassSimplified(subClass, flattenConfig, isPolyAsResource)) {
|
||||
let config = cloneFlattenConfig(flattenConfig);
|
||||
const config = cloneFlattenConfig(flattenConfig);
|
||||
config.maxLevel = Math.max(32, config.maxLevel);
|
||||
Helper.logDebug(`Try to flatten poly schema ${subClass.language.default.name} from ${baseSchema.language.default.name} with paramName ${paramName}, polyAsResource=${isPolyAsResource}`)
|
||||
Helper.logDebug(`Try to flatten poly schema ${subClass.language.default.name} from ${baseSchema.language.default.name} with paramName ${paramName}, polyAsResource=${isPolyAsResource}`);
|
||||
this.flattenSchemaFromPayload(subClass, curLevel, flattenSimpleObject || (!isPolyAsResource), config);
|
||||
}
|
||||
}
|
||||
|
@ -195,14 +194,14 @@ export class FlattenSetter {
|
|||
if (!(schema instanceof ObjectSchema))
|
||||
return;
|
||||
if (curLevel >= flattenConfig.maxLevel) {
|
||||
let indicator = NodeCliHelper.getSimplifyIndicator(schema);
|
||||
const indicator = NodeCliHelper.getSimplifyIndicator(schema);
|
||||
// Continue flatten if there is only one property even when we hit the max level
|
||||
if (indicator.simplifiable !== true || indicator.propertyCountIfSimplify !== 1)
|
||||
return;
|
||||
Helper.logDebug(`continue flatten ${schema.language.default.name} when maxLevel is met because it's simplifiyIndicator.propertyCountIfSimplify is ${indicator.propertyCountIfSimplify}`);
|
||||
}
|
||||
|
||||
for (let prop of getAllProperties(schema)) {
|
||||
for (const prop of getAllProperties(schema)) {
|
||||
if (prop.readOnly)
|
||||
continue;
|
||||
if (prop.schema instanceof ObjectSchema) {
|
||||
|
@ -222,7 +221,7 @@ export class FlattenSetter {
|
|||
// put 32 as max flatten level for array object flatten here just in case,
|
||||
// it should be big enough value for array object flattening, but handle unexpected circle
|
||||
// situation though it's not expected
|
||||
let config = cloneFlattenConfig(flattenConfig);
|
||||
const config = cloneFlattenConfig(flattenConfig);
|
||||
config.maxLevel = Math.max(32, config.maxLevel);
|
||||
this.flattenSchemaFromPayload(prop.schema.elementType, curLevel, true, config);
|
||||
}
|
||||
|
@ -231,35 +230,35 @@ export class FlattenSetter {
|
|||
}
|
||||
}
|
||||
|
||||
private flattenPayload(param: Parameter, flattenConfig: FlattenConfig) {
|
||||
private flattenPayload(param: Parameter, flattenConfig: FlattenConfig): void {
|
||||
if (!(param.schema instanceof ObjectSchema))
|
||||
return;
|
||||
if (NodeHelper.HasSubClass(param.schema)) {
|
||||
this.flattenPolySchema(param.schema, NodeCliHelper.getCliKey(param, "noParamCliKey"), 0, true, flattenConfig);
|
||||
}
|
||||
else {
|
||||
let r = this.calcPayloadFlatten(param.schema, flattenConfig);
|
||||
const r = this.calcPayloadFlatten(param.schema, flattenConfig);
|
||||
if (r > 0) {
|
||||
NodeExtensionHelper.setFlatten(param, true, flattenConfig.overwriteSwagger);
|
||||
let config = cloneFlattenConfig(flattenConfig);
|
||||
const config = cloneFlattenConfig(flattenConfig);
|
||||
config.maxLevel = r;
|
||||
this.flattenSchemaFromPayload(param.schema, 0, false, config);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async process(host: Host) {
|
||||
public async process(): Promise<CodeModel> {
|
||||
|
||||
let overwriteSwagger = await this.session.getValue(CliConst.CLI_FLATTEN_SET_FLATTEN_ALL_OVERWRITE_SWAGGER_KEY, false);
|
||||
let flattenAll = await this.session.getValue(CliConst.CLI_FLATTEN_SET_FLATTEN_ALL_KEY, false);
|
||||
const overwriteSwagger = await this.session.getValue(CliConst.CLI_FLATTEN_SET_FLATTEN_ALL_OVERWRITE_SWAGGER_KEY, false);
|
||||
const flattenAll = await this.session.getValue(CliConst.CLI_FLATTEN_SET_FLATTEN_ALL_KEY, false);
|
||||
|
||||
let flattenSchema = await this.session.getValue(CliConst.CLI_FLATTEN_SET_FLATTEN_SCHEMA_KEY, false);
|
||||
const flattenSchema = await this.session.getValue(CliConst.CLI_FLATTEN_SET_FLATTEN_SCHEMA_KEY, false);
|
||||
|
||||
// by default on when the flatten_all flag is one
|
||||
if (flattenSchema === true || flattenAll === true) {
|
||||
this.codeModel.schemas.objects.forEach(o => {
|
||||
if (!NodeHelper.HasSubClass(o)) {
|
||||
for (let p of getAllProperties(o)) {
|
||||
for (const p of getAllProperties(o)) {
|
||||
if (isObjectSchema(p.schema)) {
|
||||
NodeExtensionHelper.setFlatten(p, !NodeHelper.HasSubClass(p.schema as ObjectSchema), overwriteSwagger);
|
||||
}
|
||||
|
@ -268,20 +267,20 @@ export class FlattenSetter {
|
|||
});
|
||||
}
|
||||
|
||||
let maxPropCount = await this.session.getValue(CliConst.CLI_FLATTEN_SET_FLATTEN_PAYLOAD_MAX_PROP_KEY, 32);
|
||||
let maxLevel = await this.session.getValue(CliConst.CLI_FLATTEN_SET_FLATTEN_PAYLOAD_MAX_LEVEL_KEY, 5);
|
||||
let maxComplexity = await this.session.getValue(CliConst.CLI_FLATTEN_SET_FLATTEN_PAYLOAD_MAX_COMPLEXITY_KEY, 1);
|
||||
let maxArrayPropCount = await this.session.getValue(CliConst.CLI_FLATTEN_SET_FLATTEN_PAYLOAD_MAX_ARRAY_OBJECT_PROP_KEY, 8);
|
||||
let maxPolyAsResourcePropCount = await this.session.getValue(CliConst.CLI_FLATTEN_SET_FLATTEN_PAYLOAD_MAX_POLY_AS_RESOURCE_PROP_KEY, 8);
|
||||
let maxPolyAsParamPropCount = await this.session.getValue(CliConst.CLI_FLATTEN_SET_FLATTEN_PAYLOAD_MAX_POLY_AS_PARAM_PROP_KEY, 8);
|
||||
let flattenPayload = await this.session.getValue(CliConst.CLI_FLATTEN_SET_FLATTEN_PAYLOAD_KEY, false);
|
||||
const maxPropCount = await this.session.getValue(CliConst.CLI_FLATTEN_SET_FLATTEN_PAYLOAD_MAX_PROP_KEY, 32);
|
||||
const maxLevel = await this.session.getValue(CliConst.CLI_FLATTEN_SET_FLATTEN_PAYLOAD_MAX_LEVEL_KEY, 5);
|
||||
const maxComplexity = await this.session.getValue(CliConst.CLI_FLATTEN_SET_FLATTEN_PAYLOAD_MAX_COMPLEXITY_KEY, 1);
|
||||
const maxArrayPropCount = await this.session.getValue(CliConst.CLI_FLATTEN_SET_FLATTEN_PAYLOAD_MAX_ARRAY_OBJECT_PROP_KEY, 8);
|
||||
const maxPolyAsResourcePropCount = await this.session.getValue(CliConst.CLI_FLATTEN_SET_FLATTEN_PAYLOAD_MAX_POLY_AS_RESOURCE_PROP_KEY, 8);
|
||||
const maxPolyAsParamPropCount = await this.session.getValue(CliConst.CLI_FLATTEN_SET_FLATTEN_PAYLOAD_MAX_POLY_AS_PARAM_PROP_KEY, 8);
|
||||
const flattenPayload = await this.session.getValue(CliConst.CLI_FLATTEN_SET_FLATTEN_PAYLOAD_KEY, false);
|
||||
|
||||
let cliDirectives = await this.session.getValue(CliConst.CLI_DIRECTIVE_KEY, []);
|
||||
const cliDirectives = await this.session.getValue(CliConst.CLI_DIRECTIVE_KEY, []);
|
||||
this.manager = new CliDirectiveManager();
|
||||
await this.manager.LoadDirective(
|
||||
cliDirectives.filter((d: CliCommonSchema.CliDirective.Directive) => (!isNullOrUndefined(d[NodeCliHelper.POLY_RESOURCE]) && d[NodeCliHelper.POLY_RESOURCE] === true))
|
||||
.map((d: CliCommonSchema.CliDirective.Directive) => {
|
||||
let r: CliCommonSchema.CliDirective.Directive = {
|
||||
const r: CliCommonSchema.CliDirective.Directive = {
|
||||
select: d.select,
|
||||
where: JSON.parse(JSON.stringify(d.where)),
|
||||
hitCount: true,
|
||||
|
@ -290,7 +289,7 @@ export class FlattenSetter {
|
|||
return r;
|
||||
}));
|
||||
|
||||
let flattenConfig: FlattenConfig = {
|
||||
const flattenConfig: FlattenConfig = {
|
||||
maxComplexity: maxComplexity,
|
||||
maxLevel: maxLevel,
|
||||
maxPropCount: maxPropCount,
|
||||
|
@ -301,7 +300,6 @@ export class FlattenSetter {
|
|||
nodeDescripter: null,
|
||||
};
|
||||
|
||||
let match = (e, v) => isNullOrUndefined(e) || Helper.matchRegex(Helper.createRegex(e), v);
|
||||
if (flattenPayload === true || flattenAll === true) {
|
||||
this.codeModel.operationGroups.forEach(group => {
|
||||
group.operations.forEach(operation => {
|
||||
|
@ -346,44 +344,42 @@ export class FlattenSetter {
|
|||
}
|
||||
});
|
||||
|
||||
})
|
||||
})
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
return this.codeModel;
|
||||
}
|
||||
}
|
||||
|
||||
export async function processRequest(host: Host) {
|
||||
let debugOutput = {};
|
||||
|
||||
export async function processRequest(host: Host): Promise<void> {
|
||||
const session = await Helper.init(host);
|
||||
|
||||
let flag = await session.getValue(CliConst.CLI_FLATTEN_SET_ENABLED_KEY, false);
|
||||
const flag = await session.getValue(CliConst.CLI_FLATTEN_SET_ENABLED_KEY, false);
|
||||
if (flag !== true) {
|
||||
Helper.logWarning(`'${CliConst.CLI_FLATTEN_SET_ENABLED_KEY}' is not set to true, skip flattenSetter`);
|
||||
}
|
||||
else {
|
||||
Helper.dumper.dumpCodeModel("flatten-set-pre");
|
||||
|
||||
let m4FlattenModels = await session.getValue('modelerfour.flatten-models', false);
|
||||
const m4FlattenModels = await session.getValue('modelerfour.flatten-models', false);
|
||||
if (m4FlattenModels !== true)
|
||||
Helper.logWarning('modelerfour.flatten-models is not turned on');
|
||||
let m4FlattenPayloads = await session.getValue('modelerfour.flatten-payloads', false);
|
||||
const m4FlattenPayloads = await session.getValue('modelerfour.flatten-payloads', false);
|
||||
if (m4FlattenPayloads !== true)
|
||||
Helper.logWarning('modelerfour.flatten-payloads is not turned on');
|
||||
|
||||
const plugin = await new FlattenSetter(session);
|
||||
let flatResult = await plugin.process(host);
|
||||
await plugin.process();
|
||||
|
||||
Helper.dumper.dumpCodeModel("flatten-set-post");
|
||||
|
||||
let directives = await session.getValue(CliConst.CLI_FLATTEN_DIRECTIVE_KEY, []);
|
||||
let cliDirectives = await session.getValue(CliConst.CLI_DIRECTIVE_KEY, []);
|
||||
const cliDirectives = await session.getValue(CliConst.CLI_DIRECTIVE_KEY, []);
|
||||
directives = directives.concat(
|
||||
cliDirectives.filter((d: CliCommonSchema.CliDirective.Directive) => (!isNullOrUndefined(d.json) || !isNullOrUndefined(d.flatten)))
|
||||
.map((d: CliCommonSchema.CliDirective.Directive) => {
|
||||
let r: CliCommonSchema.CliDirective.Directive = {
|
||||
const r: CliCommonSchema.CliDirective.Directive = {
|
||||
select: d.select,
|
||||
where: JSON.parse(JSON.stringify(d.where)),
|
||||
json: d.json,
|
||||
|
@ -391,16 +387,16 @@ export async function processRequest(host: Host) {
|
|||
};
|
||||
return r;
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
if (!isNullOrUndefined(directives) && isArray(directives) && directives.length > 0) {
|
||||
const modifier = await new Modifier(session).init(directives);
|
||||
let modResult: CodeModel = modifier.process();
|
||||
modifier.process();
|
||||
Helper.dumper.dumpCodeModel("flatten-modifier-post");
|
||||
}
|
||||
|
||||
}
|
||||
let finalMapping = new FlattenValidator(session).validate(session.model.schemas.objects)
|
||||
const finalMapping = new FlattenValidator(session).validate(session.model.schemas.objects);
|
||||
Helper.dumper.dump('clicommon-flatten-object-map.txt', finalMapping, true /*debug only*/);
|
||||
|
||||
Helper.outputToModelerfour();
|
||||
|
|
|
@ -1,7 +1,6 @@
|
|||
import { Session } from "@azure-tools/autorest-extension-base";
|
||||
import { CodeModel, isObjectSchema, ObjectSchema, Property } from "@azure-tools/codemodel";
|
||||
import { isNullOrUndefined } from "util";
|
||||
import { CliConst } from "../../schema";
|
||||
import { Helper } from "../../helper";
|
||||
import { NodeHelper, NodeExtensionHelper } from "../../nodeHelper";
|
||||
|
||||
|
@ -9,9 +8,9 @@ const BASECLASS_INDICATOR = '*';
|
|||
const CIRCLE_VICIM_INDICATOR = '#';
|
||||
|
||||
class PropertyInfo {
|
||||
public isFlatten: boolean = false;
|
||||
public isPointToBaseClass: boolean = false;
|
||||
public isCirculeVictim: boolean = false;
|
||||
public isFlatten = false;
|
||||
public isPointToBaseClass = false;
|
||||
public isCirculeVictim = false;
|
||||
|
||||
public get nodeKey() {
|
||||
return this.property.schema.language.default.name;
|
||||
|
@ -22,18 +21,18 @@ class PropertyInfo {
|
|||
this.isPointToBaseClass = NodeHelper.HasSubClass(property.schema as ObjectSchema);
|
||||
}
|
||||
|
||||
public toOutputString(withClass: boolean) {
|
||||
public toOutputString(withClass: boolean): string {
|
||||
return `${this.property.language.default.name}${this.isPointToBaseClass ? BASECLASS_INDICATOR : ''}${this.isCirculeVictim ? CIRCLE_VICIM_INDICATOR : ''}${withClass ? ':' + this.property.schema.language.default.name : ''}`;
|
||||
}
|
||||
|
||||
public unflattenAsCirculeVictim() {
|
||||
public unflattenAsCirculeVictim(): void {
|
||||
NodeExtensionHelper.setFlatten(this.property, false, true);
|
||||
this.isCirculeVictim = true;
|
||||
}
|
||||
}
|
||||
|
||||
class NodeInfo {
|
||||
public isBaseClass: boolean = false;
|
||||
public isBaseClass = false;
|
||||
public flattenProperty: PropertyInfo[] = [];
|
||||
public unflattenProperty: PropertyInfo[] = [];
|
||||
|
||||
|
@ -51,7 +50,7 @@ class NodeInfo {
|
|||
this.unflattenProperty = [];
|
||||
if (!isNullOrUndefined(this.node.properties) && this.node.properties.length > 0) {
|
||||
for (let i = 0; i < this.node.properties.length; i++) {
|
||||
let p = this.node.properties[i];
|
||||
const p = this.node.properties[i];
|
||||
if (isObjectSchema(p.schema)) {
|
||||
NodeExtensionHelper.isFlattened(p) ? this.flattenProperty.push(new PropertyInfo(p)) : this.unflattenProperty.push(new PropertyInfo(p));
|
||||
}
|
||||
|
@ -59,19 +58,19 @@ class NodeInfo {
|
|||
}
|
||||
}
|
||||
|
||||
public toOutputString(withPropertyClass: boolean) {
|
||||
public toOutputString(withPropertyClass: boolean): string {
|
||||
return this.node.language.default.name +
|
||||
`<${isNullOrUndefined(this.node.properties) ? '0' : this.node.properties.length}>` +
|
||||
(this.isBaseClass ? BASECLASS_INDICATOR : '') +
|
||||
(this.unflattenProperty.length == 0 ? '' : `(${this.unflattenProperty.map(pi => pi.toOutputString(withPropertyClass)).join(', ')})`);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
class NodeLink {
|
||||
constructor(public preNode: NodeInfo, public linkProperty: PropertyInfo) {
|
||||
}
|
||||
|
||||
public toOutputString() {
|
||||
public toOutputString(): string {
|
||||
if (isNullOrUndefined(this.linkProperty))
|
||||
return this.preNode.toOutputString(true);
|
||||
else
|
||||
|
@ -83,7 +82,7 @@ class NodePath {
|
|||
constructor(public path: NodeLink[]) {
|
||||
}
|
||||
|
||||
public toOutputString() {
|
||||
public toOutputString(): string {
|
||||
return isNullOrUndefined(this.path) || this.path.length == 0 ? '<emptyNodePath>' : this.path.map(l => l.toOutputString()).join(' -> ');
|
||||
}
|
||||
}
|
||||
|
@ -95,14 +94,14 @@ export class FlattenValidator {
|
|||
this.codeModel = session.model;
|
||||
}
|
||||
|
||||
visitNode(ni: NodeInfo, pre: NodeLink[], founds: NodePath[], visited: Set<string>) {
|
||||
visitNode(ni: NodeInfo, pre: NodeLink[], founds: NodePath[], visited: Set<string>): void {
|
||||
|
||||
visited.add(ni.key);
|
||||
|
||||
for (let i = ni.flattenProperty.length - 1; i >= 0; i--) {
|
||||
let pi = ni.flattenProperty[i];
|
||||
let ppre = pre.concat(new NodeLink(ni, pi));
|
||||
let index = ppre.findIndex((v, i, o) => v.preNode.key === pi.nodeKey);
|
||||
const pi = ni.flattenProperty[i];
|
||||
const ppre = pre.concat(new NodeLink(ni, pi));
|
||||
const index = ppre.findIndex((v) => v.preNode.key === pi.nodeKey);
|
||||
|
||||
if (index >= 0) {
|
||||
Helper.logWarning('Circle found in flatten: ' + new NodePath(ppre).toOutputString() + ' ==> ' + pi.toOutputString(true));
|
||||
|
@ -115,7 +114,7 @@ export class FlattenValidator {
|
|||
|
||||
ni.flattenProperty.forEach(pi => {
|
||||
this.visitNode(new NodeInfo(pi.property.schema as ObjectSchema), pre.concat(new NodeLink(ni, pi)), founds, visited);
|
||||
})
|
||||
});
|
||||
|
||||
if (ni.flattenProperty.length == 0) {
|
||||
founds.push(new NodePath(pre.concat(new NodeLink(ni, null))));
|
||||
|
@ -124,10 +123,10 @@ export class FlattenValidator {
|
|||
|
||||
public validate(objects: ObjectSchema[]): string {
|
||||
|
||||
let result: NodePath[] = [];
|
||||
let visited = new Set<string>();
|
||||
const result: NodePath[] = [];
|
||||
const visited = new Set<string>();
|
||||
objects.forEach(o => {
|
||||
let ni = new NodeInfo(o);
|
||||
const ni = new NodeInfo(o);
|
||||
if (!visited.has(ni.key))
|
||||
this.visitNode(ni, [], result, visited);
|
||||
});
|
||||
|
|
|
@ -1,19 +1,15 @@
|
|||
import { Host, Session, startSession } from "@azure-tools/autorest-extension-base";
|
||||
import { serialize } from "@azure-tools/codegen";
|
||||
import { CodeModel, codeModelSchema, Metadata, ObjectSchema, isObjectSchema, Property, Extensions, Scheme } from "@azure-tools/codemodel";
|
||||
import { isNullOrUndefined, isArray } from "util";
|
||||
import { Host, Session } from "@azure-tools/autorest-extension-base";
|
||||
import { CodeModel } from "@azure-tools/codemodel";
|
||||
import { isNullOrUndefined } from "util";
|
||||
import { Helper } from "../helper";
|
||||
import { CopyHelper } from "../copyHelper";
|
||||
import { CliConst, M4Node } from "../schema";
|
||||
import { NodeHelper } from "../nodeHelper";
|
||||
import { normalize } from "path";
|
||||
|
||||
export class ModelerPostProcessor{
|
||||
export class ModelerPostProcessor {
|
||||
|
||||
constructor(protected session: Session<CodeModel>){
|
||||
constructor(protected session: Session<CodeModel>) {
|
||||
}
|
||||
|
||||
public process() {
|
||||
public process(): void {
|
||||
Helper.enumerateCodeModel(this.session.model, (n) => {
|
||||
|
||||
// In case cli is shared by multiple instances during modelerfour, do deep copy
|
||||
|
@ -24,12 +20,12 @@ export class ModelerPostProcessor{
|
|||
}
|
||||
}
|
||||
|
||||
export async function processRequest(host: Host) {
|
||||
export async function processRequest(host: Host): Promise<void> {
|
||||
|
||||
const session = await Helper.init(host);
|
||||
Helper.dumper.dumpCodeModel("modeler-post-processor-pre");
|
||||
|
||||
let pn = new ModelerPostProcessor(session);
|
||||
const pn = new ModelerPostProcessor(session);
|
||||
pn.process();
|
||||
|
||||
Helper.dumper.dumpCodeModel("modeler-post-processor-post");
|
||||
|
|
|
@ -1,8 +1,6 @@
|
|||
import { NodeSelector } from "./cliDirectiveSelector"
|
||||
import { Action } from "./cliDirectiveAction"
|
||||
import { CliCommonSchema, CliConst } from "../../schema"
|
||||
import { CodeModel, } from "@azure-tools/codemodel";
|
||||
import { Session, } from "@azure-tools/autorest-extension-base";
|
||||
import { NodeSelector } from "./cliDirectiveSelector";
|
||||
import { Action } from "./cliDirectiveAction";
|
||||
import { CliCommonSchema } from "../../schema";
|
||||
import { isNullOrUndefined } from "util";
|
||||
|
||||
class CliDirective {
|
||||
|
@ -21,7 +19,7 @@ class CliDirective {
|
|||
|
||||
process(descriptor: CliCommonSchema.CodeModel.NodeDescriptor): void {
|
||||
if (this.selector.match(descriptor)) {
|
||||
for (var action of this.actions) {
|
||||
for (const action of this.actions) {
|
||||
action.process(descriptor);
|
||||
}
|
||||
}
|
||||
|
@ -31,13 +29,13 @@ class CliDirective {
|
|||
export class CliDirectiveManager {
|
||||
private directives: CliDirective[] = [];
|
||||
|
||||
public async LoadDirective(directives: CliCommonSchema.CliDirective.Directive[]) {
|
||||
public async LoadDirective(directives: CliCommonSchema.CliDirective.Directive[]): Promise<void> {
|
||||
|
||||
this.directives = isNullOrUndefined(directives) ? [] : await Promise.all(directives.map(async v => new CliDirective(v).init()));
|
||||
}
|
||||
|
||||
public process(descripter: CliCommonSchema.CodeModel.NodeDescriptor) {
|
||||
for (var d of this.directives)
|
||||
public process(descripter: CliCommonSchema.CodeModel.NodeDescriptor): void {
|
||||
for (const d of this.directives)
|
||||
d.process(descripter);
|
||||
}
|
||||
}
|
|
@ -1,21 +1,24 @@
|
|||
import { Session } from "@azure-tools/autorest-extension-base";
|
||||
import { CodeModel } from "@azure-tools/codemodel";
|
||||
import { isNullOrUndefined, isArray } from "util";
|
||||
import { Helper } from "../../helper";
|
||||
import { CliCommonSchema, CliConst, M4Node } from "../../schema";
|
||||
import { CliCommonSchema, CliConst } from "../../schema";
|
||||
import { NodeHelper, NodeCliHelper, NodeExtensionHelper } from "../../nodeHelper";
|
||||
|
||||
export abstract class Action {
|
||||
constructor() {
|
||||
|
||||
function validateDirective(directive: CliCommonSchema.CliDirective.Directive | string, name: string): void {
|
||||
if (isNullOrUndefined(directive)) {
|
||||
throw Error(`Validation failed: '${name}' is null or undefined`);
|
||||
}
|
||||
}
|
||||
|
||||
export abstract class Action {
|
||||
|
||||
public abstract process(node: CliCommonSchema.CodeModel.NodeDescriptor): void;
|
||||
|
||||
public static async buildActionList(directive: CliCommonSchema.CliDirective.Directive): Promise<Action[]> {
|
||||
Helper.validateNullOrUndefined(directive, 'directive');
|
||||
var arr: Action[] = [];
|
||||
validateDirective(directive, 'directive');
|
||||
const arr: Action[] = [];
|
||||
|
||||
for (var key in directive) {
|
||||
var value = directive[key];
|
||||
for (let key in directive) {
|
||||
const value = directive[key];
|
||||
if (isNullOrUndefined(value))
|
||||
continue;
|
||||
|
||||
|
@ -45,7 +48,7 @@ export abstract class Action {
|
|||
case 'alias':
|
||||
case 'description':
|
||||
case 'default-value':
|
||||
arr.push(new ActionSetProperty(value, key, () => { throw Error(`${key} missing in directive`) }))
|
||||
arr.push(new ActionSetProperty(value, key, () => { throw Error(`${key} missing in directive`); }));
|
||||
break;
|
||||
case 'replace':
|
||||
arr.push(new ActionReplace(value));
|
||||
|
@ -79,6 +82,7 @@ export class ActionHitCount extends Action {
|
|||
super();
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
public process(descriptor: CliCommonSchema.CodeModel.NodeDescriptor): void {
|
||||
ActionHitCount.hitCount++;
|
||||
}
|
||||
|
@ -91,8 +95,8 @@ export class ActionJson extends Action {
|
|||
}
|
||||
|
||||
public process(descriptor: CliCommonSchema.CodeModel.NodeDescriptor): void {
|
||||
let node = descriptor.target;
|
||||
NodeHelper.setJson(node, this.directiveValue === true, true /*modify flatten*/)
|
||||
const node = descriptor.target;
|
||||
NodeHelper.setJson(node, this.directiveValue === true, true /*modify flatten*/);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -103,19 +107,20 @@ export class ActionFlatten extends Action {
|
|||
}
|
||||
|
||||
public process(descriptor: CliCommonSchema.CodeModel.NodeDescriptor): void {
|
||||
let node = descriptor.target;
|
||||
NodeExtensionHelper.setFlatten(node, this.directiveValue === true, true /*overwrite*/)
|
||||
const node = descriptor.target;
|
||||
NodeExtensionHelper.setFlatten(node, this.directiveValue === true, true /*overwrite*/);
|
||||
}
|
||||
}
|
||||
|
||||
export class ActionSetProperty extends Action {
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
constructor(private directiveValue: CliCommonSchema.CliDirective.ValueClause, private propertyName: string, private getDefault: () => any) {
|
||||
super();
|
||||
}
|
||||
|
||||
public process(descriptor: CliCommonSchema.CodeModel.NodeDescriptor): void {
|
||||
let node = descriptor.target;
|
||||
const node = descriptor.target;
|
||||
NodeCliHelper.setCliProperty(node, this.propertyName, this.directiveValue ?? this.getDefault());
|
||||
}
|
||||
}
|
||||
|
@ -143,9 +148,9 @@ export class ActionSet extends Action {
|
|||
}
|
||||
|
||||
public process(descriptor: CliCommonSchema.CodeModel.NodeDescriptor): void {
|
||||
let node = descriptor.target;
|
||||
for (var key in this.directiveSet) {
|
||||
let value = this.directiveSet[key];
|
||||
const node = descriptor.target;
|
||||
for (const key in this.directiveSet) {
|
||||
const value = this.directiveSet[key];
|
||||
NodeCliHelper.setCliProperty(node, key, value);
|
||||
}
|
||||
}
|
||||
|
@ -158,7 +163,7 @@ export class ActionFormatTable extends Action {
|
|||
}
|
||||
|
||||
public process(descriptor: CliCommonSchema.CodeModel.NodeDescriptor): void {
|
||||
let node = descriptor.target;
|
||||
const node = descriptor.target;
|
||||
if (!isNullOrUndefined(this.directiveFormatTable.properties)) {
|
||||
NodeCliHelper.setCliProperty(node, CliConst.CLI_FORMATTABLE, {
|
||||
[CliConst.CLI_FORMATTABLE_PROPERTIES]: this.directiveFormatTable.properties
|
||||
|
@ -173,17 +178,17 @@ export class ActionReplace extends Action {
|
|||
}
|
||||
|
||||
public process(descriptor: CliCommonSchema.CodeModel.NodeDescriptor): void {
|
||||
let node = descriptor.target;
|
||||
Helper.validateNullOrUndefined(this.actionReplace.field, 'field');
|
||||
Helper.validateNullOrUndefined(this.actionReplace.old, 'old');
|
||||
Helper.validateNullOrUndefined(this.actionReplace.new, 'new');
|
||||
const node = descriptor.target;
|
||||
validateDirective(this.actionReplace.field, 'field');
|
||||
validateDirective(this.actionReplace.old, 'old');
|
||||
validateDirective(this.actionReplace.new, 'new');
|
||||
|
||||
var original: string = node.language.default[this.actionReplace.field].toString();
|
||||
const original: string = node.language.default[this.actionReplace.field].toString();
|
||||
if (isNullOrUndefined(this.actionReplace.isRegex) || this.actionReplace.isRegex == false) {
|
||||
NodeCliHelper.setCliProperty(node, this.actionReplace.field, original.replace(this.actionReplace.old, this.actionReplace.new));
|
||||
}
|
||||
else {
|
||||
var regex = new RegExp(this.actionReplace.old);
|
||||
const regex = new RegExp(this.actionReplace.old);
|
||||
NodeCliHelper.setCliProperty(node, this.actionReplace.field, original.replace(regex, this.actionReplace.new));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -11,7 +11,7 @@ export class NodeSelector {
|
|||
this.where = directive.where;
|
||||
this.selectType = directive.select;
|
||||
|
||||
let alias = {
|
||||
const alias = {
|
||||
parameter: ['param'],
|
||||
requestIndex: ['request-index'],
|
||||
operation: ['op'],
|
||||
|
@ -22,9 +22,9 @@ export class NodeSelector {
|
|||
choiceValue: ['value', 'choice-value'],
|
||||
};
|
||||
|
||||
for (let key in alias) {
|
||||
for (const key in alias) {
|
||||
alias[key].forEach(av => this.where[key] = this.where[key] ?? this.where[av]);
|
||||
};
|
||||
}
|
||||
|
||||
// TODO: support alias for 'select'? let's support it when needed considering in most case people dont need to specify it...
|
||||
|
||||
|
@ -51,11 +51,11 @@ export class NodeSelector {
|
|||
public match(descriptor: CliCommonSchema.CodeModel.NodeDescriptor): boolean {
|
||||
|
||||
// TODO: seperate different node type to get better performance when needed
|
||||
let match = (e, v) => isNullOrUndefined(e) || Helper.matchRegex(Helper.createRegex(e), v);
|
||||
const match = (e, v) => isNullOrUndefined(e) || Helper.matchRegex(Helper.createRegex(e), v);
|
||||
if (Helper.ToM4NodeType(descriptor.target) !== this.selectType)
|
||||
return false;
|
||||
|
||||
let r: boolean = false;
|
||||
let r = false;
|
||||
switch (this.selectType) {
|
||||
case CliConst.SelectType.operationGroup:
|
||||
case CliConst.SelectType.operation:
|
||||
|
@ -76,7 +76,7 @@ export class NodeSelector {
|
|||
match(this.where.property, descriptor.propertyCliKey);
|
||||
break;
|
||||
default:
|
||||
throw Error(`Unknown select type: ${this.selectType}`)
|
||||
throw Error(`Unknown select type: ${this.selectType}`);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
|
|
@ -8,7 +8,7 @@ import { Helper } from "../../helper";
|
|||
export class Modifier {
|
||||
private manager: CliDirectiveManager;
|
||||
|
||||
get codeModel() {
|
||||
get codeModel(): CodeModel {
|
||||
return this.session.model;
|
||||
}
|
||||
|
||||
|
@ -19,7 +19,7 @@ export class Modifier {
|
|||
if (isNullOrUndefined(directives))
|
||||
directives = [];
|
||||
if (!isNullOrUndefined(directives) && !Array.isArray(directives))
|
||||
throw Error("directive is expected to be an array. Please check '-' is set property in yaml")
|
||||
throw Error("directive is expected to be an array. Please check '-' is set property in yaml");
|
||||
|
||||
this.manager = new CliDirectiveManager();
|
||||
await this.manager.LoadDirective(directives);
|
||||
|
@ -34,7 +34,7 @@ export class Modifier {
|
|||
|
||||
}
|
||||
|
||||
export async function processRequest(host: Host) {
|
||||
export async function processRequest(host: Host): Promise<void> {
|
||||
const session = await Helper.init(host);
|
||||
|
||||
Helper.dumper.dumpCodeModel("modifier-pre");
|
||||
|
|
|
@ -1,11 +1,10 @@
|
|||
import { CodeModel, codeModelSchema, Property, Language, Metadata, Operation, OperationGroup, Parameter, ComplexSchema, ObjectSchema, ChoiceSchema, ChoiceValue, SealedChoiceSchema } from '@azure-tools/codemodel';
|
||||
import { Session, Host, startSession, Channel } from '@azure-tools/autorest-extension-base';
|
||||
import { serialize, deserialize } from '@azure-tools/codegen';
|
||||
import { values, items, length, Dictionary, keys } from '@azure-tools/linq';
|
||||
import { CodeModel, Language, Metadata, Operation, Parameter } from '@azure-tools/codemodel';
|
||||
import { Session, Host, Channel } from '@azure-tools/autorest-extension-base';
|
||||
import { values } from '@azure-tools/linq';
|
||||
import { isNullOrUndefined } from 'util';
|
||||
import { CliCommonSchema, CliConst, LanguageType, M4Node } from '../schema';
|
||||
import { CliCommonSchema } from '../schema';
|
||||
import { Helper } from '../helper';
|
||||
import { NodeHelper, NodeExtensionHelper, NodeCliHelper } from '../nodeHelper';
|
||||
import { NodeExtensionHelper, NodeCliHelper } from '../nodeHelper';
|
||||
import { FlattenHelper } from '../flattenHelper';
|
||||
|
||||
export class CommonNamer {
|
||||
|
@ -18,7 +17,7 @@ export class CommonNamer {
|
|||
this.codeModel = session.model;
|
||||
}
|
||||
|
||||
public async init() {
|
||||
public async init(): Promise<CommonNamer> {
|
||||
// any configuration if necessary
|
||||
this.cliNamingSettings = Helper.normalizeNamingSettings(await this.session.getValue("cli.naming.cli", {}));
|
||||
this.defaultNamingSettings = Helper.normalizeNamingSettings(await this.session.getValue("cli.naming.default", {}));
|
||||
|
@ -26,7 +25,7 @@ export class CommonNamer {
|
|||
return this;
|
||||
}
|
||||
|
||||
public process() {
|
||||
public process(): CodeModel {
|
||||
this.flag = new Set<Metadata>();
|
||||
this.applyNamingConvention(this.codeModel);
|
||||
this.processGlobalParam();
|
||||
|
@ -37,54 +36,54 @@ export class CommonNamer {
|
|||
return this.codeModel;
|
||||
}
|
||||
|
||||
private processSchemas() {
|
||||
let schemas = this.codeModel.schemas;
|
||||
private processSchemas(): void {
|
||||
const schemas = this.codeModel.schemas;
|
||||
|
||||
for (let obj of values(schemas.objects)) {
|
||||
for (const obj of values(schemas.objects)) {
|
||||
this.applyNamingConvention(obj);
|
||||
for (let property of values(obj.properties)) {
|
||||
for (const property of values(obj.properties)) {
|
||||
this.applyNamingConvention(property);
|
||||
}
|
||||
}
|
||||
|
||||
for (let dict of values(schemas.dictionaries)) {
|
||||
for (const dict of values(schemas.dictionaries)) {
|
||||
this.applyNamingConvention(dict);
|
||||
this.applyNamingConvention(dict.elementType);
|
||||
}
|
||||
|
||||
for (let enumn of values(schemas.choices)) {
|
||||
for (const enumn of values(schemas.choices)) {
|
||||
this.applyNamingConvention(enumn);
|
||||
for (let item of values(enumn.choices)) {
|
||||
for (const item of values(enumn.choices)) {
|
||||
this.applyNamingConvention(item);
|
||||
}
|
||||
}
|
||||
|
||||
for (let enumn of values(schemas.sealedChoices)) {
|
||||
for (const enumn of values(schemas.sealedChoices)) {
|
||||
this.applyNamingConvention(enumn);
|
||||
for (let item of values(enumn.choices)) {
|
||||
for (const item of values(enumn.choices)) {
|
||||
this.applyNamingConvention(item);
|
||||
}
|
||||
}
|
||||
|
||||
for (let arr of values(schemas.arrays)) {
|
||||
for (const arr of values(schemas.arrays)) {
|
||||
this.applyNamingConvention(arr);
|
||||
this.applyNamingConvention(arr.elementType);
|
||||
}
|
||||
|
||||
for (let cons of values(schemas.constants)) {
|
||||
for (const cons of values(schemas.constants)) {
|
||||
this.applyNamingConvention(cons);
|
||||
}
|
||||
|
||||
for (let num of values(schemas.numbers)) {
|
||||
for (const num of values(schemas.numbers)) {
|
||||
this.applyNamingConvention(num);
|
||||
}
|
||||
|
||||
for (let str of values(schemas.strings)) {
|
||||
for (const str of values(schemas.strings)) {
|
||||
this.applyNamingConvention(str);
|
||||
}
|
||||
}
|
||||
|
||||
private processOperationGroups() {
|
||||
private processOperationGroups(): void {
|
||||
for (const operationGroup of values(this.codeModel.operationGroups)) {
|
||||
this.applyNamingConvention(operationGroup);
|
||||
|
||||
|
@ -107,13 +106,13 @@ export class CommonNamer {
|
|||
}
|
||||
}
|
||||
|
||||
private processGlobalParam() {
|
||||
for (let para of values(this.codeModel.globalParameters)) {
|
||||
private processGlobalParam(): void {
|
||||
for (const para of values(this.codeModel.globalParameters)) {
|
||||
this.applyNamingConvention(para);
|
||||
}
|
||||
}
|
||||
|
||||
private processCliOperation() {
|
||||
private processCliOperation(): void {
|
||||
|
||||
// To be backward compatiable, reassign poly operations and parameters' default name and cli name
|
||||
for (const operationGroup of values(this.codeModel.operationGroups)) {
|
||||
|
@ -136,7 +135,7 @@ export class CommonNamer {
|
|||
}
|
||||
}
|
||||
|
||||
private applyNamingConventionOnCliOperation(operation: Operation, cliOperation: Operation) {
|
||||
private applyNamingConventionOnCliOperation(operation: Operation, cliOperation: Operation): void {
|
||||
if (cliOperation == null || cliOperation.language == null) {
|
||||
this.session.message({ Channel: Channel.Warning, Text: "working in obj has problems" });
|
||||
return;
|
||||
|
@ -151,7 +150,7 @@ export class CommonNamer {
|
|||
cliOperation.language['cli']['name'] = Helper.createPolyOperationCliName(operation, discriminatorValue);
|
||||
}
|
||||
|
||||
private applyNamingConventionOnCliParameter(cliParameter: Parameter) {
|
||||
private applyNamingConventionOnCliParameter(cliParameter: Parameter): void {
|
||||
if (cliParameter == null || cliParameter.language == null) {
|
||||
this.session.message({ Channel: Channel.Warning, Text: "working in obj has problems" });
|
||||
return;
|
||||
|
@ -175,7 +174,8 @@ export class CommonNamer {
|
|||
cliParameter.language['cli']['name'] = FlattenHelper.createFlattenedParameterCliName(prop, prefix);
|
||||
}
|
||||
|
||||
private applyNamingConvention(obj: any) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
private applyNamingConvention(obj: any): void {
|
||||
if (obj == null || obj.language == null) {
|
||||
this.session.message({ Channel: Channel.Warning, Text: "working in obj has problems" });
|
||||
return;
|
||||
|
@ -190,9 +190,9 @@ export class CommonNamer {
|
|||
obj.language['cli']['description'] = obj.language.default.description;
|
||||
|
||||
if (!isNullOrUndefined(obj['discriminatorValue'])) {
|
||||
let dv: string = obj['discriminatorValue'];
|
||||
const dv: string = obj['discriminatorValue'];
|
||||
// dv should be in pascal format, let's do a simple convert to snake
|
||||
let newValue = dv.replace(/([A-Z][a-z0-9]+)|([A-Z]+(?=[A-Z][a-z0-9]+))|([A-Z]+$)/g, '_$1$2$3').substr(1).toLowerCase();
|
||||
const newValue = dv.replace(/([A-Z][a-z0-9]+)|([A-Z]+(?=[A-Z][a-z0-9]+))|([A-Z]+$)/g, '_$1$2$3').substr(1).toLowerCase();
|
||||
NodeCliHelper.setCliDiscriminatorValue(obj, newValue);
|
||||
}
|
||||
|
||||
|
@ -210,7 +210,7 @@ export class CommonNamer {
|
|||
}
|
||||
}
|
||||
|
||||
export async function processRequest(host: Host) {
|
||||
export async function processRequest(host: Host): Promise<void> {
|
||||
const session = await Helper.init(host);
|
||||
Helper.dumper.dumpCodeModel("namer-pre");
|
||||
|
||||
|
|
|
@ -1,24 +1,20 @@
|
|||
import { Host, Session, startSession } from "@azure-tools/autorest-extension-base";
|
||||
import { CodeModel, Request, codeModelSchema, Metadata, ObjectSchema, isObjectSchema, Property, Extensions, Scheme, ComplexSchema, Operation, OperationGroup, Parameter, VirtualParameter, ImplementationLocation } from "@azure-tools/codemodel";
|
||||
import { isNullOrUndefined, isArray } from "util";
|
||||
import { Host, Session } from "@azure-tools/autorest-extension-base";
|
||||
import { CodeModel, ObjectSchema, Operation, Parameter } from "@azure-tools/codemodel";
|
||||
import { isNullOrUndefined } from "util";
|
||||
import { Helper } from "../helper";
|
||||
import { CliConst, M4Node, CliCommonSchema } from "../schema";
|
||||
import { Dumper } from "../dumper";
|
||||
import { Dictionary, values } from '@azure-tools/linq';
|
||||
import { CliCommonSchema } from "../schema";
|
||||
import { NodeHelper, NodeCliHelper, NodeExtensionHelper } from "../nodeHelper";
|
||||
import { FlattenHelper } from "../flattenHelper";
|
||||
|
||||
|
||||
export class PolyAsParamModifier {
|
||||
|
||||
constructor(protected session: Session<CodeModel>) {
|
||||
}
|
||||
|
||||
public process() {
|
||||
public process(): void {
|
||||
this.processPolyAsParam();
|
||||
}
|
||||
|
||||
private buildSubclassParamName(baseParam: Parameter, subClassName: string) {
|
||||
private buildSubclassParamName(baseParam: Parameter, subClassName: string): string {
|
||||
return `${baseParam.language.default.name}_${subClassName}`;
|
||||
}
|
||||
|
||||
|
@ -30,7 +26,7 @@ export class PolyAsParamModifier {
|
|||
return JSON.parse(JSON.stringify(obj)) as T;
|
||||
}
|
||||
|
||||
private cloneParamForSubclass(p: Parameter, newParamName: string, newSchema: ObjectSchema) {
|
||||
private cloneParamForSubclass(p: Parameter, newParamName: string, newSchema: ObjectSchema): Parameter {
|
||||
|
||||
const newParam = new Parameter(newParamName, p.language.default.description, newSchema, {
|
||||
implementation: p.implementation,
|
||||
|
@ -41,39 +37,39 @@ export class PolyAsParamModifier {
|
|||
|
||||
newParam.language.default.name = newParamName;
|
||||
|
||||
for (let key in p)
|
||||
for (const key in p)
|
||||
if (isNullOrUndefined(newParam[key]))
|
||||
newParam[key] = p[key];
|
||||
|
||||
NodeExtensionHelper.setPolyAsParamBaseSchema(newParam, p.schema);
|
||||
return newParam
|
||||
return newParam;
|
||||
}
|
||||
|
||||
public processPolyAsParam() {
|
||||
public processPolyAsParam(): void {
|
||||
|
||||
let getDefaultRequest = (op: Operation) => op.requests[0];
|
||||
const getDefaultRequest = (op: Operation) => op.requests[0];
|
||||
|
||||
this.session.model.operationGroups.forEach(g => {
|
||||
if (g.operations.findIndex(op => op.requests.length > 1) >= 0)
|
||||
throw Error("Multiple requests in one operation found! not supported yet");
|
||||
|
||||
// we need to modify the operations array, so get a copy of it first
|
||||
let operations = g.operations.filter(op => op.requests?.length == 1);
|
||||
const operations = g.operations.filter(op => op.requests?.length == 1);
|
||||
|
||||
operations.forEach(op => {
|
||||
|
||||
let request = getDefaultRequest(op);
|
||||
const request = getDefaultRequest(op);
|
||||
if (isNullOrUndefined(request.parameters))
|
||||
return;
|
||||
let allPolyParam: Parameter[] = request.parameters.filter(p =>
|
||||
const allPolyParam: Parameter[] = request.parameters.filter(p =>
|
||||
p.schema instanceof ObjectSchema &&
|
||||
(p.schema as ObjectSchema).discriminator);
|
||||
if (allPolyParam.length == 0)
|
||||
return;
|
||||
|
||||
for (let polyParam of allPolyParam) {
|
||||
for (const polyParam of allPolyParam) {
|
||||
if (NodeCliHelper.getComplexity(polyParam.schema) !== CliCommonSchema.CodeModel.Complexity.object_simple) {
|
||||
Helper.logWarning(`Skip on complex poly param: ${NodeCliHelper.getCliKey(polyParam, '<clikey-missing>')}(${NodeCliHelper.getCliKey(polyParam, '<clikey-missing>')})`)
|
||||
Helper.logWarning(`Skip on complex poly param: ${NodeCliHelper.getCliKey(polyParam, '<clikey-missing>')}(${NodeCliHelper.getCliKey(polyParam, '<clikey-missing>')})`);
|
||||
continue;
|
||||
}
|
||||
|
||||
|
@ -82,11 +78,11 @@ export class PolyAsParamModifier {
|
|||
continue;
|
||||
}
|
||||
|
||||
let baseSchema = polyParam.schema as ObjectSchema;
|
||||
let allSubClass = baseSchema.discriminator.all;
|
||||
const baseSchema = polyParam.schema as ObjectSchema;
|
||||
const allSubClass = baseSchema.discriminator.all;
|
||||
|
||||
for (let key in allSubClass) {
|
||||
let subClass = allSubClass[key];
|
||||
for (const key in allSubClass) {
|
||||
const subClass = allSubClass[key];
|
||||
if (!(subClass instanceof ObjectSchema)) {
|
||||
Helper.logWarning("subclass is not ObjectSchema: " + subClass.language.default.name);
|
||||
continue;
|
||||
|
@ -96,7 +92,7 @@ export class PolyAsParamModifier {
|
|||
continue;
|
||||
}
|
||||
|
||||
let param2: Parameter = this.cloneParamForSubclass(polyParam, this.buildSubclassParamName(polyParam, key), subClass);
|
||||
const param2: Parameter = this.cloneParamForSubclass(polyParam, this.buildSubclassParamName(polyParam, key), subClass);
|
||||
NodeExtensionHelper.setPolyAsParamOriginalParam(param2, polyParam);
|
||||
request.addParameter(param2);
|
||||
}
|
||||
|
@ -108,14 +104,14 @@ export class PolyAsParamModifier {
|
|||
}
|
||||
}
|
||||
|
||||
export async function processRequest(host: Host) {
|
||||
export async function processRequest(host: Host): Promise<void> {
|
||||
|
||||
const session = await Helper.init(host);
|
||||
|
||||
Helper.dumper.dumpCodeModel('poly-as-param-pre');
|
||||
|
||||
if ((await session.getValue('cli.polymorphism.expand-as-param', false)) === true) {
|
||||
let rd = new PolyAsParamModifier(session);
|
||||
const rd = new PolyAsParamModifier(session);
|
||||
rd.process();
|
||||
}
|
||||
|
||||
|
|
|
@ -3,11 +3,9 @@ import { CodeModel, Request, ObjectSchema, Operation, OperationGroup, Parameter
|
|||
import { isNullOrUndefined } from "util";
|
||||
import { Helper } from "../helper";
|
||||
import { NodeHelper, NodeCliHelper, NodeExtensionHelper } from "../nodeHelper";
|
||||
import { FlattenHelper } from "../flattenHelper";
|
||||
import { CopyHelper } from "../copyHelper";
|
||||
import { CliConst, CliCommonSchema } from "../schema";
|
||||
import { Modifier } from "./modifier/modifier";
|
||||
import { CommonNamer } from "./namer";
|
||||
|
||||
|
||||
export class PolyAsResourceModifier {
|
||||
|
@ -15,16 +13,16 @@ export class PolyAsResourceModifier {
|
|||
constructor(protected session: Session<CodeModel>) {
|
||||
}
|
||||
|
||||
public async process() {
|
||||
public async process(): Promise<void> {
|
||||
await this.modifier();
|
||||
|
||||
this.processPolyAsResource();
|
||||
}
|
||||
|
||||
private async modifier() {
|
||||
private async modifier(): Promise<void> {
|
||||
const directives = (await this.session.getValue(CliConst.CLI_DIRECTIVE_KEY, []))
|
||||
.filter((dir) => dir[NodeCliHelper.POLY_RESOURCE])
|
||||
.map((dir) => this.copyDirectiveOnlyForPolyResource(dir));
|
||||
.filter((dir) => dir[NodeCliHelper.POLY_RESOURCE])
|
||||
.map((dir) => this.copyDirectiveOnlyForPolyResource(dir));
|
||||
if (directives && directives.length > 0) {
|
||||
Helper.dumper.dumpCodeModel('poly-as-resource-modifier-pre');
|
||||
const modifier = await new Modifier(this.session).init(directives);
|
||||
|
@ -41,7 +39,7 @@ export class PolyAsResourceModifier {
|
|||
}
|
||||
}
|
||||
|
||||
private modifierForExtendPolyResource() {
|
||||
private modifierForExtendPolyResource(): void {
|
||||
this.session.model.operationGroups.forEach((group) => {
|
||||
group.operations.forEach((operation) => {
|
||||
const request = this.getDefaultRequest(operation);
|
||||
|
@ -64,29 +62,29 @@ export class PolyAsResourceModifier {
|
|||
if (polyParams.has(NodeCliHelper.getCliKey(p, null))) {
|
||||
NodeCliHelper.setPolyAsResource(p, true);
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private copyDirectiveOnlyForPolyResource(src: CliCommonSchema.CliDirective.Directive): CliCommonSchema.CliDirective.Directive {
|
||||
const copy: CliCommonSchema.CliDirective.Directive = {
|
||||
select: src.select,
|
||||
where: CopyHelper.deepCopy(src.where),
|
||||
}
|
||||
};
|
||||
copy[NodeCliHelper.POLY_RESOURCE] = src[NodeCliHelper.POLY_RESOURCE];
|
||||
return copy;
|
||||
}
|
||||
|
||||
private processPolyAsResource() {
|
||||
private processPolyAsResource(): void {
|
||||
|
||||
this.session.model.operationGroups.forEach(g => {
|
||||
if (g.operations.findIndex(op => op.requests.length > 1) >= 0)
|
||||
throw Error("Multiple requests in one operation found! not supported yet");
|
||||
|
||||
// we need to modify the operations array, so get a copy of it first
|
||||
let operations = g.operations.filter(op => op.requests?.length == 1);
|
||||
const operations = g.operations.filter(op => op.requests?.length == 1);
|
||||
|
||||
operations.forEach(op => {
|
||||
|
||||
|
@ -104,11 +102,11 @@ export class PolyAsResourceModifier {
|
|||
const polyParam = allPolyParam[0];
|
||||
const baseSchema = polyParam.schema as ObjectSchema;
|
||||
|
||||
for (let subClass of NodeHelper.getSubClasses(baseSchema, true)) {
|
||||
for (const subClass of NodeHelper.getSubClasses(baseSchema, true)) {
|
||||
|
||||
let discriminatorValue = NodeCliHelper.getCliDiscriminatorValue(subClass);
|
||||
const discriminatorValue = NodeCliHelper.getCliDiscriminatorValue(subClass);
|
||||
|
||||
let op2: Operation = this.cloneOperationForSubclass(op, baseSchema, subClass);
|
||||
const op2: Operation = this.cloneOperationForSubclass(op, baseSchema, subClass);
|
||||
|
||||
Helper.logDebug(`${g.language.default.name}/${op.language.default.name} cloned for subclass ${discriminatorValue}`);
|
||||
NodeExtensionHelper.addCliOperation(op, op2);
|
||||
|
@ -123,7 +121,7 @@ export class PolyAsResourceModifier {
|
|||
return group.operations.filter((op) => {
|
||||
const originalOp = NodeExtensionHelper.getSplitOperationOriginalOperation(op);
|
||||
return originalOp && NodeCliHelper.getCliKey(operation, null) === NodeCliHelper.getCliKey(originalOp, '');
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
private findPolyParameters(request: Request): Parameter[] {
|
||||
|
@ -138,12 +136,12 @@ export class PolyAsResourceModifier {
|
|||
return operation.requests?.[0];
|
||||
}
|
||||
|
||||
private cloneOperationForSubclass(op: Operation, baseSchema: ObjectSchema, subSchema: ObjectSchema) {
|
||||
private cloneOperationForSubclass(op: Operation, baseSchema: ObjectSchema, subSchema: ObjectSchema): Operation {
|
||||
|
||||
let polyParam: Parameter = null;
|
||||
const discriminatorValue = NodeCliHelper.getCliDiscriminatorValue(subSchema);
|
||||
const newDefaultName = Helper.createPolyOperationDefaultName(op, discriminatorValue);
|
||||
const newCliKey = Helper.createPolyOperationCliKey(op, discriminatorValue)
|
||||
const newCliKey = Helper.createPolyOperationCliKey(op, discriminatorValue);
|
||||
|
||||
const cloneParam = (p: Parameter): Parameter => {
|
||||
const vp = CopyHelper.copyParameter(p, p.schema === baseSchema ? subSchema : p.schema);
|
||||
|
@ -170,14 +168,14 @@ export class PolyAsResourceModifier {
|
|||
}
|
||||
}
|
||||
|
||||
export async function processRequest(host: Host) {
|
||||
export async function processRequest(host: Host): Promise<void> {
|
||||
|
||||
const session = await Helper.init(host);
|
||||
|
||||
Helper.dumper.dumpCodeModel('poly-as-resource-pre');
|
||||
|
||||
if ((await session.getValue('cli.polymorphism.expand-as-resource', false)) === true) {
|
||||
let rd = new PolyAsResourceModifier(session);
|
||||
const rd = new PolyAsResourceModifier(session);
|
||||
await rd.process();
|
||||
}
|
||||
else {
|
||||
|
|
|
@ -1,17 +1,15 @@
|
|||
import { Host, Session, startSession } from "@azure-tools/autorest-extension-base";
|
||||
import { serialize } from "@azure-tools/codegen";
|
||||
import { CodeModel, codeModelSchema, Metadata, ObjectSchema, isObjectSchema, Property, Extensions, Scheme } from "@azure-tools/codemodel";
|
||||
import { isNullOrUndefined, isArray } from "util";
|
||||
import { Host, Session } from "@azure-tools/autorest-extension-base";
|
||||
import { CodeModel } from "@azure-tools/codemodel";
|
||||
import { isNullOrUndefined } from "util";
|
||||
import { Helper } from "../helper";
|
||||
import { CliConst, M4Node } from "../schema";
|
||||
import { NodeHelper, NodeCliHelper } from "../nodeHelper";
|
||||
import { NodeCliHelper } from "../nodeHelper";
|
||||
|
||||
export class PreNamer{
|
||||
|
||||
constructor(protected session: Session<CodeModel>){
|
||||
constructor(protected session: Session<CodeModel>) {
|
||||
}
|
||||
|
||||
public process() {
|
||||
public process(): void {
|
||||
Helper.enumerateCodeModel(this.session.model, (n) => {
|
||||
if (!isNullOrUndefined(n.target.language.default.name))
|
||||
NodeCliHelper.setCliKey(n.target, n.target.language.default.name);
|
||||
|
@ -19,12 +17,12 @@ export class PreNamer{
|
|||
}
|
||||
}
|
||||
|
||||
export async function processRequest(host: Host) {
|
||||
export async function processRequest(host: Host): Promise<void> {
|
||||
|
||||
const session = await Helper.init(host);
|
||||
Helper.dumper.dumpCodeModel("prename-pre");
|
||||
|
||||
let pn = new PreNamer(session);
|
||||
const pn = new PreNamer(session);
|
||||
pn.process();
|
||||
|
||||
Helper.dumper.dumpCodeModel("prename-post");
|
||||
|
|
|
@ -1,18 +1,17 @@
|
|||
import { Host, Session } from "@azure-tools/autorest-extension-base";
|
||||
import { CodeModel, Request, Operation, Parameter } from "@azure-tools/codemodel";
|
||||
import { isNullOrUndefined } from "util";
|
||||
import { CodeModel, Operation } from "@azure-tools/codemodel";
|
||||
import { Helper } from "../helper";
|
||||
import { CliConst, CliCommonSchema } from "../schema";
|
||||
import { NodeHelper, NodeCliHelper, NodeExtensionHelper } from "../nodeHelper";
|
||||
import { NodeCliHelper, NodeExtensionHelper } from "../nodeHelper";
|
||||
import { Modifier } from "./modifier/modifier";
|
||||
import { CopyHelper } from "../copyHelper";
|
||||
|
||||
export class SplitOperation{
|
||||
|
||||
constructor(protected session: Session<CodeModel>){
|
||||
constructor(protected session: Session<CodeModel>) {
|
||||
}
|
||||
|
||||
public async process() {
|
||||
public async process(): Promise<void> {
|
||||
|
||||
await this.modifier();
|
||||
|
||||
|
@ -43,7 +42,7 @@ export class SplitOperation{
|
|||
}
|
||||
}
|
||||
|
||||
private async modifier() {
|
||||
private async modifier(): Promise<void> {
|
||||
const directives = (await this.session.getValue(CliConst.CLI_DIRECTIVE_KEY, []))
|
||||
.filter((dir) => dir[NodeCliHelper.SPLIT_OPERATION_NAMES])
|
||||
.map((dir) => this.copyDirective(dir,NodeCliHelper.SPLIT_OPERATION_NAMES));
|
||||
|
@ -83,13 +82,13 @@ export class SplitOperation{
|
|||
const copy: CliCommonSchema.CliDirective.Directive = {
|
||||
select: src.select,
|
||||
where: CopyHelper.deepCopy(src.where),
|
||||
}
|
||||
};
|
||||
copy[prop] = src[prop];
|
||||
return copy;
|
||||
}
|
||||
}
|
||||
|
||||
export async function processRequest(host: Host) {
|
||||
export async function processRequest(host: Host): Promise<void> {
|
||||
|
||||
const session = await Helper.init(host);
|
||||
Helper.dumper.dumpCodeModel("split-operation-pre");
|
||||
|
|
|
@ -1,12 +1,8 @@
|
|||
import { Host, Session, startSession } from "@azure-tools/autorest-extension-base";
|
||||
import { CodeModel, Request, codeModelSchema, Metadata, ObjectSchema, isObjectSchema, Property, Extensions, Scheme, ComplexSchema, Operation, OperationGroup, Parameter, VirtualParameter, ImplementationLocation, ArraySchema, DictionarySchema, ConstantSchema, getAllProperties } from "@azure-tools/codemodel";
|
||||
import { isNullOrUndefined, isArray, isNull } from "util";
|
||||
import { Host, Session } from "@azure-tools/autorest-extension-base";
|
||||
import { CodeModel, ObjectSchema, isObjectSchema, Parameter, ArraySchema, DictionarySchema, ConstantSchema } from "@azure-tools/codemodel";
|
||||
import { Helper } from "../helper";
|
||||
import { CliConst, M4Node, CliCommonSchema } from "../schema";
|
||||
import { Dumper } from "../dumper";
|
||||
import { Dictionary, values } from '@azure-tools/linq';
|
||||
import { CliCommonSchema } from "../schema";
|
||||
import { NodeHelper, NodeCliHelper } from "../nodeHelper";
|
||||
import { FlattenHelper } from "../flattenHelper";
|
||||
|
||||
class VisibilityCleaner {
|
||||
|
||||
|
@ -15,7 +11,7 @@ class VisibilityCleaner {
|
|||
|
||||
private calcObject(schema: ObjectSchema): CliCommonSchema.CodeModel.Visibility {
|
||||
|
||||
let visibleProperty = NodeCliHelper.getIsVisibleFlag(schema);
|
||||
const visibleProperty = NodeCliHelper.getIsVisibleFlag(schema);
|
||||
if (visibleProperty) {
|
||||
if (visibleProperty === CliCommonSchema.CodeModel.Visibility.unknown) {
|
||||
// a circle found, lets go around it again to calculate the correct visibility
|
||||
|
@ -33,7 +29,7 @@ class VisibilityCleaner {
|
|||
let visible = CliCommonSchema.CodeModel.Visibility.false;
|
||||
|
||||
if (schema.properties && schema.properties.length > 0) {
|
||||
for (let prop of schema.properties) {
|
||||
for (const prop of schema.properties) {
|
||||
if (!NodeHelper.checkVisibility(prop))
|
||||
continue;
|
||||
if (isObjectSchema(prop.schema)) {
|
||||
|
@ -55,7 +51,7 @@ class VisibilityCleaner {
|
|||
|
||||
if (visible === CliCommonSchema.CodeModel.Visibility.false) {
|
||||
if (NodeHelper.HasSubClass(schema)) {
|
||||
for (let subClass of NodeHelper.getSubClasses(schema, true)) {
|
||||
for (const subClass of NodeHelper.getSubClasses(schema, true)) {
|
||||
if (this.calcObject(subClass) === CliCommonSchema.CodeModel.Visibility.true) {
|
||||
visible = CliCommonSchema.CodeModel.Visibility.true;
|
||||
break;
|
||||
|
@ -68,7 +64,7 @@ class VisibilityCleaner {
|
|||
return visible;
|
||||
}
|
||||
|
||||
public process() {
|
||||
public process(): void {
|
||||
|
||||
this.session.model.schemas.objects.forEach(obj => {
|
||||
this.calcObject(obj);
|
||||
|
@ -86,16 +82,16 @@ class VisibilityCleaner {
|
|||
}
|
||||
}
|
||||
|
||||
export async function processRequest(host: Host) {
|
||||
export async function processRequest(host: Host): Promise<void> {
|
||||
|
||||
const session = await Helper.init(host);
|
||||
|
||||
let flag = await session.getValue('cli.auto-parameter-hidden', false);
|
||||
const flag = await session.getValue('cli.auto-parameter-hidden', false);
|
||||
if (flag === true) {
|
||||
|
||||
Helper.dumper.dumpCodeModel('visibility-cleaner-pre');
|
||||
|
||||
let cm = new VisibilityCleaner(session);
|
||||
const cm = new VisibilityCleaner(session);
|
||||
cm.process();
|
||||
|
||||
Helper.dumper.dumpCodeModel('visibility-cleaner-post');
|
||||
|
|
|
@ -6,30 +6,31 @@ export type M4NodeType = 'operationGroup' | 'operation' | 'parameter' | 'objectS
|
|||
export type LanguageType = 'cli' | 'default';
|
||||
export type M4Node = Metadata | ChoiceValue;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-namespace
|
||||
export namespace CliConst {
|
||||
// Todo: merge this into code model?
|
||||
export const CLI_FORMATTABLE: string = "formatTable";
|
||||
export const CLI_FORMATTABLE_PROPERTIES: string = "properties";
|
||||
export const CLI_DIRECTIVE: string = "cli-directive";
|
||||
export const CLI_DIRECTIVE_KEY: string = 'cli.cli-directive';
|
||||
export const CLI_FORMATTABLE = "formatTable";
|
||||
export const CLI_FORMATTABLE_PROPERTIES = "properties";
|
||||
export const CLI_DIRECTIVE = "cli-directive";
|
||||
export const CLI_DIRECTIVE_KEY = 'cli.cli-directive';
|
||||
|
||||
export const CLI_FLATTEN_DIRECTIVE_KEY: string = "cli.flatten.cli-flatten-directive";
|
||||
export const CLI_FLATTEN_SET_ENABLED_KEY: string = 'cli.flatten.cli-flatten-set-enabled';
|
||||
export const CLI_FLATTEN_SET_FLATTEN_ALL_KEY: string = 'cli.flatten.cli-flatten-all';
|
||||
export const CLI_FLATTEN_SET_FLATTEN_SCHEMA_KEY: string = 'cli.flatten.cli-flatten-schema';
|
||||
export const CLI_FLATTEN_SET_FLATTEN_PAYLOAD_KEY: string = 'cli.flatten.cli-flatten-payload';
|
||||
export const CLI_FLATTEN_SET_FLATTEN_PAYLOAD_MAX_PROP_KEY: string = 'cli.flatten.cli-flatten-payload-max-prop';
|
||||
export const CLI_FLATTEN_SET_FLATTEN_PAYLOAD_MAX_COMPLEXITY_KEY: string = 'cli.flatten.cli-flatten-payload-max-complexity';
|
||||
export const CLI_FLATTEN_SET_FLATTEN_PAYLOAD_MAX_LEVEL_KEY: string = 'cli.flatten.cli-flatten-payload-max-level';
|
||||
export const CLI_FLATTEN_SET_FLATTEN_PAYLOAD_MAX_ARRAY_OBJECT_PROP_KEY: string = 'cli.flatten.cli-flatten-payload-max-array-object-prop-count';
|
||||
export const CLI_FLATTEN_SET_FLATTEN_PAYLOAD_MAX_POLY_AS_RESOURCE_PROP_KEY: string = 'cli.flatten.cli-flatten-payload-max-poly-as-resource-prop-count';
|
||||
export const CLI_FLATTEN_SET_FLATTEN_PAYLOAD_MAX_POLY_AS_PARAM_PROP_KEY: string = 'cli.flatten.cli-flatten-payload-max-poly-as-param-prop-count';
|
||||
export const CLI_FLATTEN_SET_FLATTEN_ALL_OVERWRITE_SWAGGER_KEY: string = 'cli.flatten.cli-flatten-all-overwrite-swagger';
|
||||
export const CLI_FLATTEN_DIRECTIVE_KEY = "cli.flatten.cli-flatten-directive";
|
||||
export const CLI_FLATTEN_SET_ENABLED_KEY = 'cli.flatten.cli-flatten-set-enabled';
|
||||
export const CLI_FLATTEN_SET_FLATTEN_ALL_KEY = 'cli.flatten.cli-flatten-all';
|
||||
export const CLI_FLATTEN_SET_FLATTEN_SCHEMA_KEY = 'cli.flatten.cli-flatten-schema';
|
||||
export const CLI_FLATTEN_SET_FLATTEN_PAYLOAD_KEY = 'cli.flatten.cli-flatten-payload';
|
||||
export const CLI_FLATTEN_SET_FLATTEN_PAYLOAD_MAX_PROP_KEY = 'cli.flatten.cli-flatten-payload-max-prop';
|
||||
export const CLI_FLATTEN_SET_FLATTEN_PAYLOAD_MAX_COMPLEXITY_KEY = 'cli.flatten.cli-flatten-payload-max-complexity';
|
||||
export const CLI_FLATTEN_SET_FLATTEN_PAYLOAD_MAX_LEVEL_KEY = 'cli.flatten.cli-flatten-payload-max-level';
|
||||
export const CLI_FLATTEN_SET_FLATTEN_PAYLOAD_MAX_ARRAY_OBJECT_PROP_KEY = 'cli.flatten.cli-flatten-payload-max-array-object-prop-count';
|
||||
export const CLI_FLATTEN_SET_FLATTEN_PAYLOAD_MAX_POLY_AS_RESOURCE_PROP_KEY = 'cli.flatten.cli-flatten-payload-max-poly-as-resource-prop-count';
|
||||
export const CLI_FLATTEN_SET_FLATTEN_PAYLOAD_MAX_POLY_AS_PARAM_PROP_KEY = 'cli.flatten.cli-flatten-payload-max-poly-as-param-prop-count';
|
||||
export const CLI_FLATTEN_SET_FLATTEN_ALL_OVERWRITE_SWAGGER_KEY = 'cli.flatten.cli-flatten-all-overwrite-swagger';
|
||||
|
||||
export const CLI_POLYMORPHISM_EXPAND_AS_RESOURCE_KEY: string = 'cli.polymorphism.expand-as-resource';
|
||||
export const CLI_POLYMORPHISM_EXPAND_AS_RESOURCE_KEY = 'cli.polymorphism.expand-as-resource';
|
||||
|
||||
export const CLI_SPLIT_OPERATION_ENABLED_KEY: string = 'cli.split-operation.cli-split-operation-enabled';
|
||||
export const CLI_SPLIT_OPERATION_EXTEND_POLY_RESOURCE_KEY: string = 'cli.split-operation.cli-split-operation-extend-poly-resource';
|
||||
export const CLI_SPLIT_OPERATION_ENABLED_KEY = 'cli.split-operation.cli-split-operation-enabled';
|
||||
export const CLI_SPLIT_OPERATION_EXTEND_POLY_RESOURCE_KEY = 'cli.split-operation.cli-split-operation-extend-poly-resource';
|
||||
|
||||
export const DEFAULT_OPERATION_PARAMETER_INDEX = -1;
|
||||
|
||||
|
@ -46,7 +47,7 @@ export namespace CliConst {
|
|||
static readonly space = "space";
|
||||
/** UPPER_CASE */
|
||||
static readonly upper = "upper";
|
||||
};
|
||||
}
|
||||
|
||||
export class NamingType {
|
||||
static readonly parameter = 'parameter';
|
||||
|
@ -71,8 +72,10 @@ export namespace CliConst {
|
|||
}
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-namespace
|
||||
export namespace CliCommonSchema {
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-namespace
|
||||
export namespace CliDirective {
|
||||
|
||||
export interface LogClause {
|
||||
|
@ -81,9 +84,11 @@ export namespace CliCommonSchema {
|
|||
logLevel?: string;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-interface
|
||||
export interface SetClause {
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-interface
|
||||
export interface ValueClause {
|
||||
}
|
||||
|
||||
|
@ -140,6 +145,7 @@ export namespace CliCommonSchema {
|
|||
appliedTo?: string[]
|
||||
singularize?: NamingType[]
|
||||
glossary?: string[]
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
override?: any
|
||||
parameter?: NamingStyle
|
||||
operation?: NamingStyle
|
||||
|
@ -150,6 +156,7 @@ export namespace CliCommonSchema {
|
|||
choiceValue?: NamingStyle
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-namespace
|
||||
export namespace CodeModel {
|
||||
export enum NodeTypeFlag {
|
||||
operationGroup = 1,
|
||||
|
@ -201,6 +208,7 @@ export namespace CliCommonSchema {
|
|||
propertyCliKey?: string;
|
||||
choiceSchemaCliKey?: string;
|
||||
choiceValueCliKey?: string;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
parent: any;
|
||||
target: M4Node;
|
||||
/** set to -1 if the parent is not an array */
|
||||
|
|
Загрузка…
Ссылка в новой задаче