From 638429d83a577bca482f01d06acdf4ce7561ae0a Mon Sep 17 00:00:00 2001 From: Lubos Date: Sun, 8 Mar 2026 17:40:25 +0100 Subject: [PATCH] chore: python sdk params --- dev/playground.py | 19 +- dev/playground.ts | 2 +- .../plugins/@hey-api/sdk/shared/operation.ts | 171 ++++++++++++++++++ .../plugins/@hey-api/sdk/shared/signature.ts | 149 +++++++++++++++ .../src/plugins/@hey-api/sdk/v1/node.ts | 17 +- .../src/plugins/pydantic/shared/export.ts | 6 +- .../src/plugins/pydantic/shared/types.ts | 4 +- .../src/plugins/pydantic/v2/toAst/array.ts | 10 +- .../src/plugins/pydantic/v2/toAst/boolean.ts | 4 +- .../src/plugins/pydantic/v2/toAst/enum.ts | 4 +- .../plugins/pydantic/v2/toAst/intersection.ts | 18 +- .../src/plugins/pydantic/v2/toAst/never.ts | 2 +- .../src/plugins/pydantic/v2/toAst/null.ts | 2 +- .../src/plugins/pydantic/v2/toAst/number.ts | 4 +- .../src/plugins/pydantic/v2/toAst/object.ts | 18 +- .../src/plugins/pydantic/v2/toAst/string.ts | 4 +- .../src/plugins/pydantic/v2/toAst/tuple.ts | 14 +- .../plugins/pydantic/v2/toAst/undefined.ts | 2 +- .../src/plugins/pydantic/v2/toAst/union.ts | 10 +- .../src/plugins/pydantic/v2/toAst/unknown.ts | 2 +- .../src/plugins/pydantic/v2/toAst/void.ts | 2 +- .../src/plugins/pydantic/v2/walker.ts | 20 +- .../openapi-python/src/py-dsl/decl/func.ts | 32 +--- .../openapi-python/src/py-dsl/decl/param.ts | 72 ++++++++ packages/openapi-python/src/py-dsl/index.ts | 8 +- .../openapi-python/src/py-dsl/mixins/param.ts | 46 +++++ .../src/py-dsl/mixins/returns.ts | 43 +++++ .../openapi-python/src/py-dsl/stmt/var.ts | 20 +- .../nodes/statements/with/with-alias.py | 7 +- .../nodes/statements/with/with-async.py | 7 +- .../nodes/statements/with/with-many-items.py | 21 ++- .../nodes/statements/with/with-tuple-alias.py | 7 +- .../nodes/statements/with/with.py | 7 +- .../src/ts-python/nodes/statement.ts | 2 + .../openapi-python/src/ts-python/printer.ts | 27 ++- packages/openapi-ts/src/ts-dsl/decl/param.ts | 10 +- .../openapi-ts/src/ts-dsl/mixins/param.ts | 9 +- packages/openapi-ts/src/ts-dsl/type/param.ts | 1 + 38 files changed, 662 insertions(+), 141 deletions(-) create mode 100644 packages/openapi-python/src/plugins/@hey-api/sdk/shared/operation.ts create mode 100644 packages/openapi-python/src/plugins/@hey-api/sdk/shared/signature.ts create mode 100644 packages/openapi-python/src/py-dsl/decl/param.ts create mode 100644 packages/openapi-python/src/py-dsl/mixins/param.ts create mode 100644 packages/openapi-python/src/py-dsl/mixins/returns.ts diff --git a/dev/playground.py b/dev/playground.py index 04cefd77d..5dd873b35 100644 --- a/dev/playground.py +++ b/dev/playground.py @@ -3,14 +3,15 @@ from gen.python import OpenCode def run(): client = OpenCode() - client.tui.publish() - # body={ - # "properties": { - # "message": "Hello from Hey API OpenAPI TS Playground!", - # "variant": "success", - # }, - # "type": "tui.toast.show", - # }, - # directory="main", + client.tui.publish( + body={ + "properties": { + "message": "Hello from Hey API OpenAPI Python Playground!", + "variant": "success", + }, + "type": "tui.toast.show", + }, + directory="main", + ) run() diff --git a/dev/playground.ts b/dev/playground.ts index 0d9192ae3..893e9bcd1 100644 --- a/dev/playground.ts +++ b/dev/playground.ts @@ -27,7 +27,7 @@ async function run() { sdk.tui.publish({ body: { properties: { - message: 'Hello from Hey API OpenAPI TS Playground!', + message: 'Hello from Hey API OpenAPI TypeScript Playground!', variant: 'success', }, type: 'tui.toast.show', diff --git a/packages/openapi-python/src/plugins/@hey-api/sdk/shared/operation.ts b/packages/openapi-python/src/plugins/@hey-api/sdk/shared/operation.ts new file mode 100644 index 000000000..5ae7bba24 --- /dev/null +++ b/packages/openapi-python/src/plugins/@hey-api/sdk/shared/operation.ts @@ -0,0 +1,171 @@ +import type { IR } from '@hey-api/shared'; +import { toCase } from '@hey-api/shared'; + +import type { $ } from '../../../../py-dsl'; +// import { py } from '../../../../ts-python'; +import type { HeyApiSdkPlugin } from '../types'; +import { getSignatureParameters } from './signature'; + +type OperationParameters = { + bodyRef?: string; + parameters: Array>; + // parameters: Array<{ + // annotation?: py.Expression; + // defaultValue?: py.Expression; + // name: string; + // }>; +}; + +const PYTHON_BUILTIN_TYPES: Record = { + array: 'list', + boolean: 'bool', + integer: 'int', + number: 'float', + object: 'dict', + string: 'str', +}; + +// eslint-disable-next-line @typescript-eslint/no-unused-vars +function schemaToPythonType(schema: IR.SchemaObject, plugin: HeyApiSdkPlugin['Instance']): string { + if (schema.$ref) { + return toCase(schema.$ref.split('/').pop()!, 'PascalCase'); + } + + if (schema.type === 'array') { + const itemsSchema = schema.items as IR.SchemaObject | undefined; + const itemType = itemsSchema ? schemaToPythonType(itemsSchema, plugin) : 'Any'; + return `list[${itemType}]`; + } + + if (schema.type === 'object' || schema.additionalProperties) { + if (schema.additionalProperties && typeof schema.additionalProperties === 'object') { + const valueType = schemaToPythonType(schema.additionalProperties as IR.SchemaObject, plugin); + return `dict[str, ${valueType}]`; + } + return 'dict[str, Any]'; + } + + if (schema.type === 'tuple') { + const itemsSchema = schema.items as IR.SchemaObject | IR.SchemaObject[] | undefined; + const itemTypes = itemsSchema + ? Array.isArray(itemsSchema) + ? itemsSchema.map((item) => schemaToPythonType(item, plugin)) + : [schemaToPythonType(itemsSchema, plugin)] + : []; + return `tuple[${itemTypes.join(', ')}]`; + } + + const builtinType = schema.type ? PYTHON_BUILTIN_TYPES[schema.type] : 'Any'; + return builtinType ?? 'Any'; +} + +export function operationParameters({ + operation, + plugin, +}: { + operation: IR.OperationObject; + plugin: HeyApiSdkPlugin['Instance']; +}): OperationParameters { + const result: OperationParameters = { + parameters: [], + }; + + if (plugin.config.paramsStructure === 'flat') { + const signature = getSignatureParameters({ operation }); + if (!signature) return result; + + // result.bodyRef = signature.bodyRef; + + // for (const param of opParameters.parameters) { + // if (param.name === '*') { + // continue; + // } + // node.param(param.name, (p) => p.type(param.annotation).default(param.defaultValue)); + // } + + // const pathParams: OperationParameters['parameters'] = []; + // const requiredParams: OperationParameters['parameters'] = []; + // const optionalParams: OperationParameters['parameters'] = []; + + // const paramNames = Object.keys(signature.parameters); + + // for (const paramName of paramNames) { + // const param = signature.parameters[paramName]!; + + // if (param.in === 'path') { + // const type = schemaToPythonType(param.schema, plugin); + // pathParams.push({ + // annotation: py.factory.createIdentifier(type), + // name: param.name, + // }); + // continue; + // } + + // if (param.in === 'body' && param.schema.$ref) { + // const refName = toCase(param.schema.$ref.split('/').pop()!, 'PascalCase'); + // if (param.isRequired) { + // requiredParams.push({ + // annotation: py.factory.createIdentifier(refName), + // name: param.name, + // }); + // } else { + // optionalParams.push({ + // annotation: py.factory.createIdentifier(`${refName} | None`), + // defaultValue: py.factory.createLiteral(null), + // name: param.name, + // }); + // } + // continue; + // } + + // const type = schemaToPythonType(param.schema, plugin); + + // if (param.isRequired) { + // requiredParams.push({ + // annotation: py.factory.createIdentifier(type), + // name: param.name, + // }); + // } else { + // let defaultValue: py.Expression = py.factory.createLiteral(null); + // if (param.schema.default !== undefined) { + // const defaultVal = param.schema.default; + // if ( + // typeof defaultVal === 'string' || + // typeof defaultVal === 'number' || + // typeof defaultVal === 'boolean' + // ) { + // defaultValue = py.factory.createLiteral(defaultVal); + // } else { + // defaultValue = py.factory.createLiteral(null); + // } + // } else if (type.startsWith('list') || type.startsWith('dict')) { + // defaultValue = py.factory.createLiteral(null); + // } + + // optionalParams.push({ + // annotation: py.factory.createIdentifier(`${type} | None`), + // defaultValue, + // name: param.name, + // }); + // } + // } + + // if (pathParams.length > 0) { + // result.parameters.push(...pathParams); + // } + + // if (requiredParams.length > 0 || optionalParams.length > 0) { + // result.parameters.push({ name: '*' }); + // result.parameters.push(...requiredParams); + // result.parameters.push(...optionalParams); + // } + + // result.parameters.push({ + // annotation: py.factory.createIdentifier('float | None'), + // defaultValue: py.factory.createLiteral(null), + // name: 'timeout', + // }); + } + + return result; +} diff --git a/packages/openapi-python/src/plugins/@hey-api/sdk/shared/signature.ts b/packages/openapi-python/src/plugins/@hey-api/sdk/shared/signature.ts new file mode 100644 index 000000000..eb99b6834 --- /dev/null +++ b/packages/openapi-python/src/plugins/@hey-api/sdk/shared/signature.ts @@ -0,0 +1,149 @@ +import type { IR } from '@hey-api/shared'; +import { refToName, toCase } from '@hey-api/shared'; + +type Location = keyof IR.ParametersObject | 'body'; + +type SignatureParameter = { + in: Location; + isRequired: boolean; + name: string; + originalName?: string; + schema: IR.SchemaObject; +}; + +type SignatureParameters = Record; + +type Signature = { + bodyRef?: string; + parameters: SignatureParameters; +}; + +export function getSignatureParameters({ + operation, +}: { + operation: IR.OperationObject; +}): Signature | undefined { + const locations = ['header', 'path', 'query'] as const satisfies ReadonlyArray; + const nameToLocations: Record> = {}; + + const addParameter = (name: string, location: Location): void => { + if (!nameToLocations[name]) { + nameToLocations[name] = new Set(); + } + nameToLocations[name]!.add(location); + }; + + for (const location of locations) { + const parameters = operation.parameters?.[location]; + if (parameters) { + for (const key in parameters) { + const parameter = parameters[key]!; + addParameter(parameter.name, location); + } + } + } + + if (operation.body) { + if ( + !operation.body.schema.logicalOperator && + operation.body.schema.type === 'object' && + operation.body.schema.properties + ) { + const properties = operation.body.schema.properties; + for (const key in properties) { + addParameter(key, 'body'); + } + } else if (operation.body.schema.$ref) { + const name = refToName(operation.body.schema.$ref); + const key = toCase(name, 'snake_case'); + addParameter(key, 'body'); + } else { + addParameter('body', 'body'); + } + } + + const conflicts = new Set(); + for (const name in nameToLocations) { + if (nameToLocations[name]!.size > 1) { + conflicts.add(name); + } + } + + const signatureParameters: SignatureParameters = {}; + + for (const location of locations) { + const parameters = operation.parameters?.[location]; + if (parameters) { + for (const key in parameters) { + const parameter = parameters[key]!; + const originalName = parameter.name; + const name = conflicts.has(originalName) ? `${location}_${originalName}` : originalName; + const signatureParameter: SignatureParameter = { + in: location, + isRequired: parameter.required ?? false, + name, + schema: parameter.schema, + }; + if (name !== originalName) { + signatureParameter.originalName = originalName; + } + signatureParameters[name] = signatureParameter; + } + } + } + + let bodyRef: string | undefined; + + if (operation.body) { + const location = 'body'; + if ( + !operation.body.schema.logicalOperator && + operation.body.schema.type === 'object' && + operation.body.schema.properties + ) { + const properties = operation.body.schema.properties; + for (const originalName in properties) { + const property = properties[originalName]!; + const name = conflicts.has(originalName) ? `${location}_${originalName}` : originalName; + const signatureParameter: SignatureParameter = { + in: location, + isRequired: operation.body.schema.required?.includes(originalName) ?? false, + name, + schema: property, + }; + if (name !== originalName) { + signatureParameter.originalName = originalName; + } + signatureParameters[name] = signatureParameter; + } + } else if (operation.body.schema.$ref) { + const value = refToName(operation.body.schema.$ref); + const originalName = toCase(value, 'snake_case'); + const name = conflicts.has(originalName) ? `${location}_${originalName}` : originalName; + bodyRef = toCase(value, 'PascalCase'); + const signatureParameter: SignatureParameter = { + in: location, + isRequired: operation.body.required ?? false, + name, + schema: operation.body.schema, + }; + if (name !== originalName) { + signatureParameter.originalName = originalName; + } + signatureParameters[name] = signatureParameter; + } else { + signatureParameters.body = { + in: location, + isRequired: operation.body.required ?? false, + name: 'body', + schema: operation.body.schema, + }; + } + } + + if (!Object.keys(signatureParameters).length) { + return; + } + + return { bodyRef, parameters: signatureParameters }; +} diff --git a/packages/openapi-python/src/plugins/@hey-api/sdk/v1/node.ts b/packages/openapi-python/src/plugins/@hey-api/sdk/v1/node.ts index 593002715..de0de6bb8 100644 --- a/packages/openapi-python/src/plugins/@hey-api/sdk/v1/node.ts +++ b/packages/openapi-python/src/plugins/@hey-api/sdk/v1/node.ts @@ -10,6 +10,7 @@ import { applyNaming, toCase } from '@hey-api/shared'; import { $ } from '../../../../py-dsl'; import { createOperationComment } from '../../../shared/utils/operation'; +import { operationParameters } from '../shared/operation'; import type { HeyApiSdkPlugin } from '../types'; export interface OperationItem { @@ -114,13 +115,15 @@ function implementFn>(args: { operation: IR.OperationObject; plugin: HeyApiSdkPlugin['Instance']; }): T { - const { node, operation } = args; - - const method = operation.method?.toLowerCase() || 'get'; - - node.do($('self').attr('client').attr(method).call($.literal(operation.path)).return()); - - return node; + const { node, operation, plugin } = args; + const method = operation.method.toLowerCase(); + const opParameters = operationParameters({ operation, plugin }); + return ( + node + .params(...opParameters.parameters) + // TODO: extract operation statements into a separate function + .do($('self').attr('client').attr(method).call($.literal(operation.path)).return()) as T + ); } export function toNode( diff --git a/packages/openapi-python/src/plugins/pydantic/shared/export.ts b/packages/openapi-python/src/plugins/pydantic/shared/export.ts index b4fc5ed40..fa7cfe0ca 100644 --- a/packages/openapi-python/src/plugins/pydantic/shared/export.ts +++ b/packages/openapi-python/src/plugins/pydantic/shared/export.ts @@ -100,7 +100,7 @@ function createFieldStatement( plugin: PydanticPlugin['Instance'], ): ReturnType { const fieldSymbol = field.name; - const varStatement = $.var(fieldSymbol).$if(field.typeAnnotation, (v, a) => v.annotate(a)); + const varStatement = $.var(fieldSymbol).$if(field.type, (v, a) => v.type(a)); const originalName = field.originalName ?? fieldSymbol.name; const needsAlias = field.originalName !== undefined && fieldSymbol.name !== originalName; @@ -135,7 +135,7 @@ function exportTypeAlias({ }): void { const typeAlias = plugin.external('typing.TypeAlias'); const statement = $.var(symbol) - .annotate(typeAlias) - .assign(final.typeAnnotation ?? plugin.external('typing.Any')); + .type(typeAlias) + .assign(final.type ?? plugin.external('typing.Any')); plugin.node(statement); } diff --git a/packages/openapi-python/src/plugins/pydantic/shared/types.ts b/packages/openapi-python/src/plugins/pydantic/shared/types.ts index 650289b91..79ce33e8e 100644 --- a/packages/openapi-python/src/plugins/pydantic/shared/types.ts +++ b/packages/openapi-python/src/plugins/pydantic/shared/types.ts @@ -1,6 +1,6 @@ import type { Symbol } from '@hey-api/codegen-core'; -import type { AnnotationExpr } from '../../../py-dsl'; +import type { VarType } from '../../../py-dsl'; import type { FieldConstraints } from '../v2/constants'; /** @@ -8,7 +8,7 @@ import type { FieldConstraints } from '../v2/constants'; */ export interface PydanticType { fieldConstraints?: FieldConstraints; - typeAnnotation?: AnnotationExpr; + type?: VarType; } /** diff --git a/packages/openapi-python/src/plugins/pydantic/v2/toAst/array.ts b/packages/openapi-python/src/plugins/pydantic/v2/toAst/array.ts index d7f06acba..cb5bc3c41 100644 --- a/packages/openapi-python/src/plugins/pydantic/v2/toAst/array.ts +++ b/packages/openapi-python/src/plugins/pydantic/v2/toAst/array.ts @@ -43,7 +43,7 @@ export function arrayToType(ctx: ArrayToTypeContext): ArrayToTypeResult { return { childResults, fieldConstraints: constraints, - typeAnnotation: $(list).slice(any), + type: $(list).slice(any), }; } @@ -60,23 +60,23 @@ export function arrayToType(ctx: ArrayToTypeContext): ArrayToTypeResult { return { childResults, fieldConstraints: constraints, - typeAnnotation: $(list).slice(itemResult.typeAnnotation ?? any), + type: $(list).slice(itemResult.type ?? any), }; } if (childResults.length > 1) { const union = plugin.external('typing.Union'); - const itemTypes = childResults.map((r) => ctx.applyModifiers(r).typeAnnotation ?? any); + const itemTypes = childResults.map((r) => ctx.applyModifiers(r).type ?? any); return { childResults, fieldConstraints: constraints, - typeAnnotation: $(list).slice($(union).slice(...itemTypes)), + type: $(list).slice($(union).slice(...itemTypes)), }; } return { childResults, fieldConstraints: constraints, - typeAnnotation: $(list).slice(any), + type: $(list).slice(any), }; } diff --git a/packages/openapi-python/src/plugins/pydantic/v2/toAst/boolean.ts b/packages/openapi-python/src/plugins/pydantic/v2/toAst/boolean.ts index 57a6d7db9..c296f6875 100644 --- a/packages/openapi-python/src/plugins/pydantic/v2/toAst/boolean.ts +++ b/packages/openapi-python/src/plugins/pydantic/v2/toAst/boolean.ts @@ -14,11 +14,11 @@ export function booleanToType({ if (typeof schema.const === 'boolean') { const literal = plugin.external('typing.Literal'); return { - typeAnnotation: $(literal).slice($.literal(schema.const)), + type: $(literal).slice($.literal(schema.const)), }; } return { - typeAnnotation: 'bool', + type: 'bool', }; } diff --git a/packages/openapi-python/src/plugins/pydantic/v2/toAst/enum.ts b/packages/openapi-python/src/plugins/pydantic/v2/toAst/enum.ts index 664489020..899a14c17 100644 --- a/packages/openapi-python/src/plugins/pydantic/v2/toAst/enum.ts +++ b/packages/openapi-python/src/plugins/pydantic/v2/toAst/enum.ts @@ -83,7 +83,7 @@ export function enumToType({ return { enumMembers, isNullable, - typeAnnotation: plugin.external('typing.Any'), + type: plugin.external('typing.Any'), }; } @@ -91,7 +91,7 @@ export function enumToType({ return { enumMembers, isNullable, - typeAnnotation: toLiteralType(enumMembers, plugin), + type: toLiteralType(enumMembers, plugin), }; } diff --git a/packages/openapi-python/src/plugins/pydantic/v2/toAst/intersection.ts b/packages/openapi-python/src/plugins/pydantic/v2/toAst/intersection.ts index 221d3c6e4..7e4385fdb 100644 --- a/packages/openapi-python/src/plugins/pydantic/v2/toAst/intersection.ts +++ b/packages/openapi-python/src/plugins/pydantic/v2/toAst/intersection.ts @@ -1,6 +1,6 @@ import type { IR } from '@hey-api/shared'; -import type { AnnotationExpr } from '../../../../py-dsl'; +import type { VarType } from '../../../../py-dsl'; import type { PydanticField, PydanticFinal, @@ -37,7 +37,7 @@ export function intersectionToType({ return { childResults, fieldConstraints: constraints, - typeAnnotation: plugin.external('typing.Any'), + type: plugin.external('typing.Any'), }; } @@ -47,7 +47,7 @@ export function intersectionToType({ childResults, fieldConstraints: { ...constraints, ...finalResult.fieldConstraints }, mergedFields: finalResult.fields, - typeAnnotation: finalResult.typeAnnotation, + type: finalResult.type, }; } @@ -59,7 +59,7 @@ export function intersectionToType({ const finalResult = applyModifiers(result); // TODO: replace - const typeStr = String(finalResult.typeAnnotation); + const typeStr = String(finalResult.type); const isReference = !finalResult.fields && typeStr !== '' && @@ -84,15 +84,15 @@ export function intersectionToType({ } } - let typeAnnotation: AnnotationExpr; + let type: VarType; if (baseClasses.length > 0 && mergedFields.length === 0) { - typeAnnotation = baseClasses[0]!; + type = baseClasses[0]!; } else if (mergedFields.length > 0) { // TODO: replace - typeAnnotation = '__INTERSECTION_PLACEHOLDER__'; + type = '__INTERSECTION_PLACEHOLDER__'; } else { - typeAnnotation = plugin.external('typing.Any'); + type = plugin.external('typing.Any'); } return { @@ -100,6 +100,6 @@ export function intersectionToType({ childResults, fieldConstraints: constraints, mergedFields: mergedFields.length > 0 ? mergedFields : undefined, - typeAnnotation, + type, }; } diff --git a/packages/openapi-python/src/plugins/pydantic/v2/toAst/never.ts b/packages/openapi-python/src/plugins/pydantic/v2/toAst/never.ts index 11e54096b..e2941f0cd 100644 --- a/packages/openapi-python/src/plugins/pydantic/v2/toAst/never.ts +++ b/packages/openapi-python/src/plugins/pydantic/v2/toAst/never.ts @@ -10,6 +10,6 @@ export function neverToType({ schema: SchemaWithType<'never'>; }): PydanticType { return { - typeAnnotation: plugin.external('typing.NoReturn'), + type: plugin.external('typing.NoReturn'), }; } diff --git a/packages/openapi-python/src/plugins/pydantic/v2/toAst/null.ts b/packages/openapi-python/src/plugins/pydantic/v2/toAst/null.ts index a888ad50c..09441f6a0 100644 --- a/packages/openapi-python/src/plugins/pydantic/v2/toAst/null.ts +++ b/packages/openapi-python/src/plugins/pydantic/v2/toAst/null.ts @@ -9,6 +9,6 @@ export function nullToType(args: { schema: SchemaWithType<'null'>; }): PydanticType { return { - typeAnnotation: 'None', + type: 'None', }; } diff --git a/packages/openapi-python/src/plugins/pydantic/v2/toAst/number.ts b/packages/openapi-python/src/plugins/pydantic/v2/toAst/number.ts index 85cab1726..306bdd404 100644 --- a/packages/openapi-python/src/plugins/pydantic/v2/toAst/number.ts +++ b/packages/openapi-python/src/plugins/pydantic/v2/toAst/number.ts @@ -17,7 +17,7 @@ export function numberToType({ if (typeof schema.const === 'number') { const literal = plugin.external('typing.Literal'); return { - typeAnnotation: $(literal).slice($.literal(schema.const)), + type: $(literal).slice($.literal(schema.const)), }; } @@ -43,6 +43,6 @@ export function numberToType({ return { fieldConstraints: constraints, - typeAnnotation: schema.type === 'integer' ? 'int' : 'float', + type: schema.type === 'integer' ? 'int' : 'float', }; } diff --git a/packages/openapi-python/src/plugins/pydantic/v2/toAst/object.ts b/packages/openapi-python/src/plugins/pydantic/v2/toAst/object.ts index 55f0cea23..bad174e50 100644 --- a/packages/openapi-python/src/plugins/pydantic/v2/toAst/object.ts +++ b/packages/openapi-python/src/plugins/pydantic/v2/toAst/object.ts @@ -1,7 +1,7 @@ import type { SchemaVisitorContext, SchemaWithType, Walker } from '@hey-api/shared'; import { childContext, toCase } from '@hey-api/shared'; -import { $, type AnnotationExpr } from '../../../../py-dsl'; +import { $, type VarType } from '../../../../py-dsl'; import { safeRuntimeName } from '../../../../py-dsl/utils/name'; import type { PydanticField, PydanticFinal, PydanticResult } from '../../shared/types'; import type { PydanticPlugin } from '../../types'; @@ -15,13 +15,11 @@ interface ObjectResolverContext { walkerCtx: SchemaVisitorContext; } -export interface ObjectToFieldsResult extends Pick { +export interface ObjectToFieldsResult extends Pick { childResults: Array; } -function resolveAdditionalProperties( - ctx: ObjectResolverContext, -): AnnotationExpr | null | undefined { +function resolveAdditionalProperties(ctx: ObjectResolverContext): VarType | null | undefined { const { schema } = ctx; if (!schema.additionalProperties || !schema.additionalProperties.type) return undefined; @@ -33,7 +31,7 @@ function resolveAdditionalProperties( ); ctx._childResults.push(result); - return result.typeAnnotation; + return result.type; } function resolveFields(ctx: ObjectResolverContext): Array { @@ -54,7 +52,7 @@ function resolveFields(ctx: ObjectResolverContext): Array { isOptional, name: ctx.plugin.symbol(snakeCaseName), originalName: name, - typeAnnotation: final.typeAnnotation, + type: final.type, }); } @@ -74,9 +72,9 @@ function objectResolver(ctx: ObjectResolverContext): Omit = []; + const itemTypes: Array = []; for (let i = 0; i < schema.items.length; i++) { const item = schema.items[i]!; @@ -46,8 +46,8 @@ export function tupleToType(ctx: TupleToTypeContext): TupleToTypeResult { childResults.push(result); const finalResult = applyModifiers(result); - if (finalResult.typeAnnotation !== undefined) { - itemTypes.push(finalResult.typeAnnotation); + if (finalResult.type !== undefined) { + itemTypes.push(finalResult.type); } } @@ -55,13 +55,13 @@ export function tupleToType(ctx: TupleToTypeContext): TupleToTypeResult { return { childResults, fieldConstraints: constraints, - typeAnnotation: $(tuple).slice(any, '...'), + type: $(tuple).slice(any, '...'), }; } return { childResults, fieldConstraints: constraints, - typeAnnotation: $(tuple).slice(...itemTypes), + type: $(tuple).slice(...itemTypes), }; } diff --git a/packages/openapi-python/src/plugins/pydantic/v2/toAst/undefined.ts b/packages/openapi-python/src/plugins/pydantic/v2/toAst/undefined.ts index 90b07a7e4..99610f0ba 100644 --- a/packages/openapi-python/src/plugins/pydantic/v2/toAst/undefined.ts +++ b/packages/openapi-python/src/plugins/pydantic/v2/toAst/undefined.ts @@ -9,6 +9,6 @@ export function undefinedToType(args: { schema: SchemaWithType<'undefined'>; }): PydanticType { return { - typeAnnotation: 'None', + type: 'None', }; } diff --git a/packages/openapi-python/src/plugins/pydantic/v2/toAst/union.ts b/packages/openapi-python/src/plugins/pydantic/v2/toAst/union.ts index bd213d389..0648fa926 100644 --- a/packages/openapi-python/src/plugins/pydantic/v2/toAst/union.ts +++ b/packages/openapi-python/src/plugins/pydantic/v2/toAst/union.ts @@ -31,7 +31,7 @@ export function unionToType({ let isNullable = false; for (const result of childResults) { - if (result.typeAnnotation === 'None') { + if (result.type === 'None') { isNullable = true; } else { nonNullResults.push(result); @@ -45,7 +45,7 @@ export function unionToType({ childResults, fieldConstraints: constraints, isNullable: true, - typeAnnotation: 'None', + type: 'None', }; } @@ -55,13 +55,13 @@ export function unionToType({ childResults, fieldConstraints: { ...constraints, ...finalResult.fieldConstraints }, isNullable, - typeAnnotation: finalResult.typeAnnotation, + type: finalResult.type, }; } const union = plugin.external('typing.Union'); const itemTypes = nonNullResults.map( - (r) => applyModifiers(r).typeAnnotation ?? plugin.external('typing.Any'), + (r) => applyModifiers(r).type ?? plugin.external('typing.Any'), ); if (isNullable) { @@ -72,6 +72,6 @@ export function unionToType({ childResults, fieldConstraints: constraints, isNullable, - typeAnnotation: $(union).slice(...itemTypes), + type: $(union).slice(...itemTypes), }; } diff --git a/packages/openapi-python/src/plugins/pydantic/v2/toAst/unknown.ts b/packages/openapi-python/src/plugins/pydantic/v2/toAst/unknown.ts index 2092ba779..c2ba4fb5a 100644 --- a/packages/openapi-python/src/plugins/pydantic/v2/toAst/unknown.ts +++ b/packages/openapi-python/src/plugins/pydantic/v2/toAst/unknown.ts @@ -10,6 +10,6 @@ export function unknownToType({ schema: SchemaWithType<'unknown'>; }): PydanticType { return { - typeAnnotation: plugin.external('typing.Any'), + type: plugin.external('typing.Any'), }; } diff --git a/packages/openapi-python/src/plugins/pydantic/v2/toAst/void.ts b/packages/openapi-python/src/plugins/pydantic/v2/toAst/void.ts index 6b0d3c9a6..4219b2953 100644 --- a/packages/openapi-python/src/plugins/pydantic/v2/toAst/void.ts +++ b/packages/openapi-python/src/plugins/pydantic/v2/toAst/void.ts @@ -9,6 +9,6 @@ export function voidToType(args: { schema: SchemaWithType<'void'>; }): PydanticType { return { - typeAnnotation: 'None', + type: 'None', }; } diff --git a/packages/openapi-python/src/plugins/pydantic/v2/walker.ts b/packages/openapi-python/src/plugins/pydantic/v2/walker.ts index 98ec2614b..d88498f89 100644 --- a/packages/openapi-python/src/plugins/pydantic/v2/walker.ts +++ b/packages/openapi-python/src/plugins/pydantic/v2/walker.ts @@ -41,12 +41,12 @@ export function createVisitor( const needsOptional = optional || hasDefault; const needsNullable = result.meta.nullable; - let typeAnnotation = result.typeAnnotation; + let type = result.type; const fieldConstraints = { ...result.fieldConstraints }; if (needsOptional || needsNullable) { const optionalType = ctx.plugin.external('typing.Optional'); - typeAnnotation = $(optionalType).slice(typeAnnotation ?? ctx.plugin.external('typing.Any')); + type = $(optionalType).slice(type ?? ctx.plugin.external('typing.Any')); if (needsOptional) { fieldConstraints.default = hasDefault ? result.meta.default : null; } @@ -56,14 +56,14 @@ export function createVisitor( enumMembers: result.enumMembers, fieldConstraints, fields: result.fields, - typeAnnotation, + type, }; }, array(schema, ctx, walk) { const applyModifiers = (result: PydanticResult, opts?: { optional?: boolean }) => this.applyModifiers(result, ctx, opts) as PydanticFinal; - const { childResults, fieldConstraints, typeAnnotation } = arrayToType({ + const { childResults, fieldConstraints, type } = arrayToType({ applyModifiers, plugin: ctx.plugin, schema, @@ -74,7 +74,7 @@ export function createVisitor( return { fieldConstraints, meta: composeMeta(childResults, { ...defaultMeta(schema) }), - typeAnnotation, + type, }; }, boolean(schema, ctx) { @@ -160,7 +160,7 @@ export function createVisitor( const applyModifiers = (result: PydanticResult, opts?: { optional?: boolean }) => this.applyModifiers(result, ctx, opts) as PydanticFinal; - const { childResults, fields, typeAnnotation } = objectToFields({ + const { childResults, fields, type } = objectToFields({ applyModifiers, plugin: ctx.plugin, schema, @@ -171,7 +171,7 @@ export function createVisitor( return { fields, meta: inheritMeta(schema, childResults), - typeAnnotation: typeAnnotation ?? '', + type: type ?? '', }; }, postProcess(result) { @@ -193,7 +193,7 @@ export function createVisitor( ...defaultMeta(schema), hasForwardReference: !isRegistered, }, - typeAnnotation: refSymbol, + type: refSymbol, }; }, string(schema, ctx) { @@ -207,7 +207,7 @@ export function createVisitor( const applyModifiers = (result: PydanticResult, opts?: { optional?: boolean }) => this.applyModifiers(result, ctx, opts) as PydanticFinal; - const { childResults, fieldConstraints, typeAnnotation } = tupleToType({ + const { childResults, fieldConstraints, type } = tupleToType({ applyModifiers, plugin: ctx.plugin, schema, @@ -218,7 +218,7 @@ export function createVisitor( return { fieldConstraints, meta: composeMeta(childResults, { ...defaultMeta(schema) }), - typeAnnotation, + type, }; }, undefined(schema, ctx) { diff --git a/packages/openapi-python/src/py-dsl/decl/func.ts b/packages/openapi-python/src/py-dsl/decl/func.ts index c4822bad0..4a552488c 100644 --- a/packages/openapi-python/src/py-dsl/decl/func.ts +++ b/packages/openapi-python/src/py-dsl/decl/func.ts @@ -8,19 +8,22 @@ import { DoMixin } from '../mixins/do'; import { DocMixin } from '../mixins/doc'; import { LayoutMixin } from '../mixins/layout'; import { AsyncMixin, ExportMixin } from '../mixins/modifiers'; +import { ParamMixin } from '../mixins/param'; +import { ReturnsMixin } from '../mixins/returns'; import { safeRuntimeName } from '../utils/name'; const Mixed = AsyncMixin( - DecoratorMixin(DocMixin(DoMixin(ExportMixin(LayoutMixin(PyDsl))))), + DecoratorMixin( + DocMixin( + DoMixin(ExportMixin(LayoutMixin(ParamMixin(ReturnsMixin(PyDsl))))), + ), + ), ); export class FuncPyDsl extends Mixed { readonly '~dsl' = 'FuncPyDsl'; override readonly nameSanitizer = safeRuntimeName; - protected _parameters: Array = []; - protected _returnType?: NodeName | py.Expression; - constructor(name: NodeName, fn?: (f: FuncPyDsl) => void) { super(); this.name.set(name); @@ -38,10 +41,6 @@ export class FuncPyDsl extends Mixed { } finally { ctx.popScope(); } - for (const param of this._parameters) { - ctx.analyze(param); - } - ctx.analyze(this._returnType); } /** Returns true when all required builder calls are present. */ @@ -49,25 +48,12 @@ export class FuncPyDsl extends Mixed { return this.missingRequiredCalls().length === 0; } - param(name: string, configure?: (p: py.FunctionParameter) => void): this { - const param = py.factory.createFunctionParameter(name, undefined, undefined, undefined); - if (configure) configure(param); - this._parameters.push(param); - return this; - } - - returns(returnType: NodeName | py.Expression): this { - this._returnType = - typeof returnType === 'string' ? py.factory.createIdentifier(returnType) : returnType; - return this; - } - override toAst() { this.$validate(); return py.factory.createFunctionDeclaration( this.name.toString(), - this._parameters, - this.$node(this._returnType), + this.$params(), + this.$returns(), this.$do(), this.$decorators(), this.$docs(), diff --git a/packages/openapi-python/src/py-dsl/decl/param.ts b/packages/openapi-python/src/py-dsl/decl/param.ts new file mode 100644 index 000000000..a976ac4ff --- /dev/null +++ b/packages/openapi-python/src/py-dsl/decl/param.ts @@ -0,0 +1,72 @@ +import type { AnalysisContext, NodeName } from '@hey-api/codegen-core'; + +import { py } from '../../ts-python'; +import { PyDsl } from '../base'; + +export type ParamDefaultValue = NodeName | py.Expression | undefined; +export type ParamFn = (p: ParamPyDsl) => void; +export type ParamName = NodeName | ParamFn; +export type ParamType = NodeName | py.Expression | undefined; + +export type ParamCtor = (name: ParamName, fn?: ParamFn) => ParamPyDsl; + +export class ParamPyDsl extends PyDsl { + readonly '~dsl' = 'ParamPyDsl'; + + protected _defaultValue?: ParamDefaultValue; + protected _type?: ParamType; + + constructor(name: ParamName, fn?: ParamFn) { + super(); + if (typeof name === 'function') { + name(this); + } else { + this.name.set(name); + fn?.(this); + } + } + + override analyze(ctx: AnalysisContext): void { + super.analyze(ctx); + ctx.analyze(this.name); + ctx.analyze(this._type); + ctx.analyze(this._defaultValue); + } + + /** Sets the parameter default value. */ + default(value: ParamDefaultValue): this { + this._defaultValue = value; + return this; + } + + get isValid(): boolean { + return this.missingRequiredCalls().length === 0; + } + + /** Sets the parameter type. */ + type(type: ParamType): this { + this._type = type; + return this; + } + + override toAst() { + this.$validate(); + return py.factory.createFunctionParameter( + this.name.toString(), + this.$node(this._type), + this.$node(this._defaultValue), + ); + } + + $validate(): asserts this { + const missing = this.missingRequiredCalls(); + if (missing.length === 0) return; + throw new Error(`Parameter missing ${missing.join(' and ')}`); + } + + private missingRequiredCalls(): ReadonlyArray { + const missing: Array = []; + if (!this.name.toString()) missing.push('name'); + return missing; + } +} diff --git a/packages/openapi-python/src/py-dsl/index.ts b/packages/openapi-python/src/py-dsl/index.ts index 7f02acd9b..6c6e96147 100644 --- a/packages/openapi-python/src/py-dsl/index.ts +++ b/packages/openapi-python/src/py-dsl/index.ts @@ -6,16 +6,16 @@ import { ClassPyDsl } from './decl/class'; // import { EnumPyDsl } from './decl/enum'; // import { FieldPyDsl } from './decl/field'; import { FuncPyDsl } from './decl/func'; -import { AttrPyDsl } from './expr/attr'; +import { ParamPyDsl } from './decl/param'; // import { GetterPyDsl } from './decl/getter'; // import { InitPyDsl } from './decl/init'; // import { EnumMemberPyDsl } from './decl/member'; // import { MethodPyDsl } from './decl/method'; -// import { ParamPyDsl } from './decl/param'; // import { PatternPyDsl } from './decl/pattern'; // import { SetterPyDsl } from './decl/setter'; // import { ArrayPyDsl } from './expr/array'; // import { AsPyDsl } from './expr/as'; +import { AttrPyDsl } from './expr/attr'; // import { AwaitPyDsl } from './expr/await'; import { BinaryPyDsl } from './expr/binary'; import { CallPyDsl } from './expr/call'; @@ -185,7 +185,7 @@ const pyDsl = { // object: (...args: ConstructorParameters) => new ObjectTsDsl(...args), /** Creates a parameter declaration for functions or methods. */ - // param: (...args: ConstructorParameters) => new ParamTsDsl(...args), + param: (...args: ConstructorParameters) => new ParamPyDsl(...args), /** Creates a pattern for destructuring or matching. */ // pattern: (...args: ConstructorParameters) => new PatternTsDsl(...args), @@ -320,7 +320,7 @@ export type { MaybePyDsl } from './base'; // export type { MaybePyDsl, TypePyDsl } from './base'; export { PyDsl } from './base'; export type { CallArgs } from './expr/call'; -export type { AnnotationExpr } from './stmt/var'; +export type { VarType } from './stmt/var'; export type { ExampleOptions } from './utils/context'; export { ctx, PyDslContext } from './utils/context'; export { keywords } from './utils/keywords'; diff --git a/packages/openapi-python/src/py-dsl/mixins/param.ts b/packages/openapi-python/src/py-dsl/mixins/param.ts new file mode 100644 index 000000000..098d43e1d --- /dev/null +++ b/packages/openapi-python/src/py-dsl/mixins/param.ts @@ -0,0 +1,46 @@ +import type { AnalysisContext, Node } from '@hey-api/codegen-core'; + +import type { py } from '../../ts-python'; +import type { MaybePyDsl } from '../base'; +import type { ParamCtor, ParamFn, ParamName } from '../decl/param'; +import { ParamPyDsl } from '../decl/param'; +import type { BaseCtor, MixinCtor } from './types'; + +export interface ParamMethods extends Node { + /** Renders the parameters into an array of `FunctionParameter`s. */ + $params(): ReadonlyArray; + /** Adds a parameter. */ + param(...args: Parameters): this; + /** Adds multiple parameters. */ + params(...params: ReadonlyArray>): this; +} + +export function ParamMixin>(Base: TBase) { + abstract class Param extends Base { + protected _params: Array> = []; + + override analyze(ctx: AnalysisContext): void { + super.analyze(ctx); + for (const param of this._params) { + ctx.analyze(param); + } + } + + protected param(name: ParamName, fn?: ParamFn): this { + const p = typeof name === 'function' ? new ParamPyDsl(name) : new ParamPyDsl(name, fn); + this._params.push(p); + return this; + } + + protected params(...params: ReadonlyArray>): this { + this._params.push(...params); + return this; + } + + protected $params(): ReadonlyArray { + return this.$node(this._params); + } + } + + return Param as unknown as MixinCtor; +} diff --git a/packages/openapi-python/src/py-dsl/mixins/returns.ts b/packages/openapi-python/src/py-dsl/mixins/returns.ts new file mode 100644 index 000000000..6b6107e81 --- /dev/null +++ b/packages/openapi-python/src/py-dsl/mixins/returns.ts @@ -0,0 +1,43 @@ +import type { AnalysisContext, Node, NodeName } from '@hey-api/codegen-core'; +import { isSymbol } from '@hey-api/codegen-core'; + +import type { py } from '../../ts-python'; +import { IdPyDsl } from '../expr/identifier'; +import type { BaseCtor, MixinCtor } from './types'; + +export interface ReturnsMethods extends Node { + $returns(): py.Expression | undefined; + returns(type: NodeName | py.Expression): this; +} + +export function ReturnsMixin>(Base: TBase) { + abstract class Returns extends Base { + protected _returns?: IdPyDsl | py.Expression; + + override analyze(ctx: AnalysisContext): void { + super.analyze(ctx); + ctx.analyze(this._returns); + } + + returns(type: NodeName | py.Expression): this { + if (typeof type === 'string' || isSymbol(type)) { + this._returns = new IdPyDsl(type); + } else { + this._returns = type as py.Expression; + } + return this; + } + + protected $returns(): py.Expression | undefined { + if (!this._returns) { + return undefined; + } + if (this._returns instanceof IdPyDsl) { + return this._returns.toAst(); + } + return this._returns as py.Expression; + } + } + + return Returns as unknown as MixinCtor; +} diff --git a/packages/openapi-python/src/py-dsl/stmt/var.ts b/packages/openapi-python/src/py-dsl/stmt/var.ts index 3e84fcc83..b2ea23228 100644 --- a/packages/openapi-python/src/py-dsl/stmt/var.ts +++ b/packages/openapi-python/src/py-dsl/stmt/var.ts @@ -9,13 +9,13 @@ import { safeRuntimeName } from '../utils/name'; const Mixed = ValueMixin(PyDsl); -export type AnnotationExpr = NodeName | MaybePyDsl; +export type VarType = NodeName | MaybePyDsl; export class VarPyDsl extends Mixed { readonly '~dsl' = 'VarPyDsl'; override readonly nameSanitizer = safeRuntimeName; - protected _annotation?: AnnotationExpr; + protected _type?: VarType; constructor(name?: NodeName) { super(); @@ -28,7 +28,7 @@ export class VarPyDsl extends Mixed { override analyze(ctx: AnalysisContext): void { super.analyze(ctx); ctx.analyze(this.name); - ctx.analyze(this._annotation); + ctx.analyze(this._type); } /** Returns true when all required builder calls are present. */ @@ -37,15 +37,15 @@ export class VarPyDsl extends Mixed { } /** Sets the type annotation for the variable. */ - annotate(annotation: AnnotationExpr): this { - this._annotation = annotation; + type(type: VarType): this { + this._type = type; return this; } override toAst() { this.$validate(); const target = this.$node(this.name)!; - const annotation = this.$annotation(); + const annotation = this.$type(); const value = this.$value(); return py.factory.createAssignment(target, annotation, value); @@ -57,17 +57,17 @@ export class VarPyDsl extends Mixed { throw new Error(`Variable assignment missing ${missing.join(' and ')}`); } - protected $annotation(): py.Expression | undefined { - return this.$node(this._annotation); + protected $type(): py.Expression | undefined { + return this.$node(this._type); } private missingRequiredCalls(): ReadonlyArray { const missing: Array = []; if (!this.$node(this.name)) missing.push('name'); - const hasAnnotation = this.$annotation(); + const hasAnnotation = this.$type(); const hasValue = this.$value(); if (!hasAnnotation && !hasValue) { - missing.push('.annotate() or .assign()'); + missing.push('.type() or .assign()'); } return missing; } diff --git a/packages/openapi-python/src/ts-python/__snapshots__/nodes/statements/with/with-alias.py b/packages/openapi-python/src/ts-python/__snapshots__/nodes/statements/with/with-alias.py index f249b12ec..7354de4cd 100644 --- a/packages/openapi-python/src/ts-python/__snapshots__/nodes/statements/with/with-alias.py +++ b/packages/openapi-python/src/ts-python/__snapshots__/nodes/statements/with/with-alias.py @@ -1,7 +1,12 @@ class context_manager: def __enter__(self): return self - def __exit__(self, exc_type, exc_val, exc_tb): + def __exit__( + self, + exc_type, + exc_val, + exc_tb, + ): return False with context_manager() as alias: diff --git a/packages/openapi-python/src/ts-python/__snapshots__/nodes/statements/with/with-async.py b/packages/openapi-python/src/ts-python/__snapshots__/nodes/statements/with/with-async.py index 8ee38a4a3..67831054d 100644 --- a/packages/openapi-python/src/ts-python/__snapshots__/nodes/statements/with/with-async.py +++ b/packages/openapi-python/src/ts-python/__snapshots__/nodes/statements/with/with-async.py @@ -1,7 +1,12 @@ class context_manager: def __enter__(self): return self - def __exit__(self, exc_type, exc_val, exc_tb): + def __exit__( + self, + exc_type, + exc_val, + exc_tb, + ): return False async def foo(): diff --git a/packages/openapi-python/src/ts-python/__snapshots__/nodes/statements/with/with-many-items.py b/packages/openapi-python/src/ts-python/__snapshots__/nodes/statements/with/with-many-items.py index 6bf36b57d..765f1db09 100644 --- a/packages/openapi-python/src/ts-python/__snapshots__/nodes/statements/with/with-many-items.py +++ b/packages/openapi-python/src/ts-python/__snapshots__/nodes/statements/with/with-many-items.py @@ -1,19 +1,34 @@ class context_manager: def __enter__(self): return self - def __exit__(self, exc_type, exc_val, exc_tb): + def __exit__( + self, + exc_type, + exc_val, + exc_tb, + ): return False class context_manager2: def __enter__(self): return self - def __exit__(self, exc_type, exc_val, exc_tb): + def __exit__( + self, + exc_type, + exc_val, + exc_tb, + ): return False class context_manager3: def __enter__(self): return self - def __exit__(self, exc_type, exc_val, exc_tb): + def __exit__( + self, + exc_type, + exc_val, + exc_tb, + ): return False with context_manager() as alias, context_manager2() as (a, b), context_manager3(): diff --git a/packages/openapi-python/src/ts-python/__snapshots__/nodes/statements/with/with-tuple-alias.py b/packages/openapi-python/src/ts-python/__snapshots__/nodes/statements/with/with-tuple-alias.py index e4aabb343..0cec7ef71 100644 --- a/packages/openapi-python/src/ts-python/__snapshots__/nodes/statements/with/with-tuple-alias.py +++ b/packages/openapi-python/src/ts-python/__snapshots__/nodes/statements/with/with-tuple-alias.py @@ -1,7 +1,12 @@ class context_manager: def __enter__(self): return self - def __exit__(self, exc_type, exc_val, exc_tb): + def __exit__( + self, + exc_type, + exc_val, + exc_tb, + ): return False with context_manager() as (a, b): diff --git a/packages/openapi-python/src/ts-python/__snapshots__/nodes/statements/with/with.py b/packages/openapi-python/src/ts-python/__snapshots__/nodes/statements/with/with.py index 71bf5dba1..32e33f5d7 100644 --- a/packages/openapi-python/src/ts-python/__snapshots__/nodes/statements/with/with.py +++ b/packages/openapi-python/src/ts-python/__snapshots__/nodes/statements/with/with.py @@ -1,7 +1,12 @@ class context_manager: def __enter__(self): return self - def __exit__(self, exc_type, exc_val, exc_tb): + def __exit__( + self, + exc_type, + exc_val, + exc_tb, + ): return False with context_manager(): diff --git a/packages/openapi-python/src/ts-python/nodes/statement.ts b/packages/openapi-python/src/ts-python/nodes/statement.ts index 192a10dcd..16676a6da 100644 --- a/packages/openapi-python/src/ts-python/nodes/statement.ts +++ b/packages/openapi-python/src/ts-python/nodes/statement.ts @@ -1,5 +1,6 @@ import type { PyClassDeclaration } from './declarations/class'; import type { PyFunctionDeclaration } from './declarations/function'; +import type { PyFunctionParameter } from './declarations/functionParameter'; import type { PyAssignment } from './statements/assignment'; import type { PyAugmentedAssignment } from './statements/augmentedAssignment'; import type { PyBreakStatement } from './statements/break'; @@ -27,6 +28,7 @@ export type PyStatement = | PyExpressionStatement | PyForStatement | PyFunctionDeclaration + | PyFunctionParameter | PyIfStatement | PyImportStatement | PyRaiseStatement diff --git a/packages/openapi-python/src/ts-python/printer.ts b/packages/openapi-python/src/ts-python/printer.ts index 973b85995..caa01336b 100644 --- a/packages/openapi-python/src/ts-python/printer.ts +++ b/packages/openapi-python/src/ts-python/printer.ts @@ -5,6 +5,8 @@ export interface PyPrinterOptions { indentSize?: number; } +const PARAMS_MULTILINE_THRESHOLD = 3; + export function createPrinter(options?: PyPrinterOptions) { const indentSize = options?.indentSize ?? 4; @@ -178,16 +180,31 @@ export function createPrinter(options?: PyPrinterOptions) { } const modifiers = node.modifiers?.map(printNode).join(' ') ?? ''; const defPrefix = modifiers ? `${modifiers} def` : 'def'; - const parameters = node.parameters.map((parameter) => { + const formatParameter = (parameter: (typeof node.parameters)[number]): string => { const children: Array = [parameter.name]; if (parameter.annotation) children.push(`: ${printNode(parameter.annotation)}`); if (parameter.defaultValue) children.push(` = ${printNode(parameter.defaultValue)}`); return children.join(''); - }); + }; const returnAnnotation = node.returnType ? ` -> ${printNode(node.returnType)}` : ''; - parts.push( - printLine(`${defPrefix} ${node.name}(${parameters.join(', ')})${returnAnnotation}:`), - ); + const preParams = `${defPrefix} ${node.name}(`; + const postParams = `)${returnAnnotation}:`; + + if (node.parameters.length > PARAMS_MULTILINE_THRESHOLD) { + parts.push(printLine(preParams)); + indentLevel += 1; + const params = node.parameters.map((parameter) => + printLine(`${formatParameter(parameter)},`), + ); + parts.push(...params); + indentLevel -= 1; + parts.push(printLine(postParams)); + } else { + const parameters = node.parameters.map((parameter) => formatParameter(parameter)); + const params = parameters.join(', '); + parts.push(printLine(`${preParams}${params}${postParams}`)); + } + if (node.docstring) { indentLevel += 1; parts.push(...printDocstring(node.docstring)); diff --git a/packages/openapi-ts/src/ts-dsl/decl/param.ts b/packages/openapi-ts/src/ts-dsl/decl/param.ts index 63701291b..02f38c31b 100644 --- a/packages/openapi-ts/src/ts-dsl/decl/param.ts +++ b/packages/openapi-ts/src/ts-dsl/decl/param.ts @@ -9,10 +9,10 @@ import { ValueMixin } from '../mixins/value'; import { TokenTsDsl } from '../token'; import { TypeExprTsDsl } from '../type/expr'; -export type ParamCtor = ( - name: NodeName | ((p: ParamTsDsl) => void), - fn?: (p: ParamTsDsl) => void, -) => ParamTsDsl; +export type ParamName = NodeName | ParamFn; +export type ParamFn = (p: ParamTsDsl) => void; + +export type ParamCtor = (name: ParamName, fn?: ParamFn) => ParamTsDsl; const Mixed = DecoratorMixin( OptionalMixin(PatternMixin(ValueMixin(TsDsl))), @@ -23,7 +23,7 @@ export class ParamTsDsl extends Mixed { protected _type?: TypeTsDsl; - constructor(name: NodeName | ((p: ParamTsDsl) => void), fn?: (p: ParamTsDsl) => void) { + constructor(name: ParamName, fn?: ParamFn) { super(); if (typeof name === 'function') { name(this); diff --git a/packages/openapi-ts/src/ts-dsl/mixins/param.ts b/packages/openapi-ts/src/ts-dsl/mixins/param.ts index 286d41f3b..13eeb1be8 100644 --- a/packages/openapi-ts/src/ts-dsl/mixins/param.ts +++ b/packages/openapi-ts/src/ts-dsl/mixins/param.ts @@ -1,8 +1,8 @@ -import type { AnalysisContext, Node, NodeName } from '@hey-api/codegen-core'; +import type { AnalysisContext, Node } from '@hey-api/codegen-core'; import type ts from 'typescript'; import type { MaybeTsDsl } from '../base'; -import type { ParamCtor } from '../decl/param'; +import type { ParamCtor, ParamFn, ParamName } from '../decl/param'; import { ParamTsDsl } from '../decl/param'; import type { BaseCtor, MixinCtor } from './types'; @@ -26,10 +26,7 @@ export function ParamMixin>(Base: T } } - protected param( - name: NodeName | ((p: ParamTsDsl) => void), - fn?: (p: ParamTsDsl) => void, - ): this { + protected param(name: ParamName, fn?: ParamFn): this { const p = new ParamTsDsl(name, fn); this._params.push(p); return this; diff --git a/packages/openapi-ts/src/ts-dsl/type/param.ts b/packages/openapi-ts/src/ts-dsl/type/param.ts index a1aef2291..766f1424d 100644 --- a/packages/openapi-ts/src/ts-dsl/type/param.ts +++ b/packages/openapi-ts/src/ts-dsl/type/param.ts @@ -29,6 +29,7 @@ export class TypeParamTsDsl extends Mixed { ctx.analyze(this.defaultValue); } + /** Sets the parameter default value. */ default(value: TypeParamExpr): this { this.defaultValue = ref(value); return this; -- knotmirror 0.0.1