Repository navigation
Expand file tree
/
Copy pathpbs_chunk_checker.py
More file actions
3146 lines (2805 loc) · 106 KB
/
Copy pathpbs_chunk_checker.py
File metadata and controls
3146 lines (2805 loc) · 106 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
"""
PBS_Chunk_Checker — Sum the actual on-disk size of unique PBS chunks
for a selected datastore object (namespace/VM/CT).
Highlights:
- Uses PBS CLI tools to resolve datastores and inspect index files (*.fidx/*.didx)
- Deduplicates referenced chunk digests and sums unique chunk sizes
- Offers an interactive TUI (curses) with a simple text fallback
This module is intentionally self-contained and depends only on Python's
standard library plus the Proxmox Backup Server CLI tools installed on the host.
References:
- Author: Jan Paulzen (VoltKraft)
- README: README.md
- Repository: https://github.com/VoltKraft/PBS_Chunk_Checker
"""
__version__ = "2.12.0"
import argparse
import concurrent.futures as futures
import hashlib
import json
import os
import re
import shutil
import signal
import subprocess
import sys
import tempfile
import time
from collections import Counter
from datetime import datetime
from pathlib import Path
from typing import (
Any,
Callable,
Dict,
Iterable,
Iterator,
List,
NamedTuple,
Optional,
Sequence,
Set,
TextIO,
Tuple,
)
import urllib.error
import urllib.request
import ssl
try:
import curses # type: ignore
except Exception:
curses = None # type: ignore
COMMAND_PATHS: Dict[str, str] = {}
DEFAULT_PATH_SEGMENTS = [
str(p)
for p in (
Path("/usr/sbin"),
Path("/usr/bin"),
Path("/sbin"),
Path("/bin"),
)
if p.exists()
]
COMMAND_ENV = os.environ.copy()
if DEFAULT_PATH_SEGMENTS:
COMMAND_ENV["PATH"] = os.pathsep.join(list(dict.fromkeys(DEFAULT_PATH_SEGMENTS)))
else:
COMMAND_ENV["PATH"] = COMMAND_ENV.get("PATH", "")
COMMAND_ENV.setdefault("LC_ALL", "C")
COMMAND_ENV.setdefault("LANG", "C")
COMMAND_TIMEOUTS = {
"manager_list": 10,
"manager_show": 10,
"debug_snapshots": 20,
"debug_inspect": 60,
}
DATASTORE_PATTERN = re.compile(r"^[A-Za-z0-9_.-]+$")
_SNAPSHOT_LIST_CACHE: Dict[Tuple[str, str], Optional[List[Dict[str, Any]]]] = {}
_GUEST_COMMENT_CACHE: Dict[Tuple[str, str, str, str], Optional[str]] = {}
GUEST_COMMENT_MAXLEN = 48
def _format_command(cmd: object) -> str:
"""Return a shell-like string for a command sequence or object."""
if isinstance(cmd, (list, tuple)):
return " ".join(str(part) for part in cmd)
return str(cmd)
# =============================================================================
# CLI helpers and shared utilities
# =============================================================================
EMOJI_ICONS: Dict[str, str] = {
"error": "❌",
"warning": "⚠️",
"info": "ℹ️",
"folder": "📁",
"folder_current": "📂",
"save": "💾",
"index": "📄",
"sum": "➕",
"chunk": "📦",
"total": "🧮",
"timer": "⏱️",
"puzzle": "🧩",
"missing": "❌",
"threads": "🧵",
"list": "📋",
}
ASCII_ICONS: Dict[str, str] = {
"error": "[ERROR]",
"warning": "[WARN]",
"info": "[INFO]",
"folder": "[DIR]",
"folder_current": "[DIR]",
"save": "[SAVE]",
"index": "[INDEX]",
"sum": "[SUM]",
"chunk": "[CHUNK]",
"total": "[TOTAL]",
"timer": "[TIME]",
"puzzle": "[DETAIL]",
"missing": "[MISSING]",
"threads": "[THREADS]",
"list": "[LIST]",
}
ICONS: Dict[str, str] = EMOJI_ICONS.copy()
_EMOJI_ENABLED = True
_SILENT = False
_SILENT_STREAM: Optional[TextIO] = None
def _set_emoji_mode(enabled: bool) -> None:
"""Switch between emoji and ASCII icon sets."""
global ICONS, _EMOJI_ENABLED
_EMOJI_ENABLED = enabled
ICONS.clear()
ICONS.update(EMOJI_ICONS if enabled else ASCII_ICONS)
def clear_console() -> None:
"""Clear the terminal similar to the POSIX 'clear' command."""
# ANSI full reset works for Linux terminal emulators
if _SILENT:
return
if not sys.stdout.isatty():
return
print("\033c", end="", flush=True)
def _enable_silent_output() -> None:
"""Suppress stdout/stderr output (best-effort)."""
global _SILENT, _SILENT_STREAM
if _SILENT:
return
_SILENT = True
try:
_SILENT_STREAM = open(os.devnull, "w")
sys.stdout = _SILENT_STREAM # type: ignore[assignment]
sys.stderr = _SILENT_STREAM # type: ignore[assignment]
except Exception:
pass
# =============================================================================
# Update check and self-update (GitHub Releases)
# =============================================================================
REPO_OWNER = "VoltKraft"
REPO_NAME = "PBS_Chunk_Checker"
GITHUB_API_LATEST = (
"https://api.github.com/repos/"
f"{REPO_OWNER}/{REPO_NAME}/releases/latest"
)
GITHUB_RAW_TEMPLATE = (
"https://raw.githubusercontent.com/"
f"{REPO_OWNER}/{REPO_NAME}/{{tag}}/pbs_chunk_checker.py"
)
def _parse_version_str(s: str) -> Tuple[int, ...]:
"""Parse version string into a comparable tuple of ints.
Accepts forms like 'v2.5.3', '2.5.3', '2.5', '2'.
Non-digit parts are ignored.
"""
s = (s or "").strip()
if s.startswith(("v", "V")):
s = s[1:]
parts = re.findall(r"\d+", s)
return tuple(int(p) for p in parts) if parts else (0,)
def _is_remote_newer(remote: str, current: str) -> bool:
ra = _parse_version_str(remote)
ca = _parse_version_str(current)
n = max(len(ra), len(ca))
ra = ra + (0,) * (n - len(ra))
ca = ca + (0,) * (n - len(ca))
return ra > ca
def _http_request(url: str, timeout: float) -> bytes:
req = urllib.request.Request(
url,
headers={
"User-Agent": f"{REPO_NAME}/{__version__}",
"Accept": (
"application/vnd.github+json, "
"application/json;q=0.9, */*;q=0.8"
),
},
)
# Use default SSL context for secure TLS
ctx = ssl.create_default_context()
with urllib.request.urlopen(req, timeout=timeout, context=ctx) as resp:
return resp.read()
def fetch_latest_release_info(timeout: float = 5.0) -> Optional[Dict[str, str]]:
"""Return dict with latest release information or None on failure.
Dict keys: version, download_url, checksum_url, notes
"""
try:
raw = _http_request(GITHUB_API_LATEST, timeout)
data = json.loads(raw.decode("utf-8", errors="ignore"))
except Exception:
return None
tag = (data.get("tag_name") or data.get("name") or "").strip()
if not tag:
return None
assets = data.get("assets") or []
download_url: Optional[str] = None
checksum_url: Optional[str] = None
# Prefer an attached Python asset if present
for asset in assets:
try:
name = (asset.get("name") or "").lower()
if name == "pbs_chunk_checker.py" or name.endswith(".py"):
download_url = asset.get("browser_download_url")
if download_url:
break
except Exception:
continue
# locate checksum asset (best-effort, e.g. *.sha256)
for asset in assets:
try:
name = (asset.get("name") or "").lower()
if "pbs_chunk_checker" in name and name.endswith(".sha256"):
candidate = asset.get("browser_download_url")
if candidate:
checksum_url = candidate
break
except Exception:
continue
# Fallback to raw file from the tag
if not download_url:
download_url = GITHUB_RAW_TEMPLATE.format(tag=tag)
notes = data.get("body") or ""
return {
"version": tag,
"download_url": download_url,
"checksum_url": checksum_url,
"notes": notes,
}
def _extract_sha256_from_text(text: str) -> Optional[str]:
"""Extract first SHA256 digest from checksum text."""
pattern = re.compile(r"\b[a-fA-F0-9]{64}\b")
for line in text.splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
match = pattern.search(line)
if match:
return match.group(0).lower()
return None
def perform_self_update(
download_url: str,
timeout: float = 30.0,
checksum_url: Optional[str] = None,
) -> Tuple[bool, str]:
"""Download latest script and replace the current file atomically.
Returns (success, message).
"""
script_path = Path(__file__).resolve()
tmp_path = script_path.with_suffix(script_path.suffix + ".new")
bak_path = script_path.with_suffix(script_path.suffix + ".bak")
replaced = False
try:
content = _http_request(download_url, timeout)
if not content:
return False, "Download returned empty content."
# Basic sanity check: ensure file looks like a Python script for this tool
header = content[:128].decode("utf-8", errors="ignore")
if "PBS_Chunk_Checker" not in header or not header.startswith("#!/"):
return False, "Downloaded file does not look like a valid script."
if checksum_url:
try:
checksum_data = _http_request(checksum_url, timeout)
checksum_text = checksum_data.decode("utf-8", errors="ignore")
except Exception as exc:
return False, f"Failed to verify checksum: {exc}"
expected = _extract_sha256_from_text(checksum_text)
if not expected:
return False, "Checksum file did not contain a SHA256 digest."
digest = hashlib.sha256(content).hexdigest()
if digest.lower() != expected.lower():
return (
False,
"Checksum mismatch: downloaded file differs "
"from release hash.",
)
# Preserve mode bits
try:
st = script_path.stat()
mode = st.st_mode
except Exception:
mode = None # best-effort
with open(tmp_path, "wb") as f:
f.write(content)
if mode is not None:
try:
os.chmod(tmp_path, mode)
except Exception:
pass
# Keep a backup copy (best-effort)
try:
shutil.copy2(script_path, bak_path)
except Exception:
pass
os.replace(tmp_path, script_path)
replaced = True
return True, f"Successfully updated. Backup saved as {bak_path.name}."
except urllib.error.URLError as e:
return False, f"Network error: {e}"
except Exception as e:
return False, f"Update failed: {e}"
finally:
try:
if not replaced and tmp_path.exists():
tmp_path.unlink()
except Exception:
pass
def format_elapsed(seconds: float) -> str:
"""Return a compact runtime string like '1h 02m 03s'."""
seconds_int = int(seconds)
hours, remainder = divmod(seconds_int, 3600)
minutes, secs = divmod(remainder, 60)
if hours:
return f"{hours}h {minutes:02}m {secs:02}s"
return f"{minutes}m {secs:02}s"
def human_readable_size(num_bytes: int) -> str:
"""Format bytes using IEC units with 'B' suffix (e.g., '1.0KiB')."""
units = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"]
size = float(num_bytes)
for unit in units:
if size < 1024.0 or unit == units[-1]:
if unit == "B":
return f"{int(size)}B"
return f"{size:.1f}{unit}"
size /= 1024.0
def run_cmd(
cmd: Sequence[str],
check: bool = True,
capture: bool = True,
text: bool = True,
timeout: Optional[float] = None,
) -> subprocess.CompletedProcess:
"""Run a command and return the CompletedProcess. Raises on failure if check=True."""
try:
if not cmd:
raise ValueError("Command must not be empty.")
command = [str(part) for part in cmd]
resolved = COMMAND_PATHS.get(command[0])
if resolved:
command[0] = resolved
return subprocess.run(
command,
check=check,
capture_output=capture,
text=text,
timeout=timeout,
env=COMMAND_ENV,
)
except FileNotFoundError as e:
sys.stderr.write(
f"{ICONS['error']} Error: required command not found: {cmd[0]}\n"
)
raise
except subprocess.TimeoutExpired as e:
executed = _format_command(command)
timeout_val = timeout if timeout is not None else e.timeout
timeout_desc = (
f"{int(timeout_val)}s"
if isinstance(timeout_val, (int, float))
else "configured limit"
)
sys.stderr.write(
f"{ICONS['error']} Error: command timed out after "
f"{timeout_desc}: {executed}\n"
)
raise
def get_datastore_path(datastore_name: str) -> str:
"""Resolve the filesystem path of a PBS datastore via proxmox-backup-manager."""
last_error = ""
try:
cp = run_cmd(
[
"proxmox-backup-manager",
"datastore",
"show",
datastore_name,
"--output-format",
"json",
],
check=False,
timeout=COMMAND_TIMEOUTS["manager_show"],
)
if cp.returncode == 0 and cp.stdout:
try:
data = json.loads(cp.stdout)
except json.JSONDecodeError:
data = {}
path = data.get("path")
if path:
return path
if cp.returncode != 0:
err_msg = ""
if cp.stderr:
err_msg = cp.stderr.strip()
elif cp.stdout:
err_msg = cp.stdout.strip()
if err_msg:
last_error = err_msg
except subprocess.TimeoutExpired as exc:
last_error = (
f"{_format_command(exc.cmd)} timed out after "
f"{COMMAND_TIMEOUTS['manager_show']}s"
)
except FileNotFoundError:
raise
try:
cp = run_cmd(
[
"proxmox-backup-manager",
"datastore",
"show",
datastore_name,
],
check=False,
timeout=COMMAND_TIMEOUTS["manager_show"],
)
m = re.search(r'"path"\s*:\s*"([^"]+)"', cp.stdout or "")
if m:
return m.group(1)
if cp.returncode != 0:
err_msg = ""
if cp.stderr:
err_msg = cp.stderr.strip()
elif cp.stdout:
err_msg = cp.stdout.strip()
if err_msg:
last_error = err_msg
except subprocess.TimeoutExpired as exc:
last_error = (
f"{_format_command(exc.cmd)} timed out after "
f"{COMMAND_TIMEOUTS['manager_show']}s"
)
except FileNotFoundError:
raise
if not last_error:
last_error = f"Datastore '{datastore_name}' not found or path not resolvable."
sys.stderr.write(f"{ICONS['error']} Error: {last_error}\n")
sys.exit(1)
def list_datastores() -> List[str]:
"""Return a list of available PBS datastores (best-effort).
Tries JSON first, falls back to parsing text output. If the command is not
available or fails, returns an empty list so the caller can ask for manual input.
"""
try:
cp = run_cmd(
[
"proxmox-backup-manager",
"datastore",
"list",
"--output-format",
"json",
]
)
if cp.stdout:
try:
data = json.loads(cp.stdout)
if isinstance(data, list):
names: List[str] = []
for item in data:
if isinstance(item, dict):
n = (
item.get("name")
or item.get("datastore")
or item.get("id")
)
if isinstance(n, str):
names.append(n)
return sorted(set(names))
except json.JSONDecodeError:
pass
except subprocess.TimeoutExpired:
return []
except subprocess.CalledProcessError:
pass
except FileNotFoundError:
return []
try:
cp = run_cmd(
["proxmox-backup-manager", "datastore", "list"],
timeout=COMMAND_TIMEOUTS["manager_list"],
)
except (subprocess.CalledProcessError, subprocess.TimeoutExpired, FileNotFoundError):
return []
names2: List[str] = []
for line in (cp.stdout or "").splitlines():
line = line.strip()
m = re.match(r"^([A-Za-z0-9_.-]+)\b", line)
if m:
names2.append(m.group(1))
return sorted(set(names2))
def ensure_required_tools() -> None:
"""Verify that required PBS CLI tools are available before proceeding."""
global COMMAND_ENV
required = ["proxmox-backup-manager", "proxmox-backup-debug"]
search_path_entries: List[str] = []
for candidate in (COMMAND_ENV.get("PATH"), os.environ.get("PATH"), os.defpath):
for segment in (candidate or "").split(os.pathsep):
if segment and segment not in search_path_entries:
search_path_entries.append(segment)
search_path = os.pathsep.join(search_path_entries)
resolved: Dict[str, str] = {}
missing = []
for cmd in required:
path = shutil.which(cmd, path=search_path)
if path is None:
missing.append(cmd)
continue
resolved[cmd] = str(Path(path).resolve())
if missing:
missing_str = ", ".join(sorted(set(missing)))
sys.stderr.write(
f"{ICONS['error']} Error: required command(s) missing: {missing_str}\n"
)
sys.stderr.write("Please install the Proxmox Backup Server CLI tools and retry.\n")
sys.exit(1)
COMMAND_PATHS.update(resolved)
path_entries: List[str] = []
for command_path in resolved.values():
parent = str(Path(command_path).parent)
if parent not in path_entries:
path_entries.append(parent)
for default_dir in DEFAULT_PATH_SEGMENTS:
if default_dir not in path_entries:
path_entries.append(default_dir)
if not path_entries and COMMAND_ENV.get("PATH"):
path_entries = COMMAND_ENV["PATH"].split(os.pathsep)
if path_entries:
COMMAND_ENV["PATH"] = os.pathsep.join(path_entries)
def find_index_files(search_path: str) -> list[str]:
"""Recursively find *.fidx and *.didx under search_path."""
matches: list[str] = []
sp = Path(search_path)
if not sp.is_dir():
sys.stderr.write(f"{ICONS['error']} Error: folder does not exist → {search_path}\n")
sys.exit(1)
for root, dirs, files in os.walk(sp):
for name in files:
if name.endswith(".fidx") or name.endswith(".didx"):
matches.append(str(Path(root) / name))
return matches
def group_index_files_by_snapshot(index_files: list[str]) -> dict[str, list[str]]:
"""Group index files by snapshot name (the parent directory name).
Returns a dict mapping snapshot name (e.g., "2026-03-29T23:38:38Z") to a
list of index file paths belonging to that snapshot.
"""
groups: dict[str, list[str]] = {}
for filepath in index_files:
parent = Path(filepath).parent
snapshot_name = parent.name
if snapshot_name not in groups:
groups[snapshot_name] = []
groups[snapshot_name].append(filepath)
return groups
def resolve_search_path(datastore_path: str, searchpath: str) -> Path:
"""Return an absolute path inside datastore_path for the provided searchpath."""
base = Path(datastore_path).resolve()
relative = (searchpath or "").lstrip("/")
candidate = base if not relative else (base / relative)
candidate = candidate.resolve()
try:
candidate.relative_to(base)
except ValueError as exc:
raise ValueError("Search path escapes datastore root.") from exc
return candidate
# =============================================================================
# Interactive helpers (menu-driven mode)
# =============================================================================
_CURSES_SENTINEL_MANUAL = "__CURSES_MANUAL__"
_UI_OPTIONS_HANDLER: Optional[Callable[[Optional[object]], None]] = None
_UI_VERSION_HANDLER: Optional[Callable[[Optional[object]], None]] = None
def _want_curses_ui() -> bool:
"""Return True if a curses UI is likely usable on this terminal."""
if os.environ.get("PBS_CC_NO_CURSES") == "1":
return False
if curses is None:
return False
try:
return os.isatty(0) and os.isatty(1) and (os.environ.get("TERM") not in (None, "", "dumb"))
except Exception:
return False
def _set_ui_handlers(
options_handler: Optional[Callable[[Optional[object]], None]] = None,
version_handler: Optional[Callable[[Optional[object]], None]] = None,
) -> None:
"""Register callbacks used by the interactive UI overlays (options/version)."""
global _UI_OPTIONS_HANDLER, _UI_VERSION_HANDLER
_UI_OPTIONS_HANDLER = options_handler
_UI_VERSION_HANDLER = version_handler
def _invoke_options_handler(stdscr: Optional[object] = None) -> None:
"""Invoke the registered options handler if present; gently flash otherwise."""
handler = _UI_OPTIONS_HANDLER
if handler is not None:
handler(stdscr)
elif stdscr is not None and curses is not None:
try:
curses.flash()
except Exception:
pass
def _invoke_version_handler(stdscr: Optional[object] = None) -> None:
"""Invoke the registered version handler if present; gently flash otherwise."""
handler = _UI_VERSION_HANDLER
if handler is not None:
handler(stdscr)
elif stdscr is not None and curses is not None:
try:
curses.flash()
except Exception:
pass
def _curses_select_menu(prompt: str, options: List[str], allow_manual: bool) -> Optional[str]:
"""Curses-based selection list. Returns the chosen label or a special
sentinel when manual input was requested. None if canceled.
"""
def _draw(stdscr):
curses.curs_set(0)
stdscr.keypad(True)
idx = 0
top = 0
while True:
stdscr.erase()
h, w = stdscr.getmaxyx()
y = 0
for line in prompt.splitlines():
try:
stdscr.addstr(y, 0, line[: max(1, w - 1)])
except Exception:
pass
y += 1
view_h = max(1, h - (y + 1))
if idx < top:
top = idx
if idx >= top + view_h:
top = max(0, idx - view_h + 1)
end = min(len(options), top + view_h)
for i in range(top, end):
label = options[i]
prefix = "> " if i == idx else " "
text = (prefix + label)[: max(1, w - 1)]
try:
stdscr.addstr(y + (i - top), 0, text, curses.A_REVERSE if i == idx else 0)
except Exception:
pass
help_line = (
"↑/↓ move Space/Enter select m manual o options v version q quit"
if allow_manual
else "↑/↓ move Space/Enter select o options v version q quit"
)
try:
stdscr.addstr(h - 1, 0, help_line[: max(1, w - 1)])
except Exception:
pass
stdscr.refresh()
ch = stdscr.getch()
if ch in (curses.KEY_UP, ord('k')):
if idx > 0:
idx -= 1
elif ch in (curses.KEY_DOWN, ord('j')):
if idx < len(options) - 1:
idx += 1
elif ch in (curses.KEY_NPAGE,):
step = max(1, view_h - 1)
idx = min(len(options) - 1, idx + step)
elif ch in (curses.KEY_PPAGE,):
step = max(1, view_h - 1)
idx = max(0, idx - step)
elif ch in (curses.KEY_HOME,):
idx = 0
elif ch in (curses.KEY_END,):
idx = len(options) - 1
elif ch in (10, 13, ord(' ')):
return options[idx]
elif allow_manual and ch in (ord('m'), ord('M')):
return _CURSES_SENTINEL_MANUAL
elif ch in (ord('o'), ord('O')):
_invoke_options_handler(stdscr)
elif ch in (ord('v'), ord('V')):
_invoke_version_handler(stdscr)
elif ch in (ord('q'), ord('Q'), 27):
return None
try:
return curses.wrapper(_draw) # type: ignore[attr-defined]
except Exception:
return None
def _curses_popup(
stdscr: object,
title: str,
body_lines: List[str],
prompt: Optional[str] = None,
) -> Optional[str]:
"""Render a centered popup window with optional input prompt.
Returns entered text if a prompt is shown. Returns None for simple
acknowledge popups or when canceled/unavailable.
"""
if curses is None:
return None
try:
h, w = stdscr.getmaxyx() # type: ignore[attr-defined]
except Exception:
return None
lines = body_lines[:]
title_width = len(title) + 2 if title else 0
line_widths = [len(line) for line in lines]
prompt_width = len(prompt) if prompt else 0
content_width = max([title_width] + line_widths + [prompt_width])
width = (
max(32, min(w - 2, content_width + 4))
if w > 10
else max(10, w - 1)
)
body_space = max(1, (h - (4 if prompt else 3)))
visible_lines = lines[:body_space]
height = len(visible_lines) + (4 if prompt else 3)
if height > h - 1:
height = max(4 if prompt else 3, h - 1)
visible_lines = visible_lines[: max(0, height - (4 if prompt else 3))]
start_y = max(0, (h - height) // 2)
start_x = max(0, (w - width) // 2)
try:
win = curses.newwin(height, width, start_y, start_x)
except Exception:
return None
win.box()
if title:
title_text = f" {title} "
try:
win.addstr(0, max(1, (width - len(title_text)) // 2), title_text, curses.A_BOLD)
except Exception:
pass
y = 1
for line in visible_lines:
truncated = line[: width - 2]
try:
win.addstr(y, 1, truncated.ljust(width - 2))
except Exception:
pass
y += 1
if prompt is None:
footer = "Press any key to continue..."
try:
win.addstr(height - 2, 1, footer[: width - 2].ljust(width - 2), curses.A_DIM)
except Exception:
pass
win.refresh()
win.getch()
del win
stdscr.touchwin() # type: ignore[attr-defined]
stdscr.refresh() # type: ignore[attr-defined]
return None
prompt_line = prompt[: width - 2]
input_y = height - 2
try:
win.addstr(input_y, 1, prompt_line.ljust(width - 2))
except Exception:
pass
win.refresh()
curses.echo()
try:
cursor_x = min(len(prompt_line) + 1, width - 2)
win.move(input_y, cursor_x)
max_chars = max(1, width - cursor_x - 1)
raw = win.getstr(input_y, cursor_x, max_chars)
except Exception:
raw = b""
finally:
curses.noecho()
text = raw.decode(errors="ignore").strip()
del win
stdscr.touchwin() # type: ignore[attr-defined]
stdscr.refresh() # type: ignore[attr-defined]
return text
def _curses_show_version(stdscr: object) -> None:
"""Show version and offer update if a newer release is available."""
# Inform about current version first
lines = [f"PBS_Chunk_Checker version {__version__}"]
info = fetch_latest_release_info(timeout=5.0)
if info is None:
lines.append("")
lines.append("Update check failed.")
_curses_popup(stdscr, "Version", lines)
return
remote_ver = info.get("version", "")
if _is_remote_newer(remote_ver, __version__):
lines.append("")
lines.append(f"New version available: {remote_ver}")
lines.append("")
choice = _curses_popup(
stdscr,
"Version",
lines + ["Update now? [y/N]"],
prompt="> "
)
if choice and choice.strip().lower().startswith("y"):
ok, msg = perform_self_update(
info["download_url"],
timeout=30.0,
checksum_url=info.get("checksum_url"),
)
if ok:
_curses_popup(
stdscr,
"Update",
[
msg,
"",
"Please restart the program to use the new version.",
],
)
sys.exit(0)
else:
_curses_popup(stdscr, "Update", [msg])
else:
_curses_popup(stdscr, "Version", lines)
else:
lines.append("")
lines.append("You already run the latest version.")
_curses_popup(stdscr, "Version", lines)
def _curses_threads_dialog(stdscr: object, args) -> None:
"""Interactive dialog to view and set the thread count (curses UI)."""
lines = [
"Threads control the number of parallel operations used to:",
" - parse index files (*.fidx/*.didx)",
" - stat chunk files under .chunks",
"",
f"Current value: {args.threads}",
"",
"Enter a number between 1 and 32.",
"Leave blank to keep the current value.",
]
result = _curses_popup(
stdscr,
"Thread Settings",
lines,
prompt="New thread count: ",
)
if result is None:
return
if not result:
return
if not result.isdigit():
_curses_popup(stdscr, "Thread Settings", ["Please enter a positive integer."])
return
val = int(result)
if val < 1 or val > 32:
_curses_popup(stdscr, "Thread Settings", ["Threads must be between 1 and 32."])
return
args.threads = val
_curses_popup(stdscr, "Thread Settings", [f"Threads set to {val}."])
def _text_show_version(pause_after: bool = True, clear_screen: bool = True) -> None:
"""Show version and offer update in text mode."""
if clear_screen:
clear_console()
print(f"PBS_Chunk_Checker version: {__version__}\n")
print("Checking for updates...")
info = fetch_latest_release_info(timeout=5.0)
if info is None:
print("Update check failed.")
if pause_after:
input("Press Enter to continue...")
return
remote_ver = info.get("version", "")
if _is_remote_newer(remote_ver, __version__):
print(f"New version available: {remote_ver}")
ans = input("Update now? [y/N]: ").strip().lower()
if ans.startswith("y"):
ok, msg = perform_self_update(
info["download_url"],
timeout=30.0,
checksum_url=info.get("checksum_url"),
)
print(msg)
if ok:
print("\nPlease restart the program to use the new version.")
if pause_after:
input("Press Enter to continue...")
sys.exit(0)
else:
if pause_after:
input("Press Enter to continue...")
return
else:
print("You already run the latest version.")
if pause_after:
input("Press Enter to continue...")
def _text_threads_dialog(args) -> None:
"""Interactive dialog to view and set thread count (text UI)."""
while True: