Coverage for downtify/fs_suggest.py: 68%
65 statements
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-21 22:18 +0000
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-21 22:18 +0000
1"""Directory-name suggestions for Settings path fields."""
3from __future__ import annotations
5import os
6from pathlib import Path
8MAX_SUGGESTIONS = 32
9_SCAN_CAP = 500
10_SKIP_AT_ROOT = frozenset({'proc', 'sys', 'dev'})
11_EMPTY_HINTS = ('/data', '/downloads', '/music', '/home')
14def suggest_directories(
15 prefix: str, *, limit: int = MAX_SUGGESTIONS
16) -> list[str]:
17 """Absolute directory paths that complete *prefix* as the user types."""
19 cap = max(1, min(int(limit), MAX_SUGGESTIONS))
20 text = str(prefix or '').strip()
21 if not text:
22 out: list[str] = []
23 for hint in _EMPTY_HINTS:
24 path = Path(hint)
25 if path.is_dir() and not _blocked(path):
26 out.append(str(path))
27 if len(out) >= cap:
28 break
29 return out
31 if not text.startswith('/'):
32 text = '/' + text.lstrip('/')
34 trailing = text.endswith('/')
35 raw = Path(text)
36 if trailing:
37 parent = raw
38 name_prefix = ''
39 else:
40 parent = raw.parent if raw.parent.as_posix() != '.' else Path('/')
41 name_prefix = raw.name.lower()
43 if _blocked(parent) or not parent.is_dir():
44 return []
46 matches: list[str] = []
47 scanned = 0
48 try:
49 with os.scandir(parent) as entries:
50 for entry in entries:
51 scanned += 1
52 if scanned > _SCAN_CAP:
53 break
54 try:
55 if not entry.is_dir(follow_symlinks=False):
56 continue
57 except OSError:
58 continue
59 if parent == Path('/') and entry.name in _SKIP_AT_ROOT:
60 continue
61 if name_prefix and not entry.name.lower().startswith(
62 name_prefix
63 ):
64 continue
65 child = Path(entry.path)
66 if _blocked(child):
67 continue
68 matches.append(str(child))
69 if len(matches) >= cap:
70 break
71 except OSError:
72 return []
73 matches.sort()
74 return matches[:cap]
77def _blocked(path: Path) -> bool:
78 try:
79 parts = path.resolve().parts
80 except OSError:
81 parts = path.parts
82 if len(parts) >= 2 and parts[1] in _SKIP_AT_ROOT:
83 return True
84 return False