Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 5 additions & 7 deletions generate_schema_types.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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) {
Expand All @@ -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 = [
Expand Down
5 changes: 4 additions & 1 deletion generate_schemas.js
Original file line number Diff line number Diff line change
Expand Up @@ -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`)]),
),
);
}

Expand Down
51 changes: 45 additions & 6 deletions schema_types.js
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}
Expand Down Expand Up @@ -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()) {
Expand Down Expand Up @@ -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]) => ({
Expand All @@ -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,
Expand Down Expand Up @@ -595,4 +634,4 @@ function loadSchemaTypes(packageDir) {
};
}

export { inlineFieldComments, loadSchemaTypes };
export { inlineFieldComments, loadSchemaTypes, withUnionOptionals };
Loading