util.py 1.9KB

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