|
| 1 | +"""Path utilities for output/export directories.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from pathlib import Path |
| 6 | +import sys |
| 7 | + |
| 8 | +from appdirs import user_data_dir |
| 9 | + |
| 10 | +_APP_DIR_NAME = "leaf_contour_efd" |
| 11 | + |
| 12 | + |
| 13 | +def _user_writable_base_dir() -> Path: |
| 14 | + """Return a user-writable directory for application outputs.""" |
| 15 | + return Path(user_data_dir(_APP_DIR_NAME)).resolve() |
| 16 | + |
| 17 | + |
| 18 | +def _is_writable_dir(path: Path) -> bool: |
| 19 | + """Return whether ``path`` can be used as a writable directory.""" |
| 20 | + try: |
| 21 | + path.mkdir(parents=True, exist_ok=True) |
| 22 | + probe = path / ".write_test" |
| 23 | + with probe.open("w", encoding="utf-8"): |
| 24 | + pass |
| 25 | + probe.unlink(missing_ok=True) |
| 26 | + return True |
| 27 | + except OSError: |
| 28 | + return False |
| 29 | + |
| 30 | + |
| 31 | +def get_output_base_dir() -> Path: |
| 32 | + """Return the base directory used for writing the ``output`` folder. |
| 33 | +
|
| 34 | + Rules |
| 35 | + ----- |
| 36 | + - Frozen on all platforms: user-writable application data directory. |
| 37 | + - Non-frozen: repository/application root when writable, otherwise user data. |
| 38 | + """ |
| 39 | + fallback = _user_writable_base_dir() |
| 40 | + |
| 41 | + if getattr(sys, "frozen", False): |
| 42 | + return fallback |
| 43 | + |
| 44 | + # Development mode: src/leaf_contour_efd/utils/paths.py -> repo root |
| 45 | + repo_root = Path(__file__).resolve().parents[3] |
| 46 | + if _is_writable_dir(repo_root): |
| 47 | + return repo_root |
| 48 | + return fallback |
| 49 | + |
| 50 | + |
| 51 | +def get_output_dir(*parts: str) -> Path: |
| 52 | + """Return an output subdirectory and ensure it exists. |
| 53 | +
|
| 54 | + If directory creation fails in the primary base location, this function |
| 55 | + transparently falls back to a user-writable directory. |
| 56 | + """ |
| 57 | + out_dir = get_output_base_dir() / "output" |
| 58 | + if parts: |
| 59 | + out_dir = out_dir.joinpath(*parts) |
| 60 | + |
| 61 | + try: |
| 62 | + out_dir.mkdir(parents=True, exist_ok=True) |
| 63 | + except OSError: |
| 64 | + out_dir = _user_writable_base_dir() / "output" |
| 65 | + if parts: |
| 66 | + out_dir = out_dir.joinpath(*parts) |
| 67 | + out_dir.mkdir(parents=True, exist_ok=True) |
| 68 | + |
| 69 | + return out_dir |
0 commit comments