1
0
Files
bagu-thesis/src/common.py

55 lines
1.8 KiB
Python
Raw Normal View History

2026-06-07 14:00:00 +08:00
from pathlib import Path
from logger import LOGGER
class BaGuException(Exception):
"""The exception raised by this project."""
pass
def resolve_resource(tobe_resolved: str, resource_dir: Path) -> Path | None:
"""
Resolve given path in resource directory or current work directory.
This function will use absolute path directly if it is and it is exist.
If not, this function will try to resolve it in resource directory first,
and then in current work directory.
:param tobe_resolved: The path to be resolved.
:param resource_dir: The resource directory.
:return: The resolved path if resolved, otherwise None.
"""
tobe_resolved_path = Path(tobe_resolved)
LOGGER.debug(f'Resolving {tobe_resolved_path} ...')
# Return absolute path directly
if tobe_resolved_path.is_absolute():
if tobe_resolved_path.is_file():
LOGGER.debug(f'Resolved {tobe_resolved_path}')
return tobe_resolved_path
else:
LOGGER.debug(f'{tobe_resolved_path} is absolute path but not a file.')
return None
# Resolve it in resource directory first
resource_dir_path = Path(resource_dir).resolve()
resolved = resource_dir_path / tobe_resolved_path
if resolved.is_file():
LOGGER.debug(f'Resolved {resolved}')
return resolved
else:
LOGGER.debug(f'Resolved failed in resource path because {resolved} is not a file.')
# Resolve it in work directory
cwd_path = Path.cwd().resolve()
resolved = cwd_path / tobe_resolved_path
if resolved.is_file():
LOGGER.debug(f'Resolved {resolved}')
return resolved
else:
LOGGER.debug(f'Resolved failed in current work directory because {resolved} is not a file.')
# Not resolved
return None