sarif_rust 0.3.0

A comprehensive Rust library for parsing, generating, and manipulating SARIF (Static Analysis Results Interchange Format) v2.1.0 files
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
//! SARIF merge and diff functionality
//!
//! This module provides utilities for merging multiple SARIF files and computing
//! differences between SARIF logs, useful for tracking changes in analysis results.

use crate::parser::{SarifError, SarifResult as ParseResult};
use crate::types::{Level, Result as SarifResult, Run, SarifLog};
use crate::utils::indexing::{ResultLocation, SarifIndex};
use std::collections::{HashMap, HashSet};

/// Configuration for SARIF merge operations
#[derive(Debug, Clone)]
pub struct MergeConfig {
    /// Whether to merge runs from the same tool into a single run
    pub consolidate_runs: bool,

    /// Whether to deduplicate results based on fingerprints
    pub deduplicate_results: bool,

    /// How to handle version conflicts between SARIF logs
    pub version_strategy: VersionMergeStrategy,

    /// Whether to preserve original file paths or normalize them
    pub normalize_paths: bool,

    /// Maximum number of runs to include in merged output
    pub max_runs: Option<usize>,

    /// Filters for including/excluding specific tools or rules
    pub filters: MergeFilters,
}

/// Strategy for handling version conflicts during merge
#[derive(Debug, Clone, PartialEq)]
pub enum VersionMergeStrategy {
    /// Use the highest version number found
    UseLatest,
    /// Use the first version encountered
    UseFirst,
    /// Require all versions to match
    RequireMatch,
    /// Use a specific version
    UseSpecific(String),
}

/// Filters for controlling what gets included in merge operations
#[derive(Debug, Clone, Default)]
pub struct MergeFilters {
    /// Include only these tools (None means include all)
    pub include_tools: Option<HashSet<String>>,

    /// Exclude these tools
    pub exclude_tools: HashSet<String>,

    /// Include only these rule IDs (None means include all)
    pub include_rules: Option<HashSet<String>>,

    /// Exclude these rule IDs
    pub exclude_rules: HashSet<String>,

    /// Include only results with these levels or higher
    pub min_level: Option<Level>,

    /// Include only results from these file patterns
    pub include_file_patterns: Vec<String>,
}

/// Configuration for SARIF diff operations
#[derive(Debug, Clone)]
pub struct DiffConfig {
    /// How to match results between different SARIF logs
    pub matching_strategy: ResultMatchingStrategy,

    /// Whether to include results that are only in the baseline
    pub include_removed: bool,

    /// Whether to include results that are only in the comparison
    pub include_added: bool,

    /// Whether to include results that have changed
    pub include_modified: bool,

    /// Whether to ignore differences in messages when comparing results
    pub ignore_message_changes: bool,

    /// Whether to ignore differences in locations when comparing results
    pub ignore_location_changes: bool,
}

/// Strategy for matching results between SARIF logs during diff
#[derive(Debug, Clone, PartialEq)]
pub enum ResultMatchingStrategy {
    /// Match by GUID (most precise)
    ByGuid,
    /// Match by rule ID + file path + line number
    ByRuleAndLocation,
    /// Match by rule ID + message fingerprint
    ByRuleAndMessage,
    /// Custom matching using fingerprints
    ByFingerprint,
}

/// Result of a SARIF merge operation
#[derive(Debug, Clone)]
pub struct MergeResult {
    /// The merged SARIF log
    pub merged_log: SarifLog,

    /// Statistics about the merge operation
    pub stats: MergeStats,

    /// Warnings or issues encountered during merge
    pub warnings: Vec<String>,
}

/// Statistics from a merge operation
#[derive(Debug, Clone, Default)]
pub struct MergeStats {
    /// Number of input SARIF logs processed
    pub input_logs: usize,

    /// Total number of runs before merge
    pub input_runs: usize,

    /// Number of runs in merged output
    pub output_runs: usize,

    /// Total number of results before merge
    pub input_results: usize,

    /// Number of results in merged output
    pub output_results: usize,

    /// Number of results deduplicated
    pub deduplicated_results: usize,

    /// Number of runs consolidated
    pub consolidated_runs: usize,
}

