| 1 | using System.Text.RegularExpressions; |
| 2 | |
| 3 | namespace DotNetBuildTestParsers; |
| 4 | |
| 5 | /// <summary>Один элемент вывода сборки: ошибка или предупреждение (файл, строка, столбец, код, сообщение).</summary> |
| 6 | public sealed record BuildDiagnostic(string File, int Line, int? Column, string? Code, string Message); |
| 7 | |
| 8 | /// <summary>Результат разбора вывода dotnet build (MSBuild-формат: path(line,col): error/warning code: message).</summary> |
| 9 | public sealed record BuildParseResult( |
| 10 | int ExitCode, |
| 11 | IReadOnlyList<BuildDiagnostic> Errors, |
| 12 | IReadOnlyList<BuildDiagnostic> Warnings) |
| 13 | { |
| 14 | public bool Success => ExitCode == 0 && Errors.Count == 0; |
| 15 | } |
| 16 | |
| 17 | public static class BuildOutputParser |
| 18 | { |
| 19 | private static readonly Regex DiagnosticRegex = new( |
| 20 | @"^(.+?)\((\d+)(?:,(\d+))?\):\s*(error|warning)\s*(\S*?):\s*(.*)$", |
| 21 | RegexOptions.Compiled); |
| 22 | |
| 23 | private static readonly Regex ExitCodeRegex = new( |
| 24 | @"Exit code:\s*(\d+)\s*$", |
| 25 | RegexOptions.Compiled | RegexOptions.Multiline); |
| 26 | |
| 27 | /// <summary>Разбирает вывод dotnet build: извлекает ошибки, предупреждения и при наличии — код выхода.</summary> |
| 28 | public static BuildParseResult Parse(string output) |
| 29 | { |
| 30 | if (string.IsNullOrEmpty(output)) |
| 31 | return new BuildParseResult(0, [], []); |
| 32 | |
| 33 | var errors = new List<BuildDiagnostic>(); |
| 34 | var warnings = new List<BuildDiagnostic>(); |
| 35 | var lines = output.Split('\n'); |
| 36 | |
| 37 | foreach (var line in lines) |
| 38 | { |
| 39 | var s = line.Trim(); |
| 40 | if (s.Length == 0) continue; |
| 41 | |
| 42 | var m = DiagnosticRegex.Match(s); |
| 43 | if (!m.Success) continue; |
| 44 | |
| 45 | var file = m.Groups[1].Value.Trim().Trim('"'); |
| 46 | var lineNum = int.Parse(m.Groups[2].ValueSpan); |
| 47 | var col = m.Groups[3].Success && m.Groups[3].Value.Length > 0 ? int.Parse(m.Groups[3].ValueSpan) : (int?)null; |
| 48 | var severity = m.Groups[4].Value; |
| 49 | var code = m.Groups[5].Success ? m.Groups[5].Value : null; |
| 50 | if (string.IsNullOrWhiteSpace(code)) code = null; |
| 51 | var message = m.Groups[6].Value.Trim(); |
| 52 | |
| 53 | var d = new BuildDiagnostic(file, lineNum, col, code, message); |
| 54 | if (severity.Equals("error", StringComparison.OrdinalIgnoreCase)) |
| 55 | errors.Add(d); |
| 56 | else |
| 57 | warnings.Add(d); |
| 58 | } |
| 59 | |
| 60 | var exitCode = 0; |
| 61 | var exitMatch = ExitCodeRegex.Match(output); |
| 62 | if (exitMatch.Success) |
| 63 | exitCode = int.Parse(exitMatch.Groups[1].ValueSpan); |
| 64 | |
| 65 | return new BuildParseResult(exitCode, errors, warnings); |
| 66 | } |
| 67 | } |
| 68 | |