1use chrono::{Datelike, NaiveDate, Timelike};
14use regex::Regex;
15
16use super::severity::detect_severity_from_text;
17use crate::models::log_entry::{LogEntry, LogFormat, Severity};
18use std::sync::OnceLock;
19
20fn engine_re() -> &'static Regex {
26 static CELL: OnceLock<Regex> = OnceLock::new();
27 CELL.get_or_init(|| {
28 Regex::new(
29 r"^MSI\s+\(([csaN])\)\s+\(([0-9A-Fa-f]+):([0-9A-Fa-f]+)\)\s+\[(\d{2}):(\d{2}):(\d{2}):(\d{3})\]:\s+(.*)$",
30 )
31 .expect("MSI engine regex must compile")
32})
33}
34
35fn header_re() -> &'static Regex {
37 static CELL: OnceLock<Regex> = OnceLock::new();
38 CELL.get_or_init(|| {
39 Regex::new(
40 r"^===\s+(?:Verbose\s+)?[Ll]ogging\s+started:\s+(\d{1,2}/\d{1,2}/\d{4})\s+(\d{1,2}:\d{2}:\d{2})\s+(.*)===\s*$",
41 )
42 .expect("MSI header regex must compile")
43})
44}
45
46fn footer_re() -> &'static Regex {
48 static CELL: OnceLock<Regex> = OnceLock::new();
49 CELL.get_or_init(|| {
50 Regex::new(r"^===\s+(?:Verbose\s+)?[Ll]ogging\s+stopped:\s+.*===\s*$")
51 .expect("MSI footer regex must compile")
52 })
53}
54
55fn action_start_re() -> &'static Regex {
57 static CELL: OnceLock<Regex> = OnceLock::new();
58 CELL.get_or_init(|| {
59 Regex::new(r"^Action start (\d{1,2}):(\d{2}):(\d{2}):\s+(\w+)\.\s*$")
60 .expect("MSI action start regex must compile")
61 })
62}
63
64fn action_ended_re() -> &'static Regex {
66 static CELL: OnceLock<Regex> = OnceLock::new();
67 CELL.get_or_init(|| {
68 Regex::new(r"^Action ended (\d{1,2}):(\d{2}):(\d{2}):\s+(\w+)\.\s+Return value (\d+)\.\s*$")
69 .expect("MSI action ended regex must compile")
70 })
71}
72
73fn action_top_re() -> &'static Regex {
75 static CELL: OnceLock<Regex> = OnceLock::new();
76 CELL.get_or_init(|| {
77 Regex::new(r"^Action (\d{1,2}):(\d{2}):(\d{2}):\s+(\w+)\.\s*$")
78 .expect("MSI top-level action regex must compile")
79 })
80}
81
82fn property_re() -> &'static Regex {
84 static CELL: OnceLock<Regex> = OnceLock::new();
85 CELL.get_or_init(|| {
86 Regex::new(r"^Property\([CScs]\):\s+(.*)$").expect("MSI property regex must compile")
87 })
88}
89
90fn main_engine_return_re() -> &'static Regex {
92 static CELL: OnceLock<Regex> = OnceLock::new();
93 CELL.get_or_init(|| {
94 Regex::new(r"^MainEngineThread is returning (\d+)")
95 .expect("MSI MainEngineThread regex must compile")
96 })
97}
98
99fn note_error_re() -> &'static Regex {
101 static CELL: OnceLock<Regex> = OnceLock::new();
102 CELL.get_or_init(|| {
103 Regex::new(r"Note:\s+1:\s+(\d+)").expect("MSI note error regex must compile")
104 })
105}
106
107pub fn matches_msi_content(line: &str) -> u32 {
114 let trimmed = line.trim();
115
116 if trimmed.starts_with("=== Verbose logging started:")
117 || trimmed.starts_with("=== Logging started:")
118 || trimmed.starts_with("=== verbose logging started:")
119 || trimmed.starts_with("=== logging started:")
120 {
121 return 3;
122 }
123
124 if trimmed.starts_with("MSI (c)")
125 || trimmed.starts_with("MSI (s)")
126 || trimmed.starts_with("MSI (a)")
127 || trimmed.starts_with("MSI (N)")
128 {
129 return 2;
130 }
131
132 if trimmed.starts_with("MainEngineThread is returning") {
133 return 2;
134 }
135
136 if action_start_re().is_match(trimmed) || action_ended_re().is_match(trimmed) {
137 return 1;
138 }
139
140 if trimmed.starts_with("Property(S):") || trimmed.starts_with("Property(C):") {
141 return 1;
142 }
143
144 0
145}
146
147struct MsiParserState {
153 current_date: Option<NaiveDate>,
155 prev_time_secs: Option<u32>,
157}
158
159impl MsiParserState {
160 fn new() -> Self {
161 Self {
162 current_date: None,
163 prev_time_secs: None,
164 }
165 }
166
167 fn advance_time(&mut self, h: u32, m: u32, s: u32) -> Option<NaiveDate> {
170 let current_secs = h * 3600 + m * 60 + s;
171
172 if let Some(prev_secs) = self.prev_time_secs {
173 if current_secs < prev_secs && (prev_secs - current_secs) > 82800 {
175 if let Some(date) = self.current_date {
176 self.current_date = date.succ_opt();
177 }
178 }
179 }
180 self.prev_time_secs = Some(current_secs);
181
182 self.current_date
183 }
184}
185
186pub fn parse_lines(lines: &[&str], file_path: &str) -> (Vec<LogEntry>, u32) {
192 let mut entries = Vec::with_capacity(lines.len());
193 let mut errors = 0u32;
194 let mut id_counter = 0u64;
195 let mut state = MsiParserState::new();
196
197 for (i, line) in lines.iter().enumerate() {
198 if line.trim().is_empty() {
199 continue;
200 }
201
202 let entry = parse_msi_line(line, file_path, &mut state, id_counter, (i + 1) as u32);
203 let is_fallback = entry.component.is_none()
204 && entry.timestamp.is_none()
205 && !footer_re().is_match(line.trim());
206
207 entries.push(entry);
208
209 if is_fallback {
210 errors += 1;
211 }
212
213 id_counter += 1;
214 }
215
216 (entries, errors)
217}
218
219fn parse_msi_line(
224 line: &str,
225 file_path: &str,
226 state: &mut MsiParserState,
227 id: u64,
228 line_number: u32,
229) -> LogEntry {
230 let trimmed = line.trim_end();
231
232 if let Some(caps) = header_re().captures(trimmed) {
234 return parse_header(caps, file_path, state, id, line_number, trimmed);
235 }
236
237 if footer_re().is_match(trimmed) {
239 return make_entry(
240 id,
241 line_number,
242 trimmed.to_string(),
243 Some("MSI-header".to_string()),
244 None,
245 None,
246 Severity::Info,
247 None,
248 None,
249 file_path,
250 );
251 }
252
253 if let Some(caps) = engine_re().captures(trimmed) {
255 return parse_engine(caps, file_path, state, id, line_number);
256 }
257
258 if let Some(caps) = action_ended_re().captures(trimmed) {
260 return parse_action_ended(caps, file_path, state, id, line_number, trimmed);
261 }
262
263 if let Some(caps) = action_start_re().captures(trimmed) {
265 return parse_action_start(caps, file_path, state, id, line_number, trimmed);
266 }
267
268 if let Some(caps) = action_top_re().captures(trimmed) {
270 return parse_action_top(caps, file_path, state, id, line_number, trimmed);
271 }
272
273 if let Some(caps) = property_re().captures(trimmed) {
275 return make_entry(
276 id,
277 line_number,
278 caps.get(1).map_or("", |m| m.as_str()).to_string(),
279 Some("MSI-properties".to_string()),
280 None,
281 None,
282 Severity::Info,
283 None,
284 None,
285 file_path,
286 );
287 }
288
289 if let Some(caps) = main_engine_return_re().captures(trimmed) {
291 let code: u32 = caps
292 .get(1)
293 .and_then(|m| m.as_str().parse().ok())
294 .unwrap_or(0);
295 let severity = severity_from_msi_exit_code(code);
296 return make_entry(
297 id,
298 line_number,
299 trimmed.to_string(),
300 Some("MSI-engine".to_string()),
301 None,
302 None,
303 severity,
304 None,
305 None,
306 file_path,
307 );
308 }
309
310 let severity = msi_text_severity(trimmed);
312 make_entry(
313 id,
314 line_number,
315 trimmed.to_string(),
316 None,
317 None,
318 None,
319 severity,
320 None,
321 None,
322 file_path,
323 )
324}
325
326fn parse_header(
331 caps: regex::Captures,
332 file_path: &str,
333 state: &mut MsiParserState,
334 id: u64,
335 line_number: u32,
336 raw: &str,
337) -> LogEntry {
338 let date_str = caps.get(1).map(|m| m.as_str()).unwrap_or("");
340 let time_str = caps.get(2).map(|m| m.as_str()).unwrap_or("");
341
342 let parsed_date = parse_us_date(date_str);
343 if let Some(d) = parsed_date {
344 state.current_date = Some(d);
345 }
346
347 let time_parts: Vec<u32> = time_str.split(':').filter_map(|p| p.parse().ok()).collect();
349 let (h, m, s) = if time_parts.len() == 3 {
350 (time_parts[0], time_parts[1], time_parts[2])
351 } else {
352 (0, 0, 0)
353 };
354
355 let (timestamp, timestamp_display) = if let Some(date) = parsed_date {
356 build_timestamp(date, h, m, s, 0)
357 } else {
358 (None, None)
359 };
360
361 if time_parts.len() == 3 {
362 state.prev_time_secs = Some(h * 3600 + m * 60 + s);
363 }
364
365 make_entry(
366 id,
367 line_number,
368 raw.to_string(),
369 Some("MSI-header".to_string()),
370 timestamp,
371 timestamp_display,
372 Severity::Info,
373 None,
374 None,
375 file_path,
376 )
377}
378
379fn parse_engine(
380 caps: regex::Captures,
381 file_path: &str,
382 state: &mut MsiParserState,
383 id: u64,
384 line_number: u32,
385) -> LogEntry {
386 let context_char = caps.get(1).map(|m| m.as_str()).unwrap_or("c");
387 let pid_hex = caps.get(2).map(|m| m.as_str()).unwrap_or("0");
388 let tid_hex = caps.get(3).map(|m| m.as_str()).unwrap_or("0");
389 let h: u32 = caps
390 .get(4)
391 .and_then(|m| m.as_str().parse().ok())
392 .unwrap_or(0);
393 let m: u32 = caps
394 .get(5)
395 .and_then(|m| m.as_str().parse().ok())
396 .unwrap_or(0);
397 let s: u32 = caps
398 .get(6)
399 .and_then(|m| m.as_str().parse().ok())
400 .unwrap_or(0);
401 let ms: u32 = caps
402 .get(7)
403 .and_then(|m| m.as_str().parse().ok())
404 .unwrap_or(0);
405 let message = caps.get(8).map(|m| m.as_str()).unwrap_or("").to_string();
406
407 let component = match context_char {
408 "c" => "MSI-client",
409 "s" => "MSI-server",
410 "a" => "MSI-action",
411 "N" => "MSI-nested",
412 _ => "MSI-client",
413 }
414 .to_string();
415
416 let thread_num = u32::from_str_radix(tid_hex, 16).ok();
417 let thread_display = Some(format!("{}:{}", pid_hex, tid_hex));
418
419 let date = state.advance_time(h, m, s);
420 let (timestamp, timestamp_display) = if let Some(d) = date {
421 build_timestamp(d, h, m, s, ms)
422 } else {
423 (None, Some(format!("{:02}:{:02}:{:02}.{:03}", h, m, s, ms)))
424 };
425
426 let severity = determine_engine_severity(&message);
428
429 make_entry(
430 id,
431 line_number,
432 message,
433 Some(component),
434 timestamp,
435 timestamp_display,
436 severity,
437 thread_num,
438 thread_display,
439 file_path,
440 )
441}
442
443fn parse_action_start(
444 caps: regex::Captures,
445 file_path: &str,
446 state: &mut MsiParserState,
447 id: u64,
448 line_number: u32,
449 raw: &str,
450) -> LogEntry {
451 let h: u32 = caps
452 .get(1)
453 .and_then(|m| m.as_str().parse().ok())
454 .unwrap_or(0);
455 let m: u32 = caps
456 .get(2)
457 .and_then(|m| m.as_str().parse().ok())
458 .unwrap_or(0);
459 let s: u32 = caps
460 .get(3)
461 .and_then(|m| m.as_str().parse().ok())
462 .unwrap_or(0);
463 let action = caps.get(4).map(|m| m.as_str()).unwrap_or("Unknown");
464
465 let date = state.advance_time(h, m, s);
466 let (timestamp, timestamp_display) = if let Some(d) = date {
467 build_timestamp(d, h, m, s, 0)
468 } else {
469 (None, Some(format!("{:02}:{:02}:{:02}.000", h, m, s)))
470 };
471
472 make_entry(
473 id,
474 line_number,
475 raw.to_string(),
476 Some(action.to_string()),
477 timestamp,
478 timestamp_display,
479 Severity::Info,
480 None,
481 None,
482 file_path,
483 )
484}
485
486fn parse_action_ended(
487 caps: regex::Captures,
488 file_path: &str,
489 state: &mut MsiParserState,
490 id: u64,
491 line_number: u32,
492 raw: &str,
493) -> LogEntry {
494 let h: u32 = caps
495 .get(1)
496 .and_then(|m| m.as_str().parse().ok())
497 .unwrap_or(0);
498 let m: u32 = caps
499 .get(2)
500 .and_then(|m| m.as_str().parse().ok())
501 .unwrap_or(0);
502 let s: u32 = caps
503 .get(3)
504 .and_then(|m| m.as_str().parse().ok())
505 .unwrap_or(0);
506 let action = caps.get(4).map(|m| m.as_str()).unwrap_or("Unknown");
507 let return_val: u32 = caps
508 .get(5)
509 .and_then(|m| m.as_str().parse().ok())
510 .unwrap_or(0);
511
512 let date = state.advance_time(h, m, s);
513 let (timestamp, timestamp_display) = if let Some(d) = date {
514 build_timestamp(d, h, m, s, 0)
515 } else {
516 (None, Some(format!("{:02}:{:02}:{:02}.000", h, m, s)))
517 };
518
519 let severity = severity_from_action_return(return_val);
520
521 make_entry(
522 id,
523 line_number,
524 raw.to_string(),
525 Some(action.to_string()),
526 timestamp,
527 timestamp_display,
528 severity,
529 None,
530 None,
531 file_path,
532 )
533}
534
535fn parse_action_top(
536 caps: regex::Captures,
537 file_path: &str,
538 state: &mut MsiParserState,
539 id: u64,
540 line_number: u32,
541 raw: &str,
542) -> LogEntry {
543 let h: u32 = caps
544 .get(1)
545 .and_then(|m| m.as_str().parse().ok())
546 .unwrap_or(0);
547 let m: u32 = caps
548 .get(2)
549 .and_then(|m| m.as_str().parse().ok())
550 .unwrap_or(0);
551 let s: u32 = caps
552 .get(3)
553 .and_then(|m| m.as_str().parse().ok())
554 .unwrap_or(0);
555 let action = caps.get(4).map(|m| m.as_str()).unwrap_or("Unknown");
556
557 let date = state.advance_time(h, m, s);
558 let (timestamp, timestamp_display) = if let Some(d) = date {
559 build_timestamp(d, h, m, s, 0)
560 } else {
561 (None, Some(format!("{:02}:{:02}:{:02}.000", h, m, s)))
562 };
563
564 make_entry(
565 id,
566 line_number,
567 raw.to_string(),
568 Some(action.to_string()),
569 timestamp,
570 timestamp_display,
571 Severity::Info,
572 None,
573 None,
574 file_path,
575 )
576}
577
578fn determine_engine_severity(message: &str) -> Severity {
585 if let Some(caps) = main_engine_return_re().captures(message) {
587 if let Some(code) = caps.get(1).and_then(|m| m.as_str().parse::<u32>().ok()) {
588 return severity_from_msi_exit_code(code);
589 }
590 }
591
592 if let Some(caps) = note_error_re().captures(message) {
594 if let Some(code) = caps.get(1).and_then(|m| m.as_str().parse::<u32>().ok()) {
595 if matches!(
597 code,
598 2318 | 2329
599 | 2331
600 | 2335
601 | 2337
602 | 2343
603 | 2345
604 | 2350
605 | 2351
606 | 2352
607 | 2355
608 | 2356
609 | 2357
610 | 2358
611 | 2359
612 | 2360
613 | 2361
614 | 2362
615 | 2371
616 | 2372
617 | 2373
618 | 2374
619 | 2375
620 | 2379
621 | 2380
622 | 2381
623 | 2382
624 ) {
625 return Severity::Error;
626 }
627 return Severity::Info;
629 }
630 }
631
632 let lower = message.to_lowercase();
634 if lower.contains("installation failed")
635 || lower.contains("error status: 1603")
636 || lower.contains("error status: 1618")
637 || lower.contains("product: error")
638 {
639 return Severity::Error;
640 }
641
642 detect_severity_from_text(message)
644}
645
646fn severity_from_msi_exit_code(code: u32) -> Severity {
648 match code {
649 0 => Severity::Info, 1707 => Severity::Info, 3010 => Severity::Info, 1602 => Severity::Warning, 1618 => Severity::Error, 1603 => Severity::Error, 1604 => Severity::Error, 1605 => Severity::Error, 1610 => Severity::Error, 1612 => Severity::Error, 1613 => Severity::Error, 1619 => Severity::Error, 1620 => Severity::Error, 1622 => Severity::Error, 1623 => Severity::Error, 1624 => Severity::Error, 1625 => Severity::Warning, 1638 => Severity::Warning, _ => {
668 if (1600..1700).contains(&code) {
670 Severity::Error
671 } else {
672 Severity::Info
673 }
674 }
675 }
676}
677
678fn severity_from_action_return(code: u32) -> Severity {
680 match code {
681 0 => Severity::Info, 1 => Severity::Info, 2 => Severity::Warning, 3 => Severity::Error, 4 => Severity::Warning, _ => Severity::Info,
687 }
688}
689
690fn msi_text_severity(text: &str) -> Severity {
692 let lower = text.to_lowercase();
693 if lower.contains("installation failed") || lower.contains("error status: 1603") {
694 return Severity::Error;
695 }
696 detect_severity_from_text(text)
697}
698
699fn parse_us_date(s: &str) -> Option<NaiveDate> {
705 let parts: Vec<&str> = s.split('/').collect();
706 if parts.len() != 3 {
707 return None;
708 }
709 let month: u32 = parts[0].parse().ok()?;
710 let day: u32 = parts[1].parse().ok()?;
711 let year: i32 = parts[2].parse().ok()?;
712 NaiveDate::from_ymd_opt(year, month, day)
713}
714
715fn build_timestamp(
717 date: NaiveDate,
718 h: u32,
719 m: u32,
720 s: u32,
721 ms: u32,
722) -> (Option<i64>, Option<String>) {
723 let dt = date.and_hms_milli_opt(h, m, s, ms);
724 let timestamp = dt.map(|ndt| ndt.and_utc().timestamp_millis());
725 let display = dt.map(|ndt| {
726 format!(
727 "{:02}-{:02}-{:04} {:02}:{:02}:{:02}.{:03}",
728 date.month(),
729 date.day(),
730 date.year(),
731 ndt.hour(),
732 ndt.minute(),
733 ndt.second(),
734 ms,
735 )
736 });
737 (timestamp, display)
738}
739
740#[allow(clippy::too_many_arguments)]
745fn make_entry(
746 id: u64,
747 line_number: u32,
748 message: String,
749 component: Option<String>,
750 timestamp: Option<i64>,
751 timestamp_display: Option<String>,
752 severity: Severity,
753 thread: Option<u32>,
754 thread_display: Option<String>,
755 file_path: &str,
756) -> LogEntry {
757 LogEntry {
758 id,
759 line_number,
760 message,
761 component,
762 timestamp,
763 timestamp_display,
764 severity,
765 thread,
766 thread_display,
767 source_file: None,
768 format: LogFormat::Timestamped,
769 file_path: file_path.to_string(),
770 timezone_offset: None,
771 error_code_spans: Vec::new(),
772 ip_address: None,
773 host_name: None,
774 mac_address: None,
775 result_code: None,
776 gle_code: None,
777 setup_phase: None,
778 operation_name: None,
779 http_method: None,
780 uri_stem: None,
781 uri_query: None,
782 status_code: None,
783 sub_status: None,
784 time_taken_ms: None,
785 client_ip: None,
786 server_ip: None,
787 user_agent: None,
788 server_port: None,
789 username: None,
790 win32_status: None,
791 query_name: None,
792 query_type: None,
793 response_code: None,
794 dns_direction: None,
795 dns_protocol: None,
796 source_ip: None,
797 dns_flags: None,
798 dns_event_id: None,
799 zone_name: None,
800 entry_kind: None,
801 whatif: None,
802 section_name: None,
803 section_color: None,
804 iteration: None,
805 tags: None,
806 }
807}
808
809#[cfg(test)]
814mod tests {
815 use super::*;
816
817 #[test]
820 fn test_matches_header() {
821 assert_eq!(
822 matches_msi_content("=== Verbose logging started: 6/13/2023 9:02:46 Build type: SHIP UNICODE 5.00.10011.00 Calling process: ... ==="),
823 3
824 );
825 }
826
827 #[test]
828 fn test_matches_logging_started_variant() {
829 assert_eq!(
830 matches_msi_content("=== Logging started: 1/2/2024 10:00:00 Build type: SHIP ==="),
831 3
832 );
833 }
834
835 #[test]
836 fn test_matches_engine_client() {
837 assert_eq!(
838 matches_msi_content("MSI (c) (8C:98) [07:42:28:452]: Resetting cached policy values"),
839 2
840 );
841 }
842
843 #[test]
844 fn test_matches_engine_server() {
845 assert_eq!(
846 matches_msi_content("MSI (s) (8C:98) [07:42:28:452]: Running server"),
847 2
848 );
849 }
850
851 #[test]
852 fn test_matches_main_engine_thread() {
853 assert_eq!(matches_msi_content("MainEngineThread is returning 0"), 2);
854 }
855
856 #[test]
857 fn test_matches_action_start() {
858 assert_eq!(
859 matches_msi_content("Action start 16:34:29: InstallFiles."),
860 1
861 );
862 }
863
864 #[test]
865 fn test_matches_action_ended() {
866 assert_eq!(
867 matches_msi_content("Action ended 16:34:29: InstallFiles. Return value 1."),
868 1
869 );
870 }
871
872 #[test]
873 fn test_matches_property() {
874 assert_eq!(
875 matches_msi_content(
876 "Property(C): ProductCode = {C64CA371-0000-0000-0000-000000000000}"
877 ),
878 1
879 );
880 }
881
882 #[test]
883 fn test_matches_plain_text_zero() {
884 assert_eq!(matches_msi_content("Just some random text"), 0);
885 }
886
887 #[test]
890 fn test_parse_header_extracts_date() {
891 let lines = [
892 "=== Verbose logging started: 6/13/2023 9:02:46 Build type: SHIP UNICODE 5.00.10011.00 Calling process: C:\\Windows\\System32\\msiexec.exe ===",
893 "MSI (c) (8C:98) [09:02:46:452]: Resetting cached policy values",
894 ];
895
896 let (entries, errors) = parse_lines(&lines, "install.log");
897
898 assert_eq!(errors, 0);
899 assert_eq!(entries.len(), 2);
900
901 assert_eq!(entries[0].component.as_deref(), Some("MSI-header"));
903 assert_eq!(entries[0].severity, Severity::Info);
904 assert!(entries[0].timestamp.is_some());
905 assert_eq!(
906 entries[0].timestamp_display.as_deref(),
907 Some("06-13-2023 09:02:46.000")
908 );
909
910 assert_eq!(entries[1].component.as_deref(), Some("MSI-client"));
912 assert!(entries[1].timestamp.is_some());
913 assert_eq!(
914 entries[1].timestamp_display.as_deref(),
915 Some("06-13-2023 09:02:46.452")
916 );
917 }
918
919 #[test]
922 fn test_parse_engine_message() {
923 let lines = [
924 "=== Verbose logging started: 1/15/2024 7:42:28 Build type: SHIP ===",
925 "MSI (c) (8C:98) [07:42:28:452]: Resetting cached policy values",
926 ];
927
928 let (entries, _) = parse_lines(&lines, "test.log");
929
930 assert_eq!(entries[1].message, "Resetting cached policy values");
931 assert_eq!(entries[1].component.as_deref(), Some("MSI-client"));
932 assert_eq!(entries[1].thread_display.as_deref(), Some("8C:98"));
933 assert_eq!(entries[1].thread, Some(0x98));
934 assert_eq!(entries[1].severity, Severity::Info);
935 }
936
937 #[test]
938 fn test_parse_engine_server_context() {
939 let lines = ["MSI (s) (4A:B0) [10:00:00:000]: Server running"];
940
941 let (entries, _) = parse_lines(&lines, "test.log");
942
943 assert_eq!(entries[0].component.as_deref(), Some("MSI-server"));
944 assert_eq!(entries[0].thread_display.as_deref(), Some("4A:B0"));
945 assert_eq!(entries[0].thread, Some(0xB0));
946 }
947
948 #[test]
949 fn test_parse_engine_action_context() {
950 let lines = ["MSI (a) (4A:B0) [10:00:00:000]: Custom action started"];
951
952 let (entries, _) = parse_lines(&lines, "test.log");
953 assert_eq!(entries[0].component.as_deref(), Some("MSI-action"));
954 }
955
956 #[test]
959 fn test_parse_action_start() {
960 let lines = [
961 "=== Verbose logging started: 1/1/2024 16:34:00 Build type: SHIP ===",
962 "Action start 16:34:29: InstallFiles.",
963 ];
964
965 let (entries, _) = parse_lines(&lines, "test.log");
966
967 assert_eq!(entries[1].component.as_deref(), Some("InstallFiles"));
968 assert_eq!(entries[1].severity, Severity::Info);
969 assert!(entries[1].timestamp.is_some());
970 }
971
972 #[test]
973 fn test_parse_action_ended_success() {
974 let lines = [
975 "=== Verbose logging started: 1/1/2024 16:34:00 Build type: SHIP ===",
976 "Action ended 16:34:29: InstallFiles. Return value 1.",
977 ];
978
979 let (entries, _) = parse_lines(&lines, "test.log");
980
981 assert_eq!(entries[1].component.as_deref(), Some("InstallFiles"));
982 assert_eq!(entries[1].severity, Severity::Info);
983 }
984
985 #[test]
986 fn test_parse_action_ended_error() {
987 let lines = [
988 "=== Verbose logging started: 1/1/2024 16:34:00 Build type: SHIP ===",
989 "Action ended 16:34:29: InstallFiles. Return value 3.",
990 ];
991
992 let (entries, _) = parse_lines(&lines, "test.log");
993 assert_eq!(entries[1].severity, Severity::Error);
994 }
995
996 #[test]
997 fn test_parse_action_ended_warning() {
998 let lines = ["Action ended 16:34:29: InstallFiles. Return value 2."];
999
1000 let (entries, _) = parse_lines(&lines, "test.log");
1001 assert_eq!(entries[0].severity, Severity::Warning);
1002 }
1003
1004 #[test]
1007 fn test_parse_property() {
1008 let lines = ["Property(C): ProductCode = {C64CA371-1234-5678-9ABC-DEF012345678}"];
1009
1010 let (entries, _) = parse_lines(&lines, "test.log");
1011
1012 assert_eq!(entries[0].component.as_deref(), Some("MSI-properties"));
1013 assert_eq!(
1014 entries[0].message,
1015 "ProductCode = {C64CA371-1234-5678-9ABC-DEF012345678}"
1016 );
1017 assert_eq!(entries[0].severity, Severity::Info);
1018 assert!(entries[0].timestamp.is_none());
1019 }
1020
1021 #[test]
1024 fn test_main_engine_thread_success() {
1025 let lines = ["MainEngineThread is returning 0"];
1026
1027 let (entries, _) = parse_lines(&lines, "test.log");
1028 assert_eq!(entries[0].severity, Severity::Info);
1029 assert_eq!(entries[0].component.as_deref(), Some("MSI-engine"));
1030 }
1031
1032 #[test]
1033 fn test_main_engine_thread_error_1603() {
1034 let lines = ["MainEngineThread is returning 1603"];
1035
1036 let (entries, _) = parse_lines(&lines, "test.log");
1037 assert_eq!(entries[0].severity, Severity::Error);
1038 }
1039
1040 #[test]
1041 fn test_main_engine_thread_warning_1602() {
1042 let lines = ["MainEngineThread is returning 1602"];
1043
1044 let (entries, _) = parse_lines(&lines, "test.log");
1045 assert_eq!(entries[0].severity, Severity::Warning);
1046 }
1047
1048 #[test]
1051 fn test_parse_footer() {
1052 let lines = ["=== Verbose logging stopped: 6/13/2023 9:03:15 ==="];
1053
1054 let (entries, errors) = parse_lines(&lines, "test.log");
1055
1056 assert_eq!(errors, 0);
1057 assert_eq!(entries[0].severity, Severity::Info);
1058 assert_eq!(entries[0].component.as_deref(), Some("MSI-header"));
1059 }
1060
1061 #[test]
1064 fn test_plain_text_fallback() {
1065 let lines = ["Some random unstructured text"];
1066
1067 let (entries, errors) = parse_lines(&lines, "test.log");
1068
1069 assert_eq!(errors, 1);
1070 assert_eq!(entries[0].severity, Severity::Info);
1071 assert!(entries[0].component.is_none());
1072 }
1073
1074 #[test]
1075 fn test_engine_error_keyword_severity() {
1076 let lines = ["MSI (c) (8C:98) [10:00:00:000]: Installation failed with error status: 1603"];
1077
1078 let (entries, _) = parse_lines(&lines, "test.log");
1079 assert_eq!(entries[0].severity, Severity::Error);
1080 }
1081
1082 #[test]
1085 fn test_midnight_rollover() {
1086 let lines = [
1087 "=== Verbose logging started: 1/15/2024 23:59:50 Build type: SHIP ===",
1088 "MSI (c) (8C:98) [23:59:55:000]: Before midnight",
1089 "MSI (c) (8C:98) [00:00:05:000]: After midnight",
1090 ];
1091
1092 let (entries, _) = parse_lines(&lines, "test.log");
1093
1094 assert!(entries[2].timestamp.is_some());
1096 assert_eq!(
1097 entries[2].timestamp_display.as_deref(),
1098 Some("01-16-2024 00:00:05.000")
1099 );
1100 }
1101
1102 #[test]
1105 fn test_empty_lines_skipped() {
1106 let lines = ["", " ", "MSI (c) (8C:98) [10:00:00:000]: Hello", ""];
1107
1108 let (entries, _) = parse_lines(&lines, "test.log");
1109 assert_eq!(entries.len(), 1);
1110 assert_eq!(entries[0].message, "Hello");
1111 }
1112
1113 #[test]
1116 fn test_ids_and_line_numbers() {
1117 let lines = [
1118 "=== Verbose logging started: 1/1/2024 10:00:00 Build type: SHIP ===",
1119 "MSI (c) (8C:98) [10:00:01:000]: First",
1120 "MSI (c) (8C:98) [10:00:02:000]: Second",
1121 ];
1122
1123 let (entries, _) = parse_lines(&lines, "test.log");
1124
1125 assert_eq!(entries[0].id, 0);
1126 assert_eq!(entries[0].line_number, 1);
1127 assert_eq!(entries[1].id, 1);
1128 assert_eq!(entries[1].line_number, 2);
1129 assert_eq!(entries[2].id, 2);
1130 assert_eq!(entries[2].line_number, 3);
1131 }
1132
1133 #[test]
1136 fn test_timestamp_display_format() {
1137 let lines = [
1138 "=== Verbose logging started: 12/25/2023 8:30:15 Build type: SHIP ===",
1139 "MSI (c) (FF:01) [08:30:15:007]: Test message",
1140 ];
1141
1142 let (entries, _) = parse_lines(&lines, "test.log");
1143
1144 assert_eq!(
1146 entries[1].timestamp_display.as_deref(),
1147 Some("12-25-2023 08:30:15.007")
1148 );
1149 }
1150
1151 #[test]
1154 fn test_engine_without_header_has_time_only_display() {
1155 let lines = ["MSI (c) (8C:98) [14:30:00:123]: No header yet"];
1156
1157 let (entries, _) = parse_lines(&lines, "test.log");
1158
1159 assert!(entries[0].timestamp.is_none());
1160 assert_eq!(
1161 entries[0].timestamp_display.as_deref(),
1162 Some("14:30:00.123")
1163 );
1164 }
1165
1166 #[test]
1169 fn test_file_path_propagated() {
1170 let lines = ["MSI (c) (8C:98) [10:00:00:000]: Test"];
1171
1172 let (entries, _) = parse_lines(&lines, "C:/Logs/install.log");
1173 assert_eq!(entries[0].file_path, "C:/Logs/install.log");
1174 }
1175
1176 #[test]
1179 fn test_log_format_is_timestamped() {
1180 let lines = [
1181 "MSI (c) (8C:98) [10:00:00:000]: Test",
1182 "Property(C): Foo = Bar",
1183 "Random line",
1184 ];
1185
1186 let (entries, _) = parse_lines(&lines, "test.log");
1187
1188 for entry in &entries {
1189 assert_eq!(entry.format, LogFormat::Timestamped);
1190 }
1191 }
1192}