/// Result of a SARIF diff operation
#[derive(Debug, Clone)]
pub struct DiffResult {
    /// Results that were added (only in comparison, not in baseline)
    pub added: Vec<(SarifResult, ResultLocation)>,

    /// Results that were removed (only in baseline, not in comparison)
    pub removed: Vec<(SarifResult, ResultLocation)>,

    /// Results that were modified between baseline and comparison
    pub modified: Vec<ResultDiff>,

    /// Results that are unchanged
    pub unchanged: Vec<(SarifResult, ResultLocation)>,

    /// Statistics about the diff operation
    pub stats: DiffStats,
}

/// Information about a modified result
#[derive(Debug, Clone)]
pub struct ResultDiff {
    /// The result from the baseline
    pub baseline: (SarifResult, ResultLocation),

    /// The result from the comparison
    pub comparison: (SarifResult, ResultLocation),

    /// Specific changes detected
    pub changes: Vec<ResultChange>,
}

/// Specific types of changes detected in results
#[derive(Debug, Clone, PartialEq)]
pub enum ResultChange {
    /// Message text changed
    MessageChanged { old: String, new: String },

    /// Level changed
    LevelChanged {
        old: Option<Level>,
        new: Option<Level>,
    },

    /// Location changed
    LocationChanged { old: String, new: String },

    /// Rule ID changed
    RuleChanged {
        old: Option<String>,
        new: Option<String>,
    },

    /// Custom property changed
    PropertyChanged {
        key: String,
        old: Option<String>,
        new: Option<String>,
    },
}

/// Statistics from a diff operation
#[derive(Debug, Clone, Default)]
pub struct DiffStats {
    /// Number of results in baseline
    pub baseline_count: usize,

    /// Number of results in comparison
    pub comparison_count: usize,

    /// Number of added results
    pub added_count: usize,

    /// Number of removed results
    pub removed_count: usize,

    /// Number of modified results
    pub modified_count: usize,

    /// Number of unchanged results
    pub unchanged_count: usize,
}

/// SARIF merger for combining multiple SARIF logs
pub struct SarifMerger {
    config: MergeConfig,
}

impl SarifMerger {
    /// Create a new SARIF merger with default configuration
    pub fn new() -> Self {
        Self {
            config: MergeConfig::default(),
        }
    }

    /// Create a SARIF merger with custom configuration
    pub fn with_config(config: MergeConfig) -> Self {
        Self { config }
    }

    /// Merge multiple SARIF logs into a single log
    pub fn merge(&self, logs: &[SarifLog]) -> ParseResult<MergeResult> {
        if logs.is_empty() {
            return Err(SarifError::custom("Cannot merge empty list of SARIF logs"));
        }

        let mut stats = MergeStats {
            input_logs: logs.len(),
            ..Default::default()
        };

        let mut warnings = Vec::new();

        // Determine the version to use
        let target_version = self.determine_target_version(logs, &mut warnings)?;

        // Collect all runs from all logs
        let mut all_runs = Vec::new();
        for log in logs {
            if self.should_include_log(log) {
                for run in &log.runs {
                    if self.should_include_run(run) {
                        all_runs.push(run.clone());
                        stats.input_runs += 1;

                        if let Some(results) = &run.results {
                            stats.input_results += results.len();
                        }
                    }
                }
            }
        }

        // Apply consolidation if configured
        let final_runs = if self.config.consolidate_runs {
            self.consolidate_runs(all_runs, &mut stats)
        } else {
            all_runs
        };

        // Apply deduplication if configured
        let final_runs = if self.config.deduplicate_results {
            self.deduplicate_results(final_runs, &mut stats)
        } else {
            final_runs
        };

        // Apply max runs limit if configured
        let final_runs = if let Some(max_runs) = self.config.max_runs {
            if final_runs.len() > max_runs {
                warnings.push(format!(
                    "Truncated output to {} runs (was {})",
                    max_runs,
                    final_runs.len()
                ));
                final_runs.into_iter().take(max_runs).collect()
            } else {
                final_runs
            }
        } else {
            final_runs
        };

        stats.output_runs = final_runs.len();
        for run in &final_runs {
            if let Some(results) = &run.results {
                stats.output_results += results.len();
            }
        }

        let merged_log = SarifLog {
            version: target_version,
            schema: logs.first().and_then(|log| log.schema.clone()),
            runs: final_runs,
            inline_external_properties: None,
            properties: None,
        };

        Ok(MergeResult {
            merged_log,
            stats,
            warnings,
        })
    }

