-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrunner.ts
More file actions
260 lines (231 loc) · 7.26 KB
/
runner.ts
File metadata and controls
260 lines (231 loc) · 7.26 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
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
import * as fs from 'fs/promises';
import * as path from 'path';
import type {
CliOptions,
MigrationSummary,
TransformResult,
ValidationError,
} from './types';
import type { Logger } from './utils/logger';
import type { TransformInfo } from './transforms';
import { createFileProcessor, type FileInfo } from './utils/file-processor';
/**
* Run the transformation on the target path
*/
export async function runTransform(
targetPath: string,
transformInfo: TransformInfo,
options: CliOptions,
logger: Logger
): Promise<MigrationSummary> {
// Load the transform module dynamically
const transformModule = await import(transformInfo.path);
const applyTransform = transformModule.applyTransform;
if (!applyTransform) {
throw new Error(
`Transform ${transformInfo.name} does not export applyTransform function`
);
}
// Step 1: Discover files
logger.startSpinner('Discovering files..');
const fileProcessor = createFileProcessor({
extensions: ['.ts', '.tsx'],
ignorePatterns: ['**/node_modules/**', '**/dist/**', '**/*.d.ts'],
});
const allFiles = await fileProcessor.discoverFiles(targetPath);
logger.succeedSpinner(`Found ${allFiles.length} files`);
// Step 2: Transform files
logger.section('🔄 Transforming files...');
const results: TransformResult[] = [];
let filesTransformed = 0;
let totalErrors = 0;
let totalWarnings = 0;
let sourceFilesCount = 0;
for (const fileInfo of fileProcessor.filterSourceFiles(allFiles)) {
sourceFilesCount++;
const result = await transformFile(
fileInfo,
applyTransform,
options,
logger
);
results.push(result);
if (result.transformed) {
filesTransformed++;
}
totalErrors += result.errors.length;
totalWarnings += result.warnings.length;
}
// Check if any files were found
if (sourceFilesCount === 0) {
logger.warnSpinner('No source framework files found');
logger.info(
'No files contain source framework imports. Migration not needed.'
);
return createEmptySummary();
}
logger.succeedSpinner(
`${sourceFilesCount} files contain source framework imports`
);
logger.subsection(
`${allFiles.length - sourceFilesCount} files skipped (no source imports)`
);
logger.newline();
// Step 3: Report summary
logger.newline();
logger.section('📊 Migration Summary');
if (filesTransformed > 0) {
logger.success(
`${filesTransformed} file${
filesTransformed > 1 ? 's' : ''
} transformed successfully`
);
}
if (sourceFilesCount - filesTransformed > 0) {
logger.info(
` ${sourceFilesCount - filesTransformed} file${
sourceFilesCount - filesTransformed > 1 ? 's' : ''
} skipped (no changes needed)`
);
}
if (totalWarnings > 0) {
logger.warn(
`${totalWarnings} warning${totalWarnings > 1 ? 's' : ''} found`
);
}
if (totalErrors > 0) {
logger.error(`${totalErrors} error${totalErrors > 1 ? 's' : ''} found`);
}
// Show detailed results if verbose
if (options.verbose) {
logger.newline();
logger.subsection('Detailed Results:');
results.forEach((result) => {
if (result.transformed) {
logger.success(` ${result.filePath}`);
result.changes.forEach((change) => logger.debug(` - ${change}`));
}
if (result.warnings.length > 0) {
result.warnings.forEach((warning) => logger.warn(` ${warning}`));
}
if (result.errors.length > 0) {
result.errors.forEach((error) => logger.error(` ${error}`));
}
});
}
return {
filesProcessed: sourceFilesCount,
filesTransformed,
filesSkipped: sourceFilesCount - filesTransformed,
errors: totalErrors,
warnings: totalWarnings,
results,
};
}
/**
* Transform a single file
*/
async function transformFile(
fileInfo: FileInfo,
applyTransform: (
source: string,
options?: { skipValidation?: boolean; parser?: string }
) => any,
options: CliOptions,
logger: Logger
): Promise<TransformResult> {
const result: TransformResult = {
filePath: fileInfo.path,
transformed: false,
changes: [],
warnings: [],
errors: [],
};
try {
// Note: Preprocessing has been disabled because the parser fallback strategy
// now uses ts/tsx parsers first, which handle TypeScript syntax correctly.
// The preprocessing was breaking valid TypeScript generic syntax like:
// unitRef.get<ChargeService>(ChargeService)
// into invalid syntax:
// unitRef.get((ChargeService) as ChargeService)
//
// If preprocessing is needed for specific edge cases, it should be done
// more carefully to avoid breaking valid TypeScript patterns.
// Apply transformation
const transformOutput = applyTransform(fileInfo.source, {
parser: options.parser,
});
// Check if code actually changed
if (transformOutput.code === fileInfo.source) {
logger.debug(
` ⊘ ${path.relative(process.cwd(), fileInfo.path)} (no changes)`
);
return result;
}
result.transformed = true;
// Collect validation errors and warnings
transformOutput.validation.errors.forEach((err: ValidationError) => {
result.errors.push(`${err.rule}: ${err.message}`);
});
transformOutput.validation.warnings.forEach((warn: ValidationError) => {
result.warnings.push(`${warn.rule}: ${warn.message}`);
});
transformOutput.validation.criticalErrors.forEach(
(err: ValidationError) => {
result.errors.push(`[CRITICAL] ${err.rule}: ${err.message}`);
}
);
// Skip write if there are critical errors (unless explicitly allowed)
const hasCriticalErrors =
transformOutput.validation.criticalErrors.length > 0;
if (hasCriticalErrors && !options.allowCriticalErrors) {
logger.error(
` ✗ ${path.relative(
process.cwd(),
fileInfo.path
)} (skipped due to critical errors)`
);
result.changes.push('Skipped (critical validation errors)');
return result;
}
// Handle --print flag (output to stdout instead of writing)
if (options.print) {
logger.info(`\n${'='.repeat(60)}`);
logger.info(`File: ${fileInfo.path}`);
logger.info('='.repeat(60));
console.log(transformOutput.code);
logger.info('='.repeat(60));
result.changes.push('Printed to stdout');
} else if (!options.dry) {
// Write transformed file
await fs.writeFile(fileInfo.path, transformOutput.code, 'utf-8');
result.changes.push('File updated');
logger.success(` ${path.relative(process.cwd(), fileInfo.path)}`);
} else {
// Dry run - just report what would change
result.changes.push('Would be updated (dry)');
logger.info(` ~ ${path.relative(process.cwd(), fileInfo.path)} (dry)`);
}
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : 'Unknown error occurred';
result.errors.push(errorMessage);
logger.error(
` ${path.relative(process.cwd(), fileInfo.path)}: ${errorMessage}`
);
}
return result;
}
/**
* Create an empty migration summary
*/
function createEmptySummary(): MigrationSummary {
return {
filesProcessed: 0,
filesTransformed: 0,
filesSkipped: 0,
errors: 0,
warnings: 0,
results: [],
};
}