|
| 1 | +namespace Microsoft.Crap4CSharp; |
| 2 | + |
| 3 | +using System.Globalization; |
| 4 | + |
| 5 | +// Faithful port of crap4java's CliApplication, adapted per docs/decisions.md departures #1 (fail-fast) |
| 6 | +// and #7 (resolve-once). Orchestrates: parse args -> pick files -> resolve module root ONCE -> |
| 7 | +// run coverage ONCE -> locate ONCE -> fail-fast gate -> parse -> analyze -> format -> print -> threshold. |
| 8 | +// Composes shipped types only; contains no resolution/coverage/parse internals of its own (the S5/T17 |
| 9 | +// model swap must touch only ModuleRootResolver -- the D-T12b seam). |
| 10 | +public sealed class CliApplication |
| 11 | +{ |
| 12 | + // Adapts crap4java's Main.usage() to the C# ecosystem: "Java" -> "C#", ".java" -> ".cs", and the |
| 13 | + // executable name to the crap4csharp product. Only ParseArguments consumes it (help + parse-error paths). |
| 14 | + private const string Usage = """ |
| 15 | + Usage: |
| 16 | + crap4csharp Analyze all C# files under src/ |
| 17 | + crap4csharp --changed Analyze changed C# files under src/ |
| 18 | + crap4csharp <path...> Analyze files, or for directory args analyze <dir>/src/**/*.cs |
| 19 | + crap4csharp --help Print this help message |
| 20 | + """; |
| 21 | + |
| 22 | + private readonly string _projectRoot; |
| 23 | + private readonly TextWriter _output; |
| 24 | + private readonly TextWriter _error; |
| 25 | + private readonly CoverageRunner _coverageRunner; |
| 26 | + |
| 27 | + public CliApplication( |
| 28 | + string projectRoot, |
| 29 | + TextWriter output, |
| 30 | + TextWriter error, |
| 31 | + CoverageRunner coverageRunner) |
| 32 | + { |
| 33 | + ArgumentNullException.ThrowIfNull(projectRoot); |
| 34 | + ArgumentNullException.ThrowIfNull(output); |
| 35 | + ArgumentNullException.ThrowIfNull(error); |
| 36 | + ArgumentNullException.ThrowIfNull(coverageRunner); |
| 37 | + _projectRoot = projectRoot; |
| 38 | + _output = output; |
| 39 | + _error = error; |
| 40 | + _coverageRunner = coverageRunner; |
| 41 | + } |
| 42 | + |
| 43 | + // Ports execute(String[]). Owns every exit code (§4): 0 (help / no files / max CRAP <= 8.0), |
| 44 | + // 1 (parse error / no report / empty report), 2 (threshold exceeded). The coverage-runner throw and |
| 45 | + // any parser throw PROPAGATE (faithful to Java's `throws Exception`); T15's Program.Main converts them |
| 46 | + // to exit 1. |
| 47 | + public int Execute(string[] args) |
| 48 | + { |
| 49 | + ParseOutcome parse = ParseArguments(args); |
| 50 | + if (parse.ExitCode >= 0) |
| 51 | + { |
| 52 | + return parse.ExitCode; |
| 53 | + } |
| 54 | + |
| 55 | + CliArguments parsed = parse.Arguments!; |
| 56 | + IReadOnlyList<string> filesToAnalyze = FilesForMode(parsed); |
| 57 | + if (filesToAnalyze.Count == 0) |
| 58 | + { |
| 59 | + _output.WriteLine("No C# files to analyze."); |
| 60 | + return 0; |
| 61 | + } |
| 62 | + |
| 63 | + // Resolve the module root ONCE and run coverage ONCE at it (departure #7: no module-group loop). |
| 64 | + string moduleRoot = ModuleRootResolver.Resolve(_projectRoot); |
| 65 | + _coverageRunner.GenerateCoverage(moduleRoot); |
| 66 | + |
| 67 | + // FAIL-FAST TRIGGER 1 (departure #1): no report produced at all. |
| 68 | + string? report = CoverageReportLocator.Locate(moduleRoot); |
| 69 | + if (report is null) |
| 70 | + { |
| 71 | + _error.WriteLine($"No coverage report was produced under '{moduleRoot}'. Ensure a test project references coverlet.collector so 'dotnet test --collect' emits coverage.cobertura.xml."); |
| 72 | + return 1; |
| 73 | + } |
| 74 | + |
| 75 | + // FAIL-FAST TRIGGER 2 (departure #1): a report was produced but carries no coverage data. Inspect |
| 76 | + // the parsed map's emptiness -- NOT the metrics: a populated-but-non-matching report ALSO yields |
| 77 | + // all-N/A metrics yet must not fail-fast (that per-method N/A path lives in CrapAnalyzer, unchanged). |
| 78 | + IReadOnlyDictionary<string, CoverageData> coverageMap = CoberturaCoverageParser.Parse(report); |
| 79 | + if (coverageMap.Count == 0) |
| 80 | + { |
| 81 | + _error.WriteLine($"Coverage report '{report}' contained no coverage data. Failing fast."); |
| 82 | + return 1; |
| 83 | + } |
| 84 | + |
| 85 | + // CrapAnalyzer re-parses `report` (locked double-parse, option A): negligible cost, zero API change. |
| 86 | + IReadOnlyList<MethodMetrics> metrics = CrapAnalyzer.Analyze(filesToAnalyze, report); |
| 87 | + |
| 88 | + // The report already ends with '\n' and is already sorted by both CrapAnalyzer and ReportFormatter, |
| 89 | + // so the Java pre-format sort is redundant and omitted (behavior-preserving; MaxCrap is order-free). |
| 90 | + _output.Write(ReportFormatter.Format(metrics)); |
| 91 | + |
| 92 | + double max = MaxCrap(metrics); |
| 93 | + if (ThresholdExceeded(max)) |
| 94 | + { |
| 95 | + _error.WriteLine(string.Format( |
| 96 | + CultureInfo.InvariantCulture, |
| 97 | + "CRAP threshold exceeded: {0:F1} > 8.0", |
| 98 | + max)); |
| 99 | + return 2; |
| 100 | + } |
| 101 | + |
| 102 | + return 0; |
| 103 | + } |
| 104 | + |
| 105 | + // Ports thresholdExceeded: strict '>' against 8.0 via CompareTo (Java's Double.compare analog). |
| 106 | + public static bool ThresholdExceeded(double max) => max.CompareTo(8.0) > 0; |
| 107 | + |
| 108 | + // Ports Main.maxCrap: the largest non-null CrapScore, or 0.0 when every method is N/A. |
| 109 | + public static double MaxCrap(IReadOnlyList<MethodMetrics> metrics) |
| 110 | + { |
| 111 | + ArgumentNullException.ThrowIfNull(metrics); |
| 112 | + |
| 113 | + double max = 0.0; |
| 114 | + foreach (MethodMetrics metric in metrics) |
| 115 | + { |
| 116 | + if (metric.CrapScore is not null) |
| 117 | + { |
| 118 | + max = Math.Max(max, metric.CrapScore.Value); |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + return max; |
| 123 | + } |
| 124 | + |
| 125 | + // Ports parseArguments: parse; on --help print usage to stdout and exit 0; on ArgumentException (W6: |
| 126 | + // the broad type, catching the ArgumentNullException null-args case too) print the message to stderr, |
| 127 | + // usage to stdout, and exit 1; otherwise proceed (ExitCode -1). |
| 128 | + private ParseOutcome ParseArguments(string[] args) |
| 129 | + { |
| 130 | + try |
| 131 | + { |
| 132 | + CliArguments parsed = CliArgumentsParser.Parse(args); |
| 133 | + if (parsed.Mode == CliMode.Help) |
| 134 | + { |
| 135 | + _output.WriteLine(Usage); |
| 136 | + return ParseOutcome.Exit(0); |
| 137 | + } |
| 138 | + |
| 139 | + return ParseOutcome.Ok(parsed); |
| 140 | + } |
| 141 | + catch (ArgumentException ex) |
| 142 | + { |
| 143 | + _error.WriteLine(ex.Message); |
| 144 | + _output.WriteLine(Usage); |
| 145 | + return ParseOutcome.Exit(1); |
| 146 | + } |
| 147 | + } |
| 148 | + |
| 149 | + // Ports filesForMode: a switch expression over all four CliMode arms plus a default throw (W7). The |
| 150 | + // Help arm is dead (ParseArguments short-circuits it), retained for exhaustiveness. |
| 151 | + private IReadOnlyList<string> FilesForMode(CliArguments parsed) |
| 152 | + { |
| 153 | + return parsed.Mode switch |
| 154 | + { |
| 155 | + CliMode.AllSrc => SourceFileFinder.FindAllCSharpFilesUnderSrc(_projectRoot), |
| 156 | + CliMode.ChangedSrc => ChangedFileDetector.ChangedCSharpFilesUnderSrc(_projectRoot), |
| 157 | + CliMode.ExplicitFiles => ExplicitFiles(parsed.FileArgs), |
| 158 | + CliMode.Help => [], |
| 159 | + _ => throw new InvalidOperationException($"Unhandled CLI mode: {parsed.Mode}"), |
| 160 | + }; |
| 161 | + } |
| 162 | + |
| 163 | + // Ports explicitFiles: resolve each arg against projectRoot; a directory arg expands via SourceFileFinder |
| 164 | + // (routing through the finder keeps the bin/obj exclusion, W12), a file arg is taken verbatim. |
| 165 | + // De-duplicate and sort with StringComparer.Ordinal (departure #3; replaces Java's LinkedHashSet + |
| 166 | + // naturalOrder), matching SourceFileFinder/ChangedFileDetector. |
| 167 | + private IReadOnlyList<string> ExplicitFiles(IReadOnlyList<string> fileArgs) |
| 168 | + { |
| 169 | + HashSet<string> files = new(StringComparer.Ordinal); |
| 170 | + foreach (string arg in fileArgs) |
| 171 | + { |
| 172 | + string path = Path.GetFullPath(Path.Combine(_projectRoot, arg)); |
| 173 | + if (Directory.Exists(path)) |
| 174 | + { |
| 175 | + foreach (string found in SourceFileFinder.FindAllCSharpFilesUnderSrc(path)) |
| 176 | + { |
| 177 | + files.Add(found); |
| 178 | + } |
| 179 | + } |
| 180 | + else |
| 181 | + { |
| 182 | + files.Add(path); |
| 183 | + } |
| 184 | + } |
| 185 | + |
| 186 | + return [.. files.OrderBy(path => path, StringComparer.Ordinal)]; |
| 187 | + } |
| 188 | + |
| 189 | + // Ports Java's ParseOutcome: Ok(arguments) proceeds (ExitCode -1); Exit(code) short-circuits with an |
| 190 | + // exit code. Arguments is non-null exactly when ExitCode < 0. |
| 191 | + private sealed class ParseOutcome |
| 192 | + { |
| 193 | + private ParseOutcome(CliArguments? arguments, int exitCode) |
| 194 | + { |
| 195 | + Arguments = arguments; |
| 196 | + ExitCode = exitCode; |
| 197 | + } |
| 198 | + |
| 199 | + public CliArguments? Arguments { get; } |
| 200 | + |
| 201 | + public int ExitCode { get; } |
| 202 | + |
| 203 | + public static ParseOutcome Ok(CliArguments arguments) => new(arguments, -1); |
| 204 | + |
| 205 | + public static ParseOutcome Exit(int code) => new(null, code); |
| 206 | + } |
| 207 | +} |
0 commit comments