Structural Diff
This example demonstrates how to find semantic differences between complex data structures, which is useful for version control, change tracking, and debugging.
1"""Example of using the structural diff tool.
2
3This example demonstrates how to find semantic differences between complex
4data structures, which is useful for version control, change tracking, and debugging.
5"""
6
7import toonverter as toon
8from toonverter.differ import DiffChange
9
10
11def run_diff_example():
12 """Run diff example."""
13 print("--- Structural Diff Example ---\n")
14
15 # 1. Define two versions of a dataset
16 version1 = {
17 "app_name": "ToonApp",
18 "version": "1.0.0",
19 "features": ["encoding", "decoding"],
20 "config": {
21 "timeout": 30,
22 "retries": 3,
23 "debug": False
24 },
25 "users": [
26 {"id": 1, "name": "Alice"},
27 {"id": 2, "name": "Bob"}
28 ]
29 }
30
31 version2 = {
32 "app_name": "ToonApp Pro", # Changed value
33 "version": "1.1.0", # Changed value
34 "features": ["encoding", "decoding", "analysis"], # Added item
35 "config": {
36 "timeout": 60, # Changed value
37 "retries": 3, # Same
38 # "debug": False # Removed key
39 "logging": True # Added key
40 },
41 "users": [
42 {"id": 1, "name": "Alice"},
43 {"id": 2, "name": "Robert"} # Changed nested value
44 ]
45 }
46
47 # 2. Calculate Diff
48 print("Calculating differences...")
49 diff_result = toon.diff(version1, version2)
50
51 print(f"\nMatch: {diff_result.match}")
52 print(f"Total Changes: {len(diff_result.changes)}")
53
54 # 3. Inspect changes
55 print("\nDetailed Changes:")
56 for change in diff_result.changes:
57 print_change(change)
58
59 # 4. Textual Report
60 # Note: You would typically use a formatter here, but we can print manually
61 print("\n--- Summary Report ---")
62 adds = sum(1 for c in diff_result.changes if c.type.value == "added")
63 removes = sum(1 for c in diff_result.changes if c.type.value == "removed")
64 mods = sum(1 for c in diff_result.changes if c.type.value == "modified")
65
66 print(f"Added: {adds}, Removed: {removes}, Modified: {mods}")
67
68
69def print_change(change: DiffChange):
70 """Helper to print a change object nicely."""
71 path_str = ".".join(str(p) for p in change.path)
72 if not path_str:
73 path_str = "(root)"
74
75 action = change.type.value.upper()
76
77 if action == "MODIFIED":
78 print(f"[{action}] {path_str}: {change.old_value} -> {change.new_value}")
79 elif action == "ADDED":
80 print(f"[{action}] {path_str}: {change.new_value}")
81 elif action == "REMOVED":
82 print(f"[{action}] {path_str}: (was {change.old_value})")
83
84
85if __name__ == "__main__":
86 run_diff_example()