Coverage for src / c41811 / config / processor / python.py: 100%

30 statements  

« prev     ^ index     » next       coverage.py v7.13.3, created at 2026-02-06 06:04 +0000

1# cython: language_level = 3 # noqa: ERA001 

2 

3 

4""" 

5Python脚本配置文件处理器 

6 

7.. versionadded:: 0.2.0 

8""" 

9 

10from typing import Any 

11from typing import cast 

12from typing import override 

13 

14from .._protocols import SupportsReadAndReadline 

15from ..abc import ABCConfigFile 

16from ..basic.core import ConfigFile 

17from ..basic.mapping import MappingConfigData 

18from ..main import BasicLocalFileConfigSL 

19 

20 

21class PythonSL(BasicLocalFileConfigSL): 

22 """ 

23 Python格式处理器 

24 

25 .. caution:: 

26 非安全沙箱执行!确保文件为受信任来源! 

27 

28 .. hint:: 

29 仅作抛砖引玉,实际并不见得好用,但是你可以参考这个实现自己的自定义SL处理器 

30 

31 .. versionchanged:: 0.3.0 

32 支持配置文件保存 

33 """ # noqa: RUF002 

34 

35 @property 

36 @override 

37 def processor_reg_name(self) -> str: 

38 return "python" 

39 

40 @property 

41 @override 

42 def supported_file_patterns(self) -> tuple[str, ...]: 

43 return (".py",) 

44 

45 supported_file_classes = [ConfigFile] # noqa: RUF012 

46 _s_open_kwargs = {"mode": "r", "encoding": "utf-8"} # noqa: RUF012 

47 

48 @override 

49 def save_file( 

50 self, 

51 config_file: ABCConfigFile[MappingConfigData[dict[str, Any]]], 

52 target_file: SupportsReadAndReadline[str], 

53 *merged_args: Any, 

54 **merged_kwargs: Any, 

55 ) -> None: 

56 with self.raises(): 

57 exec(target_file.read(), {}, config_file.config.data) # noqa: S102 

58 

59 @override 

60 def load_file( 

61 self, source_file: SupportsReadAndReadline[str], *merged_args: Any, **merged_kwargs: Any 

62 ) -> ConfigFile[MappingConfigData[dict[str, Any]]]: 

63 names: dict[str, Any] = {} 

64 with self.raises(): 

65 exec(source_file.read(), {}, names) # noqa: S102 

66 

67 return cast(ConfigFile[MappingConfigData[dict[str, Any]]], ConfigFile(names, config_format=self.reg_name)) 

68 

69 

70__all__ = ("PythonSL",)