Coverage for ntnlog / ntn_utils.py: 100%

11 statements  

« prev     ^ index     » next       coverage.py v7.14.0, created at 2026-05-21 04:50 +0000

1import os 

2 

3 

4def get_working_dir() -> str: 

5 """Return the current working directory as an absolute path.""" 

6 return os.getcwd() 

7 

8 

9def resolve_path(path: str, must_exist: bool = False) -> str: 

10 """ 

11 Resolve *path* relative to the working directory and verify it stays within it. 

12 

13 Parameters 

14 ---------- 

15 path : str 

16 Relative or absolute path to resolve. 

17 must_exist : bool 

18 If ``True``, raises ``FileNotFoundError`` when the resolved path does 

19 not exist on disk. 

20 

21 Returns 

22 ------- 

23 str 

24 Resolved absolute path. 

25 

26 Raises 

27 ------ 

28 ValueError 

29 If the resolved path escapes the working directory. 

30 FileNotFoundError 

31 If ``must_exist`` is ``True`` and the path does not exist. 

32 """ 

33 cwd = get_working_dir() 

34 resolved = os.path.normpath(os.path.join(cwd, path)) 

35 

36 if not resolved.startswith(cwd): 

37 raise ValueError( 

38 f"Path '{path}' escapes the working directory '{cwd}'" 

39 ) 

40 

41 if must_exist and not os.path.exists(resolved): 

42 raise FileNotFoundError( 

43 f"Path '{resolved}' does not exist" 

44 ) 

45 

46 return resolved