Skip to content

Commit

Permalink
format changes
Browse files Browse the repository at this point in the history
  • Loading branch information
RodgeFu committed Mar 12, 2024
1 parent f16ff49 commit a810530
Show file tree
Hide file tree
Showing 9 changed files with 75 additions and 74 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { getSession } from "../autorest-session";
import { generateArmResourceClientDecorator, generateEnumClientDecorator, generateObjectClientDecorator } from "../generate/generate-client";
import {
generateArmResourceClientDecorator,
generateEnumClientDecorator,
generateObjectClientDecorator,
} from "../generate/generate-client";
import { TypespecProgram } from "../interfaces";
import { getOptions } from "../options";
import { formatTypespecFile } from "../utils/format";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,7 @@ export function generateEnumClientDecorator(typespecEnum: TypespecEnum) {
definitions.push(generateAugmentedDecorators(typespecEnum.name, typespecEnum.clientDecorators));

for (const choice of typespecEnum.members) {
const decorators = generateAugmentedDecorators(
`${typespecEnum.name}.${choice.name}`,
choice.clientDecorators,
);
const decorators = generateAugmentedDecorators(`${typespecEnum.name}.${choice.name}`, choice.clientDecorators);
decorators && definitions.push(decorators);
}

Expand All @@ -42,7 +39,6 @@ export function generateOperationClientDecorator(operation: TypespecOperation) {
return definitions.join("\n");
}


export function generateArmResourceClientDecorator(resource: TspArmResource): string {
const definitions: string[] = [];

Expand All @@ -54,22 +50,18 @@ export function generateArmResourceClientDecorator(resource: TspArmResource): st
definitions.push(`@@clientName(${formalOperationGroupName}OperationGroup, "${formalOperationGroupName}")`);
}

if(resource.clientDecorators && resource.clientDecorators.length > 0)
if (resource.clientDecorators && resource.clientDecorators.length > 0)
definitions.push(generateAugmentedDecorators(resource.name, resource.clientDecorators));

for (const op of resource.resourceOperations) {
if(op.clientDecorators && op.clientDecorators.length > 0)
if (op.clientDecorators && op.clientDecorators.length > 0)
definitions.push(generateAugmentedDecorators(`${targetName}.${op.name}`, op.clientDecorators));
}

for (const property of resource.properties) {
const decorators = generateAugmentedDecorators(
`${targetName}.${property.name}`,
property.clientDecorators,
);
const decorators = generateAugmentedDecorators(`${targetName}.${property.name}`, property.clientDecorators);
decorators && definitions.push(decorators);
}


return definitions.join("\n");
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,21 @@
import { ChoiceSchema, CodeModel, ObjectSchema, SealedChoiceSchema, Schema, ChoiceValue, Property, Parameter, SchemaType, Operation } from "@autorest/codemodel";
import {
ChoiceSchema,
CodeModel,
ObjectSchema,
SealedChoiceSchema,
Schema,
ChoiceValue,
Property,
Parameter,
SchemaType,
Operation,
} from "@autorest/codemodel";
import { TypespecDecorator } from "../interfaces";
import { getOptions } from "../options";
import { getLogger } from "../utils/logger";
import { Metadata, getArmResourcesMetadata } from "../utils/resource-discovery";

type RenamableSchema = Schema | Property | Parameter | ChoiceValue | Operation
type RenamableSchema = Schema | Property | Parameter | ChoiceValue | Operation;

const logger = () => getLogger("rename-pretransform");

Expand All @@ -25,10 +36,7 @@ export function createCSharpNameDecorator(schema: RenamableSchema): TypespecDeco
name: "clientName",
module: "@azure-tools/typespec-client-generator-core",
namespace: "Azure.ClientGenerator.Core",
arguments: [
schema.language.csharp!.name,
"csharp"
]
arguments: [schema.language.csharp!.name, "csharp"],
};
}

