-
Notifications
You must be signed in to change notification settings - Fork 328
Expand file tree
/
Copy pathdiff.rs
More file actions
828 lines (741 loc) · 29.4 KB
/
Copy pathdiff.rs
File metadata and controls
828 lines (741 loc) · 29.4 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
use std::cmp::Ordering;
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use std::process::ExitCode;
use crate::snapshot::{EnumSnapshot, UpgradeMeta, VariantMeta};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Severity {
/// New versioned types, variants, or upgrades being introduced.
Neutral,
/// Struct layout, upgrade logic, or enum removal that may hide a breaking change.
Warning,
/// Variant removal makes existing serialized data impossible to deserialize.
Error,
}
/// Each variant represents a distinct type of change between two snapshots.
/// The severity is derived from the variant -- change the `severity()` match
/// to update the rules in one place.
#[derive(Debug, Clone)]
pub enum DiffEntry {
/// A new versions dispatch enum appeared (new versioned type family).
VersionsDispatchEnumAdded { name: String, variant_count: usize },
/// A versions dispatch enum was removed. May indicate dropped versioned types.
VersionsDispatchEnumRemoved { name: String },
/// A new variant was added to a versions dispatch enum (new version of a type).
VersionsDispatchVariantAdded {
enum_name: String,
index: usize,
type_path: String,
},
/// A variant was removed from a versions dispatch enum.
/// Existing serialized data referencing this variant can no longer be deserialized.
/// This can cause version confusion and introduce dangerous security vulnerabilities.
VersionsDispatchVariantRemoved {
enum_name: String,
index: usize,
type_path: String,
},
/// The struct hash of a versioned type changed, meaning its layout was modified.
/// May break deserialization of data serialized with the old layout.
VersionedTypeHashChanged {
enum_name: String,
index: usize,
type_path: String,
old_hash: String,
new_hash: String,
},
/// A new upgrade path was added between two versions.
UpgradeAdded {
enum_name: String,
source: String,
target: String,
},
/// An upgrade path was removed. May break the upgrade chain.
UpgradeRemoved {
enum_name: String,
source: String,
target: String,
},
/// An upgrade function body changed. Migration logic was modified.
UpgradeHashChanged {
enum_name: String,
source: String,
target: String,
old_hash: String,
new_hash: String,
},
}
impl DiffEntry {
pub fn versions_dispatch_enum_added(snap: &EnumSnapshot) -> Self {
Self::VersionsDispatchEnumAdded {
name: snap.enum_name.clone(),
variant_count: snap.variants.len(),
}
}
pub fn versions_dispatch_enum_removed(snap: &EnumSnapshot) -> Self {
Self::VersionsDispatchEnumRemoved {
name: snap.enum_name.clone(),
}
}
pub fn versions_dispatch_variant_added(enum_name: &str, v: &VariantMeta) -> Self {
Self::VersionsDispatchVariantAdded {
enum_name: enum_name.to_string(),
index: v.index,
type_path: v.inner_type_def_path.clone(),
}
}
pub fn versions_dispatch_variant_removed(enum_name: &str, v: &VariantMeta) -> Self {
Self::VersionsDispatchVariantRemoved {
enum_name: enum_name.to_string(),
index: v.index,
type_path: v.inner_type_def_path.clone(),
}
}
pub fn versioned_type_hash_changed(
enum_name: &str,
old: &VariantMeta,
new: &VariantMeta,
) -> Self {
Self::VersionedTypeHashChanged {
enum_name: enum_name.to_string(),
index: old.index,
type_path: old.inner_type_def_path.clone(),
old_hash: old.type_hash.clone(),
new_hash: new.type_hash.clone(),
}
}
pub fn upgrade_added(enum_name: &str, u: &UpgradeMeta) -> Self {
Self::UpgradeAdded {
enum_name: enum_name.to_string(),
source: u.source_def_path.clone(),
target: u.target_def_path.clone(),
}
}
pub fn upgrade_removed(enum_name: &str, u: &UpgradeMeta) -> Self {
Self::UpgradeRemoved {
enum_name: enum_name.to_string(),
source: u.source_def_path.clone(),
target: u.target_def_path.clone(),
}
}
pub fn upgrade_hash_changed(enum_name: &str, old: &UpgradeMeta, new: &UpgradeMeta) -> Self {
Self::UpgradeHashChanged {
enum_name: enum_name.to_string(),
source: old.source_def_path.clone(),
target: old.target_def_path.clone(),
old_hash: old.body_hash.clone(),
new_hash: new.body_hash.clone(),
}
}
/// Split a slice of entries into (errors, warnings, neutral) by severity.
pub fn split_by_severity(
entries: &[DiffEntry],
) -> (Vec<&DiffEntry>, Vec<&DiffEntry>, Vec<&DiffEntry>) {
let errors = entries
.iter()
.filter(|e| e.severity() == Severity::Error)
.collect();
let warnings = entries
.iter()
.filter(|e| e.severity() == Severity::Warning)
.collect();
let neutral = entries
.iter()
.filter(|e| e.severity() == Severity::Neutral)
.collect();
(errors, warnings, neutral)
}
/// Single source of truth for severity rules.
pub fn severity(&self) -> Severity {
match self {
Self::VersionsDispatchEnumAdded { .. }
| Self::VersionsDispatchVariantAdded { .. }
| Self::UpgradeAdded { .. } => Severity::Neutral,
Self::VersionsDispatchEnumRemoved { .. }
| Self::VersionedTypeHashChanged { .. }
| Self::UpgradeRemoved { .. }
| Self::UpgradeHashChanged { .. } => Severity::Warning,
Self::VersionsDispatchVariantRemoved { .. } => Severity::Error,
}
}
}
impl std::fmt::Display for DiffEntry {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::VersionsDispatchEnumAdded {
name,
variant_count,
} => {
write!(f, "New enum `{name}` ({variant_count} variants)")
}
Self::VersionsDispatchEnumRemoved { name } => {
write!(f, "Enum `{name}` removed")
}
Self::VersionsDispatchVariantAdded {
enum_name,
index,
type_path,
} => {
write!(f, "`{enum_name}`: new variant {index} (`{type_path}`)")
}
Self::VersionsDispatchVariantRemoved {
enum_name,
index,
type_path,
} => {
write!(f, "`{enum_name}`: variant {index} (`{type_path}`) removed")
}
Self::VersionedTypeHashChanged {
enum_name,
index,
type_path,
old_hash,
new_hash,
} => {
write!(
f,
"`{enum_name}` variant {index} (`{type_path}`):\n \
struct hash changed\n \
old: {old_hash}\n \
new: {new_hash}"
)
}
Self::UpgradeAdded {
enum_name,
source,
target,
} => {
write!(f, "`{enum_name}`: new upgrade `{source}` → `{target}`")
}
Self::UpgradeRemoved {
enum_name,
source,
target,
} => {
write!(f, "`{enum_name}`: upgrade `{source}` → `{target}` removed")
}
Self::UpgradeHashChanged {
enum_name,
source,
target,
old_hash,
new_hash,
} => {
write!(
f,
"`{enum_name}` upgrade `{source}` → `{target}`:\n \
body hash changed\n \
old: {old_hash}\n \
new: {new_hash}"
)
}
}
}
}
/// Collection of enum snapshots loaded from a directory, sorted by enum name.
/// Used as one side of a diff (base or head).
#[derive(Debug, Clone)]
pub struct Registry(Vec<EnumSnapshot>);
impl Registry {
/// Load all `lint_enum_snapshots_*.json` files from `dir` into a sorted registry.
pub fn load_registry(dir: &Path) -> Result<Self, ExitCode> {
let mut snapshots = Vec::new();
let entries = match fs::read_dir(dir) {
Ok(e) => e,
Err(err) => {
eprintln!("Cannot read directory {}: {}", dir.display(), err);
return Err(ExitCode::from(1));
}
};
for entry in entries.flatten() {
let path = entry.path();
// Skip subdirectories (e.g. "head" generated by make backward_snapshot_head)
if path.is_dir() {
continue;
}
let file_name = match path.file_name().and_then(|n| n.to_str()) {
Some(n) => n.to_string(),
None => continue,
};
if !file_name.starts_with("lint_enum_snapshots_") || !file_name.ends_with(".json") {
eprint!(
"We should not have this kind of file in the snapshot directory: {}. ",
path.display()
);
continue;
}
let content = match fs::read_to_string(&path) {
Ok(c) => c,
Err(err) => {
eprintln!("Cannot read {}: {}", path.display(), err);
return Err(ExitCode::from(1));
}
};
let file_snapshots: Vec<EnumSnapshot> = match serde_json::from_str(&content) {
Ok(s) => s,
Err(err) => {
eprintln!("Cannot parse {}: {}", path.display(), err);
return Err(ExitCode::from(1));
}
};
snapshots.extend(file_snapshots);
}
snapshots.sort_by(|a, b| a.enum_name.cmp(&b.enum_name));
eprintln!("Loaded {} enums from {}", snapshots.len(), dir.display(),);
Ok(Registry(snapshots))
}
/// Compare two registries using a sorted merge and return all detected changes.
pub fn diff(&self, new: &Registry) -> Vec<DiffEntry> {
let mut entries = Vec::new();
let mut old_iter = self.0.iter().peekable();
let mut new_iter = new.0.iter().peekable();
loop {
match (old_iter.peek(), new_iter.peek()) {
// Case where both old and new have an enum to compare
(Some(old_snap), Some(new_snap)) => {
// As everything is sorted by enum_name, we can compare the names to decide
// what to do
match old_snap.enum_name.cmp(&new_snap.enum_name) {
// This case represents a removal, as the old enum does not exist in the
// new registry (we have exhausted the new enums with smaller names)
// We move the old iterator forward and record the removal, but we keep the
// new iterator
Ordering::Less => {
let old_snap = old_iter.next().unwrap();
entries.push(DiffEntry::versions_dispatch_enum_removed(old_snap));
}
// This case represents an addition, as the new enum does not exist in the
// old registry
// We move the new iterator forward and record the addition, but we keep
// the old
Ordering::Greater => {
let new_snap = new_iter.next().unwrap();
entries.push(DiffEntry::versions_dispatch_enum_added(new_snap));
}
// We have the same enum name in both registries, we need to compare them
// for modifications
// We move both iterators forward and compare the enums, and we
// modify the diff entries if needed
Ordering::Equal => {
let old_snap = old_iter.next().unwrap();
let new_snap = new_iter.next().unwrap();
Self::diff_enum(old_snap, new_snap, &mut entries);
}
}
}
// Case where we have exhausted the new enums but still have old enums left
// (removals)
(Some(_), None) => {
let old_snap = old_iter.next().unwrap();
entries.push(DiffEntry::versions_dispatch_enum_removed(old_snap));
}
// Case where we have exhausted the old enums but still have new enums left
(None, Some(_)) => {
let new_snap = new_iter.next().unwrap();
entries.push(DiffEntry::versions_dispatch_enum_added(new_snap));
}
// Both iterators are exhausted, we are done
(None, None) => break,
}
}
entries
}
fn diff_enum(old_enum: &EnumSnapshot, new_enum: &EnumSnapshot, entries: &mut Vec<DiffEntry>) {
let name = &old_enum.enum_name;
let mut rename_map: HashMap<&str, &str> = HashMap::new();
for ov in &old_enum.variants {
if let Some(nv) = new_enum.variants.iter().find(|nv| nv.index == ov.index) {
if ov.inner_type_def_path != nv.inner_type_def_path {
rename_map.insert(&ov.inner_type_def_path, &nv.inner_type_def_path);
}
}
}
// Variant additions & modifications
for nv in &new_enum.variants {
match old_enum.variants.iter().find(|ov| ov.index == nv.index) {
None => entries.push(DiffEntry::versions_dispatch_variant_added(name, nv)),
Some(ov) if ov.type_hash != nv.type_hash => {
entries.push(DiffEntry::versioned_type_hash_changed(name, ov, nv));
}
_ => {}
}
}
// Variant removals
for ov in &old_enum.variants {
if !new_enum.variants.iter().any(|nv| nv.index == ov.index) {
entries.push(DiffEntry::versions_dispatch_variant_removed(name, ov));
}
}
// Upgrade additions & modifications
for nu in &new_enum.upgrades {
match old_enum.upgrades.iter().find(|ou| {
let resolved_target = rename_map
.get(ou.target_def_path.as_str())
.copied()
.unwrap_or(ou.target_def_path.as_str());
ou.source_def_path == nu.source_def_path && resolved_target == nu.target_def_path
}) {
None => entries.push(DiffEntry::upgrade_added(name, nu)),
Some(ou) if ou.body_hash != nu.body_hash => {
entries.push(DiffEntry::upgrade_hash_changed(name, ou, nu));
}
_ => {}
}
}
// Upgrade removals
for ou in &old_enum.upgrades {
if !new_enum.upgrades.iter().any(|nu| {
let resolved_target = rename_map
.get(ou.target_def_path.as_str())
.copied()
.unwrap_or(ou.target_def_path.as_str());
nu.source_def_path == ou.source_def_path && resolved_target == nu.target_def_path
}) {
entries.push(DiffEntry::upgrade_removed(name, ou));
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn variant(index: usize, def_path: &str, hash: &str) -> VariantMeta {
VariantMeta {
index,
inner_type_def_path: def_path.to_string(),
inner_type_display: def_path.to_string(),
type_hash: hash.to_string(),
}
}
fn upgrade(source: &str, target: &str, hash: &str) -> UpgradeMeta {
UpgradeMeta {
source_def_path: source.to_string(),
target_def_path: target.to_string(),
body_hash: hash.to_string(),
}
}
fn enum_snap(
name: &str,
variants: Vec<VariantMeta>,
upgrades: Vec<UpgradeMeta>,
) -> EnumSnapshot {
EnumSnapshot {
enum_name: name.to_string(),
variants,
upgrades,
}
}
fn registry(mut snaps: Vec<EnumSnapshot>) -> Registry {
snaps.sort_by(|a, b| a.enum_name.cmp(&b.enum_name));
Registry(snaps)
}
/// Helper: count entries by severity
fn count_by_severity(entries: &[DiffEntry], severity: Severity) -> usize {
entries.iter().filter(|e| e.severity() == severity).count()
}
// ---- diff: additions ----
#[test]
fn additions_new_enum() {
let old = registry(vec![enum_snap("Old", vec![variant(0, "T", "aaa")], vec![])]);
let new = registry(vec![
enum_snap("Old", vec![variant(0, "T", "aaa")], vec![]),
enum_snap("New", vec![variant(0, "T", "bbb")], vec![]),
]);
let entries = old.diff(&new);
assert_eq!(count_by_severity(&entries, Severity::Neutral), 1);
assert!(
matches!(&entries[0], DiffEntry::VersionsDispatchEnumAdded { name, .. } if name == "New")
);
assert_eq!(count_by_severity(&entries, Severity::Warning), 0);
assert_eq!(count_by_severity(&entries, Severity::Error), 0);
}
#[test]
fn additions_new_variant() {
let old = registry(vec![enum_snap("E", vec![variant(0, "V0", "aaa")], vec![])]);
let new = registry(vec![enum_snap(
"E",
vec![variant(0, "V0", "aaa"), variant(1, "V1", "bbb")],
vec![],
)]);
let entries = old.diff(&new);
assert_eq!(count_by_severity(&entries, Severity::Neutral), 1);
assert!(matches!(
&entries[0],
DiffEntry::VersionsDispatchVariantAdded { index: 1, .. }
));
assert_eq!(count_by_severity(&entries, Severity::Warning), 0);
assert_eq!(count_by_severity(&entries, Severity::Error), 0);
}
#[test]
fn additions_new_upgrade() {
let old = registry(vec![enum_snap(
"E",
vec![variant(0, "V0", "aaa"), variant(1, "V1", "bbb")],
vec![],
)]);
let new = registry(vec![enum_snap(
"E",
vec![variant(0, "V0", "aaa"), variant(1, "V1", "bbb")],
vec![upgrade("V0", "V1", "uuu")],
)]);
let entries = old.diff(&new);
assert_eq!(count_by_severity(&entries, Severity::Neutral), 1);
assert!(matches!(&entries[0], DiffEntry::UpgradeAdded { .. }));
assert_eq!(count_by_severity(&entries, Severity::Warning), 0);
assert_eq!(count_by_severity(&entries, Severity::Error), 0);
}
#[test]
fn additions_none_when_identical() {
let old = registry(vec![enum_snap("E", vec![variant(0, "V0", "aaa")], vec![])]);
let new = old.clone();
let entries = old.diff(&new);
assert!(entries.is_empty());
}
// ---- diff: warnings (struct hash, upgrade changes, enum removals) ----
#[test]
fn warning_variant_hash_changed() {
let old = registry(vec![enum_snap("E", vec![variant(0, "V0", "aaa")], vec![])]);
let new = registry(vec![enum_snap(
"E",
vec![variant(0, "V0", "CHANGED")],
vec![],
)]);
let entries = old.diff(&new);
assert_eq!(count_by_severity(&entries, Severity::Warning), 1);
assert!(matches!(
&entries[0],
DiffEntry::VersionedTypeHashChanged { .. }
));
assert_eq!(count_by_severity(&entries, Severity::Neutral), 0);
assert_eq!(count_by_severity(&entries, Severity::Error), 0);
}
#[test]
fn warning_upgrade_hash_changed() {
let old = registry(vec![enum_snap(
"E",
vec![variant(0, "V0", "aaa"), variant(1, "V1", "bbb")],
vec![upgrade("V0", "V1", "uuu")],
)]);
let new = registry(vec![enum_snap(
"E",
vec![variant(0, "V0", "aaa"), variant(1, "V1", "bbb")],
vec![upgrade("V0", "V1", "CHANGED")],
)]);
let entries = old.diff(&new);
assert_eq!(count_by_severity(&entries, Severity::Warning), 1);
assert!(matches!(&entries[0], DiffEntry::UpgradeHashChanged { .. }));
assert_eq!(count_by_severity(&entries, Severity::Neutral), 0);
assert_eq!(count_by_severity(&entries, Severity::Error), 0);
}
#[test]
fn warning_upgrade_removed() {
let old = registry(vec![enum_snap(
"E",
vec![variant(0, "V0", "aaa"), variant(1, "V1", "bbb")],
vec![upgrade("V0", "V1", "uuu")],
)]);
let new = registry(vec![enum_snap(
"E",
vec![variant(0, "V0", "aaa"), variant(1, "V1", "bbb")],
vec![],
)]);
let entries = old.diff(&new);
assert_eq!(count_by_severity(&entries, Severity::Warning), 1);
assert!(matches!(&entries[0], DiffEntry::UpgradeRemoved { .. }));
assert_eq!(count_by_severity(&entries, Severity::Error), 0);
}
#[test]
fn warning_enum_removed() {
let old = registry(vec![enum_snap("E", vec![variant(0, "V0", "aaa")], vec![])]);
let new = registry(vec![]);
let entries = old.diff(&new);
assert_eq!(count_by_severity(&entries, Severity::Warning), 1);
assert!(matches!(
&entries[0],
DiffEntry::VersionsDispatchEnumRemoved { .. }
));
assert_eq!(count_by_severity(&entries, Severity::Neutral), 0);
assert_eq!(count_by_severity(&entries, Severity::Error), 0);
}
#[test]
fn warnings_none_when_identical() {
let old = registry(vec![enum_snap(
"E",
vec![variant(0, "V0", "aaa")],
vec![upgrade("V0", "V1", "uuu")],
)]);
let new = old.clone();
let entries = old.diff(&new);
assert_eq!(count_by_severity(&entries, Severity::Warning), 0);
}
// ---- diff: errors (variant removals) ----
#[test]
fn error_variant_removed() {
let old = registry(vec![enum_snap(
"E",
vec![variant(0, "V0", "aaa"), variant(1, "V1", "bbb")],
vec![],
)]);
let new = registry(vec![enum_snap("E", vec![variant(0, "V0", "aaa")], vec![])]);
let entries = old.diff(&new);
assert_eq!(count_by_severity(&entries, Severity::Error), 1);
assert!(matches!(
&entries[0],
DiffEntry::VersionsDispatchVariantRemoved { index: 1, .. }
));
assert_eq!(count_by_severity(&entries, Severity::Warning), 0);
}
#[test]
fn errors_none_when_identical() {
let old = registry(vec![enum_snap("E", vec![variant(0, "V0", "aaa")], vec![])]);
let new = old.clone();
let entries = old.diff(&new);
assert_eq!(count_by_severity(&entries, Severity::Error), 0);
}
#[test]
fn errors_none_when_enum_removed() {
let old = registry(vec![enum_snap("E", vec![variant(0, "V0", "aaa")], vec![])]);
let new = registry(vec![]);
let entries = old.diff(&new);
// Enum removal is a warning, not an error
assert_eq!(count_by_severity(&entries, Severity::Error), 0);
assert!(count_by_severity(&entries, Severity::Warning) > 0);
}
// ---- end-to-end diff flow ----
#[test]
fn diff_full_flow_only_additions() {
let old = registry(vec![enum_snap("E", vec![variant(0, "V0", "aaa")], vec![])]);
let new = registry(vec![
enum_snap(
"E",
vec![variant(0, "V0", "aaa"), variant(1, "V1", "bbb")],
vec![upgrade("V0", "V1", "uuu")],
),
enum_snap("New", vec![variant(0, "T", "ccc")], vec![]),
]);
let entries = old.diff(&new);
assert_eq!(count_by_severity(&entries, Severity::Neutral), 3); // new enum + new variant + new upgrade
assert_eq!(count_by_severity(&entries, Severity::Warning), 0);
assert_eq!(count_by_severity(&entries, Severity::Error), 0);
}
// ---- upgrade target rename (adding a new enum version) ----
/// Simulates adding V2 to an enum: Foo (at V1) becomes FooV1, new Foo is V2.
/// The existing upgrade FooV0 → Foo should be recognized as FooV0 → FooV1
/// (same upgrade, just renamed target) and NOT produce a false UpgradeRemoved + UpgradeAdded.
#[test]
fn no_false_positive_when_new_version_renames_target() {
// Before: V0(FooV0), V1(Foo) with upgrade FooV0 → Foo
let old = registry(vec![enum_snap(
"FooVersions",
vec![variant(0, "FooV0", "aaa"), variant(1, "Foo", "bbb")],
vec![upgrade("FooV0", "Foo", "uuu")],
)]);
// After: V0(FooV0), V1(FooV1), V2(Foo) with upgrades FooV0 → FooV1, FooV1 → Foo
let new = registry(vec![enum_snap(
"FooVersions",
vec![
variant(0, "FooV0", "aaa"),
variant(1, "FooV1", "bbb"), // same hash, just renamed
variant(2, "Foo", "ccc"),
],
vec![
upgrade("FooV0", "FooV1", "uuu"), // same body hash as the old FooV0 → Foo
upgrade("FooV1", "Foo", "vvv"), // genuinely new upgrade
],
)]);
let entries = old.diff(&new);
// Expected: new variant V2 + new upgrade FooV1→Foo = 2 neutral, 0 warnings, 0 errors
assert_eq!(count_by_severity(&entries, Severity::Neutral), 2);
assert_eq!(count_by_severity(&entries, Severity::Warning), 0);
assert_eq!(count_by_severity(&entries, Severity::Error), 0);
// Verify the 2 neutral entries are exactly: variant added + upgrade added
assert!(
entries
.iter()
.any(|e| matches!(e, DiffEntry::VersionsDispatchVariantAdded { index: 2, .. }))
);
assert!(entries.iter().any(|e| matches!(
e,
DiffEntry::UpgradeAdded {
source,
target,
..
} if source == "FooV1" && target == "Foo"
)));
}
/// Same scenario but the upgrade body also changed — should produce a hash-changed warning
/// instead of a false removed+added pair.
#[test]
fn renamed_target_with_changed_upgrade_body() {
let old = registry(vec![enum_snap(
"FooVersions",
vec![variant(0, "FooV0", "aaa"), variant(1, "Foo", "bbb")],
vec![upgrade("FooV0", "Foo", "uuu")],
)]);
let new = registry(vec![enum_snap(
"FooVersions",
vec![
variant(0, "FooV0", "aaa"),
variant(1, "FooV1", "bbb"),
variant(2, "Foo", "ccc"),
],
vec![
upgrade("FooV0", "FooV1", "CHANGED"), // same logical upgrade, body changed
upgrade("FooV1", "Foo", "vvv"),
],
)]);
let entries = old.diff(&new);
// The renamed upgrade has a changed body → 1 warning (UpgradeHashChanged)
// New variant + new upgrade → 2 neutral
assert_eq!(count_by_severity(&entries, Severity::Neutral), 2);
assert_eq!(count_by_severity(&entries, Severity::Warning), 1);
assert_eq!(count_by_severity(&entries, Severity::Error), 0);
assert!(
entries
.iter()
.any(|e| matches!(e, DiffEntry::UpgradeHashChanged { .. }))
);
}
/// When no rename happens (target name is stable), upgrades still match normally.
#[test]
fn no_rename_upgrades_still_match() {
let old = registry(vec![enum_snap(
"E",
vec![variant(0, "V0", "aaa"), variant(1, "V1", "bbb")],
vec![upgrade("V0", "V1", "uuu")],
)]);
let new = registry(vec![enum_snap(
"E",
vec![variant(0, "V0", "aaa"), variant(1, "V1", "bbb")],
vec![upgrade("V0", "V1", "uuu")],
)]);
let entries = old.diff(&new);
assert!(entries.is_empty());
}
#[test]
fn diff_full_flow_mixed_changes() {
let old = registry(vec![
enum_snap(
"A",
vec![variant(0, "V0", "aaa"), variant(1, "V1", "bbb")],
vec![upgrade("V0", "V1", "uuu")],
),
enum_snap("B", vec![variant(0, "T", "ccc")], vec![]),
]);
let new = registry(vec![enum_snap(
"A",
vec![
variant(0, "V0", "aaa"),
// V1 removed -> error
variant(2, "V2", "ddd"),
],
vec![upgrade("V0", "V1", "CHANGED")], // upgrade modified -> warning
)]);
// B removed -> warning
let entries = old.diff(&new);
assert_eq!(count_by_severity(&entries, Severity::Neutral), 1); // new variant V2
assert_eq!(count_by_severity(&entries, Severity::Warning), 2); // upgrade hash changed + enum B removed
assert_eq!(count_by_severity(&entries, Severity::Error), 1); // variant V1 removed
}
}