-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerator.ts
44 lines (40 loc) · 1.35 KB
/
generator.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
import { readProjectConfiguration, Tree } from '@nx/devkit';
import { tsquery } from '@phenomnomnominal/tsquery';
import { TypeReferenceNode } from 'typescript';
/**
* Run the callback on all files inside the specified path
*/
function visitAllFiles(
tree: Tree,
path: string,
callback: (filePath: string) => void
) {
tree.children(path).forEach((fileName) => {
const filePath = `${path}/${fileName}`;
if (!tree.isFile(filePath)) {
visitAllFiles(tree, filePath, callback);
} else {
callback(filePath);
}
});
}
export default function (tree: Tree, schema: any) {
const sourceRoot = readProjectConfiguration(tree, schema.name).sourceRoot!;
visitAllFiles(tree, sourceRoot, (filePath) => {
const fileEntry = tree.read(filePath);
const contents = fileEntry?.toString();
// Check each `TypeReference` node to see if we need to replace it
const newContents = tsquery.replace(contents!, 'TypeReference', (node) => {
const trNode = node as TypeReferenceNode;
if (trNode.typeName.getText() === 'Array') {
const typeArgument = trNode.typeArguments?.[0];
return `${typeArgument?.getText()}[]`;
}
// return undefined does not replace anything
});
// only write the file if something has changed
if (newContents !== contents) {
tree.write(filePath, newContents);
}
});
}