Coverage for portality / lib / paths.py: 92%
26 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-05-05 00:09 +0100
« prev ^ index » next coverage.py v7.13.5, created at 2026-05-05 00:09 +0100
1import os
2import tempfile
3from pathlib import Path
4from typing import Union, TypeVar
6PathStr = TypeVar("PathStr", str, Path) # type of str or Path
9def rel2abs(src, *paths):
10 """ Output is absolute path of paths joined with src's dir
12 Example:
13 >>> rel2abs('/opt/doaj/abc.xml', 'corrections.csv')
14 '/opt/doaj/corrections.csv'
15 >>> rel2abs('/opt/doaj/', 'corrections.csv')
16 '/opt/doaj/corrections.csv'
17 >>> rel2abs('/opt/doaj/abc.xml', '..', 'corrections.csv')
18 '/opt/corrections.csv'
20 :param src:
21 :param paths:
22 :return:
23 """
24 src = os.path.realpath(src)
25 if os.path.isfile(src):
26 src = os.path.dirname(src)
27 return os.path.abspath(os.path.join(src, *paths))
30def list_subdirs(path):
31 return [x for x in os.listdir(path) if os.path.isdir(os.path.join(path, x))]
34def get_project_root() -> Path:
35 """ Should return folder path of `doaj` """
36 return Path(__file__).parent.parent.parent.absolute()
39def create_tmp_path(is_auto_mkdir=False) -> Path:
40 num_retry = 20
41 for _ in range(num_retry):
42 path = Path(tempfile.NamedTemporaryFile().name)
43 if not path.exists():
44 break
45 else:
46 raise EnvironmentError(f'create tmp dir retry [{num_retry}] failed')
48 if is_auto_mkdir:
49 path.mkdir(parents=True, exist_ok=True)
50 return path
53def abs_dir_path(src: PathStr) -> str:
54 """ Return absolute dir path of src
56 Example:
57 >>> abs_dir_path('/opt/doaj/abc.xml')
58 '/opt/doaj'
59 >>> abs_dir_path('/opt/doaj/')
60 '/opt'
61 """
62 return os.path.dirname(os.path.realpath(src))