    /// Determine the target version based on merge strategy
    fn determine_target_version(
        &self,
        logs: &[SarifLog],
        _warnings: &mut Vec<String>,
    ) -> ParseResult<String> {
        match &self.config.version_strategy {
            VersionMergeStrategy::UseSpecific(version) => Ok(version.clone()),
            VersionMergeStrategy::UseFirst => Ok(logs[0].version.clone()),
            VersionMergeStrategy::UseLatest => {
                let mut versions: Vec<_> = logs.iter().map(|log| &log.version).collect();
                versions.sort();
                Ok(versions.last().unwrap().to_string())
            }
            VersionMergeStrategy::RequireMatch => {
                let first_version = &logs[0].version;
                for log in &logs[1..] {
                    if log.version != *first_version {
                        return Err(SarifError::custom(format!(
                            "Version mismatch: {} vs {}",
                            first_version, log.version
                        )));
                    }
                }
                Ok(first_version.clone())
            }
        }
    }

    /// Check if a log should be included based on filters
    fn should_include_log(&self, _log: &SarifLog) -> bool {
        // For now, include all logs - could add log-level filters later
        true
    }

    /// Check if a run should be included based on filters
    fn should_include_run(&self, run: &Run) -> bool {
        let tool_name = &run.tool.driver.name;

        // Check tool inclusion filters
        if let Some(ref include_tools) = self.config.filters.include_tools
            && !include_tools.contains(tool_name)
        {
            return false;
        }

        // Check tool exclusion filters
        if self.config.filters.exclude_tools.contains(tool_name) {
            return false;
        }

        true
    }


    /// Consolidate runs from the same tool
    fn consolidate_runs(&self, runs: Vec<Run>, stats: &mut MergeStats) -> Vec<Run> {
        let mut tool_runs: HashMap<String, Vec<Run>> = HashMap::new();

        for run in runs {
            tool_runs
                .entry(run.tool.driver.name.clone())
                .or_default()
                .push(run);
        }

        let mut consolidated = Vec::new();

        for (_tool_name, mut tool_run_list) in tool_runs {
            if tool_run_list.len() > 1 {
                stats.consolidated_runs += tool_run_list.len() - 1;

                // Merge all runs for this tool into the first one
                let mut base_run = tool_run_list.remove(0);

                for additional_run in tool_run_list {
                    // Merge results
                    if let Some(additional_results) = additional_run.results {
                        base_run
                            .results
                            .get_or_insert_with(Vec::new)
                            .extend(additional_results);
                    }

                    // Merge artifacts
                    if let Some(additional_artifacts) = additional_run.artifacts {
                        base_run
                            .artifacts
                            .get_or_insert_with(Vec::new)
                            .extend(additional_artifacts);
                    }

                    // Merge invocations
                    if let Some(additional_invocations) = additional_run.invocations {
                        base_run
                            .invocations
                            .get_or_insert_with(Vec::new)
                            .extend(additional_invocations);
                    }
                }

                consolidated.push(base_run);
            } else {
                consolidated.push(tool_run_list.into_iter().next().unwrap());
            }
        }

        consolidated
    }

    /// Deduplicate results within runs
    fn deduplicate_results(&self, mut runs: Vec<Run>, stats: &mut MergeStats) -> Vec<Run> {
        for run in &mut runs {
            if let Some(ref mut results) = run.results {
                let original_count = results.len();
                let mut seen_fingerprints = HashSet::new();

                results.retain(|result| {
                    let fingerprint = self.compute_result_fingerprint(result);
                    if seen_fingerprints.contains(&fingerprint) {
                        false
                    } else {
                        seen_fingerprints.insert(fingerprint);
                        true
                    }
                });

                stats.deduplicated_results += original_count - results.len();
            }
        }

        runs
    }