Expand All @@ -40,99 +48,89 @@ function parseNewCSharpNameAndSetToSchema(schema: RenamableSchema, renameValue:
function setSchemaCSharpName(schema: RenamableSchema, newName: string) {
if (!schema.language.csharp)
schema.language.csharp = { name: newName, description: schema.language.default.description };
else
schema.language.csharp.name = newName;
else schema.language.csharp.name = newName;
}

function parseNewName(value: string) {
// TODO: format not supported
return value.split('|')[0].trim();
return value.split("|")[0].trim();
}

function applyOverrideOperationName(metadata: Metadata, codeModel: CodeModel) {
for (const opId in metadata.OverrideOperationName) {
const found = codeModel.operationGroups.flatMap(og => og.operations).find(op => op.operationId === opId);
if (found)
parseNewCSharpNameAndSetToSchema(found, metadata.OverrideOperationName[opId]);
const found = codeModel.operationGroups.flatMap((og) => og.operations).find((op) => op.operationId === opId);
if (found) parseNewCSharpNameAndSetToSchema(found, metadata.OverrideOperationName[opId]);
else
logger().warning(`Can't find operation to rename for OverrideOperationName rule: ${opId}->${metadata.OverrideOperationName[opId]}`)
logger().warning(
`Can't find operation to rename for OverrideOperationName rule: ${opId}->${metadata.OverrideOperationName[opId]}`,
);
}
}

function applyRenameMapping(metadata: Metadata, codeModel: CodeModel) {
for (const key in metadata.RenameMapping) {
const subKeys = key.split(".").map(s => s.trim()).filter(s => s.length > 0);
if (subKeys.length === 0)
continue;
const subKeys = key
.split(".")
.map((s) => s.trim())
.filter((s) => s.length > 0);
if (subKeys.length === 0) continue;
const lowerFirstSubKey = subKeys[0].toLowerCase();
const value = metadata.RenameMapping[key];

const found: Schema | undefined = [
...(codeModel.schemas.choices ?? []),
...(codeModel.schemas.sealedChoices ?? []),
...(codeModel.schemas.objects ?? [])]
.find((o: Schema) => o.language.default.name.toLowerCase() === lowerFirstSubKey);
...(codeModel.schemas.objects ?? []),
].find((o: Schema) => o.language.default.name.toLowerCase() === lowerFirstSubKey);

if (!found) {
logger().warning(`Can't find object or enum for RenameMapping rule: ${key} -> ${value}`)
logger().warning(`Can't find object or enum for RenameMapping rule: ${key} -> ${value}`);
continue;
}

if (found.type === SchemaType.Choice || found.type == SchemaType.SealedChoice) {
transformEnum(subKeys, value, found as ChoiceSchema | SealedChoiceSchema);
}
else if (found.type === SchemaType.Object) {
} else if (found.type === SchemaType.Object) {
transformObject(subKeys, value, found as ObjectSchema);
}
else {
logger().error(`Unexpected schema type '${found.type}' found with key ${key}`)
} else {
logger().error(`Unexpected schema type '${found.type}' found with key ${key}`);
}
}
}

function transformEnum(keys: string[], value: string, target: ChoiceSchema | SealedChoiceSchema) {
if (keys.length === 1)
parseNewCSharpNameAndSetToSchema(target, value);
if (keys.length === 1) parseNewCSharpNameAndSetToSchema(target, value);
else if (keys.length === 2) {
const lowerMemberValue = keys[1].toLowerCase();
const found = target.choices.find(c => c.language.default.name.toLowerCase() === lowerMemberValue);
if (found)
parseNewCSharpNameAndSetToSchema(found, value);
else
logger().warning(`Can't find enum member for RenameMapping rule: ${keys.join('.')} -> ${value}`);
}
else {
logger().error(`Unexpected keys for enum RenameMapping: ${keys.join('.')}`);
const found = target.choices.find((c) => c.language.default.name.toLowerCase() === lowerMemberValue);
if (found) parseNewCSharpNameAndSetToSchema(found, value);
else logger().warning(`Can't find enum member for RenameMapping rule: ${keys.join(".")} -> ${value}`);
} else {
logger().error(`Unexpected keys for enum RenameMapping: ${keys.join(".")}`);
}
}

