-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
72 lines (55 loc) · 1.88 KB
/
utils.py
File metadata and controls
72 lines (55 loc) · 1.88 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
from __future__ import annotations
import re
import time
from pathlib import Path
_slug_re = re.compile(r"[^a-zA-Z0-9]+")
def slugify(value: str) -> str:
cleaned = _slug_re.sub("_", value.strip().lower()).strip("_")
return cleaned or "file"
def ensure_dir(path: str | Path) -> Path:
directory = Path(path)
directory.mkdir(parents=True, exist_ok=True)
return directory
def unique_path(path: Path) -> Path:
if not path.exists():
return path
stem = path.stem
suffix = path.suffix
parent = path.parent
counter = 2
while True:
candidate = parent / f"{stem}_{counter}{suffix}"
if not candidate.exists():
return candidate
counter += 1
def _can_open_exclusive(path: Path) -> bool:
"""Windowsでコピー中のファイルは排他オープンできない。開けるかどうかで書き込み完了を判定する。"""
try:
with path.open("rb"):
return True
except OSError:
return False
def wait_until_file_ready(path: Path, checks: int, interval_sec: float, timeout_sec: float) -> bool:
start = time.time()
stable_count = 0
last_size = -1
while time.time() - start < timeout_sec:
if not path.exists() or not path.is_file():
time.sleep(interval_sec)
continue
# Windowsではコピー中ファイルを開けないので、開けるまで待つ
if not _can_open_exclusive(path):
stable_count = 0
last_size = -1
time.sleep(interval_sec)
continue
current_size = path.stat().st_size
if current_size > 0 and current_size == last_size:
stable_count += 1
if stable_count >= checks:
return True
else:
stable_count = 0
last_size = current_size
time.sleep(interval_sec)
return False