config_manager.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # github https://github.com/runhey
  4. import re
  5. from pathlib import Path
  6. from module.logger import logger
  7. class ConfigManager:
  8. @staticmethod
  9. def all_script_files() -> list[str]:
  10. """
  11. 获取所有的脚本文件 除了tmplate
  12. :return: ['oas1', 'oas2']
  13. """
  14. # 获取某个路径的所有json文件名
  15. config_path = Path.cwd() / 'config'
  16. json_files = config_path.glob('*.json')
  17. result = []
  18. for json in json_files:
  19. if json.stem == 'template':
  20. continue
  21. result.append(json.stem)
  22. if len(result) == 0:
  23. # 如果没有脚本文件 则创建一个
  24. ConfigManager.copy(file='oas1', template='template')
  25. result.append('oas1')
  26. return result
  27. @staticmethod
  28. def all_json_file() -> list:
  29. """
  30. 获取所有的json文件
  31. :return: ['oas1', 'oas2']
  32. """
  33. # 获取某个路径的所有json文件名
  34. config_path = Path.cwd() / 'config'
  35. json_files = config_path.glob('*.json')
  36. result = []
  37. for json in json_files:
  38. if json.stem == 'template':
  39. result.insert(0, json.stem)
  40. else:
  41. result.append(json.stem)
  42. return result
  43. @staticmethod
  44. def copy(file: str, template: str = 'template') -> None:
  45. """
  46. 复制一个配置文件
  47. :param file: 不带json后缀
  48. :param template:
  49. :return:
  50. """
  51. config_path = Path.cwd() / 'config'
  52. template_path = config_path / f'{template}.json'
  53. file_path = config_path / f'{file}.json'
  54. if file_path.exists():
  55. logger.error(f'{file_path} is exists')
  56. return
  57. with open(template_path, 'r', encoding='utf-8') as f:
  58. template_content = f.read()
  59. with open(file_path, 'w', encoding='utf-8') as f:
  60. f.write(template_content)
  61. logger.info(f'copy {template_path} to {file_path}')
  62. @staticmethod
  63. def generate_script_name() -> str:
  64. """
  65. 生成一个新的配置的名字
  66. :return:
  67. """
  68. all_script_files = ConfigManager.all_script_files()
  69. if not all_script_files:
  70. return 'oas1'
  71. script_numbers = []
  72. for script_file in all_script_files:
  73. match = re.search(r'\d+', script_file)
  74. if match:
  75. script_number = int(match.group())
  76. script_numbers.append(script_number)
  77. if not script_numbers:
  78. return 'oas1'
  79. script_numbers.sort()
  80. new_script_number = script_numbers[-1] + 1
  81. return f'oas{new_script_number}'