| | | 1 | | // Copyright DotNet API Diff Project Contributors - SPDX Identifier: MIT |
| | | 2 | | |
| | | 3 | | using System.Reflection; |
| | | 4 | | using DotNetApiDiff.Interfaces; |
| | | 5 | | using DotNetApiDiff.Models; |
| | | 6 | | using Microsoft.Extensions.Logging; |
| | | 7 | | |
| | | 8 | | namespace DotNetApiDiff.ApiExtraction; |
| | | 9 | | |
| | | 10 | | /// <summary> |
| | | 11 | | /// Extracts public API members from .NET assemblies using reflection |
| | | 12 | | /// </summary> |
| | | 13 | | public class ApiExtractor : IApiExtractor |
| | | 14 | | { |
| | | 15 | | private readonly ITypeAnalyzer _typeAnalyzer; |
| | | 16 | | private readonly ILogger<ApiExtractor> _logger; |
| | | 17 | | |
| | | 18 | | /// <summary> |
| | | 19 | | /// Creates a new instance of the ApiExtractor |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="typeAnalyzer">Type analyzer for detailed member analysis</param> |
| | | 22 | | /// <param name="logger">Logger for diagnostic information</param> |
| | 13 | 23 | | public ApiExtractor(ITypeAnalyzer typeAnalyzer, ILogger<ApiExtractor> logger) |
| | 13 | 24 | | { |
| | 13 | 25 | | _typeAnalyzer = typeAnalyzer ?? throw new ArgumentNullException(nameof(typeAnalyzer)); |
| | 13 | 26 | | _logger = logger ?? throw new ArgumentNullException(nameof(logger)); |
| | 13 | 27 | | } |
| | | 28 | | |
| | | 29 | | /// <summary> |
| | | 30 | | /// Extracts all public API members from the specified assembly |
| | | 31 | | /// </summary> |
| | | 32 | | /// <param name="assembly">Assembly to extract API members from</param> |
| | | 33 | | /// <param name="filterConfig">Optional filter configuration to apply</param> |
| | | 34 | | /// <returns>Collection of public API members</returns> |
| | | 35 | | public IEnumerable<ApiMember> ExtractApiMembers( |
| | | 36 | | Assembly assembly, |
| | | 37 | | Models.Configuration.FilterConfiguration? filterConfig = null) |
| | 2 | 38 | | { |
| | 2 | 39 | | if (assembly == null) |
| | 1 | 40 | | { |
| | 1 | 41 | | throw new ArgumentNullException(nameof(assembly)); |
| | | 42 | | } |
| | | 43 | | |
| | 1 | 44 | | _logger.LogInformation("Extracting API members from assembly: {AssemblyName}", assembly.GetName().Name); |
| | | 45 | | |
| | 1 | 46 | | if (filterConfig != null) |
| | 0 | 47 | | { |
| | 0 | 48 | | _logger.LogInformation( |
| | 0 | 49 | | "Applying filter configuration with {IncludeCount} includes and {ExcludeCount} excludes", |
| | 0 | 50 | | filterConfig.IncludeNamespaces.Count + filterConfig.IncludeTypes.Count, |
| | 0 | 51 | | filterConfig.ExcludeNamespaces.Count + filterConfig.ExcludeTypes.Count); |
| | 0 | 52 | | } |
| | | 53 | | |
| | 1 | 54 | | var apiMembers = new List<ApiMember>(); |
| | | 55 | | |
| | | 56 | | try |
| | 1 | 57 | | { |
| | | 58 | | // Get all public types from the assembly, applying filters if provided |
| | 1 | 59 | | var types = GetPublicTypes(assembly, filterConfig).ToList(); |
| | 1 | 60 | | _logger.LogDebug( |
| | 1 | 61 | | "Found {TypeCount} public types in assembly {AssemblyName} after filtering", |
| | 1 | 62 | | types.Count, |
| | 1 | 63 | | assembly.GetName().Name); |
| | | 64 | | |
| | | 65 | | // Process each type |
| | 7 | 66 | | foreach (var type in types) |
| | 2 | 67 | | { |
| | | 68 | | try |
| | 2 | 69 | | { |
| | | 70 | | // Add the type itself |
| | 2 | 71 | | var typeMember = _typeAnalyzer.AnalyzeType(type); |
| | 2 | 72 | | apiMembers.Add(typeMember); |
| | | 73 | | |
| | | 74 | | // Add all members of the type |
| | 2 | 75 | | var typeMembers = ExtractTypeMembers(type).ToList(); |
| | 2 | 76 | | apiMembers.AddRange(typeMembers); |
| | | 77 | | |
| | 2 | 78 | | _logger.LogDebug( |
| | 2 | 79 | | "Extracted {MemberCount} members from type {TypeName}", |
| | 2 | 80 | | typeMembers.Count, |
| | 2 | 81 | | type.FullName); |
| | 2 | 82 | | } |
| | 0 | 83 | | catch (Exception ex) |
| | 0 | 84 | | { |
| | 0 | 85 | | _logger.LogError(ex, "Error extracting members from type {TypeName}", type.FullName); |
| | 0 | 86 | | } |
| | 2 | 87 | | } |
| | | 88 | | |
| | 1 | 89 | | _logger.LogInformation( |
| | 1 | 90 | | "Extracted {MemberCount} total API members from assembly {AssemblyName}", |
| | 1 | 91 | | apiMembers.Count, |
| | 1 | 92 | | assembly.GetName().Name); |
| | | 93 | | |
| | 1 | 94 | | return apiMembers; |
| | | 95 | | } |
| | 0 | 96 | | catch (ReflectionTypeLoadException ex) |
| | 0 | 97 | | { |
| | 0 | 98 | | _logger.LogError(ex, "Error loading types from assembly {AssemblyName}", assembly.GetName().Name); |
| | | 99 | | |
| | | 100 | | // Log the loader exceptions for more detailed diagnostics |
| | 0 | 101 | | if (ex.LoaderExceptions != null) |
| | 0 | 102 | | { |
| | 0 | 103 | | foreach (var loaderEx in ex.LoaderExceptions) |
| | 0 | 104 | | { |
| | 0 | 105 | | if (loaderEx != null) |
| | 0 | 106 | | { |
| | 0 | 107 | | _logger.LogError(loaderEx, "Loader exception: {Message}", loaderEx.Message); |
| | 0 | 108 | | } |
| | 0 | 109 | | } |
| | 0 | 110 | | } |
| | | 111 | | |
| | | 112 | | // Return any types that were successfully loaded |
| | 0 | 113 | | return apiMembers; |
| | | 114 | | } |
| | 0 | 115 | | catch (Exception ex) |
| | 0 | 116 | | { |
| | 0 | 117 | | _logger.LogError( |
| | 0 | 118 | | ex, |
| | 0 | 119 | | "Error extracting API members from assembly {AssemblyName}", |
| | 0 | 120 | | assembly.GetName().Name); |
| | 0 | 121 | | return apiMembers; |
| | | 122 | | } |
| | 1 | 123 | | } |
| | | 124 | | |
| | | 125 | | /// <summary> |
| | | 126 | | /// Extracts public API members from a specific type |
| | | 127 | | /// </summary> |
| | | 128 | | /// <param name="type">Type to extract members from</param> |
| | | 129 | | /// <returns>Collection of public API members for the type</returns> |
| | | 130 | | public IEnumerable<ApiMember> ExtractTypeMembers(Type type) |
| | 4 | 131 | | { |
| | 4 | 132 | | if (type == null) |
| | 1 | 133 | | { |
| | 1 | 134 | | throw new ArgumentNullException(nameof(type)); |
| | | 135 | | } |
| | | 136 | | |
| | 3 | 137 | | var members = new List<ApiMember>(); |
| | | 138 | | |
| | | 139 | | try |
| | 3 | 140 | | { |
| | | 141 | | // Extract methods |
| | 3 | 142 | | members.AddRange(_typeAnalyzer.AnalyzeMethods(type)); |
| | | 143 | | |
| | | 144 | | // Extract properties |
| | 3 | 145 | | members.AddRange(_typeAnalyzer.AnalyzeProperties(type)); |
| | | 146 | | |
| | | 147 | | // Extract fields |
| | 3 | 148 | | members.AddRange(_typeAnalyzer.AnalyzeFields(type)); |
| | | 149 | | |
| | | 150 | | // Extract events |
| | 3 | 151 | | members.AddRange(_typeAnalyzer.AnalyzeEvents(type)); |
| | | 152 | | |
| | | 153 | | // Extract constructors |
| | 3 | 154 | | members.AddRange(_typeAnalyzer.AnalyzeConstructors(type)); |
| | | 155 | | |
| | 3 | 156 | | return members; |
| | | 157 | | } |
| | 0 | 158 | | catch (Exception ex) |
| | 0 | 159 | | { |
| | 0 | 160 | | _logger.LogError( |
| | 0 | 161 | | ex, |
| | 0 | 162 | | "Error extracting members from type {TypeName}", |
| | 0 | 163 | | type.FullName); |
| | 0 | 164 | | return members; |
| | | 165 | | } |
| | 3 | 166 | | } |
| | | 167 | | |
| | | 168 | | /// <summary> |
| | | 169 | | /// Gets all public types from the specified assembly |
| | | 170 | | /// </summary> |
| | | 171 | | /// <param name="assembly">Assembly to get types from</param> |
| | | 172 | | /// <param name="filterConfig">Optional filter configuration to apply</param> |
| | | 173 | | /// <returns>Collection of public types</returns> |
| | | 174 | | public virtual IEnumerable<Type> GetPublicTypes( |
| | | 175 | | Assembly assembly, |
| | | 176 | | Models.Configuration.FilterConfiguration? filterConfig = null) |
| | 2 | 177 | | { |
| | 2 | 178 | | if (assembly == null) |
| | 1 | 179 | | { |
| | 1 | 180 | | throw new ArgumentNullException(nameof(assembly)); |
| | | 181 | | } |
| | | 182 | | |
| | | 183 | | try |
| | 1 | 184 | | { |
| | | 185 | | // Get all exported (public) types from the assembly |
| | 1 | 186 | | var types = assembly.GetExportedTypes() |
| | 46 | 187 | | .Where(t => !t.IsCompilerGenerated() && !t.IsSpecialName); |
| | | 188 | | |
| | | 189 | | // Apply filtering if configuration is provided |
| | 1 | 190 | | if (filterConfig != null) |
| | 0 | 191 | | { |
| | | 192 | | // Filter by namespace includes if specified |
| | 0 | 193 | | if (filterConfig.IncludeNamespaces.Count > 0) |
| | 0 | 194 | | { |
| | 0 | 195 | | _logger.LogDebug( |
| | 0 | 196 | | "Filtering types to include only namespaces: {Namespaces}", |
| | 0 | 197 | | string.Join(", ", filterConfig.IncludeNamespaces)); |
| | | 198 | | |
| | 0 | 199 | | types = types.Where( |
| | 0 | 200 | | t => |
| | 0 | 201 | | filterConfig.IncludeNamespaces.Any( |
| | 0 | 202 | | ns => |
| | 0 | 203 | | (t.Namespace ?? string.Empty).StartsWith(ns, StringComparison.OrdinalIgnoreCase))); |
| | 0 | 204 | | } |
| | | 205 | | |
| | | 206 | | // Filter by namespace excludes |
| | 0 | 207 | | if (filterConfig.ExcludeNamespaces.Count > 0) |
| | 0 | 208 | | { |
| | 0 | 209 | | _logger.LogDebug( |
| | 0 | 210 | | "Filtering types to exclude namespaces: {Namespaces}", |
| | 0 | 211 | | string.Join(", ", filterConfig.ExcludeNamespaces)); |
| | | 212 | | |
| | 0 | 213 | | types = types.Where( |
| | 0 | 214 | | t => |
| | 0 | 215 | | !filterConfig.ExcludeNamespaces.Any( |
| | 0 | 216 | | ns => |
| | 0 | 217 | | (t.Namespace ?? string.Empty).StartsWith(ns, StringComparison.OrdinalIgnoreCase))); |
| | 0 | 218 | | } |
| | | 219 | | |
| | | 220 | | // Filter by type name includes if specified |
| | 0 | 221 | | if (filterConfig.IncludeTypes.Count > 0) |
| | 0 | 222 | | { |
| | 0 | 223 | | _logger.LogDebug( |
| | 0 | 224 | | "Filtering types to include only types matching patterns: {Patterns}", |
| | 0 | 225 | | string.Join(", ", filterConfig.IncludeTypes)); |
| | | 226 | | |
| | 0 | 227 | | types = types.Where( |
| | 0 | 228 | | t => |
| | 0 | 229 | | filterConfig.IncludeTypes.Any( |
| | 0 | 230 | | pattern => |
| | 0 | 231 | | IsTypeMatchingPattern(t, pattern))); |
| | 0 | 232 | | } |
| | | 233 | | |
| | | 234 | | // Filter by type name excludes |
| | 0 | 235 | | if (filterConfig.ExcludeTypes.Count > 0) |
| | 0 | 236 | | { |
| | 0 | 237 | | _logger.LogDebug( |
| | 0 | 238 | | "Filtering types to exclude types matching patterns: {Patterns}", |
| | 0 | 239 | | string.Join(", ", filterConfig.ExcludeTypes)); |
| | | 240 | | |
| | 0 | 241 | | types = types.Where( |
| | 0 | 242 | | t => |
| | 0 | 243 | | !filterConfig.ExcludeTypes.Any( |
| | 0 | 244 | | pattern => |
| | 0 | 245 | | IsTypeMatchingPattern(t, pattern))); |
| | 0 | 246 | | } |
| | | 247 | | |
| | | 248 | | // Filter internal types if not included |
| | 0 | 249 | | if (!filterConfig.IncludeInternals) |
| | 0 | 250 | | { |
| | 0 | 251 | | types = types.Where(t => t.IsPublic); |
| | 0 | 252 | | } |
| | | 253 | | |
| | | 254 | | // Filter compiler-generated types if not included |
| | 0 | 255 | | if (!filterConfig.IncludeCompilerGenerated) |
| | 0 | 256 | | { |
| | 0 | 257 | | types = types.Where(t => !IsCompilerGeneratedType(t)); |
| | 0 | 258 | | } |
| | 0 | 259 | | } |
| | | 260 | | |
| | 46 | 261 | | return types.OrderBy(t => t.FullName); |
| | | 262 | | } |
| | 0 | 263 | | catch (ReflectionTypeLoadException ex) |
| | 0 | 264 | | { |
| | 0 | 265 | | _logger.LogError( |
| | 0 | 266 | | ex, |
| | 0 | 267 | | "Error loading types from assembly {AssemblyName}", |
| | 0 | 268 | | assembly.GetName().Name); |
| | | 269 | | |
| | | 270 | | // Return any types that were successfully loaded |
| | 0 | 271 | | return ex.Types.Where(t => t != null).Cast<Type>(); |
| | | 272 | | } |
| | 0 | 273 | | catch (Exception ex) |
| | 0 | 274 | | { |
| | 0 | 275 | | _logger.LogError( |
| | 0 | 276 | | ex, |
| | 0 | 277 | | "Error getting public types from assembly {AssemblyName}", |
| | 0 | 278 | | assembly.GetName().Name); |
| | 0 | 279 | | return Enumerable.Empty<Type>(); |
| | | 280 | | } |
| | 1 | 281 | | } |
| | | 282 | | |
| | | 283 | | /// <summary> |
| | | 284 | | /// Checks if a type matches a wildcard pattern |
| | | 285 | | /// </summary> |
| | | 286 | | /// <param name="type">Type to check</param> |
| | | 287 | | /// <param name="pattern">Pattern to match against</param> |
| | | 288 | | /// <returns>True if the type matches the pattern, false otherwise</returns> |
| | | 289 | | private bool IsTypeMatchingPattern(Type type, string pattern) |
| | 0 | 290 | | { |
| | 0 | 291 | | var typeName = type.FullName ?? type.Name; |
| | | 292 | | |
| | | 293 | | // Convert wildcard pattern to regex |
| | 0 | 294 | | var regexPattern = "^" + System.Text.RegularExpressions.Regex.Escape(pattern) |
| | 0 | 295 | | .Replace("\\*", ".*") |
| | 0 | 296 | | .Replace("\\?", ".") + "$"; |
| | | 297 | | |
| | | 298 | | try |
| | 0 | 299 | | { |
| | 0 | 300 | | return System.Text.RegularExpressions.Regex.IsMatch( |
| | 0 | 301 | | typeName, |
| | 0 | 302 | | regexPattern, |
| | 0 | 303 | | System.Text.RegularExpressions.RegexOptions.IgnoreCase); |
| | | 304 | | } |
| | 0 | 305 | | catch |
| | 0 | 306 | | { |
| | | 307 | | // If regex fails, fall back to simple string comparison |
| | 0 | 308 | | return typeName.Equals(pattern, StringComparison.OrdinalIgnoreCase); |
| | | 309 | | } |
| | 0 | 310 | | } |
| | | 311 | | |
| | | 312 | | /// <summary> |
| | | 313 | | /// Checks if a type is compiler-generated |
| | | 314 | | /// </summary> |
| | | 315 | | /// <param name="type">Type to check</param> |
| | | 316 | | /// <returns>True if compiler-generated, false otherwise</returns> |
| | | 317 | | private bool IsCompilerGeneratedType(Type type) |
| | 0 | 318 | | { |
| | | 319 | | // Check for compiler-generated attributes |
| | 0 | 320 | | if (type.IsDefined(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute), true)) |
| | 0 | 321 | | { |
| | 0 | 322 | | return true; |
| | | 323 | | } |
| | | 324 | | |
| | | 325 | | // Check for compiler-generated naming patterns |
| | 0 | 326 | | return type.Name.Contains('<') || |
| | 0 | 327 | | type.Name.StartsWith("__") || |
| | 0 | 328 | | type.Name.Contains("AnonymousType") || |
| | 0 | 329 | | type.Name.Contains("DisplayClass"); |
| | 0 | 330 | | } |
| | | 331 | | } |
| | | 332 | | |
| | | 333 | | /// <summary> |
| | | 334 | | /// Extension methods for reflection types |
| | | 335 | | /// </summary> |
| | | 336 | | public static class ReflectionExtensions |
| | | 337 | | { |
| | | 338 | | /// <summary> |
| | | 339 | | /// Checks if a type is compiler-generated |
| | | 340 | | /// </summary> |
| | | 341 | | /// <param name="type">Type to check</param> |
| | | 342 | | /// <returns>True if compiler-generated, false otherwise</returns> |
| | | 343 | | public static bool IsCompilerGenerated(this Type type) |
| | | 344 | | { |
| | | 345 | | // Check for compiler-generated types like closures, iterators, etc. |
| | | 346 | | if (type.Name.Contains('<') || type.Name.StartsWith("__")) |
| | | 347 | | { |
| | | 348 | | return true; |
| | | 349 | | } |
| | | 350 | | |
| | | 351 | | // Check for CompilerGeneratedAttribute using IsDefined for better performance |
| | | 352 | | return type.IsDefined(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute), true); |
| | | 353 | | } |
| | | 354 | | } |