    /// Compute a fingerprint for a result to identify duplicates
    fn compute_result_fingerprint(&self, result: &SarifResult) -> String {
        let mut parts = Vec::new();

        if let Some(ref rule_id) = result.rule_id {
            parts.push(rule_id.clone());
        }

        if let Some(ref message) = result.message.text {
            parts.push(message.clone());
        }

        if let Some(ref locations) = result.locations {
            for location in locations {
                if let Some(ref physical_location) = location.physical_location {
                    if let Some(ref artifact_location) = physical_location.artifact_location
                        && let Some(ref uri) = artifact_location.uri
                    {
                        parts.push(uri.clone());
                    }
                    if let Some(ref region) = physical_location.region {
                        parts.push(format!(
                            "{}:{}",
                            region.start_line.unwrap_or(0),
                            region.start_column.unwrap_or(0)
                        ));
                    }
                }
            }
        }

        parts.join("|")
    }
}

/// SARIF differ for computing differences between SARIF logs
pub struct SarifDiffer {
    config: DiffConfig,
}

impl SarifDiffer {
    /// Create a new SARIF differ with default configuration
    pub fn new() -> Self {
        Self {
            config: DiffConfig::default(),
        }
    }

    /// Create a SARIF differ with custom configuration
    pub fn with_config(config: DiffConfig) -> Self {
        Self { config }
    }

    /// Compare two SARIF logs and compute the differences
    pub fn diff(&self, baseline: &SarifLog, comparison: &SarifLog) -> ParseResult<DiffResult> {
        // Index both logs for efficient lookup
        let baseline_index = SarifIndex::from_sarif_log(baseline);
        let comparison_index = SarifIndex::from_sarif_log(comparison);

        let mut added = Vec::new();
        let mut removed = Vec::new();
        let mut modified = Vec::new();
        let mut unchanged = Vec::new();

        let baseline_results: HashMap<String, (SarifResult, ResultLocation)> =
            baseline_index.results.clone();
        let comparison_results: HashMap<String, (SarifResult, ResultLocation)> =
            comparison_index.results.clone();

        // Find added results (in comparison but not in baseline)
        for (key, (result, location)) in &comparison_results {
            match self.find_matching_result(key, result, &baseline_results) {
                Some(_) => {
                    // Will be handled in the modification check below
                }
                None => {
                    if self.config.include_added {
                        added.push((result.clone(), location.clone()));
                    }
                }
            }
        }

        // Find removed results (in baseline but not in comparison)
        for (key, (result, location)) in &baseline_results {
            match self.find_matching_result(key, &result, &comparison_results) {
                Some(_) => {
                    // Will be handled in the modification check below
                }
                None => {
                    if self.config.include_removed {
                        removed.push((result.clone(), location.clone()));
                    }
                }
            }
        }

        // Find modified and unchanged results
        for (baseline_key, (baseline_result, baseline_location)) in &baseline_results {
            if let Some((_comparison_key, (comparison_result, comparison_location))) =
                self.find_matching_result(baseline_key, baseline_result, &comparison_results)
            {
                let changes = self.compute_result_changes(baseline_result, &comparison_result);

                if changes.is_empty() {
                    unchanged.push((baseline_result.clone(), baseline_location.clone()));
                } else if self.config.include_modified {
                    modified.push(ResultDiff {
                        baseline: (baseline_result.clone(), baseline_location.clone()),
                        comparison: (comparison_result.clone(), comparison_location.clone()),
                        changes,
                    });
                }
            }
        }

        let stats = DiffStats {
            baseline_count: baseline_results.len(),
            comparison_count: comparison_results.len(),
            added_count: added.len(),
            removed_count: removed.len(),
            modified_count: modified.len(),
            unchanged_count: unchanged.len(),
        };

        Ok(DiffResult {
            added,
            removed,
            modified,
            unchanged,
            stats,
        })
    }

