Repository navigation
Expand file tree
/
Copy pathresolver.py
More file actions
79 lines (66 loc) 路 2.31 KB
/
Copy pathresolver.py
File metadata and controls
79 lines (66 loc) 路 2.31 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
"""Bounded path resolver for folder names with well-known expansions."""
from pathlib import Path
from typing import Optional
WELL_KNOWN = {
"desktop": Path.home() / "Desktop",
"downloads": Path.home() / "Downloads",
"download": Path.home() / "Downloads",
"documents": Path.home() / "Documents",
"home": Path.home(),
"pictures": Path.home() / "Pictures",
"music": Path.home() / "Music",
"movies": Path.home() / "Movies",
}
MAX_DEPTH = 4
def resolve_folder(name: str, max_depth: int = MAX_DEPTH) -> Optional[Path]:
"""Find a folder by name using well-known dirs first, then shallow search.
Returns the first match or None.
"""
name = name.strip()
if not name:
return None
# Strip any stray non-path suffix (e.g. ".aiguba")
import re as _re
name = _re.sub(r'\.[a-zA-Z0-9]+$', '', name)
# 1. Direct well-known lookup
lower = name.lower()
if lower in WELL_KNOWN:
p = WELL_KNOWN[lower]
if p.is_dir():
return p.resolve()
# 2. Absolute or ~ path
if name.startswith("~") or name.startswith("/"):
p = Path(name).expanduser()
# Safety: if resolved path doesn't start with home, something went wrong
home = str(Path.home())
p_str = str(p)
if not p_str.startswith(home) and not p_str.startswith("/"):
# Fall back to home-relative
name_clean = name.lstrip("~/").split("/")[0]
p = Path.home() / name_clean
if p.is_dir():
return p.resolve()
# 3. Shallow search from well-known roots
bases = [Path.home()]
for base in bases:
try:
for child in base.iterdir():
if child.name.lower() == lower and child.is_dir():
return child.resolve()
except PermissionError:
continue
# 4. Walk well-known dirs shallowly
for root in WELL_KNOWN.values():
if not root.is_dir():
continue
try:
for child in root.iterdir():
if child.name.lower() == lower and child.is_dir():
return child.resolve()
except PermissionError:
continue
# 5. Relative to CWD
cwd_candidate = Path.cwd() / name
if cwd_candidate.is_dir():
return cwd_candidate.resolve()
return None