pathflow-toolkit 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- path_file/__init__.py +223 -0
- path_file/__main__.py +6 -0
- path_file/_internal/__init__.py +87 -0
- path_file/_internal/_iterators.py +349 -0
- path_file/_internal/_log.py +153 -0
- path_file/_internal/_parsers.py +234 -0
- path_file/_internal/_safety.py +268 -0
- path_file/_version.py +1 -0
- path_file/actions.py +855 -0
- path_file/archive.py +447 -0
- path_file/chain.py +1028 -0
- path_file/cli.py +582 -0
- path_file/entries.py +459 -0
- path_file/exceptions.py +174 -0
- path_file/filters.py +654 -0
- path_file/hash.py +338 -0
- path_file/progress.py +321 -0
- path_file/py.typed +0 -0
- path_file/report.py +348 -0
- path_file/rules.py +481 -0
- path_file/search.py +472 -0
- path_file/sync.py +384 -0
- path_file/units.py +420 -0
- path_file/utils.py +509 -0
- path_file/watch.py +310 -0
- pathflow_toolkit-0.1.0.dist-info/METADATA +219 -0
- pathflow_toolkit-0.1.0.dist-info/RECORD +30 -0
- pathflow_toolkit-0.1.0.dist-info/WHEEL +4 -0
- pathflow_toolkit-0.1.0.dist-info/entry_points.txt +2 -0
- pathflow_toolkit-0.1.0.dist-info/licenses/LICENSE +21 -0
path_file/hash.py
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
"""Hash computation and duplicate detection utilities."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import threading
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from path_file._internal._log import get_logger, log_debug
|
|
12
|
+
from path_file.entries import Entry
|
|
13
|
+
|
|
14
|
+
logger = get_logger(__name__)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
18
|
+
# SINGLE FILE HASHING
|
|
19
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
20
|
+
|
|
21
|
+
DEFAULT_CHUNK_SIZE = 65536 # 64 KB
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def hash_file(
|
|
25
|
+
path: Path,
|
|
26
|
+
algorithm: str = "sha256",
|
|
27
|
+
chunk_size: int = DEFAULT_CHUNK_SIZE,
|
|
28
|
+
) -> str:
|
|
29
|
+
"""
|
|
30
|
+
Compute hash of a file.
|
|
31
|
+
|
|
32
|
+
Args:
|
|
33
|
+
path: File path
|
|
34
|
+
algorithm: Hash algorithm (md5, sha1, sha256, sha512, blake2b, blake2s)
|
|
35
|
+
chunk_size: Read chunk size in bytes
|
|
36
|
+
|
|
37
|
+
Returns:
|
|
38
|
+
Hex digest string
|
|
39
|
+
|
|
40
|
+
Raises:
|
|
41
|
+
HashError: If file cannot be read
|
|
42
|
+
"""
|
|
43
|
+
try:
|
|
44
|
+
h = hashlib.new(algorithm)
|
|
45
|
+
except ValueError as e:
|
|
46
|
+
from path_file.exceptions import HashError
|
|
47
|
+
|
|
48
|
+
raise HashError(str(path), f"Unknown algorithm: {algorithm}") from e
|
|
49
|
+
|
|
50
|
+
try:
|
|
51
|
+
with path.open("rb") as f:
|
|
52
|
+
for chunk in iter(lambda: f.read(chunk_size), b""):
|
|
53
|
+
h.update(chunk)
|
|
54
|
+
except (OSError, PermissionError) as e:
|
|
55
|
+
from path_file.exceptions import HashError
|
|
56
|
+
|
|
57
|
+
raise HashError(str(path), f"Cannot read file: {e}") from e
|
|
58
|
+
|
|
59
|
+
return h.hexdigest()
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def hash_file_fast(
|
|
63
|
+
path: Path,
|
|
64
|
+
algorithm: str = "sha256",
|
|
65
|
+
sample_size: int = 4096,
|
|
66
|
+
) -> str:
|
|
67
|
+
"""
|
|
68
|
+
Fast hash using only first N bytes (for quick duplicate detection).
|
|
69
|
+
|
|
70
|
+
Not cryptographically secure - use for preliminary filtering only.
|
|
71
|
+
"""
|
|
72
|
+
try:
|
|
73
|
+
h = hashlib.new(algorithm)
|
|
74
|
+
with path.open("rb") as f:
|
|
75
|
+
h.update(f.read(sample_size))
|
|
76
|
+
return h.hexdigest()
|
|
77
|
+
except (OSError, PermissionError, ValueError) as e:
|
|
78
|
+
from path_file.exceptions import HashError
|
|
79
|
+
|
|
80
|
+
raise HashError(str(path), f"Fast hash failed: {e}") from e
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
84
|
+
# BATCH HASHING
|
|
85
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def hash_files(
|
|
89
|
+
entries: list[Entry],
|
|
90
|
+
algorithm: str = "sha256",
|
|
91
|
+
parallel: bool = True,
|
|
92
|
+
workers: int = 8,
|
|
93
|
+
progress: Callable[[int, int], None] | None = None,
|
|
94
|
+
) -> dict[Path, str]:
|
|
95
|
+
"""
|
|
96
|
+
Compute hashes for multiple files.
|
|
97
|
+
|
|
98
|
+
Args:
|
|
99
|
+
entries: List of Entry objects (only files are hashed)
|
|
100
|
+
algorithm: Hash algorithm
|
|
101
|
+
parallel: Use thread pool
|
|
102
|
+
workers: Number of worker threads
|
|
103
|
+
progress: Optional callback(current, total)
|
|
104
|
+
|
|
105
|
+
Returns:
|
|
106
|
+
Dict mapping Path -> hash string
|
|
107
|
+
"""
|
|
108
|
+
files = [e for e in entries if e.is_file]
|
|
109
|
+
results: dict[Path, str] = {}
|
|
110
|
+
lock = threading.Lock()
|
|
111
|
+
completed = 0
|
|
112
|
+
|
|
113
|
+
def hash_one(entry: Entry) -> tuple[Path, str]:
|
|
114
|
+
return entry.path, hash_file(entry.path, algorithm)
|
|
115
|
+
|
|
116
|
+
if parallel and len(files) > 1:
|
|
117
|
+
with ThreadPoolExecutor(max_workers=workers) as executor:
|
|
118
|
+
futures = {executor.submit(hash_one, e): e for e in files}
|
|
119
|
+
for future in as_completed(futures):
|
|
120
|
+
try:
|
|
121
|
+
path, hash_val = future.result()
|
|
122
|
+
with lock:
|
|
123
|
+
results[path] = hash_val
|
|
124
|
+
completed += 1
|
|
125
|
+
if progress:
|
|
126
|
+
progress(completed, len(files))
|
|
127
|
+
except Exception as e:
|
|
128
|
+
entry = futures[future]
|
|
129
|
+
log_debug(f"Hash failed for {entry.path}: {e}")
|
|
130
|
+
else:
|
|
131
|
+
for entry in files:
|
|
132
|
+
try:
|
|
133
|
+
results[entry.path] = hash_file(entry.path, algorithm)
|
|
134
|
+
completed += 1
|
|
135
|
+
if progress:
|
|
136
|
+
progress(completed, len(files))
|
|
137
|
+
except Exception as e:
|
|
138
|
+
log_debug(f"Hash failed for {entry.path}: {e}")
|
|
139
|
+
|
|
140
|
+
return results
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
144
|
+
# DUPLICATE DETECTION
|
|
145
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def find_duplicates(
|
|
149
|
+
entries: list[Entry],
|
|
150
|
+
algorithm: str = "sha256",
|
|
151
|
+
parallel: bool = True,
|
|
152
|
+
workers: int = 8,
|
|
153
|
+
min_size: int = 1,
|
|
154
|
+
) -> dict[str, list[Entry]]:
|
|
155
|
+
"""
|
|
156
|
+
Find duplicate files by content hash.
|
|
157
|
+
|
|
158
|
+
Args:
|
|
159
|
+
entries: List of Entry objects
|
|
160
|
+
algorithm: Hash algorithm
|
|
161
|
+
parallel: Use parallel hashing
|
|
162
|
+
workers: Worker threads
|
|
163
|
+
min_size: Minimum file size to consider (bytes)
|
|
164
|
+
|
|
165
|
+
Returns:
|
|
166
|
+
Dict mapping hash -> list of duplicate Entries (only groups with 2+ files)
|
|
167
|
+
"""
|
|
168
|
+
# Filter files by minimum size
|
|
169
|
+
files = [e for e in entries if e.is_file and e.size >= min_size]
|
|
170
|
+
|
|
171
|
+
if len(files) < 2:
|
|
172
|
+
return {}
|
|
173
|
+
|
|
174
|
+
# Quick pass: group by size first
|
|
175
|
+
by_size: dict[int, list[Entry]] = {}
|
|
176
|
+
for f in files:
|
|
177
|
+
by_size.setdefault(f.size, []).append(f)
|
|
178
|
+
|
|
179
|
+
# Only hash groups with same size
|
|
180
|
+
candidates = []
|
|
181
|
+
for _size, group in by_size.items():
|
|
182
|
+
if len(group) > 1:
|
|
183
|
+
candidates.extend(group)
|
|
184
|
+
|
|
185
|
+
if not candidates:
|
|
186
|
+
return {}
|
|
187
|
+
|
|
188
|
+
# Hash candidates
|
|
189
|
+
hashes = hash_files(candidates, algorithm, parallel, workers)
|
|
190
|
+
|
|
191
|
+
# Group by hash
|
|
192
|
+
by_hash: dict[str, list[Entry]] = {}
|
|
193
|
+
for entry in candidates:
|
|
194
|
+
h = hashes.get(entry.path)
|
|
195
|
+
if h:
|
|
196
|
+
by_hash.setdefault(h, []).append(entry)
|
|
197
|
+
|
|
198
|
+
# Return only duplicates (2+ files with same hash)
|
|
199
|
+
return {h: group for h, group in by_hash.items() if len(group) > 1}
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def find_duplicates_quick(
|
|
203
|
+
entries: list[Entry],
|
|
204
|
+
sample_size: int = 4096,
|
|
205
|
+
) -> dict[tuple[int, str], list[Entry]]:
|
|
206
|
+
"""
|
|
207
|
+
Quick duplicate detection using (size, partial_hash) as key.
|
|
208
|
+
|
|
209
|
+
Much faster but may have false positives (same size + same prefix).
|
|
210
|
+
Use find_duplicates() for confirmation.
|
|
211
|
+
|
|
212
|
+
Returns:
|
|
213
|
+
Dict mapping (size, partial_hash) -> list of Entries
|
|
214
|
+
"""
|
|
215
|
+
files = [e for e in entries if e.is_file]
|
|
216
|
+
by_key: dict[tuple[int, str], list[Entry]] = {}
|
|
217
|
+
|
|
218
|
+
for entry in files:
|
|
219
|
+
try:
|
|
220
|
+
partial = hash_file_fast(entry.path, "sha256", sample_size)
|
|
221
|
+
key = (entry.size, partial)
|
|
222
|
+
by_key.setdefault(key, []).append(entry)
|
|
223
|
+
except Exception as e:
|
|
224
|
+
log_debug(f"Fast hash failed for {entry.path}: {e}")
|
|
225
|
+
continue
|
|
226
|
+
|
|
227
|
+
return {k: v for k, v in by_key.items() if len(v) > 1}
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def find_duplicates_by_name(entries: list[Entry]) -> dict[str, list[Entry]]:
|
|
231
|
+
"""Find files with same name (regardless of content)."""
|
|
232
|
+
by_name: dict[str, list[Entry]] = {}
|
|
233
|
+
for e in entries:
|
|
234
|
+
if e.is_file:
|
|
235
|
+
by_name.setdefault(e.name.lower(), []).append(e)
|
|
236
|
+
return {k: v for k, v in by_name.items() if len(v) > 1}
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
240
|
+
# HASH VERIFICATION
|
|
241
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def verify_hash(
|
|
245
|
+
path: Path,
|
|
246
|
+
expected_hash: str,
|
|
247
|
+
algorithm: str = "sha256",
|
|
248
|
+
) -> bool:
|
|
249
|
+
"""Verify file matches expected hash."""
|
|
250
|
+
try:
|
|
251
|
+
actual = hash_file(path, algorithm)
|
|
252
|
+
return actual.lower() == expected_hash.lower()
|
|
253
|
+
except Exception:
|
|
254
|
+
return False
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def verify_hashes(
|
|
258
|
+
file_hashes: dict[Path, str],
|
|
259
|
+
algorithm: str = "sha256",
|
|
260
|
+
parallel: bool = True,
|
|
261
|
+
workers: int = 8,
|
|
262
|
+
) -> dict[Path, bool]:
|
|
263
|
+
"""Verify multiple files against expected hashes."""
|
|
264
|
+
results: dict[Path, bool] = {}
|
|
265
|
+
|
|
266
|
+
def verify_one(path: Path, expected: str) -> tuple[Path, bool]:
|
|
267
|
+
return path, verify_hash(path, expected, algorithm)
|
|
268
|
+
|
|
269
|
+
if parallel and len(file_hashes) > 1:
|
|
270
|
+
with ThreadPoolExecutor(max_workers=workers) as executor:
|
|
271
|
+
futures = {executor.submit(verify_one, p, h): p for p, h in file_hashes.items()}
|
|
272
|
+
for future in as_completed(futures):
|
|
273
|
+
path, ok = future.result()
|
|
274
|
+
results[path] = ok
|
|
275
|
+
else:
|
|
276
|
+
for path, expected in file_hashes.items():
|
|
277
|
+
results[path] = verify_hash(path, expected, algorithm)
|
|
278
|
+
|
|
279
|
+
return results
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
283
|
+
# CHECKSUM FILES
|
|
284
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def write_checksums(
|
|
288
|
+
entries: list[Entry],
|
|
289
|
+
output: Path,
|
|
290
|
+
algorithm: str = "sha256",
|
|
291
|
+
format: str = "md5sum", # or "sha256sum", "b2sum"
|
|
292
|
+
) -> None:
|
|
293
|
+
"""
|
|
294
|
+
Write checksums to file in standard format.
|
|
295
|
+
|
|
296
|
+
Format: hash *path (one per line)
|
|
297
|
+
"""
|
|
298
|
+
files = [e for e in entries if e.is_file]
|
|
299
|
+
hashes = hash_files(files, algorithm)
|
|
300
|
+
|
|
301
|
+
lines = []
|
|
302
|
+
for entry in files:
|
|
303
|
+
h = hashes.get(entry.path)
|
|
304
|
+
if h:
|
|
305
|
+
# Use relative path if possible
|
|
306
|
+
try:
|
|
307
|
+
rel_path = entry.path.relative_to(output.parent)
|
|
308
|
+
path_str = str(rel_path)
|
|
309
|
+
except ValueError:
|
|
310
|
+
path_str = str(entry.path)
|
|
311
|
+
lines.append(f"{h} *{path_str}")
|
|
312
|
+
|
|
313
|
+
output.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def read_checksums(
|
|
317
|
+
checksum_file: Path,
|
|
318
|
+
) -> dict[Path, str]:
|
|
319
|
+
"""
|
|
320
|
+
Read checksums from file.
|
|
321
|
+
|
|
322
|
+
Supports: md5sum, sha256sum, b2sum formats
|
|
323
|
+
"""
|
|
324
|
+
result = {}
|
|
325
|
+
content = checksum_file.read_text(encoding="utf-8")
|
|
326
|
+
|
|
327
|
+
for line in content.splitlines():
|
|
328
|
+
line = line.strip()
|
|
329
|
+
if not line or line.startswith("#"):
|
|
330
|
+
continue
|
|
331
|
+
parts = line.split(None, 2)
|
|
332
|
+
if len(parts) >= 2:
|
|
333
|
+
hash_val = parts[0]
|
|
334
|
+
# Path may have leading * or space
|
|
335
|
+
path_str = parts[1].lstrip("* ")
|
|
336
|
+
result[Path(path_str)] = hash_val
|
|
337
|
+
|
|
338
|
+
return result
|
path_file/progress.py
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
"""Progress reporting: progress bar and spinner (stdlib only)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import contextlib
|
|
6
|
+
import shutil
|
|
7
|
+
import sys
|
|
8
|
+
import time
|
|
9
|
+
from typing import IO, ClassVar
|
|
10
|
+
|
|
11
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
12
|
+
# TERMINAL HELPERS
|
|
13
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def terminal_width(default: int = 80) -> int:
|
|
17
|
+
"""Return the current terminal width (falling back to ``default``)."""
|
|
18
|
+
try:
|
|
19
|
+
size = shutil.get_terminal_size(fallback=(default, 24))
|
|
20
|
+
except (ValueError, OSError):
|
|
21
|
+
return default
|
|
22
|
+
return max(20, int(size.columns))
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _can_encode(stream: IO[str], text: str) -> bool:
|
|
26
|
+
"""Check whether a stream can encode text without loss."""
|
|
27
|
+
try:
|
|
28
|
+
encoding = getattr(stream, "encoding", None) or "ascii"
|
|
29
|
+
text.encode(encoding, errors="strict")
|
|
30
|
+
return True
|
|
31
|
+
except (UnicodeError, LookupError, AttributeError):
|
|
32
|
+
return False
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _safe_write(stream: IO[str], text: str) -> None:
|
|
36
|
+
"""Write to a stream, falling back to a replacement-safe encode."""
|
|
37
|
+
try:
|
|
38
|
+
stream.write(text)
|
|
39
|
+
except UnicodeEncodeError:
|
|
40
|
+
encoding = getattr(stream, "encoding", None) or "ascii"
|
|
41
|
+
stream.write(text.encode(encoding, errors="replace").decode(encoding, errors="replace"))
|
|
42
|
+
except (ValueError, OSError):
|
|
43
|
+
pass
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
47
|
+
# PROGRESS BAR
|
|
48
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class ProgressBar:
|
|
52
|
+
"""
|
|
53
|
+
Simple determinate progress bar.
|
|
54
|
+
|
|
55
|
+
Example:
|
|
56
|
+
>>> with ProgressBar(100, prefix="copy: ") as bar: # doctest: +SKIP
|
|
57
|
+
... for _ in range(100):
|
|
58
|
+
... bar.update(1)
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
# Unicode glyphs (used when the stream can encode them)
|
|
62
|
+
FILLED = "\u2588"
|
|
63
|
+
EMPTY = "\u2591"
|
|
64
|
+
ARROW = "\u25b6"
|
|
65
|
+
|
|
66
|
+
# ASCII fallbacks
|
|
67
|
+
FILLED_ASCII = "#"
|
|
68
|
+
EMPTY_ASCII = "-"
|
|
69
|
+
ARROW_ASCII = ">"
|
|
70
|
+
|
|
71
|
+
def __init__(
|
|
72
|
+
self,
|
|
73
|
+
total: int,
|
|
74
|
+
prefix: str = "",
|
|
75
|
+
width: int | None = None,
|
|
76
|
+
stream: IO[str] | None = None,
|
|
77
|
+
show_percent: bool = True,
|
|
78
|
+
show_count: bool = True,
|
|
79
|
+
refresh_interval: float = 0.05,
|
|
80
|
+
) -> None:
|
|
81
|
+
self.total = max(0, int(total))
|
|
82
|
+
self.prefix = prefix
|
|
83
|
+
self.width = width if width is not None else 40
|
|
84
|
+
self.stream = stream if stream is not None else sys.stderr
|
|
85
|
+
self.show_percent = show_percent
|
|
86
|
+
self.show_count = show_count
|
|
87
|
+
self.refresh_interval = refresh_interval
|
|
88
|
+
|
|
89
|
+
self.count = 0
|
|
90
|
+
self.started_at = time.monotonic()
|
|
91
|
+
self._last_render = 0.0
|
|
92
|
+
self._closed = False
|
|
93
|
+
self._entered = False
|
|
94
|
+
|
|
95
|
+
# Choose glyphs based on what the stream can encode
|
|
96
|
+
if _can_encode(self.stream, self.FILLED + self.EMPTY + self.ARROW):
|
|
97
|
+
self._filled, self._empty, self._arrow = self.FILLED, self.EMPTY, self.ARROW
|
|
98
|
+
else:
|
|
99
|
+
self._filled, self._empty, self._arrow = (
|
|
100
|
+
self.FILLED_ASCII,
|
|
101
|
+
self.EMPTY_ASCII,
|
|
102
|
+
self.ARROW_ASCII,
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
# ─── Properties ───────────────────────────────────────────────────────────
|
|
106
|
+
|
|
107
|
+
@property
|
|
108
|
+
def fraction(self) -> float:
|
|
109
|
+
"""Completion fraction between 0 and 1."""
|
|
110
|
+
if self.total == 0:
|
|
111
|
+
return 1.0
|
|
112
|
+
return min(1.0, self.count / self.total)
|
|
113
|
+
|
|
114
|
+
@property
|
|
115
|
+
def percent(self) -> float:
|
|
116
|
+
"""Completion percentage between 0 and 100."""
|
|
117
|
+
return self.fraction * 100
|
|
118
|
+
|
|
119
|
+
@property
|
|
120
|
+
def elapsed(self) -> float:
|
|
121
|
+
"""Seconds since the bar was created."""
|
|
122
|
+
return time.monotonic() - self.started_at
|
|
123
|
+
|
|
124
|
+
@property
|
|
125
|
+
def rate(self) -> float:
|
|
126
|
+
"""Items per second (0 when unknown)."""
|
|
127
|
+
if self.elapsed <= 0 or self.count == 0:
|
|
128
|
+
return 0.0
|
|
129
|
+
return self.count / self.elapsed
|
|
130
|
+
|
|
131
|
+
@property
|
|
132
|
+
def eta(self) -> float | None:
|
|
133
|
+
"""Estimated remaining seconds, or None when unknown."""
|
|
134
|
+
if self.total <= self.count or self.rate <= 0:
|
|
135
|
+
return None
|
|
136
|
+
return (self.total - self.count) / self.rate
|
|
137
|
+
|
|
138
|
+
# ─── Rendering ────────────────────────────────────────────────────────────
|
|
139
|
+
|
|
140
|
+
def _render(self, force: bool = False) -> str:
|
|
141
|
+
"""Build the bar string."""
|
|
142
|
+
now = time.monotonic()
|
|
143
|
+
if not force and (now - self._last_render) < self.refresh_interval:
|
|
144
|
+
return ""
|
|
145
|
+
self._last_render = now
|
|
146
|
+
|
|
147
|
+
filled = round(self.width * self.fraction) if self.total > 0 else self.width
|
|
148
|
+
bar = self._filled * filled + self._empty * max(0, self.width - filled)
|
|
149
|
+
|
|
150
|
+
parts = [self.prefix, bar]
|
|
151
|
+
if self.show_percent:
|
|
152
|
+
parts.append(f" {self.percent:5.1f}%")
|
|
153
|
+
if self.show_count:
|
|
154
|
+
if self.total:
|
|
155
|
+
parts.append(f" ({self.count}/{self.total})")
|
|
156
|
+
else:
|
|
157
|
+
parts.append(f" ({self.count})")
|
|
158
|
+
return "".join(parts)
|
|
159
|
+
|
|
160
|
+
def update(self, n: int = 1) -> None:
|
|
161
|
+
"""Advance the bar by ``n`` items and redraw."""
|
|
162
|
+
if self._closed:
|
|
163
|
+
return
|
|
164
|
+
self.count = min(self.count + max(0, int(n)), self.total) if self.total else self.count + n
|
|
165
|
+
line = self._render()
|
|
166
|
+
if line:
|
|
167
|
+
_safe_write(self.stream, "\r" + line.ljust(terminal_width() - 1))
|
|
168
|
+
|
|
169
|
+
def set(self, value: int) -> None:
|
|
170
|
+
"""Set the bar to an absolute item count."""
|
|
171
|
+
if self._closed:
|
|
172
|
+
return
|
|
173
|
+
self.count = min(max(0, int(value)), self.total) if self.total else int(value)
|
|
174
|
+
line = self._render(force=True)
|
|
175
|
+
if line:
|
|
176
|
+
_safe_write(self.stream, "\r" + line.ljust(terminal_width() - 1))
|
|
177
|
+
|
|
178
|
+
def finish(self) -> None:
|
|
179
|
+
"""Complete the bar and move to the next line."""
|
|
180
|
+
if self._closed:
|
|
181
|
+
return
|
|
182
|
+
self.count = self.total
|
|
183
|
+
line = self._render(force=True)
|
|
184
|
+
if line:
|
|
185
|
+
_safe_write(self.stream, "\r" + line.ljust(terminal_width() - 1) + "\n")
|
|
186
|
+
flush = getattr(self.stream, "flush", None)
|
|
187
|
+
if flush is not None:
|
|
188
|
+
with contextlib.suppress(ValueError, OSError):
|
|
189
|
+
flush()
|
|
190
|
+
self._closed = True
|
|
191
|
+
|
|
192
|
+
# ─── Context Manager ──────────────────────────────────────────────────────
|
|
193
|
+
|
|
194
|
+
def __enter__(self) -> ProgressBar:
|
|
195
|
+
self._entered = True
|
|
196
|
+
if self.total:
|
|
197
|
+
line = self._render(force=True)
|
|
198
|
+
if line:
|
|
199
|
+
_safe_write(self.stream, "\r" + line.ljust(terminal_width() - 1))
|
|
200
|
+
return self
|
|
201
|
+
|
|
202
|
+
def __exit__(self, exc_type: object, exc: object, tb: object) -> None:
|
|
203
|
+
self.finish()
|
|
204
|
+
self._entered = False
|
|
205
|
+
|
|
206
|
+
def __repr__(self) -> str:
|
|
207
|
+
return f"ProgressBar(count={self.count}, total={self.total}, percent={self.percent:.1f})"
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
211
|
+
# SPINNER (indeterminate progress)
|
|
212
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
class Spinner:
|
|
216
|
+
"""
|
|
217
|
+
Indeterminate spinner for operations with unknown duration.
|
|
218
|
+
|
|
219
|
+
Example:
|
|
220
|
+
>>> with Spinner("Working"): # doctest: +SKIP
|
|
221
|
+
... do_something_slow()
|
|
222
|
+
"""
|
|
223
|
+
|
|
224
|
+
FRAMES: ClassVar[list[str]] = [
|
|
225
|
+
"\u280b",
|
|
226
|
+
"\u2819",
|
|
227
|
+
"\u2839",
|
|
228
|
+
"\u2838",
|
|
229
|
+
"\u283c",
|
|
230
|
+
"\u2834",
|
|
231
|
+
"\u2826",
|
|
232
|
+
"\u2827",
|
|
233
|
+
"\u2807",
|
|
234
|
+
"\u280f",
|
|
235
|
+
]
|
|
236
|
+
FRAMES_ASCII: ClassVar[list[str]] = ["|", "/", "-", "\\"]
|
|
237
|
+
|
|
238
|
+
def __init__(
|
|
239
|
+
self,
|
|
240
|
+
message: str = "",
|
|
241
|
+
interval: float = 0.1,
|
|
242
|
+
stream: IO[str] | None = None,
|
|
243
|
+
) -> None:
|
|
244
|
+
self.message = message
|
|
245
|
+
self.interval = interval
|
|
246
|
+
self.stream = stream if stream is not None else sys.stderr
|
|
247
|
+
self.count = 0
|
|
248
|
+
self._frame = 0
|
|
249
|
+
self._last_render = 0.0
|
|
250
|
+
self._closed = False
|
|
251
|
+
self._entered = False
|
|
252
|
+
|
|
253
|
+
if _can_encode(self.stream, "".join(self.FRAMES)):
|
|
254
|
+
self._frames = self.FRAMES
|
|
255
|
+
else:
|
|
256
|
+
self._frames = self.FRAMES_ASCII
|
|
257
|
+
|
|
258
|
+
def update(self, message: str | None = None) -> None:
|
|
259
|
+
"""Redraw the spinner (optionally with a new message)."""
|
|
260
|
+
if self._closed:
|
|
261
|
+
return
|
|
262
|
+
if message is not None:
|
|
263
|
+
self.message = message
|
|
264
|
+
self.count += 1
|
|
265
|
+
now = time.monotonic()
|
|
266
|
+
if (now - self._last_render) < self.interval:
|
|
267
|
+
return
|
|
268
|
+
self._last_render = now
|
|
269
|
+
frame = self._frames[self._frame % len(self._frames)]
|
|
270
|
+
self._frame += 1
|
|
271
|
+
text = f"\r{frame} {self.message}" if self.message else f"\r{frame}"
|
|
272
|
+
_safe_write(self.stream, text.ljust(terminal_width() - 1))
|
|
273
|
+
|
|
274
|
+
def stop(self) -> None:
|
|
275
|
+
"""Clear the spinner line."""
|
|
276
|
+
if self._closed:
|
|
277
|
+
return
|
|
278
|
+
_safe_write(self.stream, "\r" + " " * (terminal_width() - 1) + "\r")
|
|
279
|
+
flush = getattr(self.stream, "flush", None)
|
|
280
|
+
if flush is not None:
|
|
281
|
+
with contextlib.suppress(ValueError, OSError):
|
|
282
|
+
flush()
|
|
283
|
+
self._closed = True
|
|
284
|
+
|
|
285
|
+
# ─── Context Manager ──────────────────────────────────────────────────────
|
|
286
|
+
|
|
287
|
+
def __enter__(self) -> Spinner:
|
|
288
|
+
self._entered = True
|
|
289
|
+
self.update()
|
|
290
|
+
return self
|
|
291
|
+
|
|
292
|
+
def __exit__(self, exc_type: object, exc: object, tb: object) -> None:
|
|
293
|
+
self.stop()
|
|
294
|
+
self._entered = False
|
|
295
|
+
|
|
296
|
+
def __repr__(self) -> str:
|
|
297
|
+
return f"Spinner(message={self.message!r}, count={self.count})"
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
301
|
+
# FACTORY
|
|
302
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def create_progress(
|
|
306
|
+
total: int | None,
|
|
307
|
+
message: str = "",
|
|
308
|
+
stream: IO[str] | None = None,
|
|
309
|
+
) -> ProgressBar | Spinner:
|
|
310
|
+
"""Create a ProgressBar when the total is known, else a Spinner."""
|
|
311
|
+
if total is not None:
|
|
312
|
+
return ProgressBar(total, prefix=message, stream=stream)
|
|
313
|
+
return Spinner(message, stream=stream)
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
__all__ = [
|
|
317
|
+
"ProgressBar",
|
|
318
|
+
"Spinner",
|
|
319
|
+
"create_progress",
|
|
320
|
+
"terminal_width",
|
|
321
|
+
]
|
path_file/py.typed
ADDED
|
File without changes
|