-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest-refactoring.js
More file actions
162 lines (134 loc) · 5.9 KB
/
test-refactoring.js
File metadata and controls
162 lines (134 loc) · 5.9 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
/**
* Test script to demonstrate the refactoring system
*/
import { LegacyCodeAnalyzer } from './src/LegacyCodeAnalyzer.js';
import { ModernCodeGenerator } from './src/generation/ModernCodeGenerator.js';
import { TestGenerator } from './src/generation/TestGenerator.js';
import BehaviorComparisonSystem from './src/validation/BehaviorComparisonSystem.js';
import { MigrationPlanner } from './src/migration/MigrationPlanner.js';
import { db } from './src/database/index.js';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
async function testRefactoringSystem() {
console.log('=== Legacy Code AI Refactoring System Demo ===\n');
try {
// Initialize database connection (optional)
console.log('1. Initializing database connection...');
try {
await db.connect();
console.log('✅ Database connected successfully');
} catch (error) {
console.log('⚠️ Database connection failed, continuing without persistence');
}
// Initialize components
const analyzer = new LegacyCodeAnalyzer({
enableQualityAssessment: true,
enableSemanticAnalysis: true,
enableCaching: true
});
const modernCodeGenerator = new ModernCodeGenerator();
const testGenerator = new TestGenerator();
const behaviorComparison = new BehaviorComparisonSystem();
const migrationPlanner = new MigrationPlanner();
// Test files
const testFiles = [
path.join(__dirname, 'test-project/legacy-code/user-manager.js'),
path.join(__dirname, 'test-project/legacy-code/database.php')
];
console.log('\n2. Analyzing legacy code files...');
for (const filePath of testFiles) {
console.log(`\n📄 Processing: ${path.basename(filePath)}`);
console.log('─'.repeat(50));
// Step 1: Analyze the legacy code
console.log('🔍 Analyzing code...');
const analysisResult = await analyzer.analyzeFile(filePath);
if (!analysisResult.success) {
console.error(`❌ Analysis failed: ${analysisResult.error}`);
continue;
}
console.log(`✅ Analysis completed in ${analysisResult.parsing.parseTime}ms`);
console.log(` Language: ${analysisResult.language}`);
console.log(` Lines of Code: ${analysisResult.parsing.metadata.linesOfCode}`);
console.log(` Complexity: ${analysisResult.parsing.metadata.complexity}`);
if (analysisResult.quality) {
console.log(` Quality Score: ${analysisResult.quality.overallScore}/100`);
console.log(` Technical Debt: ${analysisResult.quality.technicalDebtScore}/100`);
}
// Step 2: Generate modern code
console.log('\n🚀 Generating modern code...');
const modernCode = await modernCodeGenerator.generateModernCode(analysisResult, {
targetLanguage: 'same',
modernizationLevel: 'moderate',
preserveComments: true,
optimizePerformance: true
});
if (!modernCode.success) {
console.error(`❌ Code generation failed: ${modernCode.error}`);
continue;
}
console.log('✅ Modern code generated successfully');
console.log(` Patterns applied: ${modernCode.patterns.length}`);
console.log(` Issues fixed: ${modernCode.issuesFixed.length}`);
// Step 3: Generate tests
console.log('\n🧪 Generating test suite...');
const testSuite = await testGenerator.generateTestSuite(analysisResult, modernCode, {
framework: 'vitest',
includeEdgeCases: true,
generateMocks: true
});
console.log('✅ Test suite generated');
console.log(` Test cases: ${testSuite.tests.length}`);
console.log(` Estimated coverage: ${testSuite.estimatedCoverage}%`);
// Step 4: Compare behavior
console.log('\n🔄 Validating behavior preservation...');
const behaviorValidation = await behaviorComparison.compareImplementations(
analysisResult,
modernCode,
testSuite
);
console.log('✅ Behavior validation completed');
console.log(` Functional equivalence: ${behaviorValidation.functionalEquivalence}%`);
console.log(` Performance: ${behaviorValidation.performanceComparison.relativeSpeed}x`);
console.log(` Side effects preserved: ${behaviorValidation.sideEffectsValidation.preserved ? 'Yes' : 'No'}`);
// Display sample of modernized code
console.log('\n📝 Sample of modernized code:');
console.log('─'.repeat(50));
const codeLines = modernCode.code.split('\n');
console.log(codeLines.slice(0, 20).join('\n'));
if (codeLines.length > 20) {
console.log('... (truncated)');
}
}
// Create migration plan
console.log('\n\n3. Creating migration plan...');
const migrationPlan = await migrationPlanner.createComprehensivePlan(
testFiles.map(f => ({ filePath: f })),
{
strategy: 'incremental',
parallelExecution: true,
riskTolerance: 'medium'
}
);
console.log('✅ Migration plan created');
console.log(` Total phases: ${migrationPlan.phases.length}`);
console.log(` Estimated duration: ${migrationPlan.estimatedDuration.value} ${migrationPlan.estimatedDuration.unit}`);
console.log(` Risk assessment: ${migrationPlan.riskAssessment.overallRisk}`);
console.log('\n📋 Migration phases:');
migrationPlan.phases.forEach((phase, index) => {
console.log(` ${index + 1}. ${phase.name} (${phase.files.length} files)`);
});
// Cleanup
console.log('\n4. Cleaning up...');
await analyzer.cleanup();
await db.disconnect();
console.log('\n✨ Demo completed successfully!');
console.log('\nTo start the full dashboard, run: npm run dashboard');
} catch (error) {
console.error('\n❌ Error during demo:', error);
process.exit(1);
}
}
// Run the test
testRefactoringSystem().catch(console.error);