-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathlist-duplicates.ts
executable file
·382 lines (366 loc) · 11.3 KB
/
list-duplicates.ts
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
#!/bin/env -S ghjk deno run -A
// Copyright Metatype OÜ, licensed under the Mozilla Public License Version 2.0.
// SPDX-License-Identifier: MPL-2.0
/**
* Usage:
* deno run -A tools/list-duplicates.ts [<options>] <file.py>
*
* Options:
* --root <N> The index of the root type
* Default: 0
*/
import { green, objectHash, parseArgs, red } from "./deps.ts";
// FIXME: import from @metatype/typegate
import type { TypeGraphDS } from "../src/typegate/src/typegraph/mod.ts";
import { visitType } from "../src/typegate/src/typegraph/visitor.ts";
import { projectDir } from "./utils.ts";
import { TypeNode } from "../src/typegate/src/typegraph/type_node.ts";
// Tries to detect structurally equivalent duplicates by iteratively
// updating composite types to refer to deduped types.
// I.e. optional<A> and optional<B> should be considered duplicates
// if A and B are duplicates of each other.
// This function is not perfect and is not able to detect some
// forms of structural equivalence. Additions to the TypeNode might
// break it.
export function listDuplicatesEnhanced(tg: TypeGraphDS, _rootIdx = 0) {
// to <- from
const reducedSetMap = new Map<number, number[]>();
const reducedSet = new Set<number>();
let cycleNo = 0;
const globalKindCounts = {} as Record<string, number>;
const dupeKindCount = {} as Record<string, number>;
while (true) {
cycleNo += 1;
const bins = new Map<string, [number, TypeNode][]>();
const edges = new Map<number, number[]>();
const revEdges = new Map<number, number[]>();
const addToRevEdges = (of: number, idx: number) => {
const prev = revEdges.get(of);
if (prev) {
prev.push(idx);
} else {
revEdges.set(of, [idx]);
}
};
let visitedTypesCount = 0;
{
let idx = -1;
for (const type of tg.types) {
idx += 1;
if (reducedSet.has(idx)) {
continue;
}
visitedTypesCount += 1;
const { title: _title, description: _description, ...structure } = type;
if (cycleNo == 1) {
incrementKindCount(type, globalKindCounts);
}
// deno-lint-ignore no-explicit-any
const hash = objectHash(structure as any);
{
const prev = bins.get(hash);
if (prev) {
prev.push([idx, type] as const);
} else {
bins.set(hash, [[idx, type]]);
}
}
switch (structure.type) {
case "function":
edges.set(idx, [structure.input, structure.output]);
addToRevEdges(structure.input, idx);
addToRevEdges(structure.output, idx);
break;
case "object":
edges.set(idx, Object.values(structure.properties));
for (const dep of Object.values(structure.properties)) {
addToRevEdges(dep, idx);
}
break;
case "either":
edges.set(idx, structure.oneOf);
for (const dep of structure.oneOf) {
addToRevEdges(dep, idx);
}
break;
case "union":
edges.set(idx, structure.anyOf);
for (const dep of structure.anyOf) {
addToRevEdges(dep, idx);
}
break;
case "list":
edges.set(idx, [structure.items]);
addToRevEdges(structure.items, idx);
break;
case "optional":
edges.set(idx, [structure.item]);
addToRevEdges(structure.item, idx);
break;
case "boolean":
case "string":
case "file":
case "integer":
case "float":
// case "any":
break;
default:
throw new Error(`unsupported type: ${type.type}`);
}
}
}
const dedupIndices = new Map<number, number>();
let cycleDupesFound = 0;
let cycleDupeBinsFound = 0;
for (const [_hash, bin] of bins.entries()) {
if (bin.length > 1) {
cycleDupeBinsFound += 1;
cycleDupesFound += bin.length;
const dedupedIdx = bin[0][0];
const set = reducedSetMap.get(dedupedIdx) ?? [];
for (const [idx, _type] of bin.slice(1)) {
const removed = reducedSetMap.get(idx);
if (removed) {
reducedSetMap.delete(idx);
set.push(...removed);
}
set.push(idx);
reducedSet.add(idx);
dedupIndices.set(idx, dedupedIdx);
}
reducedSetMap.set(dedupedIdx, set);
}
}
if (cycleDupeBinsFound == 0) {
break;
}
console.log("reducing dupe bins", {
cycleDupesFound,
cycleDupeBinsFound,
reducedSetCount: reducedSet.size,
visitedTypesCount,
cycleNo,
});
for (const [from, to] of dedupIndices) {
const itemsToUpdate = revEdges.get(from) ?? [];
for (const targetIdx of itemsToUpdate) {
const type = tg.types[targetIdx];
const noMatchError = () => {
console.log("no match on dupe reduction", {
from: tg.types[from],
to: tg.types[to],
target: type,
});
return Error("no match on dupe reduction");
};
switch (type.type) {
case "function":
if (type.input == from) {
type.input = to;
} else if (type.output == from) {
type.output = to;
} else {
throw noMatchError();
}
break;
case "object": {
let updated = false;
for (const [key, id] of Object.entries(type.properties)) {
if (id == from) {
type.properties[key] = to;
updated = true;
break;
}
}
if (!updated) {
throw noMatchError();
}
break;
}
case "either": {
const updateIdx = type.oneOf.indexOf(from);
if (updateIdx == -1) {
throw noMatchError();
}
type.oneOf[updateIdx] = to;
break;
}
case "union": {
const updateIdx = type.anyOf.indexOf(from);
if (updateIdx == -1) {
throw noMatchError();
}
type.anyOf[updateIdx] = to;
break;
}
case "list":
type.items = to;
break;
case "optional":
type.item = to;
break;
case "boolean":
case "string":
case "file":
case "integer":
case "float":
throw new Error("impossible");
default:
throw new Error(`unsupported type: ${type.type}`);
}
}
}
}
const sortedDupes = [] as [number, number][];
for (const [toIdx, bin] of reducedSetMap.entries()) {
if (bin.length > 1) {
sortedDupes.push([toIdx, bin.length]);
const toType = tg.types[toIdx];
incrementKindCount(toType, dupeKindCount);
// console.log(`${cyan(toType.title)}`);
for (const fromIdx of bin) {
const fromType = tg.types[fromIdx];
incrementKindCount(fromType, dupeKindCount);
/* const injection = "injection" in fromType
// deno-lint-ignore no-explicit-any
? ` (injection ${(fromType.injection as any).source})`
: "";
console.log(
` ${
green(fromIdx.toString())
} ${fromType.type}:${fromType.title}${injection}`,
); */
}
}
}
sortedDupes.sort((a, b) => a[1] - b[1]);
const dupesBinsFound = sortedDupes.length;
const dupesFound = sortedDupes
.map(([_rootIdx, count]) => count)
.reduce((a, b) => a + b);
console.log(
`${green("dupeCount")} kind:selected dedup root title`,
);
for (const [rootIdx, count] of sortedDupes) {
const type = tg.types[rootIdx];
console.log(
`${green(count.toString()) + "dupes"} ${type.type}:${type.title}`,
);
}
console.log(
`${green("dupeCount")} kind:selected dedup root title`,
);
console.log("that's it folks!", {
globalKindCounts,
dupeKindCount,
dupesFound,
dupesBinsFound,
totalCycles: cycleNo,
tgSize: tg.types.length,
});
}
function incrementKindCount(type: TypeNode, sumMap: Record<string, number>) {
if (type.title.match(/_where_/)) {
const key = "prismaWhereFilterRelated";
sumMap[key] = (sumMap[key] ?? 0) + 1;
}
if (type.title.match(/_update_input/)) {
const key = "prismaUpdateInputRelated";
sumMap[key] = (sumMap[key] ?? 0) + 1;
}
if (type.title.match(/_create_input/)) {
const key = "prismaCreateInputRelated";
sumMap[key] = (sumMap[key] ?? 0) + 1;
}
if (type.title.match(/_output/)) {
const key = "prismaOutputRelated";
sumMap[key] = (sumMap[key] ?? 0) + 1;
}
sumMap[type.type] = (sumMap[type.type] ?? 0) + 1;
}
export function listDuplicates(tg: TypeGraphDS, rootIdx = 0) {
const bins = new Map<string, readonly [number, TypeNode][]>();
const duplicateNameBins = new Map<string, readonly [number, TypeNode][]>();
visitType(tg, rootIdx, ({ type, idx }) => {
const { title, description: _description, ...structure } = type;
// deno-lint-ignore no-explicit-any
const hash = objectHash(structure as any);
bins.set(hash, [...bins.get(hash) ?? [], [idx, type] as const]);
duplicateNameBins.set(title, [
...duplicateNameBins.get(title) ?? [],
[idx, type] as const,
]);
return true;
}, { allowCircular: false });
let dupesBinsFound = 0;
let dupesFound = 0;
for (const [_hash, bin] of bins.entries()) {
if (bin.length > 1) {
dupesBinsFound += 1;
dupesFound += bin.length;
/* console.log(`${cyan(hash)}`);
for (const [idx, type] of bin) {
const injection = "injection" in type
? ` (injection ${(type.injection as any).source})`
: "";
console.log(
` ${green(idx.toString())} ${type.type}:${type.title}${injection}`,
);
}
*/
}
}
console.log({ dupesFound, dupesBinsFound });
for (const [hash, bin] of duplicateNameBins.entries()) {
if (bin.length > 1) {
console.log(`${red(hash)}`);
for (const [idx, type] of bin) {
const injection = "injection" in type
// deno-lint-ignore no-explicit-any
? ` (injection ${(type.injection as any).source})`
: "";
console.log(
` ${green(idx.toString())} ${type.type}:${type.title}${injection}`,
);
}
}
}
}
const args = parseArgs(Deno.args, {
string: ["root"],
});
const rootIdx = argToInt(args.root, 0);
const files = args._ as string[];
if (files.length === 0) {
throw new Error("Path to typegraph definition module is required.");
}
if (files.length > 1) {
throw new Error("Cannot accept more than one file");
}
const cmd = [
"cargo",
"run",
"--manifest-path",
`${projectDir}/Cargo.toml`,
"-p",
"meta-cli",
"--",
"serialize",
"-f",
files[0],
];
const { stdout } = await new Deno.Command(cmd[0], {
args: cmd.slice(1),
stdout: "piped",
stderr: "inherit",
}).output();
const tgs: TypeGraphDS[] = JSON.parse(
new TextDecoder().decode(stdout),
);
for (const tg of tgs) {
listDuplicatesEnhanced(tg, rootIdx);
}
function argToInt(arg: string | undefined, defaultValue: number): number {
const parsed = parseInt(arg ?? `${defaultValue}`);
return isNaN(parsed) ? defaultValue : parsed;
}