Skip to content

Commit

Permalink
Output autogen information (#4975)
Browse files Browse the repository at this point in the history
1. Fix #4963
2. Support "x-ms-identifiers"
3. Add #suppress
"@azure-tools/typespec-azure-resource-manager/arm-resource-provisioning-state"
on the enum for provisioning.
  • Loading branch information
pshao25 committed Jun 7, 2024
1 parent 2ec0240 commit 6e0147d
Show file tree
Hide file tree
Showing 52 changed files with 491 additions and 8 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"changes": [
{
"packageName": "@autorest/openapi-to-typespec",
"comment": "Add output information to generated tsp",
"type": "patch"
}
],
"packageName": "@autorest/openapi-to-typespec"
}
15 changes: 14 additions & 1 deletion packages/extensions/openapi-to-typespec/src/emiters/emit-main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,27 @@ import { TypespecProgram } from "../interfaces";
import { getOptions } from "../options";
import { formatTypespecFile } from "../utils/format";
import { getArmResourcesMetadata } from "../utils/resource-discovery";
const packageInfo = require("../../package.json");

export async function emitMain(filePath: string, program: TypespecProgram): Promise<void> {
const { isArm } = getOptions();
const content = isArm ? getArmServiceInformation(program) : getServiceInformation(program);
const content = `${getHeaders()}\n${isArm ? getArmServiceInformation(program) : getServiceInformation(program)}`;
const session = getSession();
session.writeFile({ filename: filePath, content: await formatTypespecFile(content, filePath) });
}

function getHeaders() {
const { isTest } = getOptions();
return [
`/**`,
`* PLEASE DO NOT REMOVE - USED FOR CONVERTER METRICS`,
`* Generated by package: ${packageInfo.name}`,
`* Version: ${isTest ? "Not generated in test" : packageInfo.version}`,
`* Date: ${isTest ? "Not generated in test" : new Date().toISOString()}`,
`*/`,
].join("\n");
}

