-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
migrate-stories-to-6-2.ts
406 lines (383 loc) · 13.2 KB
/
migrate-stories-to-6-2.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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
import {
applyChangesToString,
ChangeType,
formatFiles,
getProjects,
logger,
stripIndents,
Tree,
visitNotIgnoredFiles,
} from '@nrwl/devkit';
import { getTsSourceFile } from '@nrwl/storybook/src/utils/utilities';
import { fileExists } from '@nrwl/workspace/src/utilities/fileutils';
import { findNodes } from '@nrwl/workspace/src/utilities/typescript/find-nodes';
import { join, normalize } from 'path';
import { SyntaxKind } from 'typescript';
import ts = require('typescript');
export async function migrateStoriesTo62Generator(tree: Tree) {
let allComponentsWithStories: {
componentName: string;
componentPath: any;
componentFileName: any;
componentStoryPath: string;
}[] = [];
const result: {
name: string;
configFolder: string;
projectRoot: string;
projectSrc: string;
}[] = findAllAngularProjectsWithStorybookConfiguration(tree);
result?.forEach(
(angularProjectWithStorybook: {
name: string;
configFolder: string;
projectRoot: string;
projectSrc: string;
}) => {
const componentResult = findAllComponentsWithStoriesForSpecificProject(
tree,
angularProjectWithStorybook.projectRoot
);
allComponentsWithStories = [
...allComponentsWithStories,
...componentResult,
];
}
);
allComponentsWithStories?.forEach((componentInfo) => {
changeSyntaxOfStory(tree, componentInfo.componentStoryPath);
});
await formatFiles(tree);
}
export function findAllAngularProjectsWithStorybookConfiguration(tree: Tree): {
name: string;
configFolder: string;
projectRoot: string;
projectSrc: string;
}[] {
const projects = getProjects(tree);
const projectsThatHaveStorybookConfiguration: {
name: string;
configFolder: string;
projectRoot: string;
projectSrc: string;
}[] = [...projects.entries()]
?.filter(
([_, projectConfig]) =>
projectConfig?.targets?.storybook?.options?.uiFramework ===
'@storybook/angular'
)
?.map(([projectName, projectConfig]) => {
return {
name: projectName,
configFolder:
projectConfig.targets.storybook?.options?.config?.configFolder,
projectRoot: projectConfig.root,
projectSrc: projectConfig.sourceRoot,
};
});
return projectsThatHaveStorybookConfiguration;
}
function findAllComponentsWithStoriesForSpecificProject(
tree: Tree,
projectPath: string
): {
componentName: string;
componentPath: any;
componentFileName: any;
componentStoryPath: string;
}[] {
let moduleFilePaths = [] as string[];
visitNotIgnoredFiles(tree, projectPath, (filePath) => {
if (filePath?.endsWith('.module.ts')) {
moduleFilePaths.push(filePath);
}
});
let componentFileInfos = [];
moduleFilePaths?.map((moduleFilePath) => {
const file = getTsSourceFile(tree, moduleFilePath);
const ngModuleDecorators = findNodes(file, ts.SyntaxKind.Decorator);
if (ngModuleDecorators.length === 0) {
return;
}
const ngModuleDecorator = ngModuleDecorators[0];
const ngModuleNode = ngModuleDecorator?.getChildren()?.find((node) => {
return node?.getText()?.startsWith('NgModule');
});
const ngModulePropertiesObject = ngModuleNode
?.getChildren()
?.find((node) => {
return node.kind === SyntaxKind.SyntaxList;
});
const ngModuleProperties = ngModulePropertiesObject
?.getChildren()[0]
?.getChildren()
?.find((node) => {
return node?.getText()?.includes('declarations');
});
const declarationsPropertyAssignment = ngModuleProperties
?.getChildren()
?.find((node) => {
return node?.getText()?.startsWith('declarations');
});
if (!declarationsPropertyAssignment) {
logger.warn(stripIndents`No components declared in ${moduleFilePath}.`);
}
let declarationArray = declarationsPropertyAssignment
?.getChildren()
?.find((node) => node.kind === SyntaxKind.ArrayLiteralExpression);
if (!declarationArray) {
// Attempt to follow a variable instead of the literal
const declarationVariable = declarationsPropertyAssignment
?.getChildren()
?.filter((node) => node.kind === SyntaxKind.Identifier)[1];
const variableName = declarationVariable?.getText();
const variableDeclaration = findNodes(
file,
SyntaxKind.VariableDeclaration
)?.find((variableDeclaration) => {
const identifier = variableDeclaration
?.getChildren()
?.find((node) => node.kind === SyntaxKind.Identifier);
return identifier?.getText() === variableName;
});
if (variableDeclaration) {
declarationArray = variableDeclaration
?.getChildren()
?.find((node) => node.kind === SyntaxKind.ArrayLiteralExpression);
}
}
const declaredComponents = declarationArray
?.getChildren()
?.find((node) => node.kind === SyntaxKind.SyntaxList)
?.getChildren()
?.filter((node) => node.kind === SyntaxKind.Identifier)
?.map((node) => node?.getText())
?.filter((name) => name?.endsWith('Component'));
const imports = file.statements?.filter(
(statement) => statement.kind === SyntaxKind.ImportDeclaration
);
const modulePath = moduleFilePath.slice(
0,
moduleFilePath?.lastIndexOf('/')
);
let componentInfo = declaredComponents?.map((componentName) => {
try {
const importStatement = imports?.find((statement) => {
const namedImports = statement
?.getChildren()
?.find((node) => node.kind === SyntaxKind.ImportClause)
?.getChildren()
?.find((node) => node.kind === SyntaxKind.NamedImports);
if (namedImports === undefined) return false;
const importedIdentifiers = namedImports
?.getChildren()
?.find((node) => node.kind === SyntaxKind.SyntaxList)
?.getChildren()
?.filter((node) => node.kind === SyntaxKind.ImportSpecifier)
?.map((node) => node?.getText());
return importedIdentifiers?.includes(componentName);
});
const fullPath = importStatement
?.getChildren()
?.find((node) => node.kind === SyntaxKind.StringLiteral)
?.getText()
?.slice(1, -1);
// if it is a directory, search recursively for the component
let fullCmpImportPath = moduleFilePath?.slice(
0,
moduleFilePath?.lastIndexOf('/')
);
if (fullCmpImportPath?.startsWith('/')) {
fullCmpImportPath = fullCmpImportPath?.slice(
1,
fullCmpImportPath.length
);
}
let componentImportPath = join(normalize(fullCmpImportPath), fullPath);
let path = null;
let componentFileName = null;
let componentStoryPath = null;
let storyExists = false;
let componentExists = false;
/**
* Here we want to remove the <component-name>.component
* part of the path, to just keep the
* apps/<project-name>/src/app/<component-name>
* or
* libs/<project-name>/src/lib/<component-name>
* part of the path
*/
componentImportPath = componentImportPath.slice(
0,
componentImportPath.lastIndexOf('/')
);
visitNotIgnoredFiles(tree, componentImportPath, (componentFilePath) => {
if (componentFilePath?.endsWith('.ts')) {
const content = tree.read(componentFilePath).toString('utf-8');
if (content?.indexOf(`class ${componentName}`) > -1) {
componentExists = true;
path = componentFilePath;
componentFileName =
componentFilePath?.slice(
componentFilePath?.lastIndexOf('/') + 1,
componentFilePath?.lastIndexOf('.')
) + '.ts';
}
if (componentFilePath?.endsWith('.stories.ts')) {
componentStoryPath = componentFilePath;
storyExists = true;
}
}
});
if (!storyExists || !componentExists) {
path = null;
componentFileName = null;
componentStoryPath = null;
}
if (path !== null) {
return {
componentName: componentName,
componentPath: path,
componentFileName,
componentStoryPath: componentStoryPath,
};
} else {
const path = fullPath?.slice(0, fullPath?.lastIndexOf('/'));
const componentFileName =
fullPath?.slice(fullPath?.lastIndexOf('/') + 1) + '.ts';
componentStoryPath = fullPath + '.stories.ts';
if (fileExists(componentStoryPath)) {
return {
componentName: componentName,
componentPath: path + componentFileName,
componentFileName,
componentStoryPath: componentStoryPath,
};
} else {
return undefined;
}
}
} catch (e) {
logger.warn(`Could not find file for ${componentName}. Error: ${e}`);
return undefined;
}
});
if (componentInfo) {
componentInfo = componentInfo?.filter((info) => info !== undefined);
componentFileInfos = [...componentFileInfos, ...componentInfo];
}
});
return componentFileInfos;
}
async function changeSyntaxOfStory(tree: Tree, storyFilePath: string) {
const file = getTsSourceFile(tree, storyFilePath);
const appFileContent = tree.read(storyFilePath, 'utf-8');
let newContents = appFileContent;
const storiesVariableDeclaration = findNodes(file, [
ts.SyntaxKind.VariableDeclaration,
]);
const storiesExportDefault = findNodes(file, [
ts.SyntaxKind.ExportAssignment,
]);
const defaultExportNode = storiesExportDefault[0];
const defaultExportObject = defaultExportNode?.getChildren()?.find((node) => {
return node.kind === SyntaxKind.ObjectLiteralExpression;
});
const defaultPropertiesList = defaultExportObject
?.getChildren()
?.find((node) => {
return node.kind === SyntaxKind.SyntaxList;
});
const hasTitle = defaultPropertiesList?.getChildren()?.find((node) => {
return (
node.kind === SyntaxKind.PropertyAssignment &&
node.getText().startsWith('title')
);
});
/**
* A component node will look like this:
*
* component: MyTestComponent
*
* And this is what we need to remove.
*/
let firstComponentNode: ts.Node;
/**
* The result of ts.Node.getStart() will give us the index
* of that node in the whole original file.
* While we're editing that file, the getStart() will
* still reference the original file. So, during deletion,
* it would go and delete characters using the original index.
*
* We need to save the length of the characters that have been removed
* so far, so that we can substract it from the index.
* Since it's parsing the file linearly and in order, then this
* logic works.
* */
let lengthOfRemovalsSoFar = 0;
storiesVariableDeclaration?.forEach((oneStory) => {
const oneExportedStoryArrowFunction = oneStory
?.getChildren()
?.find((node) => {
return node.kind === SyntaxKind.ArrowFunction;
});
const inParenthesis = oneExportedStoryArrowFunction
?.getChildren()
?.find((node) => {
return node.kind === SyntaxKind.ParenthesizedExpression;
});
const objectLiteralOfStory = inParenthesis?.getChildren()?.find((node) => {
return node.kind === SyntaxKind.ObjectLiteralExpression;
});
const propertiesList = objectLiteralOfStory?.getChildren()?.find((node) => {
return node.kind === SyntaxKind.SyntaxList;
});
const hasComponentDeclared = propertiesList?.getChildren()?.find((node) => {
return (
node.kind === SyntaxKind.PropertyAssignment &&
node.getText().startsWith('component')
);
});
if (hasComponentDeclared) {
/**
* Here I am saving the first component to appear
* in the case where we have multiple stories
*/
if (!firstComponentNode) {
firstComponentNode = hasComponentDeclared;
}
/**
* Here we are performing the following check:
* If the component we will be adding in the default declaration
* which is the first component that we find
* is the same for this story as well,
* then remove it.
*/
if (hasComponentDeclared.getText() === firstComponentNode.getText()) {
const indexOfPropertyName = hasComponentDeclared.getStart();
const lengthOfRemoval = hasComponentDeclared?.getText()?.length + 1;
newContents = applyChangesToString(newContents, [
{
type: ChangeType.Delete,
start: indexOfPropertyName - lengthOfRemovalsSoFar,
length: lengthOfRemoval,
},
]);
lengthOfRemovalsSoFar = lengthOfRemovalsSoFar + lengthOfRemoval;
}
}
});
if (hasTitle && firstComponentNode) {
const indexOfPropertyName = hasTitle.getEnd();
newContents = applyChangesToString(newContents, [
{
type: ChangeType.Insert,
index: indexOfPropertyName + 2,
text: firstComponentNode.getText() + ',',
},
]);
tree.write(storyFilePath, newContents);
}
await formatFiles(tree);
}