utils.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. # copy from alas https://github.com/LmeSzinc/AzurLaneAutoScript
  2. import os
  3. import re
  4. from typing import Callable, Generic, TypeVar
  5. T = TypeVar("T")
  6. DEPLOY_CONFIG = './config/deploy.yaml'
  7. DEPLOY_TEMPLATE = './deploy/template'
  8. class cached_property(Generic[T]):
  9. """
  10. cached-property from https://github.com/pydanny/cached-property
  11. Add typing support
  12. A property that is only computed once per instance and then replaces itself
  13. with an ordinary attribute. Deleting the attribute resets the property.
  14. Source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f53071897e6f76
  15. """
  16. def __init__(self, func: Callable[..., T]):
  17. self.func = func
  18. def __get__(self, obj, cls) -> T:
  19. if obj is None:
  20. return self
  21. value = obj.__dict__[self.func.__name__] = self.func(obj)
  22. return value
  23. def iter_folder(folder, is_dir=False, ext=None):
  24. """
  25. Args:
  26. folder (str):
  27. is_dir (bool): True to iter directories only
  28. ext (str): File extension, such as `.yaml`
  29. Yields:
  30. str: Absolute path of files
  31. """
  32. for file in os.listdir(folder):
  33. sub = os.path.join(folder, file)
  34. if is_dir:
  35. if os.path.isdir(sub):
  36. yield sub.replace('\\\\', '/').replace('\\', '/')
  37. elif ext is not None:
  38. if not os.path.isdir(sub):
  39. _, extension = os.path.splitext(file)
  40. if extension == ext:
  41. yield os.path.join(folder, file).replace('\\\\', '/').replace('\\', '/')
  42. else:
  43. yield os.path.join(folder, file).replace('\\\\', '/').replace('\\', '/')
  44. def poor_yaml_read(file):
  45. """
  46. Poor implementation to load yaml without pyyaml dependency, but with re
  47. Args:
  48. file (str):
  49. Returns:
  50. dict:
  51. """
  52. if not os.path.exists(file):
  53. return {}
  54. data = {}
  55. regex = re.compile(r'^(.*?):(.*?)$')
  56. with open(file, 'r', encoding='utf-8') as f:
  57. for line in f.readlines():
  58. line = line.strip('\n\r\t ').replace('\\', '/')
  59. if line.startswith('#'):
  60. continue
  61. result = re.match(regex, line)
  62. if result:
  63. k, v = result.group(1), result.group(2).strip('\n\r\t\' ')
  64. if v:
  65. if v.lower() == 'null':
  66. v = None
  67. elif v.lower() == 'false':
  68. v = False
  69. elif v.lower() == 'true':
  70. v = True
  71. elif v.isdigit():
  72. v = int(v)
  73. data[k] = v
  74. return data
  75. def poor_yaml_write(data, file, template_file=DEPLOY_TEMPLATE):
  76. """
  77. Args:
  78. data (dict):
  79. file (str):
  80. template_file (str):
  81. """
  82. with open(template_file, 'r', encoding='utf-8') as f:
  83. text = f.read().replace('\\', '/')
  84. for key, value in data.items():
  85. if value is None:
  86. value = 'null'
  87. elif value is True:
  88. value = "true"
  89. elif value is False:
  90. value = "false"
  91. text = re.sub(f'{key}:.*?\n', f'{key}: {value}\n', text)
  92. with open(file, 'w', encoding='utf-8', newline='') as f:
  93. f.write(text)