Debian Codegraph @

merge/src/merge.ts

raw symbols SCIP
1 /* eslint-disable @typescript-eslint/no-use-before-define */
2 import {
3 Project,
4 ts,
5 SourceFile,
6 Node,
7 Symbol as TSMSymbol,
8 ArrayLiteralExpression,
9 ObjectLiteralExpression,
10 Expression,
11 ObjectLiteralElementLike,
12 ExportAssignment,
13 } from "ts-morph";
14 import * as prettier from "prettier";
15 import { defaultPreset, presets } from "./presets";
16 import type { PresetName, Preset } from "./presets";
17 import { Errors } from "./errors";
18
19 const project = new Project();
20
21 function parseFile(filePath: string, input: string): SourceFile {
22 return project.createSourceFile(filePath, input, { overwrite: true });
23 }
24
25 function setupFile(
26 path: string,
27 file: string,
28 getDefaultExport?: true
29 ): [sourceFile: SourceFile, defaultExport: TSMSymbol];
30 function setupFile(path: string, file: string, getDefaultExport: false): [sourceFile: SourceFile];
31 function setupFile(path: string, file: string, getDefaultExport = true) {
32 const sourceFile = parseFile(path, file);
33 if (getDefaultExport) {
34 const sourceFileDefaultExport = sourceFile.getDefaultExportSymbol();
35 if (!sourceFileDefaultExport) throw Errors.MissingDefaultExport(path);
36 return [sourceFile, sourceFileDefaultExport];
37 }
38 return [sourceFile];
39 }
40
41 function isSpecObject(statement: Node<ts.Statement>, name: string): boolean {
42 if (Node.isVariableStatement(statement)) {
43 const declarations = statement.getDeclarationList().getDeclarations();
44 return declarations.some((declaration) => declaration.getName() === name);
45 }
46 return false;
47 }
48
49 /**
50 * @returns {ts.Node[]} the node path of the specified node, it should be read from the end to the start
51 */
52 // TODO: find a way to avoid recalculating this every time. It may be expensive for complex specs
53 function generateNodePath(node: ts.PropertyAssignment | ts.ShorthandPropertyAssignment): ts.Node[] {
54 let currentNode: ts.Node = node;
55 const path: ts.Node[] = [];
56 do {
57 path.push(currentNode);
58 currentNode = currentNode.parent;
59 } while (!ts.isVariableDeclaration(currentNode));
60 return path;
61 }
62
63 function compareObjectLiteralElementLike(
64 nodeA: ts.ObjectLiteralElementLike,
65 nodeB: ObjectLiteralElementLike
66 ): boolean {
67 if (nodeA.kind !== nodeB.getKind()) return false;
68 if (Node.isPropertyAssignment(nodeB)) {
69 return expressionsAreEqual(
70 (nodeA as ts.PropertyAssignment).initializer,
71 nodeB.getInitializer()
72 );
73 }
74 // true for ShorthandPropertyAssignment, SpreadAssignment
75 return true;
76 }
77
78 /**
79 * Checks if A is a literal contained in B (ArrayLiteral)
80 * @param expressionA
81 * @param expressionB
82 */
83 function expressionAIsSubsetOfB(expressionA?: ts.Expression, expressionB?: ts.Expression): boolean {
84 if (!expressionA || !expressionB) return false;
85 if (
86 expressionB.kind === ts.SyntaxKind.ArrayLiteralExpression &&
87 (expressionA.kind === ts.SyntaxKind.StringLiteral ||
88 expressionA.kind === ts.SyntaxKind.NoSubstitutionTemplateLiteral ||
89 expressionA.kind === ts.SyntaxKind.NumericLiteral)
90 ) {
91 const expressionAText = expressionA.getText();
92 return (expressionB as ts.ArrayLiteralExpression).elements.some(
93 (node) => node.getText() === expressionAText
94 );
95 }
96 return false;
97 }
98
99 function expressionsAreEqual(
100 expressionA?: ts.Expression,
101 expressionB?: Expression<ts.Expression>
102 ): boolean {
103 if (!expressionA || !expressionB) return false;
104 if (expressionA.kind !== expressionB.getKind()) return false;
105 if (Node.isArrayLiteralExpression(expressionB)) {
106 const elementsA = (expressionA as ts.ArrayLiteralExpression).elements;
107 const elementsB = expressionB.getElements();
108 return (
109 elementsA.length === elementsB.length &&
110 elementsA.every((element, index) => expressionsAreEqual(element, elementsB[index]))
111 );
112 }
113 if (
114 Node.isStringLiteral(expressionB) ||
115 Node.isNoSubstitutionTemplateLiteral(expressionB) ||
116 Node.isNumericLiteral(expressionB)
117 ) {
118 // @ts-expect-error
119 return expressionB.getLiteralText() === expressionA.text;
120 }
121 if (Node.isObjectLiteralExpression(expressionB)) {
122 const propertiesA = (expressionA as ts.ObjectLiteralExpression).properties;
123 const propertiesB = expressionB.getProperties();
124 return (
125 propertiesA.length === propertiesB.length &&
126 propertiesA.every((property, index) => {
127 const propertyText = property.name?.getText();
128 // if the properties at the same index has the same name we avoid an useless search
129 if (propertyText === propertiesB[index].compilerNode.name?.getText()) {
130 return compareObjectLiteralElementLike(property, propertiesB[index]);
131 }
132 // otherwise we need to search an eventual property with the same name
133 const foundProperty = propertiesB.find(
134 (prop) => propertyText === prop.compilerNode.name?.getText()
135 );
136 if (!foundProperty) return false;
137 return compareObjectLiteralElementLike(property, foundProperty);
138 })
139 );
140 }
141 // fallback for all other nodes that should just have the same kind e.g. FalseNode and TrueNode
142 return true;
143 }
144
145 function resolveArrayLiteral(path: ts.Node[], arrayNode: ArrayLiteralExpression): Node | undefined {
146 const newPath = path.slice(0, -1);
147 const currentPathItem = newPath[newPath.length - 1];
148 const elements = arrayNode.getElements();
149
150 // The assertion below is an identity, we just use it for type casting
151 if (ts.isObjectLiteralExpression(currentPathItem)) {
152 // Check if the object has a name property and get its value
153 const nameToFind = currentPathItem.properties.filter(
154 (prop): prop is ts.PropertyAssignment =>
155 ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name) && prop.name.text === "name"
156 )[0]?.initializer;
157
158 if (nameToFind) {
159 for (const element of elements) {
160 if (Node.isObjectLiteralExpression(element)) {
161 const nameProp = element.getProperty("name");
162 if (nameProp && Node.isPropertyAssignment(nameProp)) {
163 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
164 const initializer = nameProp.getInitializer()!; // getInitializer on PropertyAssignment never returns undefined
165 if (
166 expressionsAreEqual(nameToFind, initializer) ||
167 // if nameToFind is StringLiteral and initializer is ArrayLiteralExpression
168 // e.g. '--name' and ['--name', '-n']
169 expressionAIsSubsetOfB(nameToFind, initializer.compilerNode) ||
170 expressionAIsSubsetOfB(initializer.compilerNode, nameToFind)
171 ) {
172 return resolve(newPath, element);
173 }
174 }
175 }
176 }
177 } else {
178 // check which is the index of currentPathItem in the parent ArrayExpression
179 const foundIndex = (currentPathItem.parent as ts.ArrayLiteralExpression).elements.findIndex(
180 (arrayElement) => arrayElement === currentPathItem
181 );
182 const element = elements[foundIndex];
183 if (element && Node.isObjectLiteralExpression(element)) {
184 return resolve(newPath, element);
185 }
186 }
187 }
188 return undefined;
189 }
190
191 function resolveObjectLiteral(
192 path: ts.Node[],
193 objectNode: ObjectLiteralExpression
194 ): Node | undefined {
195 const newPath = path.slice(0, -1);
196 const currentPathItem = newPath[newPath.length - 1];
197 // expect child item of an ObjectLiteral to be a PropertyAssignment
198 if (!(ts.isPropertyAssignment(currentPathItem) && ts.isIdentifier(currentPathItem.name))) {
199 return undefined;
200 }
201 const propNameToFind = currentPathItem.name.text;
202 const props = objectNode.getProperties();
203 for (const prop of props) {
204 if (Node.isPropertyAssignment(prop) && prop.getName() === propNameToFind) {
205 // if there is a matching prop and this is the last one item of the path return the prop.
206 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
207 return resolve(newPath.slice(0, -1), prop.getInitializer()!); // getInitializer on PropertyAssignment never returns undefined
208 }
209 }
210 if (newPath.length === 1) {
211 // if the last property of the path is only in the old spec (still needs to be added to the new one)
212 return objectNode;
213 }
214 return undefined;
215 }
216
217 // The first item of a path is always a PropertyAssignment (the first is effectively the last item, the one we are looking for)
218 function resolve(path: ts.Node[], baseNode: Node): Node | undefined {
219 if (!path.length) return baseNode;
220
221 const currentItem = path[path.length - 1];
222 if (ts.isObjectLiteralExpression(currentItem) && Node.isObjectLiteralExpression(baseNode)) {
223 return resolveObjectLiteral(path, baseNode);
224 }
225 if (ts.isArrayLiteralExpression(currentItem) && Node.isArrayLiteralExpression(baseNode)) {
226 return resolveArrayLiteral(path, baseNode);
227 }
228 return undefined;
229 }
230
231 function resolveAndUpdateNodePath(
232 path: ts.Node[],
233 newSpec: SourceFile,
234 nodeToAdd: { name: string; initializer: string },
235 newFileName: string
236 ): boolean {
237 // TODO: we currently assume we have just one declaration in the new file since it should be autogenerated by some kind of tool
238 const statement = newSpec.getFirstDescendantByKind(ts.SyntaxKind.VariableDeclaration);
239 if (!statement) throw Errors.MissingSpecVariableDeclaration(newFileName);
240
241 const statementInitializer = statement.getInitializer();
242 if (statementInitializer && Node.isObjectLiteralExpression(statementInitializer)) {
243 const out = resolve(path, statementInitializer);
244 if (out && Node.isObjectLiteralExpression(out)) {
245 out.addPropertyAssignment(nodeToAdd);
246 return true;
247 }
248 // if Node.isPropertyAssignement(out) -> the property already exist at the specified path. We keep the updated one.
249 return false;
250 }
251 throw Errors.MissingSpecVariableDeclaration(newFileName);
252 }
253
254 function getFirstParentProperty(nodePath: ts.Node[]): ts.PropertyAssignment | undefined {
255 let i = 1; // exclude the first element as we know it is a property (the leaf property)
256 while (i <= nodePath.length - 1) {
257 const node = nodePath[i];
258 if (ts.isPropertyAssignment(node)) {
259 return node;
260 }
261 i += 1;
262 }
263 return undefined;
264 }
265
266 function getObservedSet(
267 updatable: Preset,
268 parentProperty?: ts.PropertyAssignment
269 ): Set<string> | undefined {
270 if (!parentProperty) return updatable.commandProps; // we are handling a top-level command
271 if (ts.isIdentifier(parentProperty.name)) {
272 const parentPropText = parentProperty.name.text;
273 // eslint-disable-next-line no-nested-ternary
274 return parentPropText === "subcommands"
275 ? updatable.commandProps
276 : parentPropText === "options"
277 ? updatable.optionProps
278 : updatable.argProps; // parentPropText === "args"
279 }
280 return undefined;
281 }
282
283 // `statement` can only be one of the top-level statements
284 function traverseSpecs(
285 statement: Node<ts.Statement>,
286 destination: SourceFile,
287 updatableProps: Preset,
288 newFileName: string
289 ) {
290 statement.transform((traversal) => {
291 const node = traversal.visitChildren();
292 if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name)) {
293 const nodePath = generateNodePath(node);
294 const parentProperty = getFirstParentProperty(nodePath);
295 const observedSet = getObservedSet(updatableProps, parentProperty);
296 if (observedSet && !observedSet.has(node.name.text)) {
297 resolveAndUpdateNodePath(
298 nodePath,
299 destination,
300 {
301 name: node.name.text,
302 initializer: node.initializer.getText(),
303 },
304 newFileName
305 );
306 }
307 }
308 return node;
309 });
310 }
311
312 export interface MergeOptions {
313 ignore?: {
314 commandProps?: string[];
315 optionProps?: string[];
316 argProps?: string[];
317 commonProps?: string[];
318 };
319 preset?: PresetName;
320 prettifyOutput?: boolean;
321 oldFileName?: string;
322 newFileName?: string;
323 }
324
325 function getPreset({ preset, ignore = {} }: MergeOptions): Preset {
326 // Props updated by the eventual CLI tool integration (preset)
327 let updatableProps = preset ? presets[preset] : undefined;
328 // If no preset was specified we default to the defaultPreset adding all props the user ignored
329 if (!updatableProps) {
330 updatableProps = defaultPreset();
331 const { commandProps = [], optionProps = [], argProps = [], commonProps = [] } = ignore;
332 for (const commandProp of commandProps) {
333 updatableProps.commandProps.add(commandProp);
334 }
335 for (const optionProp of optionProps) {
336 updatableProps.optionProps.add(optionProp);
337 }
338 for (const argProp of argProps) {
339 updatableProps.argProps.add(argProp);
340 }
341 for (const commonProp of commonProps) {
342 updatableProps.commandProps.add(commonProp);
343 updatableProps.optionProps.add(commonProp);
344 updatableProps.argProps.add(commonProp);
345 }
346 }
347 return updatableProps;
348 }
349
350 export async function merge(
351 oldFileContent: string,
352 newFileContent: string,
353 options: MergeOptions
354 ): Promise<string> {
355 const oldFileName = options.oldFileName ?? "oldfile.ts";
356 const newFileName = options.newFileName ?? "newfile.ts";
357
358 const updatableProps = getPreset(options);
359
360 const [oldSourceFile, oldSourceFileDefaultExport] = setupFile(oldFileName, oldFileContent);
361 const [newSourceFile] = setupFile(newFileName, newFileContent, false);
362 /// MARK: Work on old source file by extracting top level statements
363 let specNodeName: string;
364 // It should contain exactly one declaration since it is a default export
365 const exportDeclaration = oldSourceFileDefaultExport.getDeclarations()[0] as ExportAssignment;
366 const exportDeclarationExpression = exportDeclaration.getExpression();
367 if (Node.isIdentifier(exportDeclarationExpression)) {
368 specNodeName = exportDeclarationExpression.getText();
369 } else if (Node.isObjectLiteralExpression(exportDeclarationExpression)) {
370 throw Errors.NoDirectDefaultExport(oldFileName);
371 } else {
372 throw Errors.DefaultExportShouldBeAnIdentifier(oldFileName);
373 }
374
375 const diffTopLevelNodes: [start: string, middle: string, end: string] = ["", "", ""];
376 const statements = oldSourceFile.getStatements();
377 let state = 0;
378 for (const statement of statements) {
379 if (isSpecObject(statement, specNodeName)) {
380 traverseSpecs(statement, newSourceFile, updatableProps, newFileName);
381 state += 1;
382 } else if (statement === exportDeclaration) {
383 state += 1;
384 } else {
385 diffTopLevelNodes[state] += statement.print();
386 }
387 }
388
389 /// MARK: Save top level statements of the old file to the new source file
390 newSourceFile.insertStatements(2, diffTopLevelNodes[2]);
391 newSourceFile.insertStatements(1, diffTopLevelNodes[1]);
392 newSourceFile.insertStatements(0, diffTopLevelNodes[0]);
393
394 const outputFile = ts.createPrinter().printFile(newSourceFile.compilerNode);
395 if (options.prettifyOutput ?? true) {
396 return prettier.format(outputFile, { parser: "typescript" });
397 }
398 return outputFile;
399 }