-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpath_utils.py
More file actions
44 lines (37 loc) · 1.41 KB
/
path_utils.py
File metadata and controls
44 lines (37 loc) · 1.41 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
from pathlib import Path
def unique_path(path: Path) -> Path:
"""Return a unique path by appending a (n) suffix if it already exists."""
if not path.exists():
return path
stem = path.stem
suffix = path.suffix
parent = path.parent
counter = 1
while True:
candidate = parent / f"{stem} ({counter}){suffix}"
if not candidate.exists():
return candidate
counter += 1
def unique_pair(
primary: Path,
secondary: Path,
*,
allow_existing_primary: Path | None = None,
allow_existing_secondary: Path | None = None,
) -> tuple[Path, Path]:
"""Return a pair of unique paths sharing the same numeric suffix when needed."""
def _conflicts(path: Path, allowed: Path | None) -> bool:
return path.exists() and path != allowed
if not _conflicts(primary, allow_existing_primary) and not _conflicts(secondary, allow_existing_secondary):
return primary, secondary
stem = primary.stem
parent = primary.parent
suffix_primary = primary.suffix
suffix_secondary = secondary.suffix
counter = 1
while True:
candidate_primary = parent / f"{stem} ({counter}){suffix_primary}"
candidate_secondary = parent / f"{stem} ({counter}){suffix_secondary}"
if not candidate_primary.exists() and not candidate_secondary.exists():
return candidate_primary, candidate_secondary
counter += 1