|
| 1 | +// Copyright DotNet API Diff Project Contributors - SPDX Identifier: MIT |
| 2 | +using DotNetApiDiff.Interfaces; |
| 3 | +using DotNetApiDiff.Models; |
| 4 | +using DotNetApiDiff.Models.Configuration; |
| 5 | +using Microsoft.Extensions.DependencyInjection; |
| 6 | +using Microsoft.Extensions.Logging; |
| 7 | +using Spectre.Console; |
| 8 | +using Spectre.Console.Cli; |
| 9 | +using System.ComponentModel; |
| 10 | +using System.Diagnostics.CodeAnalysis; |
| 11 | + |
| 12 | +namespace DotNetApiDiff.Commands; |
| 13 | + |
| 14 | +/// <summary> |
| 15 | +/// Settings for the compare command |
| 16 | +/// </summary> |
| 17 | +public class CompareCommandSettings : CommandSettings |
| 18 | +{ |
| 19 | + [CommandArgument(0, "<oldAssembly>")] |
| 20 | + [Description("Path to the old/baseline assembly")] |
| 21 | + public required string OldAssemblyPath { get; init; } |
| 22 | + |
| 23 | + [CommandArgument(1, "<newAssembly>")] |
| 24 | + [Description("Path to the new/current assembly")] |
| 25 | + public required string NewAssemblyPath { get; init; } |
| 26 | + |
| 27 | + [CommandOption("-c|--config <configFile>")] |
| 28 | + [Description("Path to configuration file")] |
| 29 | + public string? ConfigFile { get; init; } |
| 30 | + |
| 31 | + [CommandOption("-o|--output <format>")] |
| 32 | + [Description("Output format (console, json, markdown)")] |
| 33 | + [DefaultValue("console")] |
| 34 | + public string OutputFormat { get; init; } = "console"; |
| 35 | + |
| 36 | + [CommandOption("-f|--filter <namespace>")] |
| 37 | + [Description("Filter to specific namespaces (can be specified multiple times)")] |
| 38 | + public string[]? NamespaceFilters { get; init; } |
| 39 | + |
| 40 | + [CommandOption("-e|--exclude <pattern>")] |
| 41 | + [Description("Exclude types matching pattern (can be specified multiple times)")] |
| 42 | + public string[]? ExcludePatterns { get; init; } |
| 43 | + |
| 44 | + [CommandOption("--no-color")] |
| 45 | + [Description("Disable colored output")] |
| 46 | + [DefaultValue(false)] |
| 47 | + public bool NoColor { get; init; } |
| 48 | + |
| 49 | + [CommandOption("-v|--verbose")] |
| 50 | + [Description("Enable verbose output")] |
| 51 | + [DefaultValue(false)] |
| 52 | + public bool Verbose { get; init; } |
| 53 | +} |
| 54 | + |
| 55 | +/// <summary> |
| 56 | +/// Command to compare two assemblies |
| 57 | +/// </summary> |
| 58 | +public class CompareCommand : Command<CompareCommandSettings> |
| 59 | +{ |
| 60 | + private readonly IServiceProvider _serviceProvider; |
| 61 | + |
| 62 | + /// <summary> |
| 63 | + /// Initializes a new instance of the <see cref="CompareCommand"/> class. |
| 64 | + /// </summary> |
| 65 | + /// <param name="serviceProvider">The service provider.</param> |
| 66 | + public CompareCommand(IServiceProvider serviceProvider) |
| 67 | + { |
| 68 | + _serviceProvider = serviceProvider; |
| 69 | + } |
| 70 | + |
| 71 | + /// <summary> |
| 72 | + /// Validates the command settings |
| 73 | + /// </summary> |
| 74 | + /// <param name="context">The command context</param> |
| 75 | + /// <param name="settings">The command settings</param> |
| 76 | + /// <returns>ValidationResult indicating success or failure</returns> |
| 77 | + public override ValidationResult Validate([NotNull] CommandContext context, [NotNull] CompareCommandSettings settings) |
| 78 | + { |
| 79 | + // Validate old assembly path |
| 80 | + if (!File.Exists(settings.OldAssemblyPath)) |
| 81 | + { |
| 82 | + return ValidationResult.Error($"Old assembly file not found: {settings.OldAssemblyPath}"); |
| 83 | + } |
| 84 | + |
| 85 | + // Validate new assembly path |
| 86 | + if (!File.Exists(settings.NewAssemblyPath)) |
| 87 | + { |
| 88 | + return ValidationResult.Error($"New assembly file not found: {settings.NewAssemblyPath}"); |
| 89 | + } |
| 90 | + |
| 91 | + // Validate config file if specified |
| 92 | + if (!string.IsNullOrEmpty(settings.ConfigFile) && !File.Exists(settings.ConfigFile)) |
| 93 | + { |
| 94 | + return ValidationResult.Error($"Configuration file not found: {settings.ConfigFile}"); |
| 95 | + } |
| 96 | + |
| 97 | + // Validate output format |
| 98 | + string format = settings.OutputFormat.ToLowerInvariant(); |
| 99 | + if (format != "console" && format != "json" && format != "markdown") |
| 100 | + { |
| 101 | + return ValidationResult.Error($"Invalid output format: {settings.OutputFormat}. Valid formats are: console, json, markdown"); |
| 102 | + } |
| 103 | + |
| 104 | + return ValidationResult.Success(); |
| 105 | + } |
| 106 | + |
| 107 | + /// <summary> |
| 108 | + /// Executes the command |
| 109 | + /// </summary> |
| 110 | + /// <param name="context">The command context</param> |
| 111 | + /// <param name="settings">The command settings</param> |
| 112 | + /// <returns>Exit code (0 for success, non-zero for failure)</returns> |
| 113 | + public override int Execute([NotNull] CommandContext context, [NotNull] CompareCommandSettings settings) |
| 114 | + { |
| 115 | + var logger = _serviceProvider.GetRequiredService<ILogger<CompareCommand>>(); |
| 116 | + |
| 117 | + try |
| 118 | + { |
| 119 | + // Set up logging level based on verbose flag |
| 120 | + if (settings.Verbose) |
| 121 | + { |
| 122 | + // This is a placeholder - in a real implementation we would configure the logging level |
| 123 | + logger.LogInformation("Verbose logging enabled"); |
| 124 | + } |
| 125 | + |
| 126 | + // Load configuration |
| 127 | + ComparisonConfiguration config; |
| 128 | + if (!string.IsNullOrEmpty(settings.ConfigFile)) |
| 129 | + { |
| 130 | + logger.LogInformation("Loading configuration from {ConfigFile}", settings.ConfigFile); |
| 131 | + // In a real implementation, we would load the configuration from the file |
| 132 | + config = ComparisonConfiguration.CreateDefault(); |
| 133 | + } |
| 134 | + else |
| 135 | + { |
| 136 | + logger.LogInformation("Using default configuration"); |
| 137 | + config = ComparisonConfiguration.CreateDefault(); |
| 138 | + } |
| 139 | + |
| 140 | + // Apply command-line filters if specified |
| 141 | + if (settings.NamespaceFilters != null && settings.NamespaceFilters.Length > 0) |
| 142 | + { |
| 143 | + logger.LogInformation("Applying namespace filters: {Filters}", string.Join(", ", settings.NamespaceFilters)); |
| 144 | + // In a real implementation, we would update the configuration with the filters |
| 145 | + } |
| 146 | + |
| 147 | + // Apply command-line exclusions if specified |
| 148 | + if (settings.ExcludePatterns != null && settings.ExcludePatterns.Length > 0) |
| 149 | + { |
| 150 | + logger.LogInformation("Applying exclusion patterns: {Patterns}", string.Join(", ", settings.ExcludePatterns)); |
| 151 | + // In a real implementation, we would update the configuration with the exclusions |
| 152 | + } |
| 153 | + |
| 154 | + // Load assemblies |
| 155 | + logger.LogInformation("Loading old assembly: {Path}", settings.OldAssemblyPath); |
| 156 | + logger.LogInformation("Loading new assembly: {Path}", settings.NewAssemblyPath); |
| 157 | + |
| 158 | + var assemblyLoader = _serviceProvider.GetRequiredService<IAssemblyLoader>(); |
| 159 | + var oldAssembly = assemblyLoader.LoadAssembly(settings.OldAssemblyPath); |
| 160 | + var newAssembly = assemblyLoader.LoadAssembly(settings.NewAssemblyPath); |
| 161 | + |
| 162 | + // Extract API information |
| 163 | + logger.LogInformation("Extracting API information from assemblies"); |
| 164 | + var apiExtractor = _serviceProvider.GetRequiredService<IApiExtractor>(); |
| 165 | + var oldApi = apiExtractor.ExtractApiMembers(oldAssembly); |
| 166 | + var newApi = apiExtractor.ExtractApiMembers(newAssembly); |
| 167 | + |
| 168 | + // Compare APIs |
| 169 | + logger.LogInformation("Comparing APIs"); |
| 170 | + var apiComparer = _serviceProvider.GetRequiredService<IApiComparer>(); |
| 171 | + var comparisonResult = apiComparer.CompareAssemblies(oldAssembly, newAssembly); |
| 172 | + |
| 173 | + // Create ApiComparison from ComparisonResult |
| 174 | + var comparison = new Models.ApiComparison |
| 175 | + { |
| 176 | + Additions = comparisonResult.Differences |
| 177 | + .Where(d => d.ChangeType == Models.ChangeType.Added) |
| 178 | + .Select(d => new Models.ApiChange |
| 179 | + { |
| 180 | + Type = Models.ChangeType.Added, |
| 181 | + TargetMember = new Models.ApiMember { Name = d.ElementName }, |
| 182 | + IsBreakingChange = d.IsBreakingChange |
| 183 | + }).ToList(), |
| 184 | + Removals = comparisonResult.Differences |
| 185 | + .Where(d => d.ChangeType == Models.ChangeType.Removed) |
| 186 | + .Select(d => new Models.ApiChange |
| 187 | + { |
| 188 | + Type = Models.ChangeType.Removed, |
| 189 | + SourceMember = new Models.ApiMember { Name = d.ElementName }, |
| 190 | + IsBreakingChange = d.IsBreakingChange |
| 191 | + }).ToList(), |
| 192 | + Modifications = comparisonResult.Differences |
| 193 | + .Where(d => d.ChangeType == Models.ChangeType.Modified) |
| 194 | + .Select(d => new Models.ApiChange |
| 195 | + { |
| 196 | + Type = Models.ChangeType.Modified, |
| 197 | + SourceMember = new Models.ApiMember { Name = d.ElementName }, |
| 198 | + TargetMember = new Models.ApiMember { Name = d.ElementName }, |
| 199 | + IsBreakingChange = d.IsBreakingChange |
| 200 | + }).ToList(), |
| 201 | + Excluded = comparisonResult.Differences |
| 202 | + .Where(d => d.ChangeType == Models.ChangeType.Excluded) |
| 203 | + .Select(d => new Models.ApiChange |
| 204 | + { |
| 205 | + Type = Models.ChangeType.Excluded, |
| 206 | + SourceMember = new Models.ApiMember { Name = d.ElementName }, |
| 207 | + IsBreakingChange = false |
| 208 | + }).ToList() |
| 209 | + }; |
| 210 | + |
| 211 | + // Generate report |
| 212 | + logger.LogInformation("Generating {Format} report", settings.OutputFormat); |
| 213 | + var reportGenerator = _serviceProvider.GetRequiredService<IReportGenerator>(); |
| 214 | + |
| 215 | + // Convert string format to ReportFormat enum |
| 216 | + ReportFormat format = settings.OutputFormat.ToLowerInvariant() switch |
| 217 | + { |
| 218 | + "json" => ReportFormat.Json, |
| 219 | + "xml" => ReportFormat.Xml, |
| 220 | + "html" => ReportFormat.Html, |
| 221 | + "markdown" => ReportFormat.Markdown, |
| 222 | + _ => ReportFormat.Console |
| 223 | + }; |
| 224 | + |
| 225 | + var report = reportGenerator.GenerateReport(comparisonResult, format); |
| 226 | + |
| 227 | + // Output report |
| 228 | + AnsiConsole.Write(report); |
| 229 | + |
| 230 | + // Determine exit code based on breaking changes |
| 231 | + bool hasBreakingChanges = comparison.Removals.Any(c => c.IsBreakingChange) || |
| 232 | + comparison.Modifications.Any(c => c.IsBreakingChange); |
| 233 | + |
| 234 | + if (hasBreakingChanges) |
| 235 | + { |
| 236 | + logger.LogWarning("Breaking changes detected"); |
| 237 | + return 1; // Non-zero exit code for breaking changes |
| 238 | + } |
| 239 | + |
| 240 | + logger.LogInformation("Comparison completed successfully with no breaking changes"); |
| 241 | + return 0; // Success |
| 242 | + } |
| 243 | + catch (Exception ex) |
| 244 | + { |
| 245 | + logger.LogError(ex, "An error occurred during comparison"); |
| 246 | + AnsiConsole.MarkupLine($"[red]Error:[/] {ex.Message}"); |
| 247 | + return 2; // Error exit code |
| 248 | + } |
| 249 | + } |
| 250 | +} |
0 commit comments