diff --git a/generate_schema_types.js b/generate_schema_types.js index fc6074d..978f7c9 100644 --- a/generate_schema_types.js +++ b/generate_schema_types.js @@ -10,7 +10,7 @@ import { fileURLToPath } from "node:url"; import { FetchingJSONSchemaStore, InputData, JSONSchemaInput, quicktype } from "quicktype-core"; // Local imports -import { inlineFieldComments, loadSchemaTypes } from "./schema_types.js"; +import { inlineFieldComments, loadSchemaTypes, withUnionOptionals } from "./schema_types.js"; const HEADER = "Generated by generate_schema_types.js from schema_types.json: do not edit"; const PYTHON_CLASS_PATTERN = /@dataclass\nclass (\w+)(?:\s*\([^)]*\))?\s*:/g; @@ -141,7 +141,6 @@ function aliases(names, schemaTypes, declaration, scalars, arrayOf) { } const MAX_LINE_LENGTH = 100; - // An import line as ruff formats it: one name per line when it is too long function formattedImport(line) { if (line.length <= MAX_LINE_LENGTH) { @@ -156,11 +155,10 @@ function formattedImport(line) { function pythonModule(classes, aliasDeclarations, sharedImports, layer, names) { const typingNames = (/^from typing import (.*)$/m.exec(classes)?.[1] ?? "") .split(", ") - .filter((name) => name && name !== "List"); - const body = classes - .replaceAll(/^(?:from|import) .*\n/gm, "") - .replaceAll(/\bList\[/g, "list[") - .trim(); + .filter((name) => name && name !== "List" && name !== "Optional"); + const body = withUnionOptionals( + classes.replaceAll(/^(?:from|import) .*\n/gm, "").replaceAll(/\bList\[/g, "list["), + ).trim(); // The imports of the dataclasses, when the package defines some const hasClasses = body.length > 0; const standardImports = [ diff --git a/generate_schemas.js b/generate_schemas.js index d826fa2..abfc97e 100755 --- a/generate_schemas.js +++ b/generate_schemas.js @@ -211,7 +211,10 @@ async function generatePythonFile(folderPath, filename, jsonData, fileContent) { } fs.writeFileSync( path.join(folderPath, filename + ".py"), - sharedTypes.useSharedPythonTypes(pythonContent), + sharedTypes.useSharedPythonTypes( + pythonContent, + new Set([quicktypeName(filename), quicktypeName(`${filename}_response`)]), + ), ); } diff --git a/schema_types.js b/schema_types.js index 8e246b3..d4efc8e 100644 --- a/schema_types.js +++ b/schema_types.js @@ -142,12 +142,40 @@ function unionKey(union) { } // The fields of a dataclass, whatever its typing style (List or list) +const OPTIONAL_PREFIX = "Optional["; + +// Each Optional[X] written X | None, X possibly holding brackets itself (e.g. Optional[list[GeodeId]]) +function withUnionOptionals(code) { + let result = code; + for ( + let start = result.indexOf(OPTIONAL_PREFIX); + start !== -1; + start = result.indexOf(OPTIONAL_PREFIX) + ) { + let depth = 1; + let end = start + OPTIONAL_PREFIX.length; + while (depth > 0 && end < result.length) { + if (result[end] === "[") { + depth += 1; + } else if (result[end] === "]") { + depth -= 1; + } + end += 1; + } + const inner = result.slice(start + OPTIONAL_PREFIX.length, end - 1); + result = `${result.slice(0, start)}${inner} | None${result.slice(end)}`; + } + return result; +} + function dataclassKey(body) { return body .split("\n") .map((line) => /^ {4}(\w+): (.+)$/.exec(line)) .filter((match) => match !== null) - .map(([, field, type]) => `${field}: ${type.replaceAll(/\bList\[/g, "list[")}`) + .map( + ([, field, type]) => `${field}: ${withUnionOptionals(type.replaceAll(/\bList\[/g, "list["))}`, + ) .toSorted() .join("\n"); } @@ -433,6 +461,13 @@ function loadSchemaTypes(packageDir) { ).map(({ name, layer, key }) => [name, { key, module: layer.pythonModule }]), ]); + // The shared Python dataclasses by their fields, when no other shared dataclass has the same ones + const pythonSharedByKey = new Map( + [...Map.groupBy([...pythonKeys], ([, { key }]) => key)] + .filter(([, sharedOfKey]) => sharedOfKey.length === 1) + .map(([key, [[name, { module }]]]) => [key, { name, module }]), + ); + // Removes the declarations of the shared types (each shared one of its declarations), renaming their uses // The kept names stay declared, as aliases of their shared type (e.g. a response that is a Point3D) function replaceDeclarations(content, declarations, sharedOf, used, keptNames = new Set()) { @@ -517,7 +552,8 @@ function loadSchemaTypes(packageDir) { // Quicktype declares its own Enum or dataclass for each shared type, named after its title: import the shared // One instead when it is the same type (the enums are Literal types, so the values stay plain strings) - function useSharedPythonTypes(content) { + // The kept names (the params and response classes of the route) are only matched by name, never by fields + function useSharedPythonTypes(content, keptNames = new Set()) { const used = []; const enums = (text) => [...text.matchAll(PYTHON_ENUM_PATTERN)].map(([declaration, name, body]) => ({ @@ -541,11 +577,14 @@ function loadSchemaTypes(packageDir) { }, used, ); + // Quicktype names a shared type used by several fields of a schema after each field (e.g. CornersColorClass + // For a ColorRGB): a dataclass not named like a shared type is still one when it has exactly its fields const sameType = ({ name, key }) => { const shared = pythonKeys.get(name); - return shared !== undefined && shared.key === key - ? { name, module: shared.module } - : undefined; + if (shared !== undefined) { + return shared.key === key ? { name, module: shared.module } : undefined; + } + return keptNames.has(name) ? undefined : pythonSharedByKey.get(key); }; let result = replaceDeclarations( withAliases, @@ -595,4 +634,4 @@ function loadSchemaTypes(packageDir) { }; } -export { inlineFieldComments, loadSchemaTypes }; +export { inlineFieldComments, loadSchemaTypes, withUnionOptionals };