Coverage for sparkle/CLI/help/nicknames.py: 0%

19 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-09-27 09:10 +0000

1"""Helper functions for CLI nicknames.""" 

2from __future__ import annotations 

3from pathlib import Path 

4from typing import Callable 

5 

6 

7def resolve_object_name(name: str | Path, 

8 nickname_dict: dict = {}, 

9 target_dir: Path = Path(), 

10 class_name: Callable = None) -> Path | any: 

11 """Attempts to resolve a (nick) name. 

12 

13 Args: 

14 name: The (nick)name to resolve 

15 target_dir: The location where the file object should exist 

16 class_name: If passed, will attempt to return an object 

17 that is constructed from this Path. 

18 

19 Returns: 

20 Path to the object, None if unresolvable. 

21 """ 

22 path = None 

23 # We cannot handle None as a name 

24 if name is None: 

25 return None 

26 # First check if the name already is a path 

27 if Path(name).exists(): 

28 path = Path(name) 

29 # Second check if its a nickname registered in Sparkle 

30 elif str(name) in nickname_dict: 

31 path = Path(nickname_dict[str(name)]) 

32 # Third check if we can create a valid path with the name 

33 elif (target_dir / name).exists(): 

34 path = (target_dir / name) 

35 # Finally, attempt to construct the object from the Path 

36 try: 

37 if class_name is not None and path is not None: 

38 return class_name(path) 

39 except Exception: 

40 return None 

41 return path