-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_schemas.js
More file actions
executable file
·162 lines (149 loc) · 5.35 KB
/
generate_schemas.js
File metadata and controls
executable file
·162 lines (149 loc) · 5.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
#!/usr/bin/env node
import fs from "fs";
import path from "path";
import { glob } from "glob";
import process from "process";
import {
quicktype,
InputData,
JSONSchemaInput,
FetchingJSONSchemaStore,
} from "quicktype-core";
console.log("process.argv", process.argv);
var projectName = process.argv[2];
console.log("projectName", projectName);
var folderName = process.argv[3];
console.log("folderName", folderName);
var key = process.argv[4];
console.log("key", key);
var separator = process.argv[5];
console.log("separator", separator);
const findDirectoryPath = (targetDirectoryName, folderName) => {
const pathToCheck = path.join(
process.cwd(),
"/src",
"/",
targetDirectoryName
);
console.log("pathToCheck", pathToCheck);
const folders = fs
.readdirSync(pathToCheck, { withFileTypes: true })
.filter(
(folder) =>
folder.isDirectory() &&
!folder.name.endsWith(".egg-info") &&
folder.name != "tests" &&
folder.name != "__pycache__" &&
folder.name.includes(folderName)
)
.map((folder) => ({
name: folder.name,
path: path.join(pathToCheck, folder.name),
}));
console.log("folders", folders);
const routesDirectory = path.join(folders[0].path);
return routesDirectory;
};
const directoryPath = findDirectoryPath(projectName, folderName);
const outputFile = path.join(process.cwd(), `${projectName}_schemas.json`);
async function quicktypeJSONSchema(filename, jsonSchemaString) {
const schemaInput = new JSONSchemaInput(new FetchingJSONSchemaStore());
await schemaInput.addSource({ name: filename, schema: jsonSchemaString });
const inputData = new InputData();
inputData.addInput(schemaInput);
return await quicktype({
inputData,
lang: "python",
rendererOptions: { "just-types": true, "python-version": "3.7" },
});
}
function return_json_schema(directoryPath, folder_path, projectName) {
console.log("return_json_schema", directoryPath, folder_path, projectName);
const folders = fs
.readdirSync(path.normalize(directoryPath), { withFileTypes: true })
.filter((folder) => folder.isDirectory() && folder.name != "__pycache__")
.map((folder) => ({
name: folder.name,
path: path.join(directoryPath, folder.name),
}));
var folders_schemas = {};
folders.forEach((folder) => {
if (folder.name == "schemas") {
fs.readdirSync(folder.path)
.filter((f) => path.extname(f).toLowerCase() === ".py")
.forEach((f) => fs.unlinkSync(path.join(folder.path, f)));
const jsonFiles = glob.sync(path.join(folder.path, "**/*.json"));
var schemas = {};
let initContent = "";
jsonFiles.forEach(async (filePath) => {
try {
const fileContent = fs.readFileSync(filePath, "utf8");
var jsonData = JSON.parse(fileContent);
var filename = filePath
.replace(/^.*[\\/]/, "")
.replace(/\.[^/.]+$/, "");
var route = jsonData[key];
var values = [projectName, folder_path, route];
values = values.map(function (x) {
return x.replace("/", "").replace(".", "");
}); // first replace first . / by empty string
values = values.map(function (x) {
return x.replaceAll("/", separator).replaceAll(".", separator);
}); // then replace all . / by separator
console.log("values", values);
jsonData["$id"] = values
.filter(function (val) {
return val;
})
.join(separator);
schemas[filename] = jsonData;
initContent += "from ." + filename + " import *\n";
const { lines: jsonTypes } = await quicktypeJSONSchema(
filename,
fileContent
);
let pythonContent =
"from dataclasses_json import DataClassJsonMixin\n" +
jsonTypes.join("\n");
pythonContent = pythonContent.replace(
/@dataclass\nclass (\w+)(?:\s*\([^)]*\))?\s*:/g,
"@dataclass\nclass $1(DataClassJsonMixin):\n def __post_init__(self) -> None:\n print(self, flush=True)\n"
);
const pythonFile = path.join(folder.path, filename + ".py");
const initFile = path.join(folder.path, "__init__.py");
fs.writeFileSync(pythonFile, pythonContent);
fs.writeFileSync(initFile, initContent);
} catch (error) {
console.error(
`Erreur lors de la lecture du fichier ${filePath}:`,
error
);
}
});
folders_schemas = Object.keys(schemas).reduce((acc, key) => {
const currentSchema = schemas[key];
const modifiedSchema = {
$id: path.join(folder_path, currentSchema["$id"]),
...currentSchema,
};
acc[key] = modifiedSchema;
return acc;
}, folders_schemas);
} else {
var new_folder_path = folder_path + "/" + folder.name;
var test = return_json_schema(folder.path, new_folder_path, projectName);
folders_schemas[folder.name] = test;
}
});
return folders_schemas;
}
if (fs.existsSync(outputFile)) {
fs.unlinkSync(outputFile);
}
async function main() {
const finalJson = {};
finalJson[projectName] = return_json_schema(directoryPath, "", projectName);
console.log("FINAL", outputFile, finalJson);
fs.writeFileSync(outputFile, JSON.stringify(finalJson, null, 2));
}
main();