util.py 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # coding: utf-8
  2. import os
  3. import typing
  4. from os import path
  5. import shutil
  6. from pathlib import Path
  7. from synergine2_cocos2d.exception import FileNotFound
  8. def get_map_file_path_from_dir(map_dir_path: str) -> str:
  9. # TODO: path is temp here
  10. return '{}.tmx'.format(os.path.join(map_dir_path,
  11. os.path.basename(map_dir_path.rstrip('/'))))
  12. class PathManager(object):
  13. def __init__(
  14. self,
  15. include_paths: typing.List[str],
  16. ) -> None:
  17. self._include_paths = [] # type: typing.List[str]
  18. self.include_paths = include_paths
  19. @property
  20. def include_paths(self) -> typing.Tuple[str, ...]:
  21. return tuple(self._include_paths)
  22. @include_paths.setter
  23. def include_paths(self, value: typing.List[str]) -> None:
  24. self._include_paths = value
  25. self._include_paths.sort(reverse=True)
  26. def add_included_path(self, included_path: str) -> None:
  27. self._include_paths.append(included_path)
  28. self._include_paths.sort(reverse=True)
  29. def path(self, file_path: str) -> str:
  30. # Search in configured paths
  31. for include_path in self._include_paths:
  32. complete_file_path = path.join(include_path, file_path)
  33. if path.isfile(complete_file_path):
  34. return complete_file_path
  35. # If not in include last chance in current dir
  36. if path.isfile(file_path):
  37. return file_path
  38. raise FileNotFound('File "{}" not found in paths {}'.format(
  39. file_path,
  40. self._include_paths,
  41. ))
  42. def ensure_dir_exist(dir_path, clear_dir: bool=False) -> None:
  43. """
  44. Create directories if no exists
  45. :param dir_path: path of wanted directory to exist
  46. :param clear_dir: Remove content of given dir
  47. """
  48. path_ = Path(dir_path)
  49. path_.mkdir(parents=True, exist_ok=True)
  50. if clear_dir:
  51. shutil.rmtree(dir_path)
  52. path_.mkdir(parents=True, exist_ok=True)