    /// Find a matching result in a collection based on the matching strategy
    fn find_matching_result(
        &self,
        key: &str,
        result: &SarifResult,
        results: &HashMap<String, (SarifResult, ResultLocation)>,
    ) -> Option<(String, (SarifResult, ResultLocation))> {
        match self.config.matching_strategy {
            ResultMatchingStrategy::ByGuid => results
                .get(key)
                .map(|(r, l)| (key.to_string(), (r.clone(), l.clone()))),
            ResultMatchingStrategy::ByRuleAndLocation => {
                let target_signature = self.compute_rule_location_signature(result);
                for (other_key, (other_result, other_location)) in results {
                    let other_signature = self.compute_rule_location_signature(other_result);
                    if target_signature == other_signature {
                        return Some((
                            other_key.clone(),
                            (other_result.clone(), other_location.clone()),
                        ));
                    }
                }
                None
            }
            ResultMatchingStrategy::ByRuleAndMessage => {
                let target_signature = self.compute_rule_message_signature(result);
                for (other_key, (other_result, other_location)) in results {
                    let other_signature = self.compute_rule_message_signature(other_result);
                    if target_signature == other_signature {
                        return Some((
                            other_key.clone(),
                            (other_result.clone(), other_location.clone()),
                        ));
                    }
                }
                None
            }
            ResultMatchingStrategy::ByFingerprint => {
                // Use existing fingerprints if available, fall back to computed fingerprint
                if let Some(ref fingerprints) = result.fingerprints {
                    for (other_key, (other_result, other_location)) in results {
                        if let Some(ref other_fingerprints) = other_result.fingerprints {
                            for (fp_key, fp_value) in fingerprints {
                                if let Some(other_fp_value) = other_fingerprints.get(fp_key)
                                    && fp_value == other_fp_value
                                {
                                    return Some((
                                        other_key.clone(),
                                        (other_result.clone(), other_location.clone()),
                                    ));
                                }
                            }
                        }
                    }
                }
                None
            }
        }
    }

    /// Compute a signature based on rule ID and location
    fn compute_rule_location_signature(&self, result: &SarifResult) -> String {
        let mut parts = Vec::new();

        if let Some(ref rule_id) = result.rule_id {
            parts.push(rule_id.clone());
        }

        if let Some(ref locations) = result.locations
            && let Some(location) = locations.first()
            && let Some(ref physical_location) = location.physical_location
        {
            if let Some(ref artifact_location) = physical_location.artifact_location
                && let Some(ref uri) = artifact_location.uri
            {
                parts.push(uri.clone());
            }
            if let Some(ref region) = physical_location.region {
                parts.push(format!(
                    "{}:{}",
                    region.start_line.unwrap_or(0),
                    region.start_column.unwrap_or(0)
                ));
            }
        }

        parts.join("|")
    }

    /// Compute a signature based on rule ID and message
    fn compute_rule_message_signature(&self, result: &SarifResult) -> String {
        let mut parts = Vec::new();

        if let Some(ref rule_id) = result.rule_id {
            parts.push(rule_id.clone());
        }

        if let Some(ref message) = result.message.text {
            parts.push(message.clone());
        }

        parts.join("|")
    }

    /// Compute the specific changes between two results
    fn compute_result_changes(
        &self,
        baseline: &SarifResult,
        comparison: &SarifResult,
    ) -> Vec<ResultChange> {
        let mut changes = Vec::new();

        // Check message changes
        if !self.config.ignore_message_changes
            && baseline.message.text != comparison.message.text
        {
            changes.push(ResultChange::MessageChanged {
                old: baseline.message.text.clone().unwrap_or_default(),
                new: comparison.message.text.clone().unwrap_or_default(),
            });
        }

        // Check level changes
        if baseline.level != comparison.level {
            changes.push(ResultChange::LevelChanged {
                old: baseline.level.clone(),
                new: comparison.level.clone(),
            });
        }

        // Check rule ID changes
        if baseline.rule_id != comparison.rule_id {
            changes.push(ResultChange::RuleChanged {
                old: baseline.rule_id.clone(),
                new: comparison.rule_id.clone(),
            });
        }

        // Check location changes
        if !self.config.ignore_location_changes {
            let baseline_location = self.extract_location_string(baseline);
            let comparison_location = self.extract_location_string(comparison);
            if baseline_location != comparison_location {
                changes.push(ResultChange::LocationChanged {
                    old: baseline_location,
                    new: comparison_location,
                });
            }
        }

        changes
    }

    /// Extract a location string from a result for comparison
    fn extract_location_string(&self, result: &SarifResult) -> String {
        if let Some(ref locations) = result.locations
            && let Some(location) = locations.first()
            && let Some(ref physical_location) = location.physical_location
        {
            let mut parts = Vec::new();

            if let Some(ref artifact_location) = physical_location.artifact_location
                && let Some(ref uri) = artifact_location.uri
            {
                parts.push(uri.clone());
            }

            if let Some(ref region) = physical_location.region {
                parts.push(format!(
                    "{}:{}",
                    region.start_line.unwrap_or(0),
                    region.start_column.unwrap_or(0)
                ));
            }

            return parts.join(":");
        }
        "unknown".to_string()
    }
}

