Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
551 lines (456 loc) · 21.8 KB
/
Copy pathProgram.cs
File metadata and controls
551 lines (456 loc) · 21.8 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
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Build.Locator;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.MSBuild;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using OfficeOpenXml;
using Microsoft.CodeAnalysis.FindSymbols;
using OfficeOpenXml.Style; // EPPlus for Excel
class Program
{
static readonly List<string> IgnoredFolders = new List<string>
{
"folder1",
"folder2",
"folder3"
};
static readonly string unusedClassesExcelPath = @"path\to\save\unusedclassesexcelfile.xlsx";
static readonly string LogFilePath = @"path/of/log/file.txt";
static async Task Main(string[] args)
{
MSBuildLocator.RegisterDefaults();
string solutionPath = @"Path/to/your/solution";
// Start logging
using StreamWriter logWriter = new(LogFilePath, append: false);
Console.SetOut(logWriter);
Console.SetError(logWriter);
Console.WriteLine($"[INFO] Starting Unused Variable Detection: {DateTime.Now}");
try
{
using var workspace = MSBuildWorkspace.Create();
var solution = await workspace.OpenSolutionAsync(solutionPath);
Console.WriteLine("find unused avariables");
var unusedVariables = await FindUnusedVariables(solution);
Console.WriteLine("found unused avariables, now start commenting");
await CommentOutUnusedVariables(unusedVariables);
var unusedFunctions = await FindUnusedFunctions(solutionPath);
Console.WriteLine("found unused functions, now start commenting");
await CommentOutUnusedFunctions(unusedFunctions);
var unusedClasses = await FindUnusedClasses(solutionPath);
Console.WriteLine("found unused classes, now start commenting");
await CommentOutUnusedClasses(unusedClasses);
Console.WriteLine("commenting done");
}
catch (Exception ex)
{
Console.WriteLine($"[ERROR] Unexpected error: {ex.Message}\n{ex.StackTrace}");
}
Console.WriteLine($"[INFO] Finished Processing: {DateTime.Now}");
}
static async Task<List<(string name, string filePath, int lineNumber, string fullLine)>> FindUnusedVariables(Solution solution)
{
var unusedVariables = new List<(string, string, int, string)>();
foreach (var project in solution.Projects)
{
foreach (var document in project.Documents)
{
string filePath = document.FilePath ?? "";
if (IgnoredFolders.Any(folder => filePath.Contains(folder, StringComparison.OrdinalIgnoreCase)))
continue;
try
{
var semanticModel = await document.GetSemanticModelAsync();
var syntaxTree = await document.GetSyntaxTreeAsync();
if (semanticModel == null || syntaxTree == null) continue;
var root = await syntaxTree.GetRootAsync();
var text = await document.GetTextAsync();
var variables = root.DescendantNodes()
.OfType<VariableDeclaratorSyntax>()
.Select(v => new { Symbol = semanticModel.GetDeclaredSymbol(v), SyntaxNode = v })
.Where(v => v.Symbol != null)
.ToList();
foreach (var variable in variables)
{
var references = await SymbolFinder.FindReferencesAsync(variable.Symbol, solution);
if (!references.Any(refs => refs.Locations.Any()))
{
var lineNumber = text.Lines.GetLineFromPosition(variable.SyntaxNode.SpanStart).LineNumber + 1;
var fullLine = text.Lines[lineNumber - 1].ToString(); // Get full line
unusedVariables.Add((variable.Symbol.ToDisplayString(), filePath, lineNumber, fullLine));
Console.WriteLine($"[INFO] Found Unused Variable: {variable.Symbol.ToDisplayString()} at {filePath} (Line {lineNumber})");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"[ERROR] Failed processing file: {filePath}\n{ex.Message}\n{ex.StackTrace}");
}
}
}
return unusedVariables;
}
static async Task<List<(string name, string filePath, int lineNumber)>> FindUnusedFunctions(string solutionPath)
{
using var workspace = MSBuildWorkspace.Create();
var solution = await workspace.OpenSolutionAsync(solutionPath);
var unusedList = new List<(string, string, int)>();
foreach (var project in solution.Projects)
{
var compilation = await project.GetCompilationAsync();
foreach (var syntaxTree in compilation.SyntaxTrees)
{
var semanticModel = compilation.GetSemanticModel(syntaxTree);
var root = await syntaxTree.GetRootAsync();
var methods = root.DescendantNodes().OfType<MethodDeclarationSyntax>();
foreach (var method in methods)
{
var symbol = semanticModel.GetDeclaredSymbol(method);
if (symbol == null) continue;
var refs = await SymbolFinder.FindReferencesAsync(symbol, solution);
if (!refs.Any(r => r.Locations.Any(l => !l.IsCandidateLocation)))
{
var location = method.GetLocation().GetLineSpan();
var filePath = syntaxTree.FilePath;
var line = location.StartLinePosition.Line + 1;
unusedList.Add((symbol.ToString(), filePath, line));
Console.WriteLine($"[UNUSED] {symbol} in {filePath} at line {line}");
}
}
}
}
return unusedList;
}
static async Task CommentOutUnusedVariables(
List<(string name, string filePath, int lineNumber, string fullLine)> unusedVariables)
{
var unusedItems = unusedVariables.GroupBy(item => item.filePath)
.ToDictionary(g => g.Key, g => g.ToList());
List<(string name, string filePath, int lineNumber)> failedChanges = new();
foreach (var file in unusedItems)
{
string filePath = file.Key;
List<(string name, string filePath, int lineNumber, string fullLine)> items = file.Value;
try
{
string[] lines = await File.ReadAllLinesAsync(filePath);
string[] originalLines = (string[])lines.Clone();
foreach (var item in items.OrderByDescending(i => i.lineNumber)) // Process from bottom up
{
if (item.lineNumber - 1 < 0 || item.lineNumber - 1 >= lines.Length)
continue;
lines[item.lineNumber - 1] = "// Remove unused code" + lines[item.lineNumber - 1];
await File.WriteAllLinesAsync(filePath, lines);
Console.WriteLine($"[INFO] Successfully commented unused variable in {filePath} (Line {item.lineNumber})");
}
}
catch (Exception ex)
{
Console.WriteLine($"[ERROR] Could not process file {filePath}\n{ex.Message}\n{ex.StackTrace}");
}
}
SaveFailedChangesToExcel(failedChanges);
}
static async Task CommentOutUnusedFunctions(
List<(string name, string filePath, int lineNumber)> unusedItems)
{
List<(string name, string filePath, int lineNumber)> failedChanges = new();
var grouped = unusedItems.GroupBy(i => i.filePath);
foreach (var fileGroup in grouped)
{
string filePath = fileGroup.Key;
string[] originalLines = await File.ReadAllLinesAsync(filePath);
var updatedLines = originalLines.ToList();
bool fileChanged = false;
try
{
var text = await File.ReadAllTextAsync(filePath);
var syntaxTree = CSharpSyntaxTree.ParseText(text);
var root = await syntaxTree.GetRootAsync();
foreach (var item in fileGroup.OrderByDescending(i => i.lineNumber))
{
var textLines = syntaxTree.GetText().Lines;
if (item.lineNumber - 1 >= textLines.Count)
continue;
var methodNode = root.DescendantNodes()
.OfType<MethodDeclarationSyntax>()
.FirstOrDefault(n =>
syntaxTree.GetLineSpan(n.Span).StartLinePosition.Line == item.lineNumber - 1);
if (methodNode == null)
continue;
var startLine = syntaxTree.GetLineSpan(methodNode.Span).StartLinePosition.Line;
var endLine = syntaxTree.GetLineSpan(methodNode.Span).EndLinePosition.Line;
for (int i = startLine; i <= endLine; i++)
{
if (!updatedLines[i].TrimStart().StartsWith("//"))
{
updatedLines[i] = "// " + updatedLines[i];
fileChanged = true;
}
}
if (startLine > 0)
{
updatedLines.Insert(startLine, "// Remove unused code");
}
else
{
updatedLines.Insert(0, "// Remove unused code");
}
Console.WriteLine($"[INFO] Commented unused method at {filePath} (Lines {startLine + 1}-{endLine + 1})");
}
if (fileChanged)
{
await File.WriteAllLinesAsync(filePath, updatedLines);
// if (!BuildSolution(solutionPath))
// {
// await File.WriteAllLinesAsync(filePath, originalLines);
// failedChanges.AddRange(fileGroup);
// Console.WriteLine($"[ERROR] Reverted {filePath} — build failed.");
// }
}
}
catch (Exception ex)
{
Console.WriteLine($"[ERROR] Failed to comment in {filePath}: {ex.Message}");
failedChanges.AddRange(fileGroup);
}
}
}
static bool BuildSolution(string solutionPath)
{
try
{
ProcessStartInfo psi = new("dotnet", $"build \"{solutionPath}\"")
{
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
using Process process = Process.Start(psi);
process.WaitForExit();
return process.ExitCode == 0;
}
catch (Exception ex)
{
Console.WriteLine($"[ERROR] Build execution failed: {ex.Message}");
return false;
}
}
static void SaveFailedChangesToExcel(List<(string name, string filePath, int lineNumber)> failedChanges)
{
if (failedChanges.Count == 0)
return;
try
{
using var package = new ExcelPackage();
var worksheet = package.Workbook.Worksheets.Add("Failed Variables");
worksheet.Cells[1, 1].Value = "Unused Variable";
worksheet.Cells[1, 2].Value = "File Path";
worksheet.Cells[1, 3].Value = "Line Number";
for (int i = 0; i < failedChanges.Count; i++)
{
worksheet.Cells[i + 2, 1].Value = failedChanges[i].name;
worksheet.Cells[i + 2, 2].Value = failedChanges[i].filePath;
worksheet.Cells[i + 2, 3].Value = failedChanges[i].lineNumber;
}
File.WriteAllBytes(unusedClassesExcelPath, package.GetAsByteArray());
Console.WriteLine($"[INFO] Saved failed variables to Excel: {unusedClassesExcelPath}");
}
catch (Exception ex)
{
Console.WriteLine($"[ERROR] Failed to write Excel file: {ex.Message}");
}
}
static async Task<List<(string name, string filePath, int lineNumber, string fullLine)>> FindUnusedClasses(
string solutionPath)
{
var unusedClasses = new List<(string, string, int, string)>();
try
{
Console.WriteLine($"[INFO] Loading solution: {solutionPath}");
var workspace = MSBuildWorkspace.Create();
var solution = await workspace.OpenSolutionAsync(solutionPath);
foreach (var project in solution.Projects)
{
Console.WriteLine($"[INFO] Analyzing project: {project.Name}");
Compilation? compilation = null;
try
{
compilation = await project.GetCompilationAsync();
}
catch (Exception ex)
{
Console.WriteLine($"[ERROR] Failed to compile project {project.Name}: {ex.Message}");
continue;
}
if (compilation == null) continue;
foreach (var syntaxTree in compilation.SyntaxTrees)
{
string filePath = syntaxTree.FilePath;
if (IgnoredFolders.Any(folder => filePath.Replace('\\', '/').Contains($"/{folder}/")))
{
Console.WriteLine($"[INFO] Skipped file in ignored folder: {filePath}");
continue;
}
try
{
var semanticModel = compilation.GetSemanticModel(syntaxTree);
var root = await syntaxTree.GetRootAsync();
var classDeclarations = root.DescendantNodes().OfType<ClassDeclarationSyntax>();
foreach (var classDecl in classDeclarations)
{
var classSymbol = semanticModel.GetDeclaredSymbol(classDecl);
if (classSymbol == null || classSymbol.DeclaredAccessibility != Accessibility.Public)
continue;
bool isUsed = false;
// Check reference to class itself
var classRefs = await SymbolFinder.FindReferencesAsync(classSymbol, solution);
if (classRefs.Any(r => r.Locations.Any(l => !l.IsCandidateLocation)))
{
isUsed = true;
}
// Check references to any members (methods, props, etc.)
if (!isUsed)
{
foreach (var member in classSymbol.GetMembers().Where(m => !m.IsImplicitlyDeclared))
{
var refs = await SymbolFinder.FindReferencesAsync(member, solution);
if (refs.Any(r => r.Locations.Any(l => !l.IsCandidateLocation)))
{
isUsed = true;
break;
}
}
}
if (!isUsed)
{
var lineSpan = syntaxTree.GetLineSpan(classDecl.Span);
int lineNumber = lineSpan.StartLinePosition.Line + 1;
string fullLine = syntaxTree.GetText().Lines[lineNumber - 1].ToString();
unusedClasses.Add((classSymbol.Name, filePath, lineNumber, fullLine));
Console.WriteLine($"[INFO] Found unused class: {classSymbol.Name} at {filePath} (Line {lineNumber})");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"[ERROR] Error analyzing file {filePath}: {ex.Message}");
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"[ERROR] Failed to process solution: {ex.Message}");
}
Console.WriteLine($"[INFO] Total unused classes found: {unusedClasses.Count}");
SaveUnusedClassesToExcel(unusedClasses,@"C:\Repo\UnusedClasses.xlsx");
return unusedClasses;
}
static async Task CommentOutUnusedClasses(
List<(string name, string filePath, int lineNumber, string fullLine)> unusedClasses)
{
var grouped = unusedClasses.GroupBy(c => c.filePath);
List<(string name, string filePath, int lineNumber)> failedChanges = new();
foreach (var fileGroup in grouped)
{
string filePath = fileGroup.Key;
try
{
Console.WriteLine($"[INFO] Processing file: {filePath}");
var text = await File.ReadAllTextAsync(filePath);
var syntaxTree = CSharpSyntaxTree.ParseText(text);
var root = await syntaxTree.GetRootAsync();
var updatedLines = text.Split('\n').ToList();
foreach (var item in fileGroup.OrderByDescending(i => i.lineNumber))
{
try
{
var classNode = root.DescendantNodes()
.OfType<ClassDeclarationSyntax>()
.FirstOrDefault(n =>
syntaxTree.GetLineSpan(n.Span).StartLinePosition.Line == item.lineNumber - 1 &&
n.Identifier.Text == item.name);
if (classNode == null)
{
Console.WriteLine($"[WARN] Could not find class node for {item.name} in {filePath}");
continue;
}
var span = syntaxTree.GetLineSpan(classNode.Span);
int startLine = span.StartLinePosition.Line;
int endLine = span.EndLinePosition.Line;
// Insert comment above class
updatedLines.Insert(startLine, "// Remove unused code");
endLine++; // Adjust because of insert
for (int i = startLine + 1; i <= endLine; i++)
{
if (!updatedLines[i].TrimStart().StartsWith("//"))
{
updatedLines[i] = "// " + updatedLines[i];
}
}
Console.WriteLine($"[INFO] Commented class {item.name} in {filePath} (Lines {startLine + 1}-{endLine + 1})");
}
catch (Exception ex)
{
Console.WriteLine($"[ERROR] Failed to comment class {item.name} in {filePath}: {ex.Message}");
failedChanges.Add((item.name, item.filePath, item.lineNumber));
}
}
await File.WriteAllLinesAsync(filePath, updatedLines);
}
catch (Exception ex)
{
Console.WriteLine($"[ERROR] Could not process file {filePath}: {ex.Message}");
failedChanges.AddRange(fileGroup.Select(i => (i.name, i.filePath, i.lineNumber)));
}
}
// SaveFailedChangesToExcel(failedChanges);
Console.WriteLine("[INFO] Finished commenting unused classes.");
}
static void SaveUnusedClassesToExcel(List<(string name, string filePath, int lineNumber, string fullLine)> unusedClasses, string outputPath)
{
try
{
// ✅ Required in EPPlus 5+ (especially 8+)
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using var package = new ExcelPackage();
var worksheet = package.Workbook.Worksheets.Add("Unused Classes");
// Header
worksheet.Cells[1, 1].Value = "Class Name";
worksheet.Cells[1, 2].Value = "File Path";
worksheet.Cells[1, 3].Value = "Line Number";
worksheet.Cells[1, 4].Value = "Code Line";
// Style
using (var range = worksheet.Cells[1, 1, 1, 4])
{
range.Style.Font.Bold = true;
range.Style.Fill.PatternType = ExcelFillStyle.Solid;
range.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightGray);
}
// Data
for (int i = 0; i < unusedClasses.Count; i++)
{
var (name, filePath, lineNumber, fullLine) = unusedClasses[i];
worksheet.Cells[i + 2, 1].Value = name;
worksheet.Cells[i + 2, 2].Value = filePath;
worksheet.Cells[i + 2, 3].Value = lineNumber;
worksheet.Cells[i + 2, 4].Value = fullLine;
}
worksheet.Cells.AutoFitColumns();
package.SaveAs(new FileInfo(outputPath));
Console.WriteLine($"[INFO] Saved unused class list to: {outputPath}");
}
catch (Exception ex)
{
Console.WriteLine($"[ERROR] Failed to export to Excel: {ex.Message}");
}
}
}