utils.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import os
  2. import sys
  3. from pathlib import Path
  4. from typing import Any, Dict, Optional, Tuple
  5. class TrieNode:
  6. def __init__(self, config_file: str = "", config_data: Optional[Dict[str, Any]] = None) -> None:
  7. if not config_data:
  8. config_data = {}
  9. self.nodes: Dict[str, TrieNode] = {}
  10. self.config_info: Tuple[str, Dict[str, Any]] = (config_file, config_data)
  11. class Trie:
  12. """
  13. A prefix tree to store the paths of all config files and to search the nearest config
  14. associated with each file
  15. """
  16. def __init__(self, config_file: str = "", config_data: Optional[Dict[str, Any]] = None) -> None:
  17. self.root: TrieNode = TrieNode(config_file, config_data)
  18. def insert(self, config_file: str, config_data: Dict[str, Any]) -> None:
  19. resolved_config_path_as_tuple = Path(config_file).parent.resolve().parts
  20. temp = self.root
  21. for path in resolved_config_path_as_tuple:
  22. if path not in temp.nodes:
  23. temp.nodes[path] = TrieNode()
  24. temp = temp.nodes[path]
  25. temp.config_info = (config_file, config_data)
  26. def search(self, filename: str) -> Tuple[str, Dict[str, Any]]:
  27. """
  28. Returns the closest config relative to filename by doing a depth
  29. first search on the prefix tree.
  30. """
  31. resolved_file_path_as_tuple = Path(filename).resolve().parts
  32. temp = self.root
  33. last_stored_config: Tuple[str, Dict[str, Any]] = ("", {})
  34. for path in resolved_file_path_as_tuple:
  35. if temp.config_info[0]:
  36. last_stored_config = temp.config_info
  37. if path not in temp.nodes:
  38. break
  39. temp = temp.nodes[path]
  40. return last_stored_config
  41. def exists_case_sensitive(path: str) -> bool:
  42. """Returns if the given path exists and also matches the case on Windows.
  43. When finding files that can be imported, it is important for the cases to match because while
  44. file os.path.exists("module.py") and os.path.exists("MODULE.py") both return True on Windows,
  45. Python can only import using the case of the real file.
  46. """
  47. result = os.path.exists(path)
  48. if (sys.platform.startswith("win") or sys.platform == "darwin") and result: # pragma: no cover
  49. directory, basename = os.path.split(path)
  50. result = basename in os.listdir(directory)
  51. return result