function transformObject(keys: string[], value: string, target: ObjectSchema) {
if (keys.length === 1)
parseNewCSharpNameAndSetToSchema(target, value);
if (keys.length === 1) parseNewCSharpNameAndSetToSchema(target, value);
else if (keys.length === 2) {
const lowerPropertyName = keys[1].toLowerCase();
const found = target.properties?.find(p => p.language.default.name.toLowerCase() === lowerPropertyName);
if (found)
parseNewCSharpNameAndSetToSchema(found, value);
else
logger().warning(`Can't find object property for RenameMapping rule: ${keys.join('.')} -> ${value}`);
}
else if (keys.length > 2) {
const found = target.properties?.find((p) => p.language.default.name.toLowerCase() === lowerPropertyName);
if (found) parseNewCSharpNameAndSetToSchema(found, value);
else logger().warning(`Can't find object property for RenameMapping rule: ${keys.join(".")} -> ${value}`);
} else if (keys.length > 2) {
// handle flatten scenario
const lowerPropName = keys.pop()?.toLowerCase();
let cur = target;
for (let i = 1; i < keys.length && cur; i++) {
const foundProp = cur.properties?.find(p => p.language.default.name.toLowerCase() === keys[i].toLowerCase());
const foundProp = cur.properties?.find((p) => p.language.default.name.toLowerCase() === keys[i].toLowerCase());
cur = foundProp?.schema as ObjectSchema;
}
const foundProp = cur?.properties?.find(p => p.language.default.name.toLowerCase() === lowerPropName);
if (foundProp)
parseNewCSharpNameAndSetToSchema(foundProp, value);
const foundProp = cur?.properties?.find((p) => p.language.default.name.toLowerCase() === lowerPropName);
if (foundProp) parseNewCSharpNameAndSetToSchema(foundProp, value);
else {
logger().warning(`Can't find object property for RenameMapping rule: ${keys.join('.')} -> ${value}`);
logger().warning(`Can't find object property for RenameMapping rule: ${keys.join(".")} -> ${value}`);
}
}
else {
logger().error(`Unexpected keys for object property RenameMapping: ${keys.join('.')}`);
} else {
logger().error(`Unexpected keys for object property RenameMapping: ${keys.join(".")}`);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -880,7 +880,11 @@ function buildResourceDecorators(schema: ArmResourceSchema): TypespecDecorator[]
return resourceModelDecorators;
}

function buildResourceClientDecorators(schema: ArmResourceSchema, armResourceOperations:TspArmResourceOperation[], normalOperations:TypespecOperation[]): TypespecDecorator[] {
function buildResourceClientDecorators(
schema: ArmResourceSchema,
armResourceOperations: TspArmResourceOperation[],
normalOperations: TypespecOperation[],
): TypespecDecorator[] {
const clientDecorator: TypespecDecorator[] = [];
if (schema.language.csharp?.name) {
clientDecorator.push(createCSharpNameDecorator(schema));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,12 @@ import { get } from "lodash";
import { getDataTypes } from "../data-types";
import { TypespecObject, TypespecObjectProperty } from "../interfaces";
import { addCorePageAlias } from "../utils/alias";
import { getModelClientDecorators, getModelDecorators, getPropertyClientDecorators, getPropertyDecorators } from "../utils/decorators";
import {
getModelClientDecorators,
getModelDecorators,
getPropertyClientDecorators,
getPropertyDecorators,
} from "../utils/decorators";
import { getDiscriminator, getOwnDiscriminator } from "../utils/discriminator";
import { getLogger } from "../utils/logger";
import {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -267,8 +267,7 @@ export function getEnumClientDecorators(enumeration: SealedChoiceSchema | Choice
return decorators;
}

export function getEnumChoiceClientDecorators(enumChoice: ChoiceValue): TypespecDecorator[]{

export function getEnumChoiceClientDecorators(enumChoice: ChoiceValue): TypespecDecorator[] {
const decorators: TypespecDecorator[] = [];

if (enumChoice.language.csharp?.name) {
Expand All @@ -278,7 +277,6 @@ export function getEnumChoiceClientDecorators(enumChoice: ChoiceValue): Typespec
}

export function getOperationClientDecorators(operation: Operation): TypespecDecorator[] {

const decorators: TypespecDecorator[] = [];

if (operation.language.csharp?.name) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export function getClientImports(program: TypespecProgram) {
dec.module && modules.add(`import "${dec.module}";`);
dec.namespace && namespaces.add(`using ${dec.namespace};`);
}
}
};
for (const model of program.models.objects) {
addImports(model.clientDecorators);
for (const property of model.properties) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ export function markPagination(codeModel: CodeModel) {
if (!isPageableOperation(operation)) {
continue;
}
const itemName = paginationExtension.itemName as string || "value";
const itemName = (paginationExtension.itemName as string) || "value";
let nextLinkName: string | null = "nextLink";

if (typeof paginationExtension.nextLinkName === "string") {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ export interface _ArmPagingMetadata {
}

export interface Metadata {
Resources: Record<string, ArmResource>,
RenameMapping: Record<string, string>,
OverrideOperationName: Record<string, string>,
Resources: Record<string, ArmResource>;
RenameMapping: Record<string, string>;
OverrideOperationName: Record<string, string>;
}

export interface ArmResource {
Expand Down

0 comments on commit a810530

Please sign in to comment.