function getServiceInformation(program: TypespecProgram) {
const imports = [
`import "@typespec/rest";`,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { TypespecEnum } from "../interfaces";
import { getOptions } from "../options";
import { generateDecorators } from "../utils/decorators";
import { generateDocs } from "../utils/docs";
import { generateSuppressions } from "../utils/suppressions";

export function generateEnums(typespecEnum: TypespecEnum) {
const { isFullCompatible } = getOptions();
const definitions: string[] = [];
const doc = generateDocs(typespecEnum);
definitions.push(doc);
Expand All @@ -14,6 +17,9 @@ export function generateEnums(typespecEnum: TypespecEnum) {
const decorators = generateDecorators(typespecEnum.decorators);
decorators && definitions.push(decorators);

if (isFullCompatible && typespecEnum.suppressions) {
definitions.push(...generateSuppressions(typespecEnum.suppressions));
}
const enumDefinition =
typespecEnum.isExtensible && !["ApiVersion"].includes(typespecEnum.name)
? `
Expand Down
5 changes: 3 additions & 2 deletions packages/extensions/openapi-to-typespec/src/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export interface TypespecOptions {
guessResourceKey: boolean;
isArm: boolean;
isFullCompatible: boolean;
isTest: boolean;
}

export interface TypespecChoiceValue extends WithDoc {
Expand Down Expand Up @@ -99,7 +100,7 @@ export interface EndpointParameter extends WithDoc {
name: string;
}

export interface TypespecDataType extends WithDoc, WithFixMe {
export interface TypespecDataType extends WithDoc, WithFixMe, WithSuppressDirectives {
kind: string;
name: string;
}
Expand Down Expand Up @@ -162,7 +163,7 @@ export interface TypespecObjectProperty extends TypespecDataType, WithSuppressDi

export interface TypespecDecorator extends WithFixMe, WithSuppressDirective {
name: string;
arguments?: (string | number)[] | DecoratorArgument[];
arguments?: (string | number | string[])[] | DecoratorArgument[];
module?: string;
namespace?: string;
target?: string;
Expand Down
5 changes: 5 additions & 0 deletions packages/extensions/openapi-to-typespec/src/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export function updateOptions() {
guessResourceKey: getGuessResourceKey(session),
isArm: getIsArm(session),
isFullCompatible: getIsFullCompatible(session),
isTest: getIsTest(session),
};
}

Expand All @@ -46,3 +47,7 @@ export function getIsFullCompatible(session: Session<CodeModel>) {
const isFullCompatible = session.configuration["isFullCompatible"] ?? false;
return isFullCompatible !== false;
}

export function getIsTest(session: Session<CodeModel>) {
return session.configuration["isTest"] === true;
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export function transformEnum(schema: SealedChoiceSchema | ChoiceSchema, codeMod
}),
choiceType: schema.choiceType.type,
};
dataTypes.set(schema, typespecEnum);
}
return typespecEnum;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
} from "@autorest/codemodel";
import { get } from "lodash";
import { getDataTypes } from "../data-types";
import { TypespecObject, TypespecObjectProperty } from "../interfaces";
import { TypespecObject, TypespecObjectProperty, WithSuppressDirective } from "../interfaces";
import { addCorePageAlias } from "../utils/alias";
import {
getModelClientDecorators,
Expand All @@ -33,8 +33,13 @@ import {
isSealedChoiceSchema,
isStringSchema,
} from "../utils/schemas";
import { getSuppressionsForRecordProperty } from "../utils/suppressions";
import {
getPropertySuppressions,
getSuppressionsForProvisioningState,
getSuppressionsForRecordProperty,
} from "../utils/suppressions";
import { getDefaultValue, transformValue } from "../utils/values";
import { transformEnum } from "./transform-choices";

const typespecTypes = new Map<string, string>([
[SchemaType.Date, "plainDate"],
Expand Down Expand Up @@ -144,6 +149,15 @@ export function transformObjectProperty(propertySchema: Property, codeModel: Cod

logger.info(`Transforming property ${propertySchema.language.default.name} of type ${propertySchema.schema.type}`);

if (isChoiceSchema(propertySchema.schema) || isSealedChoiceSchema(propertySchema.schema)) {
const type = transformEnum(propertySchema.schema, codeModel);
if (name === "provisioningState" && isStringSchema(propertySchema.schema.choiceType)) {
const choiceValue = propertySchema.schema.choices.map((choiceValue) => choiceValue.value);
if (!(choiceValue.includes("Succeeded") && choiceValue.includes("Failed") && choiceValue.includes("Canceled"))) {
type.suppressions = getSuppressionsForProvisioningState();
}
}
}
const type = getTypespecType(propertySchema.schema, codeModel);
return {
kind: "property",
Expand All @@ -155,7 +169,7 @@ export function transformObjectProperty(propertySchema: Property, codeModel: Cod
clientDecorators: getPropertyClientDecorators(propertySchema),
fixMe: getFixme(propertySchema, codeModel),
defaultValue: getDefaultValue(type, propertySchema.schema),
suppressions: isDictionarySchema(propertySchema.schema) ? getSuppressionsForRecordProperty() : undefined,
suppressions: getPropertySuppressions(propertySchema),
};
}

Expand Down
13 changes: 12 additions & 1 deletion packages/extensions/openapi-to-typespec/src/utils/decorators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,15 @@ export function getPropertyDecorators(element: Property | Parameter): TypespecDe
});
}

if (!isParameter(element) && element.extensions?.["x-ms-identifiers"]?.length >= 0) {
decorators.push({
name: "OpenAPI.extension",
arguments: ["x-ms-identifiers", element.extensions!["x-ms-identifiers"]],
//namespace: "TypeSpec.OpenAPI",
//module: "@typespec/openapi",
});
}

return decorators;
}

Expand Down Expand Up @@ -311,11 +320,13 @@ export function generateAugmentedDecorators(keyName: string, decorators: Typespe
return definitions.join("\n");
}

function getArgumentValue(argument: DecoratorArgument | string | number): string {
function getArgumentValue(argument: DecoratorArgument | string | number | string[]): string {
if (typeof argument === "string") {
return `"${argument}"`;
} else if (typeof argument === "number") {
return `${argument}`;
} else if (Array.isArray(argument)) {
return `[${argument.map((a) => `"${a}"`).join(", ")}]`;
} else {
let value = argument.value;
if (!argument.options?.unwrap) {
Expand Down
15 changes: 15 additions & 0 deletions packages/extensions/openapi-to-typespec/src/utils/suppressions.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import { ChoiceSchema, Property, Schema, SealedChoiceSchema } from "@autorest/codemodel";
import { WithSuppressDirective } from "../interfaces";
import { isChoiceSchema, isSealedChoiceSchema, isDictionarySchema, isStringSchema } from "./schemas";

export function getPropertySuppressions(propertySchema: Property): WithSuppressDirective[] | undefined {
return isDictionarySchema(propertySchema.schema) ? getSuppressionsForRecordProperty() : undefined;
}

export function generateSuppressions(suppressions: WithSuppressDirective[]): string[] {
const definitions: string[] = [];
Expand Down Expand Up @@ -39,3 +45,12 @@ export function getSuppressionsForRecordProperty(): WithSuppressDirective[] {
},
];
}

export function getSuppressionsForProvisioningState(): WithSuppressDirective[] {
return [
{
suppressionCode: "@azure-tools/typespec-azure-resource-manager/arm-resource-provisioning-state",
suppressionMessage: "For backward compatibility",
},
];
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
/**
* PLEASE DO NOT REMOVE - USED FOR CONVERTER METRICS
* Generated by package: @autorest/openapi-to-typespec
* Version: Not generated in test
* Date: Not generated in test
*/
import "@typespec/rest";
import "@typespec/http";
import "./routes.tsp";
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
/**
* PLEASE DO NOT REMOVE - USED FOR CONVERTER METRICS
* Generated by package: @autorest/openapi-to-typespec
* Version: Not generated in test
* Date: Not generated in test
*/
import "@typespec/rest";
import "@typespec/http";
import "./routes.tsp";
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
/**
* PLEASE DO NOT REMOVE - USED FOR CONVERTER METRICS
* Generated by package: @autorest/openapi-to-typespec
* Version: Not generated in test
* Date: Not generated in test
*/
import "@typespec/rest";
import "@typespec/versioning";
import "@azure-tools/typespec-azure-core";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ union AuthCredentialsKind {
/**
* Data Manager For Agriculture instance provisioning state.
*/
#suppress "@azure-tools/typespec-azure-resource-manager/arm-resource-provisioning-state" "For backward compatibility"
union ProvisioningState {
string,
Creating: "Creating",
Expand Down Expand Up @@ -55,6 +56,7 @@ union PrivateEndpointServiceConnectionStatus {
/**
* The current provisioning state.
*/
#suppress "@azure-tools/typespec-azure-resource-manager/arm-resource-provisioning-state" "For backward compatibility"
union PrivateEndpointConnectionProvisioningState {
string,
Succeeded: "Succeeded",
Expand Down Expand Up @@ -222,6 +224,7 @@ model DataManagerForAgricultureExtensionProperties {
* customParameters, PlatformParameters and Units supported.
*/
@visibility("read")
@OpenAPI.extension("x-ms-identifiers", [])
detailedInformation?: DetailedInformation[];
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
/**
* PLEASE DO NOT REMOVE - USED FOR CONVERTER METRICS
* Generated by package: @autorest/openapi-to-typespec
* Version: Not generated in test
* Date: Not generated in test
*/
import "@typespec/rest";
import "@typespec/versioning";
import "@azure-tools/typespec-azure-core";
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
/**
* PLEASE DO NOT REMOVE - USED FOR CONVERTER METRICS
* Generated by package: @autorest/openapi-to-typespec
* Version: Not generated in test
* Date: Not generated in test
*/
import "@typespec/rest";
import "@typespec/versioning";
import "@azure-tools/typespec-azure-core";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ union State {
/**
* The current deployment state of Analysis Services resource. The provisioningState is to indicate states for resource provisioning.
*/
#suppress "@azure-tools/typespec-azure-resource-manager/arm-resource-provisioning-state" "For backward compatibility"
union ProvisioningState {
string,
Deleting: "Deleting",
Expand Down Expand Up @@ -215,6 +216,7 @@ model IPv4FirewallSettings {
/**
* An array of firewall rules.
*/
@OpenAPI.extension("x-ms-identifiers", ["firewallRuleName"])
firewallRules?: IPv4FirewallRule[];

/**
Expand Down Expand Up @@ -313,6 +315,7 @@ model SkuEnumerationForExistingResourceResult {
/**
* The collection of available SKUs for existing resources.
*/
@OpenAPI.extension("x-ms-identifiers", ["sku/name"])
value?: SkuDetailsForExistingResource[];
}

Expand Down Expand Up @@ -408,12 +411,14 @@ model OperationPropertiesServiceSpecification {
* The metric specifications.
*/
@visibility("read")
@OpenAPI.extension("x-ms-identifiers", ["name"])
metricSpecifications?: MetricSpecifications[];

/**
* The log specifications.
*/
@visibility("read")
@OpenAPI.extension("x-ms-identifiers", ["name"])
logSpecifications?: LogSpecifications[];
}

Expand Down Expand Up @@ -455,6 +460,7 @@ model MetricSpecifications {
* The dimensions of metric.
*/
@visibility("read")
@OpenAPI.extension("x-ms-identifiers", ["name"])
dimensions?: MetricDimensions[];
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
/**
* PLEASE DO NOT REMOVE - USED FOR CONVERTER METRICS
* Generated by package: @autorest/openapi-to-typespec
* Version: Not generated in test
* Date: Not generated in test
*/
import "@typespec/rest";
import "@typespec/versioning";
import "@azure-tools/typespec-azure-core";
Expand Down
Loading

0 comments on commit 6e0147d

Please sign in to comment.