forked from rtk-ai/rtk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinlog.rs
More file actions
1649 lines (1453 loc) · 54.3 KB
/
Copy pathbinlog.rs
File metadata and controls
1649 lines (1453 loc) · 54.3 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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::utils::strip_ansi;
use anyhow::{Context, Result};
use flate2::read::GzDecoder;
use lazy_static::lazy_static;
use regex::Regex;
use std::collections::HashSet;
use std::io::{Cursor, Read};
use std::path::Path;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BinlogIssue {
pub code: String,
pub file: String,
pub line: u32,
pub column: u32,
pub message: String,
}
#[derive(Debug, Clone, Default)]
pub struct BuildSummary {
pub succeeded: bool,
pub project_count: usize,
pub errors: Vec<BinlogIssue>,
pub warnings: Vec<BinlogIssue>,
pub duration_text: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FailedTest {
pub name: String,
pub details: Vec<String>,
}
#[derive(Debug, Clone, Default)]
pub struct TestSummary {
pub passed: usize,
pub failed: usize,
pub skipped: usize,
pub total: usize,
pub project_count: usize,
pub failed_tests: Vec<FailedTest>,
pub duration_text: Option<String>,
}
#[derive(Debug, Clone, Default)]
pub struct RestoreSummary {
pub restored_projects: usize,
pub warnings: usize,
pub errors: usize,
pub duration_text: Option<String>,
}
lazy_static! {
static ref ISSUE_RE: Regex = Regex::new(
r"(?m)^\s*(?P<file>[^\r\n:(]+)\((?P<line>\d+),(?P<column>\d+)\):\s*(?P<kind>error|warning)\s*(?:(?P<code>[A-Za-z]+\d+)\s*:\s*)?(?P<msg>.*)$"
)
.expect("valid regex");
static ref BUILD_SUMMARY_RE: Regex = Regex::new(r"(?mi)^\s*(?P<count>\d+)\s+(?P<kind>warning|error)\(s\)")
.expect("valid regex");
static ref ERROR_COUNT_RE: Regex =
Regex::new(r"(?i)\b(?P<count>\d+)\s+error\(s\)").expect("valid regex");
static ref WARNING_COUNT_RE: Regex =
Regex::new(r"(?i)\b(?P<count>\d+)\s+warning\(s\)").expect("valid regex");
static ref FALLBACK_ERROR_LINE_RE: Regex =
Regex::new(r"(?mi)^.+\(\d+,\d+\):\s*error(?:\s+[A-Za-z]{2,}\d{3,})?(?:\s*:.*)?$")
.expect("valid regex");
static ref FALLBACK_WARNING_LINE_RE: Regex =
Regex::new(r"(?mi)^.+\(\d+,\d+\):\s*warning(?:\s+[A-Za-z]{2,}\d{3,})?(?:\s*:.*)?$")
.expect("valid regex");
static ref DURATION_RE: Regex =
Regex::new(r"(?m)^\s*Time Elapsed\s+(?P<duration>[^\r\n]+)$").expect("valid regex");
static ref TEST_RESULT_RE: Regex = Regex::new(
r"(?m)(?:Passed!|Failed!)\s*-\s*Failed:\s*(?P<failed>\d+),\s*Passed:\s*(?P<passed>\d+),\s*Skipped:\s*(?P<skipped>\d+),\s*Total:\s*(?P<total>\d+),\s*Duration:\s*(?P<duration>[^\r\n-]+)"
)
.expect("valid regex");
static ref TEST_SUMMARY_RE: Regex = Regex::new(
r"(?mi)^\s*Test summary:\s*total:\s*(?P<total>\d+),\s*failed:\s*(?P<failed>\d+),\s*(?:succeeded|passed):\s*(?P<passed>\d+),\s*skipped:\s*(?P<skipped>\d+),\s*duration:\s*(?P<duration>[^\r\n]+)$"
)
.expect("valid regex");
static ref FAILED_TEST_HEAD_RE: Regex = Regex::new(
r"(?m)^\s*Failed\s+(?P<name>[^\r\n\[]+)\s+\[[^\]\r\n]+\]\s*$"
)
.expect("valid regex");
static ref RESTORE_PROJECT_RE: Regex =
Regex::new(r"(?m)^\s*Restored\s+.+\.csproj\s*\(").expect("valid regex");
static ref RESTORE_DIAGNOSTIC_RE: Regex = Regex::new(
r"(?mi)^\s*(?:(?P<file>.+?)\s+:\s+)?(?P<kind>warning|error)\s+(?P<code>[A-Za-z]{2,}\d{3,})\s*:\s*(?P<msg>.+)$"
)
.expect("valid regex");
static ref PROJECT_PATH_RE: Regex =
Regex::new(r"(?m)^\s*([A-Za-z]:)?[^\r\n]*\.csproj(?:\s|$)").expect("valid regex");
static ref PRINTABLE_RUN_RE: Regex = Regex::new(r"[\x20-\x7E]{5,}").expect("valid regex");
static ref DIAGNOSTIC_CODE_RE: Regex =
Regex::new(r"^[A-Za-z]{2,}\d{3,}$").expect("valid regex");
static ref SOURCE_FILE_RE: Regex = Regex::new(r"(?i)([A-Za-z]:)?[/\\][^\s]+\.(cs|vb|fs)")
.expect("valid regex");
static ref SENSITIVE_ENV_RE: Regex = {
let keys = SENSITIVE_ENV_VARS
.iter()
.map(|key| regex::escape(key))
.collect::<Vec<_>>()
.join("|");
Regex::new(&format!(
r"(?P<prefix>\b(?:{})\s*(?:=|:)\s*)(?P<value>[^\s;]+)",
keys
))
.expect("valid regex")
};
}
const SENSITIVE_ENV_VARS: &[&str] = &[
"PATH",
"HOME",
"USERPROFILE",
"USERNAME",
"USER",
"APPDATA",
"LOCALAPPDATA",
"TEMP",
"TMP",
"SSH_AUTH_SOCK",
"SSH_AGENT_LAUNCHER",
"GH_TOKEN",
"GITHUB_TOKEN",
"GITHUB_PAT",
"NUGET_API_KEY",
"NUGET_AUTH_TOKEN",
"VSS_NUGET_EXTERNAL_FEED_ENDPOINTS",
"AZURE_DEVOPS_TOKEN",
"AZURE_CLIENT_SECRET",
"AZURE_TENANT_ID",
"AZURE_CLIENT_ID",
"AWS_ACCESS_KEY_ID",
"AWS_SECRET_ACCESS_KEY",
"AWS_SESSION_TOKEN",
"API_TOKEN",
"AUTH_TOKEN",
"ACCESS_TOKEN",
"BEARER_TOKEN",
"PASSWORD",
"CONNECTION_STRING",
"DATABASE_URL",
"DOCKER_CONFIG",
"KUBECONFIG",
];
const RECORD_END_OF_FILE: i32 = 0;
const RECORD_BUILD_STARTED: i32 = 1;
const RECORD_BUILD_FINISHED: i32 = 2;
const RECORD_PROJECT_STARTED: i32 = 3;
const RECORD_PROJECT_FINISHED: i32 = 4;
const RECORD_ERROR: i32 = 9;
const RECORD_WARNING: i32 = 10;
const RECORD_MESSAGE: i32 = 11;
const RECORD_CRITICAL_BUILD_MESSAGE: i32 = 13;
const RECORD_PROJECT_IMPORT_ARCHIVE: i32 = 17;
const RECORD_NAME_VALUE_LIST: i32 = 23;
const RECORD_STRING: i32 = 24;
const FLAG_BUILD_EVENT_CONTEXT: i32 = 1 << 0;
const FLAG_MESSAGE: i32 = 1 << 2;
const FLAG_TIMESTAMP: i32 = 1 << 5;
const FLAG_ARGUMENTS: i32 = 1 << 14;
const FLAG_IMPORTANCE: i32 = 1 << 15;
const FLAG_EXTENDED: i32 = 1 << 16;
const STRING_RECORD_START_INDEX: i32 = 10;
pub fn parse_build(binlog_path: &Path) -> Result<BuildSummary> {
let parsed = parse_events_from_binlog(binlog_path)
.with_context(|| format!("Failed to parse binlog at {}", binlog_path.display()))?;
let strings_blob = parsed.string_records.join("\n");
let text_fallback = parse_build_from_text(&strings_blob);
let duration_text = match (parsed.build_started_ticks, parsed.build_finished_ticks) {
(Some(start), Some(end)) if end >= start => Some(format_ticks_duration(end - start)),
_ => None,
};
let parsed_project_count = parsed.project_files.len();
Ok(BuildSummary {
succeeded: parsed.build_succeeded.unwrap_or(false),
project_count: if parsed_project_count > 0 {
parsed_project_count
} else {
text_fallback.project_count
},
errors: select_best_issues(parsed.errors, text_fallback.errors),
warnings: select_best_issues(parsed.warnings, text_fallback.warnings),
duration_text,
})
}
fn select_best_issues(primary: Vec<BinlogIssue>, fallback: Vec<BinlogIssue>) -> Vec<BinlogIssue> {
if primary.is_empty() {
return fallback;
}
if fallback.is_empty() {
return primary;
}
if primary.iter().all(is_suspicious_issue) && fallback.iter().any(is_contextual_issue) {
return fallback;
}
if issues_quality_score(&fallback) > issues_quality_score(&primary) {
fallback
} else {
primary
}
}
fn issues_quality_score(issues: &[BinlogIssue]) -> usize {
issues.iter().map(issue_quality_score).sum()
}
fn issue_quality_score(issue: &BinlogIssue) -> usize {
let mut score = 0;
if is_contextual_issue(issue) {
score += 4;
}
if !issue.code.is_empty() && is_likely_diagnostic_code(&issue.code) {
score += 2;
}
if issue.line > 0 {
score += 1;
}
if issue.column > 0 {
score += 1;
}
if !issue.message.is_empty() && issue.message != "Build issue" {
score += 1;
}
score
}
fn is_contextual_issue(issue: &BinlogIssue) -> bool {
!issue.file.is_empty() && !is_likely_diagnostic_code(&issue.file)
}
fn is_suspicious_issue(issue: &BinlogIssue) -> bool {
issue.code.is_empty() && is_likely_diagnostic_code(&issue.file)
}
pub fn parse_test(binlog_path: &Path) -> Result<TestSummary> {
let parsed = parse_events_from_binlog(binlog_path)
.with_context(|| format!("Failed to parse binlog at {}", binlog_path.display()))?;
let blob = parsed.string_records.join("\n");
let mut summary = parse_test_from_text(&blob);
let parsed_project_count = parsed.project_files.len();
if parsed_project_count > 0 {
summary.project_count = parsed_project_count;
}
Ok(summary)
}
pub fn parse_restore(binlog_path: &Path) -> Result<RestoreSummary> {
let parsed = parse_events_from_binlog(binlog_path)
.with_context(|| format!("Failed to parse binlog at {}", binlog_path.display()))?;
let blob = parsed.string_records.join("\n");
let mut summary = parse_restore_from_text(&blob);
let parsed_project_count = parsed.project_files.len();
if parsed_project_count > 0 {
summary.restored_projects = parsed_project_count;
}
Ok(summary)
}
#[derive(Default)]
struct ParsedBinlog {
string_records: Vec<String>,
messages: Vec<String>,
project_files: HashSet<String>,
errors: Vec<BinlogIssue>,
warnings: Vec<BinlogIssue>,
build_succeeded: Option<bool>,
build_started_ticks: Option<i64>,
build_finished_ticks: Option<i64>,
}
#[derive(Default)]
struct ParsedEventFields {
message: Option<String>,
timestamp_ticks: Option<i64>,
}
fn parse_events_from_binlog(path: &Path) -> Result<ParsedBinlog> {
let bytes = std::fs::read(path)
.with_context(|| format!("Failed to read binlog at {}", path.display()))?;
if bytes.is_empty() {
anyhow::bail!("Failed to parse binlog at {}: empty file", path.display());
}
let mut decoder = GzDecoder::new(bytes.as_slice());
let mut payload = Vec::new();
decoder.read_to_end(&mut payload).with_context(|| {
format!(
"Failed to parse binlog at {}: gzip decode failed",
path.display()
)
})?;
let mut reader = BinReader::new(&payload);
let file_format_version = reader
.read_i32_le()
.context("binlog header missing file format version")?;
let _minimum_reader_version = reader
.read_i32_le()
.context("binlog header missing minimum reader version")?;
if file_format_version < 18 {
anyhow::bail!(
"Failed to parse binlog at {}: unsupported binlog format {}",
path.display(),
file_format_version
);
}
let mut parsed = ParsedBinlog::default();
while !reader.is_eof() {
let kind = reader
.read_7bit_i32()
.context("failed to read record kind")?;
if kind == RECORD_END_OF_FILE {
break;
}
match kind {
RECORD_STRING => {
let text = reader
.read_dotnet_string()
.context("failed to read string record")?;
parsed.string_records.push(text);
}
RECORD_NAME_VALUE_LIST | RECORD_PROJECT_IMPORT_ARCHIVE => {
let len = reader
.read_7bit_i32()
.context("failed to read record length")?;
if len < 0 {
anyhow::bail!("negative record length: {}", len);
}
reader
.skip(len as usize)
.context("failed to skip auxiliary record payload")?;
}
_ => {
let len = reader
.read_7bit_i32()
.context("failed to read event length")?;
if len < 0 {
anyhow::bail!("negative event length: {}", len);
}
let payload = reader
.read_exact(len as usize)
.context("failed to read event payload")?;
let mut event_reader = BinReader::new(payload);
let _ =
parse_event_record(kind, &mut event_reader, file_format_version, &mut parsed);
}
}
}
Ok(parsed)
}
fn parse_event_record(
kind: i32,
reader: &mut BinReader<'_>,
file_format_version: i32,
parsed: &mut ParsedBinlog,
) -> Result<()> {
match kind {
RECORD_BUILD_STARTED => {
let fields = read_event_fields(reader, file_format_version, parsed, false)?;
parsed.build_started_ticks = fields.timestamp_ticks;
}
RECORD_BUILD_FINISHED => {
let fields = read_event_fields(reader, file_format_version, parsed, false)?;
parsed.build_finished_ticks = fields.timestamp_ticks;
parsed.build_succeeded = Some(reader.read_bool()?);
}
RECORD_PROJECT_STARTED => {
let _fields = read_event_fields(reader, file_format_version, parsed, false)?;
if reader.read_bool()? {
skip_build_event_context(reader, file_format_version)?;
}
if let Some(project_file) = read_optional_string(reader, parsed)? {
if !project_file.is_empty() {
parsed.project_files.insert(project_file);
}
}
}
RECORD_PROJECT_FINISHED => {
let _fields = read_event_fields(reader, file_format_version, parsed, false)?;
if let Some(project_file) = read_optional_string(reader, parsed)? {
if !project_file.is_empty() {
parsed.project_files.insert(project_file);
}
}
let _ = reader.read_bool()?;
}
RECORD_ERROR | RECORD_WARNING => {
let fields = read_event_fields(reader, file_format_version, parsed, false)?;
let _subcategory = read_optional_string(reader, parsed)?;
let code = read_optional_string(reader, parsed)?.unwrap_or_default();
let file = read_optional_string(reader, parsed)?.unwrap_or_default();
let _project_file = read_optional_string(reader, parsed)?;
let line = reader.read_7bit_i32()?.max(0) as u32;
let column = reader.read_7bit_i32()?.max(0) as u32;
let _ = reader.read_7bit_i32()?;
let _ = reader.read_7bit_i32()?;
let issue = BinlogIssue {
code,
file,
line,
column,
message: fields.message.unwrap_or_default(),
};
if kind == RECORD_ERROR {
parsed.errors.push(issue);
} else {
parsed.warnings.push(issue);
}
}
RECORD_MESSAGE => {
let fields = read_event_fields(reader, file_format_version, parsed, true)?;
if let Some(message) = fields.message {
parsed.messages.push(message);
}
}
RECORD_CRITICAL_BUILD_MESSAGE => {
let fields = read_event_fields(reader, file_format_version, parsed, false)?;
if let Some(message) = fields.message {
parsed.messages.push(message);
}
}
_ => {}
}
Ok(())
}
fn read_event_fields(
reader: &mut BinReader<'_>,
file_format_version: i32,
parsed: &ParsedBinlog,
read_importance: bool,
) -> Result<ParsedEventFields> {
let flags = reader.read_7bit_i32()?;
let mut result = ParsedEventFields::default();
if flags & FLAG_MESSAGE != 0 {
result.message = read_deduplicated_string(reader, parsed)?;
}
if flags & FLAG_BUILD_EVENT_CONTEXT != 0 {
skip_build_event_context(reader, file_format_version)?;
}
if flags & FLAG_TIMESTAMP != 0 {
result.timestamp_ticks = Some(reader.read_i64_le()?);
let _ = reader.read_7bit_i32()?;
}
if flags & FLAG_EXTENDED != 0 {
let _ = read_optional_string(reader, parsed)?;
skip_string_dictionary(reader, file_format_version)?;
let _ = read_optional_string(reader, parsed)?;
}
if flags & FLAG_ARGUMENTS != 0 {
let count = reader.read_7bit_i32()?.max(0) as usize;
for _ in 0..count {
let _ = read_deduplicated_string(reader, parsed)?;
}
}
if (file_format_version < 13 && read_importance) || (flags & FLAG_IMPORTANCE != 0) {
let _ = reader.read_7bit_i32()?;
}
Ok(result)
}
fn skip_build_event_context(reader: &mut BinReader<'_>, file_format_version: i32) -> Result<()> {
let count = if file_format_version > 1 { 7 } else { 6 };
for _ in 0..count {
let _ = reader.read_7bit_i32()?;
}
Ok(())
}
fn skip_string_dictionary(reader: &mut BinReader<'_>, file_format_version: i32) -> Result<()> {
if file_format_version < 10 {
anyhow::bail!("legacy dictionary format is unsupported");
}
let _ = reader.read_7bit_i32()?;
Ok(())
}
fn read_optional_string(
reader: &mut BinReader<'_>,
parsed: &ParsedBinlog,
) -> Result<Option<String>> {
read_deduplicated_string(reader, parsed)
}
fn read_deduplicated_string(
reader: &mut BinReader<'_>,
parsed: &ParsedBinlog,
) -> Result<Option<String>> {
let index = reader.read_7bit_i32()?;
if index == 0 {
return Ok(None);
}
if index == 1 {
return Ok(Some(String::new()));
}
if index < STRING_RECORD_START_INDEX {
return Ok(None);
}
let record_idx = (index - STRING_RECORD_START_INDEX) as usize;
parsed
.string_records
.get(record_idx)
.cloned()
.map(Some)
.with_context(|| format!("invalid string record index {}", index))
}
fn format_ticks_duration(ticks: i64) -> String {
let total_seconds = ticks.div_euclid(10_000_000);
let centiseconds = ticks.rem_euclid(10_000_000) / 100_000;
let hours = total_seconds / 3600;
let minutes = (total_seconds % 3600) / 60;
let seconds = total_seconds % 60;
format!(
"{:02}:{:02}:{:02}.{:02}",
hours, minutes, seconds, centiseconds
)
}
struct BinReader<'a> {
cursor: Cursor<&'a [u8]>,
}
impl<'a> BinReader<'a> {
fn new(bytes: &'a [u8]) -> Self {
Self {
cursor: Cursor::new(bytes),
}
}
fn is_eof(&self) -> bool {
(self.cursor.position() as usize) >= self.cursor.get_ref().len()
}
fn read_exact(&mut self, len: usize) -> Result<&'a [u8]> {
let start = self.cursor.position() as usize;
let end = start.saturating_add(len);
if end > self.cursor.get_ref().len() {
anyhow::bail!("unexpected end of stream");
}
self.cursor.set_position(end as u64);
Ok(&self.cursor.get_ref()[start..end])
}
fn skip(&mut self, len: usize) -> Result<()> {
let _ = self.read_exact(len)?;
Ok(())
}
fn read_u8(&mut self) -> Result<u8> {
Ok(self.read_exact(1)?[0])
}
fn read_bool(&mut self) -> Result<bool> {
Ok(self.read_u8()? != 0)
}
fn read_i32_le(&mut self) -> Result<i32> {
let b = self.read_exact(4)?;
Ok(i32::from_le_bytes([b[0], b[1], b[2], b[3]]))
}
fn read_i64_le(&mut self) -> Result<i64> {
let b = self.read_exact(8)?;
Ok(i64::from_le_bytes([
b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7],
]))
}
fn read_7bit_i32(&mut self) -> Result<i32> {
let mut value: u32 = 0;
let mut shift = 0;
loop {
let byte = self.read_u8()?;
value |= ((byte & 0x7F) as u32) << shift;
if (byte & 0x80) == 0 {
return Ok(value as i32);
}
shift += 7;
if shift >= 35 {
anyhow::bail!("invalid 7-bit encoded integer");
}
}
}
fn read_dotnet_string(&mut self) -> Result<String> {
let len = self.read_7bit_i32()?;
if len < 0 {
anyhow::bail!("negative string length: {}", len);
}
let bytes = self.read_exact(len as usize)?;
String::from_utf8(bytes.to_vec()).context("invalid UTF-8 string")
}
}
pub fn scrub_sensitive_env_vars(input: &str) -> String {
SENSITIVE_ENV_RE
.replace_all(input, "${prefix}[REDACTED]")
.into_owned()
}
pub fn parse_build_from_text(text: &str) -> BuildSummary {
let text = text.replace("\r\n", "\n");
let clean = strip_ansi(&text);
let scrubbed = scrub_sensitive_env_vars(&clean);
let mut seen_errors: HashSet<(String, String, u32, u32, String)> = HashSet::new();
let mut seen_warnings: HashSet<(String, String, u32, u32, String)> = HashSet::new();
let mut summary = BuildSummary {
succeeded: scrubbed.contains("Build succeeded") && !scrubbed.contains("Build FAILED"),
project_count: count_projects(&scrubbed),
errors: Vec::new(),
warnings: Vec::new(),
duration_text: extract_duration(&scrubbed),
};
for captures in ISSUE_RE.captures_iter(&scrubbed) {
let issue = BinlogIssue {
code: captures
.name("code")
.map(|m| m.as_str().to_string())
.unwrap_or_default(),
file: captures
.name("file")
.map(|m| m.as_str().to_string())
.unwrap_or_default(),
line: captures
.name("line")
.and_then(|m| m.as_str().parse::<u32>().ok())
.unwrap_or(0),
column: captures
.name("column")
.and_then(|m| m.as_str().parse::<u32>().ok())
.unwrap_or(0),
message: captures
.name("msg")
.map(|m| {
let msg = m.as_str().trim();
if msg.is_empty() {
"diagnostic without message".to_string()
} else {
msg.to_string()
}
})
.unwrap_or_default(),
};
let key = (
issue.code.clone(),
issue.file.clone(),
issue.line,
issue.column,
issue.message.clone(),
);
match captures.name("kind").map(|m| m.as_str()) {
Some("error") => {
if seen_errors.insert(key) {
summary.errors.push(issue);
}
}
Some("warning") => {
if seen_warnings.insert(key) {
summary.warnings.push(issue);
}
}
_ => {}
}
}
if summary.errors.is_empty() || summary.warnings.is_empty() {
let mut warning_count_from_summary = 0;
let mut error_count_from_summary = 0;
for captures in BUILD_SUMMARY_RE.captures_iter(&scrubbed) {
let count = captures
.name("count")
.and_then(|m| m.as_str().parse::<usize>().ok())
.unwrap_or(0);
match captures
.name("kind")
.map(|m| m.as_str().to_ascii_lowercase())
.as_deref()
{
Some("warning") => {
warning_count_from_summary = warning_count_from_summary.max(count)
}
Some("error") => error_count_from_summary = error_count_from_summary.max(count),
_ => {}
}
}
let inline_error_count = ERROR_COUNT_RE
.captures_iter(&scrubbed)
.filter_map(|captures| {
captures
.name("count")
.and_then(|m| m.as_str().parse::<usize>().ok())
})
.max()
.unwrap_or(0);
let inline_warning_count = WARNING_COUNT_RE
.captures_iter(&scrubbed)
.filter_map(|captures| {
captures
.name("count")
.and_then(|m| m.as_str().parse::<usize>().ok())
})
.max()
.unwrap_or(0);
warning_count_from_summary = warning_count_from_summary.max(inline_warning_count);
error_count_from_summary = error_count_from_summary.max(inline_error_count);
if summary.errors.is_empty() {
for idx in 0..error_count_from_summary {
summary.errors.push(BinlogIssue {
code: String::new(),
file: String::new(),
line: 0,
column: 0,
message: format!("Build error #{} (details omitted)", idx + 1),
});
}
}
if summary.warnings.is_empty() {
for idx in 0..warning_count_from_summary {
summary.warnings.push(BinlogIssue {
code: String::new(),
file: String::new(),
line: 0,
column: 0,
message: format!("Build warning #{} (details omitted)", idx + 1),
});
}
}
if summary.errors.is_empty() {
let fallback_error_lines = FALLBACK_ERROR_LINE_RE.captures_iter(&scrubbed).count();
for idx in 0..fallback_error_lines {
summary.errors.push(BinlogIssue {
code: String::new(),
file: String::new(),
line: 0,
column: 0,
message: format!("Build error #{} (details omitted)", idx + 1),
});
}
}
if summary.warnings.is_empty() {
let fallback_warning_lines = FALLBACK_WARNING_LINE_RE.captures_iter(&scrubbed).count();
for idx in 0..fallback_warning_lines {
summary.warnings.push(BinlogIssue {
code: String::new(),
file: String::new(),
line: 0,
column: 0,
message: format!("Build warning #{} (details omitted)", idx + 1),
});
}
}
}
let has_error_signal = scrubbed.contains("Build FAILED")
|| scrubbed.contains(": error ")
|| BUILD_SUMMARY_RE.captures_iter(&scrubbed).any(|captures| {
let is_error = matches!(
captures
.name("kind")
.map(|m| m.as_str().to_ascii_lowercase())
.as_deref(),
Some("error")
);
let count = captures
.name("count")
.and_then(|m| m.as_str().parse::<usize>().ok())
.unwrap_or(0);
is_error && count > 0
});
if summary.errors.is_empty() || summary.warnings.is_empty() {
let (diagnostic_errors, diagnostic_warnings) = parse_restore_issues_from_text(&scrubbed);
if summary.errors.is_empty() {
summary.errors = diagnostic_errors;
}
if summary.warnings.is_empty() {
summary.warnings = diagnostic_warnings;
}
}
if summary.errors.is_empty() && !summary.succeeded && has_error_signal {
summary.errors = extract_binary_like_issues(&scrubbed);
}
if summary.project_count == 0
&& (scrubbed.contains("Build succeeded")
|| scrubbed.contains("Build FAILED")
|| scrubbed.contains(" -> "))
{
summary.project_count = 1;
}
summary
}
pub fn parse_test_from_text(text: &str) -> TestSummary {
let text = text.replace("\r\n", "\n");
let clean = strip_ansi(&text);
let scrubbed = scrub_sensitive_env_vars(&clean);
let mut summary = TestSummary {
passed: 0,
failed: 0,
skipped: 0,
total: 0,
project_count: count_projects(&scrubbed).max(1),
failed_tests: Vec::new(),
duration_text: extract_duration(&scrubbed),
};
let mut found_summary_line = false;
let mut fallback_duration = None;
for captures in TEST_RESULT_RE.captures_iter(&scrubbed) {
found_summary_line = true;
summary.passed += captures
.name("passed")
.and_then(|m| m.as_str().parse::<usize>().ok())
.unwrap_or(0);
summary.failed += captures
.name("failed")
.and_then(|m| m.as_str().parse::<usize>().ok())
.unwrap_or(0);
summary.skipped += captures
.name("skipped")
.and_then(|m| m.as_str().parse::<usize>().ok())
.unwrap_or(0);
summary.total += captures
.name("total")
.and_then(|m| m.as_str().parse::<usize>().ok())
.unwrap_or(0);
if let Some(duration) = captures.name("duration") {
fallback_duration = Some(duration.as_str().trim().to_string());
}
}
if found_summary_line && summary.duration_text.is_none() {
summary.duration_text = fallback_duration;
}
if let Some(captures) = TEST_SUMMARY_RE.captures_iter(&scrubbed).last() {
summary.passed = captures
.name("passed")
.and_then(|m| m.as_str().parse::<usize>().ok())
.unwrap_or(summary.passed);
summary.failed = captures
.name("failed")
.and_then(|m| m.as_str().parse::<usize>().ok())
.unwrap_or(summary.failed);
summary.skipped = captures
.name("skipped")
.and_then(|m| m.as_str().parse::<usize>().ok())
.unwrap_or(summary.skipped);
summary.total = captures
.name("total")
.and_then(|m| m.as_str().parse::<usize>().ok())
.unwrap_or(summary.total);
if let Some(duration) = captures.name("duration") {
summary.duration_text = Some(duration.as_str().trim().to_string());
}
}
let lines: Vec<&str> = scrubbed.lines().collect();
let mut idx = 0;
while idx < lines.len() {
let line = lines[idx];
if let Some(captures) = FAILED_TEST_HEAD_RE.captures(line) {
let name = captures
.name("name")
.map(|m| m.as_str().trim().to_string())
.unwrap_or_else(|| "unknown".to_string());
let mut details = Vec::new();
idx += 1;
while idx < lines.len() {
let detail_line = lines[idx].trim_end();
if FAILED_TEST_HEAD_RE.is_match(detail_line) {
idx = idx.saturating_sub(1);
break;
}
let detail_trimmed = detail_line.trim_start();
if detail_trimmed.starts_with("Failed! -")
|| detail_trimmed.starts_with("Passed! -")
|| detail_trimmed.starts_with("Test summary:")
|| detail_trimmed.starts_with("Build ")
{
idx = idx.saturating_sub(1);
break;
}
if detail_line.trim().is_empty() {
if !details.is_empty() {
details.push(String::new());
}
} else {
details.push(detail_line.trim().to_string());
}
if details.len() >= 20 {
break;
}
idx += 1;
}
summary.failed_tests.push(FailedTest { name, details });
}
idx += 1;
}
if summary.failed == 0 {
summary.failed = summary.failed_tests.len();
}
if summary.total == 0 {
summary.total = summary.passed + summary.failed + summary.skipped;
}
summary
}
pub fn parse_restore_from_text(text: &str) -> RestoreSummary {
let text = text.replace("\r\n", "\n");
let (errors, warnings) = parse_restore_issues_from_text(&text);
let clean = strip_ansi(&text);
let scrubbed = scrub_sensitive_env_vars(&clean);
RestoreSummary {
restored_projects: RESTORE_PROJECT_RE.captures_iter(&scrubbed).count(),
warnings: warnings.len(),
errors: errors.len(),
duration_text: extract_duration(&scrubbed),
}
}
pub fn parse_restore_issues_from_text(text: &str) -> (Vec<BinlogIssue>, Vec<BinlogIssue>) {
let text = text.replace("\r\n", "\n");
let clean = strip_ansi(&text);
let scrubbed = scrub_sensitive_env_vars(&clean);
let mut errors = Vec::new();
let mut warnings = Vec::new();
let mut seen_errors: HashSet<(String, String, u32, u32, String)> = HashSet::new();
let mut seen_warnings: HashSet<(String, String, u32, u32, String)> = HashSet::new();
for captures in RESTORE_DIAGNOSTIC_RE.captures_iter(&scrubbed) {
let issue = BinlogIssue {
code: captures
.name("code")
.map(|m| m.as_str().trim().to_string())
.unwrap_or_default(),
file: captures
.name("file")
.map(|m| m.as_str().trim().to_string())
.unwrap_or_default(),
line: 0,
column: 0,
message: captures
.name("msg")
.map(|m| m.as_str().trim().to_string())
.unwrap_or_default(),
};