-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathComponentAnalyzer.cs
More file actions
388 lines (319 loc) · 12.7 KB
/
ComponentAnalyzer.cs
File metadata and controls
388 lines (319 loc) · 12.7 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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License
// See the LICENSE file in the project root for more information.
// Maintainer: Argo Zhang(argo@live.ca) Website: https://www.blazor.zone
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Text.RegularExpressions;
namespace BootstrapBlazorLLMsDocsGenerator;
/// <summary>
/// Analyzes Blazor component source files using Roslyn
/// </summary>
public partial class ComponentAnalyzer
{
private readonly string _sourcePath;
private readonly string _componentsPath;
private readonly string _samplesPath;
public ComponentAnalyzer(string sourcePath)
{
_sourcePath = sourcePath;
_componentsPath = Path.Combine(sourcePath, "Components");
_samplesPath = Path.Combine(Path.GetDirectoryName(sourcePath)!, "BootstrapBlazor.Server", "Components", "Samples");
}
/// <summary>
/// Analyze all components in the source directory
/// </summary>
public async Task<List<ComponentInfo>> AnalyzeAllComponentsAsync()
{
var components = new List<ComponentInfo>();
if (!Directory.Exists(_componentsPath))
{
Console.WriteLine($"Components directory not found: {_componentsPath}");
return components;
}
// Find all .razor.cs files
var files = Directory.GetFiles(_componentsPath, "*.razor.cs", SearchOption.AllDirectories);
foreach (var file in files)
{
var component = await AnalyzeFileAsync(file);
if (component != null && component.Parameters.Count > 0)
{
components.Add(component);
}
}
// Also analyze .cs files that might be component base classes
var csFiles = Directory.GetFiles(_componentsPath, "*Base.cs", SearchOption.AllDirectories);
foreach (var file in csFiles)
{
var component = await AnalyzeFileAsync(file);
if (component != null && component.Parameters.Count > 0)
{
components.Add(component);
}
}
return components.OrderBy(c => c.Name).ToList();
}
/// <summary>
/// Analyze a specific component by name
/// </summary>
public async Task<ComponentInfo?> AnalyzeComponentAsync(string componentName)
{
var pattern = $"{componentName}.razor.cs";
var files = Directory.GetFiles(_componentsPath, pattern, SearchOption.AllDirectories);
if (files.Length == 0)
{
// Try without .razor extension
pattern = $"{componentName}.cs";
files = Directory.GetFiles(_componentsPath, pattern, SearchOption.AllDirectories);
}
if (files.Length == 0)
{
return null;
}
return await AnalyzeFileAsync(files[0]);
}
private async Task<ComponentInfo?> AnalyzeFileAsync(string filePath)
{
try
{
var code = await File.ReadAllTextAsync(filePath);
var tree = CSharpSyntaxTree.ParseText(code);
var root = await tree.GetRootAsync();
// Find the class declaration
var classDeclaration = root.DescendantNodes()
.OfType<ClassDeclarationSyntax>()
.FirstOrDefault();
if (classDeclaration == null)
{
return null;
}
var component = new ComponentInfo
{
Name = GetClassName(classDeclaration),
FullName = GetFullClassName(classDeclaration, root),
Summary = ExtractXmlSummary(classDeclaration),
TypeParameters = GetTypeParameters(classDeclaration),
BaseClass = GetBaseClass(classDeclaration),
SourcePath = GetRelativePath(filePath),
LastModified = File.GetLastWriteTimeUtc(filePath),
SamplePath = FindSamplePath(GetClassName(classDeclaration))
};
// Extract parameters
component.Parameters = ExtractParameters(classDeclaration);
// Extract public methods
component.PublicMethods = ExtractPublicMethods(classDeclaration);
return component;
}
catch (Exception ex)
{
Console.WriteLine($"Error analyzing {filePath}: {ex.Message}");
return null;
}
}
private string GetClassName(ClassDeclarationSyntax classDeclaration)
{
return classDeclaration.Identifier.Text;
}
private string GetFullClassName(ClassDeclarationSyntax classDeclaration, SyntaxNode root)
{
var namespaceName = root.DescendantNodes()
.OfType<BaseNamespaceDeclarationSyntax>()
.FirstOrDefault()?.Name.ToString() ?? "";
var className = classDeclaration.Identifier.Text;
if (classDeclaration.TypeParameterList != null)
{
className += classDeclaration.TypeParameterList.ToString();
}
return string.IsNullOrEmpty(namespaceName) ? className : $"{namespaceName}.{className}";
}
private List<string> GetTypeParameters(ClassDeclarationSyntax classDeclaration)
{
if (classDeclaration.TypeParameterList == null)
{
return new List<string>();
}
return classDeclaration.TypeParameterList.Parameters
.Select(p => p.Identifier.Text)
.ToList();
}
private string? GetBaseClass(ClassDeclarationSyntax classDeclaration)
{
var baseList = classDeclaration.BaseList;
if (baseList == null) return null;
var baseType = baseList.Types.FirstOrDefault();
return baseType?.Type.ToString();
}
private List<ParameterInfo> ExtractParameters(ClassDeclarationSyntax classDeclaration)
{
var parameters = new List<ParameterInfo>();
var properties = classDeclaration.DescendantNodes()
.OfType<PropertyDeclarationSyntax>();
foreach (var property in properties)
{
// Check if property has [Parameter] attribute
var hasParameterAttr = property.AttributeLists
.SelectMany(a => a.Attributes)
.Any(a => a.Name.ToString() is "Parameter" or "ParameterAttribute");
if (!hasParameterAttr) continue;
var paramInfo = new ParameterInfo
{
Name = property.Identifier.Text,
Type = SimplifyTypeName(property.Type?.ToString() ?? "unknown"),
DefaultValue = GetDefaultValue(property),
Description = ExtractXmlSummary(property),
IsRequired = HasAttribute(property, "EditorRequired"),
IsObsolete = HasAttribute(property, "Obsolete"),
ObsoleteMessage = GetObsoleteMessage(property),
IsEventCallback = property.Type?.ToString().Contains("EventCallback") ?? false
};
// Skip obsolete parameters
if (!paramInfo.IsObsolete)
{
parameters.Add(paramInfo);
}
}
return parameters.OrderBy(p => p.Name).ToList();
}
private List<MethodInfo> ExtractPublicMethods(ClassDeclarationSyntax classDeclaration)
{
var methods = new List<MethodInfo>();
var methodDeclarations = classDeclaration.DescendantNodes()
.OfType<MethodDeclarationSyntax>()
.Where(m => m.Modifiers.Any(mod => mod.IsKind(SyntaxKind.PublicKeyword)));
foreach (var method in methodDeclarations)
{
// Skip property accessors, overrides of base class methods
if (method.Modifiers.Any(m => m.IsKind(SyntaxKind.OverrideKeyword)))
continue;
var methodInfo = new MethodInfo
{
Name = method.Identifier.Text,
ReturnType = SimplifyTypeName(method.ReturnType.ToString()),
Description = ExtractXmlSummary(method),
IsJSInvokable = HasAttribute(method, "JSInvokable"),
Parameters = method.ParameterList.Parameters
.Select(p => (SimplifyTypeName(p.Type?.ToString() ?? ""), p.Identifier.Text))
.ToList()
};
methods.Add(methodInfo);
}
return methods;
}
private string? ExtractXmlSummary(SyntaxNode node)
{
var trivia = node.GetLeadingTrivia();
var xmlTrivia = trivia.FirstOrDefault(t =>
t.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia) ||
t.IsKind(SyntaxKind.MultiLineDocumentationCommentTrivia));
if (xmlTrivia == default)
return null;
var xmlText = xmlTrivia.ToString();
// Extract content from <summary> tags
var match = SummaryRegex().Match(xmlText);
if (match.Success)
{
var summary = match.Groups[1].Value;
// Clean up the summary
summary = CleanXmlComment(summary);
return string.IsNullOrWhiteSpace(summary) ? null : summary;
}
return null;
}
private string CleanXmlComment(string comment)
{
// Remove /// prefixes and extra whitespace
var lines = comment.Split('\n')
.Select(l => l.Trim().TrimStart('/').Trim())
.Where(l => !string.IsNullOrWhiteSpace(l));
return string.Join(" ", lines);
}
private string? GetDefaultValue(PropertyDeclarationSyntax property)
{
var initializer = property.Initializer;
if (initializer != null)
{
return SimplifyDefaultValue(initializer.Value.ToString());
}
// Check for default in constructor or OnParametersSet
return null;
}
private string SimplifyDefaultValue(string value)
{
// Simplify common patterns
if (value == "false") return "false";
if (value == "true") return "true";
if (value == "null") return "null";
if (value == "0") return "0";
if (value == "string.Empty" || value == "\"\"") return "\"\"";
if (value.StartsWith("new ")) return "new()";
return value;
}
private string SimplifyTypeName(string typeName)
{
// Remove common namespace prefixes
var result = typeName
.Replace("System.", "")
.Replace("Collections.Generic.", "")
.Replace("Threading.Tasks.", "");
// Handle Nullable<T> -> T? (must be done carefully to not break other generics)
result = NullableRegex().Replace(result, "$1?");
// Simplify primitive type names
result = result
.Replace("Int32", "int")
.Replace("Int64", "long")
.Replace("Boolean", "bool")
.Replace("String", "string")
.Replace("Object", "object");
return result;
}
[GeneratedRegex(@"Nullable<([^>]+)>")]
private static partial Regex NullableRegex();
private bool HasAttribute(MemberDeclarationSyntax member, string attributeName)
{
return member.AttributeLists
.SelectMany(a => a.Attributes)
.Any(a => a.Name.ToString() == attributeName ||
a.Name.ToString() == attributeName + "Attribute");
}
private string? GetObsoleteMessage(PropertyDeclarationSyntax property)
{
var obsoleteAttr = property.AttributeLists
.SelectMany(a => a.Attributes)
.FirstOrDefault(a => a.Name.ToString() is "Obsolete" or "ObsoleteAttribute");
if (obsoleteAttr?.ArgumentList?.Arguments.Count > 0)
{
return obsoleteAttr.ArgumentList.Arguments[0].ToString().Trim('"');
}
return null;
}
private string GetRelativePath(string fullPath)
{
var basePath = Path.GetDirectoryName(Path.GetDirectoryName(_sourcePath))!;
return Path.GetRelativePath(basePath, fullPath).Replace('\\', '/');
}
private string? FindSamplePath(string componentName)
{
if (!Directory.Exists(_samplesPath))
return null;
// Try common sample file naming patterns
var patterns = new[]
{
$"{componentName}s.razor",
$"{componentName}.razor",
$"{componentName}Demo.razor",
$"{componentName}Sample.razor"
};
foreach (var pattern in patterns)
{
var files = Directory.GetFiles(_samplesPath, pattern, SearchOption.AllDirectories);
if (files.Length > 0)
{
return GetRelativePath(files[0]);
}
}
return null;
}
[GeneratedRegex(@"<summary>\s*(.*?)\s*</summary>", RegexOptions.Singleline)]
private static partial Regex SummaryRegex();
}