impl Default for MergeConfig {
    fn default() -> Self {
        Self {
            consolidate_runs: false,
            deduplicate_results: true,
            version_strategy: VersionMergeStrategy::UseLatest,
            normalize_paths: false,
            max_runs: None,
            filters: MergeFilters::default(),
        }
    }
}

impl Default for DiffConfig {
    fn default() -> Self {
        Self {
            matching_strategy: ResultMatchingStrategy::ByGuid,
            include_removed: true,
            include_added: true,
            include_modified: true,
            ignore_message_changes: false,
            ignore_location_changes: false,
        }
    }
}

impl Default for SarifMerger {
    fn default() -> Self {
        Self::new()
    }
}

impl Default for SarifDiffer {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::builder::SarifLogBuilder;

    #[test]
    fn test_simple_merge() {
        let log1 =
            SarifLogBuilder::single_error("tool1", "Error 1", "file1.rs", 10).build_unchecked();
        let log2 =
            SarifLogBuilder::single_warning("tool2", "Warning 1", "file2.rs", 20).build_unchecked();

        let merger = SarifMerger::new();
        let result = merger.merge(&[log1, log2]).unwrap();

        assert_eq!(result.stats.input_logs, 2);
        assert_eq!(result.stats.input_runs, 2);
        assert_eq!(result.stats.output_runs, 2);
        assert_eq!(result.merged_log.runs.len(), 2);
    }

    #[test]
    fn test_merge_with_consolidation() {
        let log1 =
            SarifLogBuilder::single_error("same-tool", "Error 1", "file1.rs", 10).build_unchecked();
        let log2 = SarifLogBuilder::single_warning("same-tool", "Warning 1", "file2.rs", 20)
            .build_unchecked();

        let config = MergeConfig {
            consolidate_runs: true,
            ..Default::default()
        };

        let merger = SarifMerger::with_config(config);
        let result = merger.merge(&[log1, log2]).unwrap();

        assert_eq!(result.stats.input_runs, 2);
        assert_eq!(result.stats.output_runs, 1);
        assert_eq!(result.stats.consolidated_runs, 1);

        // Check that results were merged
        let merged_run = &result.merged_log.runs[0];
        assert_eq!(merged_run.tool.driver.name, "same-tool");
        assert_eq!(merged_run.results.as_ref().unwrap().len(), 2);
    }

    #[test]
    fn test_merge_with_deduplication() {
        let log1 = SarifLogBuilder::error_finding(
            "tool",
            "RULE001",
            "Duplicate error",
            "file.rs",
            10,
            5,
            10,
            15,
        )
        .build_unchecked();
        let log2 = SarifLogBuilder::error_finding(
            "tool",
            "RULE001",
            "Duplicate error",
            "file.rs",
            10,
            5,
            10,
            15,
        )
        .build_unchecked();

        let config = MergeConfig {
            consolidate_runs: true,
            deduplicate_results: true,
            ..Default::default()
        };

        let merger = SarifMerger::with_config(config);
        let result = merger.merge(&[log1, log2]).unwrap();

        assert_eq!(result.stats.input_results, 2);
        assert_eq!(result.stats.output_results, 1);
        assert_eq!(result.stats.deduplicated_results, 1);
    }

    #[test]
    fn test_merge_with_filters() {
        let log1 =
            SarifLogBuilder::single_error("tool1", "Error 1", "file1.rs", 10).build_unchecked();
        let log2 =
            SarifLogBuilder::single_warning("tool2", "Warning 1", "file2.rs", 20).build_unchecked();

        let mut include_tools = HashSet::new();
        include_tools.insert("tool1".to_string());

        let config = MergeConfig {
            filters: MergeFilters {
                include_tools: Some(include_tools),
                ..Default::default()
            },
            ..Default::default()
        };

        let merger = SarifMerger::with_config(config);
        let result = merger.merge(&[log1, log2]).unwrap();

        assert_eq!(result.stats.output_runs, 1);
        assert_eq!(result.merged_log.runs[0].tool.driver.name, "tool1");
    }

