-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjdiff-internal.py
More file actions
105 lines (82 loc) · 3.86 KB
/
jdiff-internal.py
File metadata and controls
105 lines (82 loc) · 3.86 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
import json
import sys
import os
import subprocess
import tempfile
import argparse
def normalize_json(obj, keep_duplicates=False):
# 1. Handle Dictionaries (always sort keys)
if isinstance(obj, dict):
return {k: normalize_json(v, keep_duplicates) for k, v in sorted(obj.items())}
# 2. Handle Lists (sort items, optionally deduplicate)
if isinstance(obj, list):
# A. Normalize all children first (Recursion)
normalized_items = [normalize_json(x, keep_duplicates) for x in obj]
# B. Deduplicate (only if keep_duplicates is False)
if not keep_duplicates:
unique_items = []
seen = set()
for item in normalized_items:
# Create signature to detect duplicates
item_signature = json.dumps(item, sort_keys=True)
if item_signature not in seen:
seen.add(item_signature)
unique_items.append(item)
items_to_sort = unique_items
else:
# Keep everything, including duplicates
items_to_sort = normalized_items
# C. Sort the list
# We sort by the JSON string representation to ensure deterministic order
# allowing for clean diffs even if elements shifted position
return sorted(items_to_sort, key=lambda x: json.dumps(x, sort_keys=True))
# 3. Primitives (int, str, bool, None) - return as is
return obj
def main():
parser = argparse.ArgumentParser(description="Normalize JSON files and open VS Code Diff.")
# Arguments
parser.add_argument("file1", help="Path to the first JSON file")
parser.add_argument("file2", help="Path to the second JSON file")
# NEUES FLAG: -d für Deduplizierung
parser.add_argument("-d", "--deduplicate",
action="store_true",
help="Remove duplicate items in lists. Default is to keep duplicates and only sort.")
args = parser.parse_args()
# Create a temporary directory
temp_dir = tempfile.mkdtemp()
try:
print(f"Loading files...")
with open(args.file1, 'r', encoding='utf-8') as f:
data1 = json.load(f)
with open(args.file2, 'r', encoding='utf-8') as f:
data2 = json.load(f)
# Wenn -d gesetzt ist, entferne duplikate
# ansonsten keep=true
should_keep = not args.deduplicate
mode_text = "Sorting & Removing Duplicates" if args.deduplicate else "Sorting & Keeping Duplicates"
print(f"Processing ({mode_text})...")
norm1 = normalize_json(data1, keep_duplicates=should_keep)
norm2 = normalize_json(data2, keep_duplicates=should_keep)
# Create sensible filenames for the temp files
suffix = "_DEDUPED" if args.deduplicate else "_SORTED"
name1 = f"{os.path.basename(args.file1)}{suffix}.json"
name2 = f"{os.path.basename(args.file2)}{suffix}.json"
path1 = os.path.join(temp_dir, name1)
path2 = os.path.join(temp_dir, name2)
# Write Normalized Data
print("Writing temp files...")
with open(path1, 'w', encoding='utf-8') as f:
json.dump(norm1, f, indent=2, sort_keys=True)
with open(path2, 'w', encoding='utf-8') as f:
json.dump(norm2, f, indent=2, sort_keys=True)
print("Launching VS Code Diff...")
# Open VS Code Diff
subprocess.run(f'code --diff "{path1}" "{path2}"', shell=True, check=False)
except json.JSONDecodeError as e:
print(f"JSON Error: {e}")
except FileNotFoundError:
print("Error: 'code' command not found. Is VS Code installed and in PATH?")
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
main()