-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpattern-break.py
More file actions
1133 lines (1008 loc) · 40.9 KB
/
pattern-break.py
File metadata and controls
1133 lines (1008 loc) · 40.9 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
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# pattern-break.py
#
# Version 0.4.12
#
# -----------------------------------------------------------------------------
# A numeric gap detection tool for files & directories.
# -----------------------------------------------------------------------------
# Licensed under the GNU General Public License v3.0
# (https://www.gnu.org/licenses/gpl-3.0.en.html)
#
# This script scans one or more directories (recursively if requested),
# gathers numeric coverage from filenames or directory names, and
# detects gaps ("missing" numeric IDs) in that coverage.
#
# Major Features:
# - Multi-block numeric detection with various policies.
# - Optionally detect ranges like 100-120 in filenames and expand coverage.
# - Grouping by directory or cross-directory.
# - Threshold-based splitting for large numeric jumps.
# - Various output modes: summary, inline, csv, json, ascii-table, rich-table.
# - Output destinations: stdout, file, or clipboard.
#
# Usage example:
# pattern-break.py -d C:\myfiles --multi-range --format=rich-table --range=compact
#
# Windows note: Some table formats produce ANSI codes, which may require
# - Windows 10+ with Virtual Terminal enabled (see enable_vt_mode() below), or
# - The 'colorama' library to handle ANSI on older shells.
# -----------------------------------------------------------------------------
__version__ = "0.4.12"
import sys
import os
import re
import fnmatch
import argparse
import json
import time
import ctypes
from datetime import datetime
try:
import pyperclip
HAS_PYPERCLIP = True
except ImportError:
HAS_PYPERCLIP = False
# Optional Rich usage (for an ANSI table).
try:
from rich.console import Console
from rich.table import Table
from rich.box import ASCII
HAS_RICH = True
except ImportError:
HAS_RICH = False
##############################################################################
# Optional: enable virtual terminal mode on Windows
##############################################################################
def enable_vt_mode():
"""
Attempt to enable Windows 10+ Virtual Terminal Processing so that ANSI
codes render correctly in cmd.exe or PowerShell.
If we're not on Windows or the call fails, we ignore it gracefully.
"""
if os.name == 'nt':
try:
kernel32 = ctypes.windll.kernel32
# STD_OUTPUT_HANDLE = -11
h_stdout = kernel32.GetStdHandle(-11)
mode = ctypes.c_uint()
# read current mode
if kernel32.GetConsoleMode(h_stdout, ctypes.byref(mode)) != 0:
# 0x0004 is ENABLE_VIRTUAL_TERMINAL_PROCESSING
mode.value |= 0x0004
kernel32.SetConsoleMode(h_stdout, mode)
except Exception:
# If any error, just pass; color might not be enabled.
pass
##############################################################################
# EXTENDED HELP TEXT
##############################################################################
EXTENDED_HELP = {
"multi-range": r"""
If --multi-range is set, we parse '(\d+)-(\d+)' (by default) from the entire name,
merging that numeric range into coverage.
""",
"range-regex": r"""
--range-regex <REGEX> (default='(\d+)-(\d+)')
Lets you override the default for multi-range expansions.
""",
"block-policy": r"""
--block-policy [first|largest|all|multi-block-advanced]
first => only the first numeric block
largest => only the largest numeric block
all => every numeric block => coverage set
multi-block-advanced => the 7-step approach to treat each block distinctly,
never merging them incorrectly.
""",
"ansi-issues": r"""
Windows CMD.exe with ANSI:
If you're using an older Windows shell, ANSI sequences might not display
properly. You can:
- Use PowerShell or Windows Terminal with Virtual Terminal enabled.
- Install 'colorama' to translate ANSI to Win32 calls.
- Switch to ASCII-only table output: --format=ascii-table
- Or use summary/inline/csv/json modes that don't rely on ANSI.
"""
}
def extended_help_lookup(argv):
"""Look for '-h topic' or '--help topic' to print extended help."""
if "-h" in argv or "--help" in argv:
idx = argv.index("-h") if "-h" in argv else argv.index("--help")
if idx + 1 < len(argv):
topic = argv[idx+1]
if topic in EXTENDED_HELP:
print(EXTENDED_HELP[topic])
sys.exit(0)
##############################################################################
# ARGUMENT PARSING
##############################################################################
def parse_args():
extended_help_lookup(sys.argv[1:])
parser = argparse.ArgumentParser(
description=f"pattern-break {__version__}: numeric gap detection tool.",
add_help=False
)
parser.add_argument("--version","-V", action="version", version=f"%(prog)s {__version__}")
parser.add_argument("--dir","-d", nargs="+", required=True,
help="Directories to scan.")
parser.add_argument("--exclude","-xd", action="append",
help="Exclude pattern(s) (fnmatch). e.g. *.txt")
parser.add_argument("--recursive","-r", action="store_true",
help="Recurse subdirectories (default=off).")
parser.add_argument("--check", choices=["files","dirs","both"], default="files",
help="Analyze files, dirs, or both (default=files).")
parser.add_argument("--pattern","-pt", help="Regex filter for names.")
parser.add_argument("--filter","-ft", help="Substring filter for names.")
parser.add_argument("--group-threshold","-gt", type=int,
help="Split groups if numeric gap > threshold.")
parser.add_argument("--cross-dir-grouping", action="store_true",
help="Merge coverage from multiple dirs if numeric values align.")
parser.add_argument("--block-policy", choices=["first","largest","all","multi-block-advanced"],
default="multi-block-advanced",
help="Which numeric blocks to interpret? (default=multi-block-advanced)")
parser.add_argument("--multi-range", action="store_true",
help="Parse range-regex from entire name for expansions.")
parser.add_argument("--range-regex", default=r"(\d+)-(\d+)",
help=r"Regex for multi-range coverage (default='(\d+)-(\d+)').")
parser.add_argument("--start-num", type=int,
help="Force sequence start.")
parser.add_argument("--end-num", type=int,
help="Force sequence end.")
parser.add_argument("--mod-boundary", type=int,
help="If set, consider missing up to next boundary (e.g. mod=100).")
parser.add_argument("--increment","-inc", type=int, default=1,
help="Step between consecutive numbers (default=1).")
parser.add_argument("--format","-fmt",
choices=["inline","summary","csv","json","ascii-table","rich-table"],
default="summary",
help="How to present results. (default=summary).")
parser.add_argument("--range", choices=["all","compact"], default="compact",
help="Show each missing item or just first..last in each segment.")
parser.add_argument("--range-fmt", choices=["spacing","nospace"], default="nospace",
help="If 'spacing', blank lines between segments (summary/inline).")
parser.add_argument("--show", choices=["filename","padded","number","significant"], default="filename",
help="How to display missing items (default=filename).")
parser.add_argument("--explain", action="store_true",
help="Add reason text (leading, internal, etc).")
parser.add_argument("--stats", action="store_true",
help="Show summary stats at the end.")
parser.add_argument("--show-empty", action="store_true",
help="Include groups with 0 missing (default=off).")
parser.add_argument("--verbose","-v", action="store_true",
help="Extra debug info (avg file size, etc).")
parser.add_argument("--quiet","-q", action="store_true",
help="Suppress stdout (still can do file/clip).")
parser.add_argument("--output","-o", action="append", choices=["stdout","file","clip","all"],
help="Where to send output (default=stdout).")
parser.add_argument("--filename","-f",
help="If output includes 'file', specify filename.")
parser.add_argument("-h","--help", action="help", default=argparse.SUPPRESS,
help="Show help or '-h topic' for extended topics like 'multi-range' or 'ansi-issues'.")
return parser.parse_args()
##############################################################################
# COLLECTION LOGIC
##############################################################################
def collect_files(dirs, excludes, recursive):
excludes = excludes or []
out = {}
def is_excluded(fp):
bn = os.path.basename(fp)
return any(fnmatch.fnmatch(bn,e) for e in excludes)
for d in dirs:
d_abs = os.path.abspath(d)
if not os.path.isdir(d_abs):
continue
for root, subdirs, files in os.walk(d_abs):
subdirs[:] = [sd for sd in subdirs if not is_excluded(os.path.join(root, sd))]
if root not in out:
out[root] = {"items": []}
for f in files:
fp = os.path.join(root, f)
if not is_excluded(fp) and os.path.isfile(fp):
out[root]["items"].append({
"path": fp,
"name": f,
"size": os.path.getsize(fp),
"is_dir": False
})
if not recursive:
break
return out
def collect_dirs(dirs, excludes, recursive):
excludes = excludes or []
out = {}
def is_excluded(fp):
bn = os.path.basename(fp)
return any(fnmatch.fnmatch(bn,e) for e in excludes)
for d in dirs:
d_abs = os.path.abspath(d)
if not os.path.isdir(d_abs):
continue
for root, subdirs, files in os.walk(d_abs):
subdirs[:] = [sd for sd in subdirs if not is_excluded(os.path.join(root, sd))]
if root not in out:
out[root] = {"items": []}
for sd in subdirs:
sdp = os.path.join(root, sd)
if not is_excluded(sdp):
out[root]["items"].append({
"path": sdp,
"name": sd,
"size": 0,
"is_dir": True
})
if not recursive:
break
return out
def item_passes_filter(it, pat, subf):
nm = it["name"]
if pat and not re.search(pat, nm):
return False
if subf and (subf not in nm):
return False
return True
##############################################################################
# COVERAGE PARSING
##############################################################################
def parse_coverage_list(it, block_policy, multi_range, range_regex):
"""
Given an item (file or directory) 'it' with name X,
parse out all numeric blocks. Then apply:
- block_policy to decide which blocks to interpret
- multi_range to expand coverage if (\\d+)-(\\d+) is found
Returns a list of coverage sets (each set is a list of integers).
"""
nm = it["name"]
blocks = re.findall(r"(\d+)", nm)
if not blocks:
return []
blocks_i = [int(b) for b in blocks]
def coverage_for_block(full_name, val):
cov = set()
cov.add(val)
if multi_range:
rngs = re.findall(range_regex, full_name)
for m in rngs:
if isinstance(m, (tuple, list)) and len(m) >= 2:
st = int(m[0])
ed = int(m[1])
lo = min(st, ed)
hi = max(st, ed)
for v in range(lo, hi+1):
cov.add(v)
return sorted(cov)
if block_policy == "first":
v = blocks_i[0]
c = coverage_for_block(nm, v)
return [c] if c else []
elif block_policy == "largest":
v = max(blocks_i)
c = coverage_for_block(nm, v)
return [c] if c else []
elif block_policy == "all":
result = []
for bval in blocks_i:
c = coverage_for_block(nm, bval)
if c:
result.append(c)
return result
else:
# multi-block-advanced => treat each block distinctly
result = []
for bval in blocks_i:
c = coverage_for_block(nm, bval)
if c:
result.append(c)
return result
##############################################################################
# GROUPING LOGIC
##############################################################################
def group_items(coll, args, artifact_type):
cross_dir = args.cross_dir_grouping
threshold = args.group_threshold
if cross_dir:
flat = []
for dkey, stuff in coll.items():
for it in stuff["items"]:
if item_passes_filter(it, args.pattern, args.filter):
coverage_list = parse_coverage_list(it,
args.block_policy,
args.multi_range,
args.range_regex)
for cov in coverage_list:
flat.append((dkey, it, cov))
return build_groups_from_flat(flat, threshold, artifact_type)
else:
out = []
for dkey, stuff in coll.items():
picks = []
for it in stuff["items"]:
if item_passes_filter(it, args.pattern, args.filter):
cov_list = parse_coverage_list(it,
args.block_policy,
args.multi_range,
args.range_regex)
for c in cov_list:
picks.append({"item": it, "coverage": c})
if not picks:
continue
picks.sort(key=lambda x: (x["coverage"][0], x["item"]["name"]))
out.extend(build_subgroups_in_dir(dkey, picks, threshold, artifact_type))
return out
def build_subgroups_in_dir(dkey, picks, threshold, artifact_type):
if not threshold:
label = compute_group_label_for_picks(picks)
return [{
"group_id": f"{dkey}__group0",
"directory": dkey,
"label": label,
"artifact_type": artifact_type,
"picks": picks
}]
groups = []
lastv = None
citems = []
idx = 0
for p in picks:
mv = p["coverage"][0]
if lastv is None:
citems = [p]
lastv = mv
else:
if (mv - lastv) > threshold:
lb = compute_group_label_for_picks(citems)
groups.append({
"group_id": f"{dkey}__group{idx}",
"directory": dkey,
"label": lb,
"artifact_type": artifact_type,
"picks": citems
})
idx += 1
citems = [p]
else:
citems.append(p)
lastv = mv
if citems:
lb = compute_group_label_for_picks(citems)
groups.append({
"group_id": f"{dkey}__group{idx}",
"directory": dkey,
"label": lb,
"artifact_type": artifact_type,
"picks": citems
})
return groups
def build_groups_from_flat(flat, threshold, artifact_type):
def min_cov(x):
return x[2][0]
flat.sort(key=lambda x: (min_cov(x), x[1]["name"]))
groups = []
citems = []
idx = 0
lastv = None
for (dkey, it, cov) in flat:
mv = cov[0]
if lastv is None:
citems = [(dkey, it, cov)]
lastv = mv
else:
if threshold and (mv - lastv) > threshold:
lb = compute_group_label_for_flat(citems)
groups.append({
"group_id": f"crossdir_{idx}",
"directory": None,
"label": lb,
"artifact_type": artifact_type,
"picks": [{"item": xx[1], "coverage": xx[2]} for xx in citems]
})
idx += 1
citems = [(dkey, it, cov)]
else:
citems.append((dkey, it, cov))
lastv = mv
if citems:
lb = compute_group_label_for_flat(citems)
groups.append({
"group_id": f"crossdir_{idx}",
"directory": None,
"label": lb,
"artifact_type": artifact_type,
"picks": [{"item": xx[1], "coverage": xx[2]} for xx in citems]
})
return groups
def compute_group_label_for_picks(picks):
for p in picks:
coverage = p["coverage"]
if coverage:
val = coverage[0]
nm = p["item"]["name"]
zval = str(val).zfill(len(str(val)))
idx = nm.find(zval)
if idx < 0:
idx = nm.find(str(val))
if idx < 0:
return "<no-numeric>"
prefix = nm[:idx]
prefix = re.sub(r"\d+$", "", prefix)
return prefix if prefix else "<no-numeric>"
return "<no-numeric>"
def compute_group_label_for_flat(citems):
for (dk, it, cov) in citems:
if cov:
val = cov[0]
nm = it["name"]
zval = str(val).zfill(len(str(val)))
idx = nm.find(zval)
if idx < 0:
idx = nm.find(str(val))
if idx < 0:
return "<no-numeric>"
prefix = nm[:idx]
prefix = re.sub(r"\d+$", "", prefix)
return prefix if prefix else "<no-numeric>"
return "<no-numeric>"
##############################################################################
# MISSING DETECTION
##############################################################################
def detect_breaks_in_group(group,
start_num=None,
end_num=None,
mod_boundary=None,
increment=1,
explain=False):
picks = group["picks"]
artifact_type = group["artifact_type"]
if not picks:
return {
"group_info": group,
"segments": [],
"stats": {"num_missing": 0, "num_real": 0, "num_segments": 0, "approx_missing_bytes": 0}
}
all_ints = set()
real_cov_items = []
total_size = 0
real_count = 0
for p in picks:
it = p["item"]
coverage = p["coverage"]
if artifact_type == "files":
total_size += it["size"]
real_count += 1
main_val = coverage[0]
px, sx = guess_prefix_suffix(it, main_val)
for v in coverage:
all_ints.add(v)
real_cov_items.append({
"val": v,
"prefix": px,
"suffix": sx,
"is_dir": it["is_dir"],
"size": it["size"]
})
sorted_ints = sorted(all_ints)
if not sorted_ints:
return {
"group_info": group,
"segments": [],
"stats": {"num_missing": 0, "num_real": 0, "num_segments": 0, "approx_missing_bytes": 0}
}
actual_min = sorted_ints[0]
actual_max = sorted_ints[-1]
# Decide sequence start
if start_num is not None:
seq_start = start_num
else:
seq_start = actual_min
if mod_boundary:
seq_start = (seq_start // mod_boundary) * mod_boundary
# Decide sequence end
if end_num is not None:
seq_end = end_num
else:
seq_end = actual_max
if mod_boundary:
seq_end = ((seq_end // mod_boundary) + 1) * mod_boundary - 1
segments = []
# Leading
if seq_start < actual_min:
st = seq_start
ed = actual_min - increment
seg = build_missing_segment(st, ed, "leading", explain, mod_boundary, increment)
if seg["count"] > 0:
segments.append(seg)
# Internal
for i in range(len(sorted_ints) - 1):
cval = sorted_ints[i]
nval = sorted_ints[i+1]
if (nval - cval) > increment:
st = cval + increment
ed = nval - 1
seg = build_missing_segment(st, ed, "internal", explain, mod_boundary, increment)
if seg["count"] > 0:
segments.append(seg)
# Trailing
if seq_end > actual_max:
st = actual_max + increment
ed = seq_end
seg = build_missing_segment(st, ed, "trailing", explain, mod_boundary, increment)
if seg["count"] > 0:
segments.append(seg)
total_missing = sum(s["count"] for s in segments)
approx_bytes = 0
if artifact_type == "files" and real_count > 0:
avg_sz = total_size / real_count
approx_bytes = avg_sz * total_missing
# fill prefix
for seg in segments:
for mi in seg["missing_items"]:
near = find_closest_prefix_suffix(mi["val"], real_cov_items)
mi["prefix"] = near["prefix"]
mi["suffix"] = near["suffix"]
return {
"group_info": group,
"segments": segments,
"stats": {
"num_missing": total_missing,
"num_real": real_count if artifact_type == "files" else len(sorted_ints),
"num_segments": len(segments),
"approx_missing_bytes": approx_bytes
}
}
def guess_prefix_suffix(it, example_val):
nm = it["name"]
zstr = str(example_val).zfill(len(str(example_val)))
idx = nm.find(zstr)
if idx < 0:
idx2 = nm.find(str(example_val))
if idx2 < 0:
return ("???_", ".xxx")
else:
px = nm[:idx2]
sx = nm[idx2+len(str(example_val)):]
return (px, sx)
else:
px = nm[:idx]
sx = nm[idx+len(zstr):]
return (px, sx)
def build_missing_segment(st, ed, btype, explain, mod_boundary, inc):
if ed < st:
return {"start_val": st, "end_val": ed, "count": 0, "boundary_type": btype, "missing_items": []}
items = []
pad_len = len(str(ed))
v = st
while v <= ed:
pstr = str(v).zfill(pad_len)
reason = btype
if explain and btype in ["leading","trailing"] and mod_boundary:
reason += " (possible boundary)"
items.append({
"val": v,
"padded": pstr,
"prefix": "",
"suffix": "",
"reason": reason
})
v += inc
return {
"start_val": st,
"end_val": ed,
"count": len(items),
"boundary_type": btype,
"missing_items": items
}
def find_closest_prefix_suffix(val, real_cov):
best = None
best_diff = float("inf")
for rc in real_cov:
diff = abs(rc["val"] - val)
if diff < best_diff:
best_diff = diff
best = rc
if best:
return {"prefix": best["prefix"], "suffix": best["suffix"]}
else:
return {"prefix": "???_", "suffix": ".xxx"}
##############################################################################
# OUTPUT FORMATTING
##############################################################################
def format_results(all_groups, args):
fmt = args.format
if fmt == "csv":
return format_csv(all_groups, args)
elif fmt == "json":
return format_json(all_groups, args)
elif fmt == "inline":
return format_inline(all_groups, args)
elif fmt == "ascii-table":
return format_ascii_table(all_groups, args)
elif fmt == "rich-table":
if HAS_RICH:
return format_rich_table(all_groups, args)
else:
return "[Error] rich-table requested but 'rich' not installed."
else:
return format_summary(all_groups, args)
def reconstruct(mi, show_mode):
if show_mode == "filename":
return f"{mi['prefix']}{mi['padded']}{mi['suffix']}"
elif show_mode == "padded":
return mi["padded"]
elif show_mode == "number":
return str(mi["val"])
elif show_mode == "significant":
# e.g. last 3 digits
return mi["padded"][-3:]
else:
return f"{mi['prefix']}{mi['padded']}{mi['suffix']}"
def global_stats_summary(bres, args):
group_count = 0
total_missing = 0
total_real = 0
total_segments = 0
total_bytes = 0
for br in bres:
if not br["segments"] and not args.show_empty:
continue
group_count += 1
st = br["stats"]
total_missing += st["num_missing"]
total_real += st["num_real"]
total_segments += st["num_segments"]
total_bytes += st["approx_missing_bytes"]
approx_mb = total_bytes / (1024 * 1024)
return f"STATS => groups:{group_count}, segments:{total_segments}, found:{total_real}, missing:{total_missing}, ~{approx_mb:.2f}MB missing"
##############################################################################
# Shared helper for table modes: build a textual segment representation
##############################################################################
def build_segment_text(segment, show_mode, range_mode, artifact_type, explain):
"""
Returns a single string describing the missing items in one segment,
respecting range_mode ('all' or 'compact'), show_mode, etc.
Example (compact, 2 items):
"dogs_m061061.jpg..dogs_m061062.jpg (2)"
Example (all, 2 items):
"dogs_m061061.jpg (internal); dogs_m061062.jpg (internal)"
"""
c = segment["count"]
if c == 0:
return ""
mis = segment["missing_items"]
if range_mode == "all":
# list each item
parts = []
for mi in mis:
lbl = reconstruct(mi, show_mode)
# optionally add reason
reason_str = f" ({mi['reason']})" if explain else ""
parts.append(f"{lbl}{reason_str}")
return "; ".join(parts)
else:
# compact
if c == 1:
mi = mis[0]
lbl = reconstruct(mi, show_mode)
reason_str = f" ({mi['reason']})" if explain else ""
# e.g. "dogs_m006057.jpg (1) (internal)"
return f"{lbl} ({c}){reason_str}"
else:
fmi = mis[0]
lmi = mis[-1]
lbl1 = reconstruct(fmi, show_mode)
lbl2 = reconstruct(lmi, show_mode)
reason_str = f" ({fmi['reason']})" if explain else ""
# e.g. "dogs_m061061.jpg..dogs_m061062.jpg (2)"
return f"{lbl1}..{lbl2} ({c}){reason_str}"
##############################################################################
# Formatting: Inline, Summary, CSV, JSON
##############################################################################
def format_inline(bres, args):
lines = []
gcount = 1
for br in bres:
segs = br["segments"]
grp = br["group_info"]
if not segs and not args.show_empty:
continue
lines.append(f"Grp #{gcount}: {grp.get('label','')} (dir:{grp.get('directory')})")
gcount += 1
if not segs:
lines.append(" No missing segments.")
continue
for i, s in enumerate(segs):
if s["count"] == 0:
continue
if i > 0 and args.range_fmt == "spacing":
lines.append("")
# build text
segtxt = build_segment_text(s, args.show, args.range, grp["artifact_type"], args.explain)
# Indent
for linepart in segtxt.split("; "):
lines.append(f" {linepart}")
if args.verbose:
st = br["stats"]
approx_mb = st["approx_missing_bytes"]/(1024*1024)
lines.append(f" [dbg] found={st['num_real']} missing={st['num_missing']} ~{approx_mb:.2f}MB missing")
if args.stats:
lines.append("")
lines.append(global_stats_summary(bres, args))
return "\n".join(lines)
def format_summary(bres, args):
lines = []
gcount = 1
for br in bres:
segs = br["segments"]
grp = br["group_info"]
if not segs and not args.show_empty:
continue
lines.append(f"Grp #{gcount}: {grp.get('label','')} (dir:{grp.get('directory')}) {{")
gcount += 1
if not segs:
lines.append(" No missing segments.")
lines.append("}")
continue
for i, s in enumerate(segs):
if s["count"] == 0:
continue
if i > 0 and args.range_fmt == "spacing":
lines.append("")
segtxt = build_segment_text(s, args.show, args.range, grp["artifact_type"], args.explain)
for linepart in segtxt.split("; "):
lines.append(f" {linepart}")
lines.append("}")
if args.verbose:
st = br["stats"]
approx_mb = st["approx_missing_bytes"]/(1024*1024)
lines.append(f" [dbg] found={st['num_real']} missing={st['num_missing']} ~{approx_mb:.2f}MB missing")
if args.stats:
lines.append("")
lines.append(global_stats_summary(bres, args))
return "\n".join(lines)
def format_csv(bres, args):
lines = []
header = ["group_id","directory","artifact_type","missing_val","missing_label","reason"]
lines.append(",".join(header))
gcount = 1
for br in bres:
segs = br["segments"]
grp = br["group_info"]
if not segs and not args.show_empty:
continue
group_id = f"group_{gcount}"
gcount += 1
dir_ = grp.get("directory","")
atype = grp.get("artifact_type","files")
if not segs:
continue
for s in segs:
if s["count"] == 0:
continue
if args.range == "all":
for mi in s["missing_items"]:
lbl = reconstruct(mi, args.show)
reason = mi["reason"] if args.explain else ""
row = [group_id, dir_, atype, str(mi["val"]), lbl, reason]
lines.append(",".join(csv_escape(x) for x in row))
else:
# compact => first..last only
c = s["count"]
mis = s["missing_items"]
if c == 1:
mi = mis[0]
lbl = reconstruct(mi, args.show)
reason = mi["reason"] if args.explain else ""
row = [group_id, dir_, atype, str(mi["val"]), lbl, reason]
lines.append(",".join(csv_escape(x) for x in row))
else:
fmi = mis[0]
lmi = mis[-1]
lbl1 = reconstruct(fmi, args.show)
lbl2 = reconstruct(lmi, args.show)
reason = fmi["reason"] if args.explain else ""
rng_label = f"{lbl1}..{lbl2} ({c} {atype})"
row = [group_id, dir_, atype, f"{fmi['val']}..{lmi['val']}", rng_label, reason]
lines.append(",".join(csv_escape(x) for x in row))
if args.stats:
lines.append(f"# {global_stats_summary(bres,args)}")
return "\n".join(lines)
def csv_escape(s):
s = str(s).replace('"','""')
if any(x in s for x in [',','"','\n','\r']):
s = f'"{s}"'
return s
def format_json(bres, args):
data = []
gcount = 1
for br in bres:
segs = br["segments"]
grp = br["group_info"]
if not segs and not args.show_empty:
continue
group_id = f"group_{gcount}"
gcount += 1
seg_data = []
for s in segs:
missing_data = []
for mi in s["missing_items"]:
lbl = reconstruct(mi, args.show)
missing_data.append({
"val": mi["val"],
"label": lbl,
"reason": mi["reason"] if args.explain else ""
})
seg_data.append({
"start_val": s["start_val"],
"end_val": s["end_val"],
"count": s["count"],
"boundary_type": s["boundary_type"],
"missing_items": missing_data
})
data.append({
"group_id": group_id,
"directory": grp.get("directory",""),
"label": grp.get("label",""),
"artifact_type": grp.get("artifact_type","files"),
"segments": seg_data,
"stats": br["stats"]
})
if args.stats:
global_st = global_stats_summary(bres, args)
return json.dumps({"results": data, "summary": global_st}, indent=2)
else:
return json.dumps({"results": data}, indent=2)
##############################################################################
# Formatting: ASCII Table / Rich Table
##############################################################################
def format_ascii_table(bres, args):
"""
Produce a minimal ASCII table, but show missing items according to
--show and --range. We create one row per segment.
If range=all, the cell may become large. If range=compact, we do
first..last style or single item with reason if enabled.
"""
lines = []
divider = "+" + "-"*10 + "+" + "-"*60 + "+" + "-"*12 + "+"
header = "| Group ID | Missing Items / Segment | Count |"
lines.append(divider)
lines.append(header)
lines.append(divider)
gcount = 1
for br in bres:
segs = br["segments"]
grp = br["group_info"]
if not segs and not args.show_empty:
continue
group_id = f"G{gcount}"
gcount += 1
for s in segs:
c = s["count"]
if c == 0:
continue
# Build a textual description using build_segment_text
segtxt = build_segment_text(s, args.show, args.range, grp["artifact_type"], args.explain)
# We could break it up if it exceeds 60 chars, but let's just put it in one line.
# We'll just store the entire string in the cell
# Possibly format the count in a separate cell or reuse c in the text
cell_count = str(c)
# We'll keep it consistent with our header columns
# We'll do a row with group_id, segtxt, c.
# But note that segtxt might already include the count in parentheses.
# We'll still store c in the last column for quick scanning.
# We can do a simple fixed width or left-justify with ljust, rjust, etc.
# For safety, let's just store them as is, truncated if needed.
segtxt_disp = segtxt[:58] + "…" if len(segtxt) > 59 else segtxt
row = f"| {group_id:<8} | {segtxt_disp:<59} | {cell_count:<10} |"
lines.append(row)
lines.append(divider)
if args.stats: