-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaudit_group.py
More file actions
507 lines (440 loc) · 14.3 KB
/
Copy pathaudit_group.py
File metadata and controls
507 lines (440 loc) · 14.3 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
#!/usr/bin/env python3
"""
Audit an Xcode PBXGroup against its folder on disk.
Compares the group hierarchy in the project file with
the actual files/folders on disk and reports differences.
Author: Deszip
Usage:
python audit_group.py <group_path>
python audit_group.py --group-id <UUID> <group_path>
Example:
python audit_group.py "Classes/SmartNotifications"
python audit_group.py --group-id ABC123... "Classes/iCloud"
"""
import os
import re
import sys
PBXPROJ_PATH = "ReaddleDocs2.xcodeproj/project.pbxproj"
class PBXGroupReader:
"""Read-only parser for PBXGroup hierarchy."""
def __init__(self, project_path):
try:
with open(project_path, 'r', encoding='utf-8') as f:
self.content = f.read()
except Exception as e:
print(f"Error reading project file: {e}")
sys.exit(1)
self.group_section = self._extract_section('PBXGroup')
self.fileref_section = self._extract_section(
'PBXFileReference'
)
self.synced_section = self._extract_section(
'PBXFileSystemSynchronizedRootGroup'
)
def _extract_section(self, name):
pattern = (
rf'/\* Begin {name} section \*/\n'
rf'(.*?)'
rf'\n/\* End {name} section \*/'
)
m = re.search(pattern, self.content, re.DOTALL)
return m.group(1) if m else ''
def find_all_groups_by_name(self, group_name):
"""Find all PBXGroup definitions with given name.
Also checks PBXFileSystemSynchronizedRootGroup."""
results = []
for section in [self.group_section, self.synced_section]:
pattern = (
rf'([A-F0-9]{{24}}) /\* '
rf'{re.escape(group_name)} \*/ = \{{'
)
for m in re.finditer(pattern, section):
results.append(m.group(1))
return results
def find_group_by_uuid(self, uuid):
"""Check if UUID is a PBXGroup definition."""
pattern = rf'{uuid} /\*[^*]+\*/ = \{{'
if re.search(pattern, self.group_section):
return True
if re.search(pattern, self.synced_section):
return True
return False
def is_synced_group(self, uuid):
"""Check if UUID is a synced root group."""
pattern = rf'{uuid} /\*[^*]+\*/ = \{{'
return bool(re.search(pattern, self.synced_section))
def get_group_entry(self, group_uuid):
"""Get the body of a group definition block."""
pattern = (
rf'^\t\t{group_uuid} /\* (.+?) \*/ = \{{\n'
rf'(.*?)\n\t\t\}};'
)
m = re.search(
pattern, self.group_section,
re.DOTALL | re.MULTILINE,
)
if m:
return m.group(1), m.group(2)
return None, None
def get_group_name(self, group_uuid):
"""Get the display name of a group."""
comment, body = self.get_group_entry(group_uuid)
if body is None:
return None
# Explicit quoted name
m = re.search(r'name = "(.*?)";', body)
if m:
return m.group(1)
# Explicit unquoted name
m = re.search(r'name = ([^";]+);', body)
if m:
return m.group(1).strip()
return comment
def get_group_path_attr(self, group_uuid):
"""Get the path attribute (actual folder name on disk)."""
_, body = self.get_group_entry(group_uuid)
if body is None:
return None
m = re.search(r'path = (.*?);', body)
if m:
return m.group(1).strip('"')
return None
def get_children(self, group_uuid):
"""Get child UUIDs of a group."""
_, body = self.get_group_entry(group_uuid)
if body is None:
return []
m = re.search(
r'children = \((.*?)\);', body, re.DOTALL
)
if not m:
return []
return re.findall(r'([A-F0-9]{24})', m.group(1))
def is_group(self, uuid):
"""Check if UUID is a PBXGroup definition."""
pattern = rf'^\t\t{uuid} /\*[^*]+\*/ = \{{'
return bool(re.search(
pattern, self.group_section, re.MULTILINE
))
def is_file_reference(self, uuid):
"""Check if UUID is a PBXFileReference."""
pattern = (
rf'{uuid} /\*[^*]+\*/ = \{{isa = PBXFileReference'
)
return bool(re.search(pattern, self.fileref_section))
def get_file_name(self, uuid):
"""Get filename from PBXFileReference comment."""
pattern = rf'{uuid} /\* (.*?) \*/ ='
m = re.search(pattern, self.fileref_section)
return m.group(1) if m else None
def get_group_hierarchy_path(self, target_uuid):
"""Trace parent chain to build a path string."""
parent_map = {}
for m in re.finditer(
r'^\t\t([A-F0-9]{24}) /\* .+? \*/ = \{'
r'[^}]*?children = \((.*?)\);',
self.group_section,
re.DOTALL | re.MULTILINE,
):
g_uuid = m.group(1)
children = re.findall(
r'([A-F0-9]{24})', m.group(2)
)
for c in children:
parent_map[c] = g_uuid
chain = []
current = target_uuid
visited = set()
while current and current not in visited:
visited.add(current)
name = self.get_group_name(current)
if name:
chain.append(name)
current = parent_map.get(current)
chain.reverse()
return '/'.join(chain) if chain else '(root)'
def collect_group_tree(reader, group_uuid, disk_prefix):
"""Recursively collect the group tree.
Returns:
files: dict of {relative_path: file_uuid}
dirs: set of relative directory paths
"""
files = {}
dirs = set()
children = reader.get_children(group_uuid)
for child_uuid in children:
if reader.is_file_reference(child_uuid):
fname = reader.get_file_name(child_uuid)
if fname:
rel = (
f"{disk_prefix}{fname}"
if disk_prefix else fname
)
files[rel] = child_uuid
elif reader.is_group(child_uuid):
name = reader.get_group_name(child_uuid)
path_attr = reader.get_group_path_attr(child_uuid)
# Display name for logical path
if not name:
continue
# Actual folder name on disk
folder = path_attr if path_attr else name
rel_dir = (
f"{disk_prefix}{folder}"
if disk_prefix else folder
)
dirs.add(rel_dir)
sub_files, sub_dirs = collect_group_tree(
reader, child_uuid, f"{rel_dir}/"
)
files.update(sub_files)
dirs.update(sub_dirs)
return files, dirs
def collect_disk_tree(base_path):
"""Recursively collect all files and dirs on disk.
Returns:
files: set of relative file paths
dirs: set of relative directory paths
"""
files = set()
dirs = set()
if not os.path.isdir(base_path):
return files, dirs
for dirpath, dirnames, filenames in os.walk(base_path):
rel_dir = os.path.relpath(dirpath, base_path)
if rel_dir == '.':
rel_dir = ''
for dname in dirnames:
rel = (
f"{rel_dir}/{dname}" if rel_dir else dname
)
dirs.add(rel)
for fname in filenames:
if fname == '.DS_Store':
continue
rel = (
f"{rel_dir}/{fname}" if rel_dir else fname
)
files.add(rel)
return files, dirs
def audit(group_path, group_id=None):
"""Run the audit."""
parts = group_path.rstrip('/').split('/')
if len(parts) < 2:
print(
"Error: group_path must be parent/group, "
f"e.g. 'Classes/Intents'. Got: '{group_path}'"
)
sys.exit(1)
parent_path = parts[0]
group_name = parts[-1]
reader = PBXGroupReader(PBXPROJ_PATH)
# Resolve group UUID
if group_id:
if not reader.find_group_by_uuid(group_id):
print(f"Error: Group UUID '{group_id}' not found")
sys.exit(1)
group_uuid = group_id
else:
matches = reader.find_all_groups_by_name(group_name)
if not matches:
print(f"Error: Group '{group_name}' not found")
sys.exit(1)
if len(matches) > 1:
print(
f"Found {len(matches)} groups named "
f"'{group_name}'."
)
print(
"Use --group-id <UUID> to pick one."
)
print()
for uuid in matches:
path = reader.get_group_hierarchy_path(uuid)
print(f" {uuid} {path}")
print()
sys.exit(1)
group_uuid = matches[0]
# Check if already a synced group
is_synced = reader.is_synced_group(group_uuid)
# Determine disk base path
if is_synced:
# Synced groups have path in single-line format
m = re.search(
rf'{group_uuid}.*?path = (.*?);',
reader.synced_section,
)
folder_name = m.group(1).strip('"') if m else group_name
else:
path_attr = reader.get_group_path_attr(group_uuid)
folder_name = path_attr if path_attr else group_name
disk_base = os.path.join(parent_path, folder_name)
print()
print("=" * 60)
print(" Group / Disk Audit")
print("=" * 60)
print(f" Group: {group_name}")
print(f" UUID: {group_uuid}")
if is_synced:
print(f" Type: PBXFileSystemSynchronizedRootGroup")
print(f" Disk: {disk_base}/")
print(f" Project: {PBXPROJ_PATH}")
print()
if is_synced:
print(
" This group is already a filesystem synced "
"folder."
)
print(
" Xcode auto-discovers files from disk — "
"no group tree to compare."
)
if os.path.isdir(disk_base):
disk_files, disk_dirs = collect_disk_tree(
disk_base
)
print(
f" Folder exists: {len(disk_files)} files, "
f"{len(disk_dirs)} subdirs"
)
else:
print(f" WARNING: Folder '{disk_base}' not found")
print()
return 0
# Collect Xcode group tree
xcode_files, xcode_dirs = collect_group_tree(
reader, group_uuid, ''
)
# Collect disk tree
disk_files, disk_dirs = collect_disk_tree(disk_base)
xcode_file_set = set(xcode_files.keys())
# --- Summary ---
print("-" * 60)
print(" SUMMARY")
print("-" * 60)
print()
print(f" Xcode group: {len(xcode_file_set)} files, "
f"{len(xcode_dirs)} subdirs")
print(f" Disk: {len(disk_files)} files, "
f"{len(disk_dirs)} subdirs")
print()
# --- Files in Xcode but missing on disk ---
missing_on_disk = xcode_file_set - disk_files
if missing_on_disk:
print("-" * 60)
print(
f" FILES IN XCODE BUT MISSING ON DISK "
f"({len(missing_on_disk)})"
)
print("-" * 60)
print()
for f in sorted(missing_on_disk):
print(f" {f}")
print()
# --- Files on disk but not in Xcode group ---
extra_on_disk = disk_files - xcode_file_set
if extra_on_disk:
print("-" * 60)
print(
f" FILES ON DISK BUT NOT IN XCODE GROUP "
f"({len(extra_on_disk)})"
)
print("-" * 60)
print()
for f in sorted(extra_on_disk):
print(f" {f}")
print()
# --- Dirs in Xcode but missing on disk ---
missing_dirs = xcode_dirs - disk_dirs
if missing_dirs:
print("-" * 60)
print(
f" SUBGROUPS WITHOUT FOLDER ON DISK "
f"({len(missing_dirs)})"
)
print("-" * 60)
print()
for d in sorted(missing_dirs):
print(f" {d}/")
print()
# --- Dirs on disk but not in Xcode group ---
extra_dirs = disk_dirs - xcode_dirs
if extra_dirs:
print("-" * 60)
print(
f" FOLDERS ON DISK NOT IN XCODE GROUP "
f"({len(extra_dirs)})"
)
print("-" * 60)
print()
for d in sorted(extra_dirs):
print(f" {d}/")
print()
# --- Empty folders on disk ---
empty_dirs = []
for d in sorted(disk_dirs):
full = os.path.join(disk_base, d)
if os.path.isdir(full):
contents = [
x for x in os.listdir(full)
if x != '.DS_Store'
]
if not contents:
empty_dirs.append(d)
if empty_dirs:
print("-" * 60)
print(f" EMPTY FOLDERS ON DISK ({len(empty_dirs)})")
print("-" * 60)
print()
for d in empty_dirs:
print(f" {d}/")
print()
# --- Result ---
issues = (
len(missing_on_disk) + len(extra_on_disk)
+ len(missing_dirs) + len(extra_dirs)
+ len(empty_dirs)
)
if issues == 0:
print("=" * 60)
print(" OK: Disk and Xcode group are in sync")
print("=" * 60)
else:
print("=" * 60)
print(f" FOUND {issues} ISSUE(S)")
print("=" * 60)
print()
return 0 if issues == 0 else 1
def main():
args = sys.argv[1:]
group_id = None
if '--group-id' in args:
idx = args.index('--group-id')
if idx + 1 >= len(args):
print("Error: --group-id requires a value")
sys.exit(1)
group_id = args[idx + 1]
args = args[:idx] + args[idx + 2:]
if len(args) != 1:
print(
"Usage: python audit_group.py "
"[--group-id <UUID>] <group_path>"
)
print()
print("Compares Xcode group hierarchy with disk "
"and reports differences.")
print()
print("Example:")
print(
" python audit_group.py "
"\"Classes/SmartNotifications\""
)
print(
" python audit_group.py "
"--group-id ABC123... \"Classes/iCloud\""
)
sys.exit(1)
group_path = args[0]
sys.exit(audit(group_path, group_id))
if __name__ == '__main__':
main()