    #[test]
    fn test_simple_diff() {
        let baseline =
            SarifLogBuilder::single_error("tool", "Error 1", "file.rs", 10).build_unchecked();
        let comparison =
            SarifLogBuilder::single_warning("tool", "Warning 1", "file.rs", 20).build_unchecked();

        let config = DiffConfig {
            matching_strategy: ResultMatchingStrategy::ByRuleAndLocation,
            ..Default::default()
        };
        let differ = SarifDiffer::with_config(config);
        let result = differ.diff(&baseline, &comparison).unwrap();

        assert_eq!(result.stats.baseline_count, 1);
        assert_eq!(result.stats.comparison_count, 1);
        assert_eq!(result.stats.added_count, 1);
        assert_eq!(result.stats.removed_count, 1);
        assert_eq!(result.stats.unchanged_count, 0);
    }

    #[test]
    fn test_diff_with_rule_location_matching() {
        let baseline = SarifLogBuilder::error_finding(
            "tool",
            "RULE001",
            "Original message",
            "file.rs",
            10,
            5,
            10,
            15,
        )
        .build_unchecked();
        let comparison = SarifLogBuilder::error_finding(
            "tool",
            "RULE001",
            "Updated message",
            "file.rs",
            10,
            5,
            10,
            15,
        )
        .build_unchecked();

        let config = DiffConfig {
            matching_strategy: ResultMatchingStrategy::ByRuleAndLocation,
            ..Default::default()
        };

        let differ = SarifDiffer::with_config(config);
        let result = differ.diff(&baseline, &comparison).unwrap();

        assert_eq!(result.stats.modified_count, 1);
        assert_eq!(result.stats.added_count, 0);
        assert_eq!(result.stats.removed_count, 0);

        let modified = &result.modified[0];
        assert_eq!(modified.changes.len(), 1);
        assert!(matches!(
            modified.changes[0],
            ResultChange::MessageChanged { .. }
        ));
    }

    #[test]
    fn test_diff_ignore_message_changes() {
        let baseline = SarifLogBuilder::error_finding(
            "tool",
            "RULE001",
            "Original message",
            "file.rs",
            10,
            5,
            10,
            15,
        )
        .build_unchecked();
        let comparison = SarifLogBuilder::error_finding(
            "tool",
            "RULE001",
            "Updated message",
            "file.rs",
            10,
            5,
            10,
            15,
        )
        .build_unchecked();

        let config = DiffConfig {
            matching_strategy: ResultMatchingStrategy::ByRuleAndLocation,
            ignore_message_changes: true,
            ..Default::default()
        };

        let differ = SarifDiffer::with_config(config);
        let result = differ.diff(&baseline, &comparison).unwrap();

        assert_eq!(result.stats.unchanged_count, 1);
        assert_eq!(result.stats.modified_count, 0);
    }

    #[test]
    fn test_version_merge_strategies() {
        let mut log1 =
            SarifLogBuilder::single_error("tool", "Error 1", "file.rs", 10).build_unchecked();
        log1.version = "2.0.0".to_string();

        let mut log2 =
            SarifLogBuilder::single_error("tool", "Error 2", "file.rs", 20).build_unchecked();
        log2.version = "2.1.0".to_string();

        // Test UseLatest
        let config = MergeConfig {
            version_strategy: VersionMergeStrategy::UseLatest,
            ..Default::default()
        };
        let merger = SarifMerger::with_config(config);
        let result = merger.merge(&[log1.clone(), log2.clone()]).unwrap();
        assert_eq!(result.merged_log.version, "2.1.0");

        // Test UseFirst
        let config = MergeConfig {
            version_strategy: VersionMergeStrategy::UseFirst,
            ..Default::default()
        };
        let merger = SarifMerger::with_config(config);
        let result = merger.merge(&[log1.clone(), log2.clone()]).unwrap();
        assert_eq!(result.merged_log.version, "2.0.0");

        // Test RequireMatch (should fail)
        let config = MergeConfig {
            version_strategy: VersionMergeStrategy::RequireMatch,
            ..Default::default()
        };
        let merger = SarifMerger::with_config(config);
        let result = merger.merge(&[log1, log2]);
        assert!(result.is_err());
    }
}