Coverage for configzen/formats/toml.py: 58%

30 statements  

« prev     ^ index     » next       coverage.py v7.5.1, created at 2024-05-15 02:42 +0000

1"""`configzen.formats.toml`: The TOML data format.""" 

2 

3from __future__ import annotations 1abcdefgh

4 

5from typing import IO, TYPE_CHECKING, ClassVar 1abcdefgh

6 

7from runtime_generics import runtime_generic 1abcdefgh

8from tomlkit.api import dump, load, register_encoder, unregister_encoder 1abcdefgh

9 

10from configzen.data import DataFormatOptions, TextDataFormat 1abcdefgh

11 

12if TYPE_CHECKING: 1abcdefgh

13 from tomlkit.items import Encoder 

14 from typing_extensions import Unpack 

15 

16 from configzen.data import Data 

17 

18 

19__all__ = ( 1abcdefgh

20 "TOMLDataFormat", 

21 "TOMLOptions", 

22) 

23 

24 

25class TOMLOptions(DataFormatOptions, total=False): 1abcdefgh

26 """Prototype of the allowed options for the TOML data format.""" 

27 

28 encoders: list[Encoder] 1abcdefgh

29 """List of encoders to perform automatic tomlkit.register_encoder() calls on.""" 

30 

31 unregister_old_encoders: bool 1abcdefgh

32 """ 

33 Whether to unregister all previously registered encoders 

34 before registering the new ones. 

35 """ 

36 

37 sort_keys: bool 1abcdefgh

38 """ 1abcdefgh

39 Whether to sort keys in the output. 

40 """ 

41 

42 

43@runtime_generic 1abcdefgh

44class TOMLDataFormat(TextDataFormat[TOMLOptions]): 1abcdefgh

45 """The TOML data format.""" 

46 

47 option_name: ClassVar[str] = "toml" 1abcdefgh

48 

49 # Subclass and override for global effect. 

50 toml_options: TOMLOptions = TOMLOptions() 1abcdefgh

51 

52 default_extension: ClassVar[str] = "toml" 1abcdefgh

53 file_extensions: ClassVar[set[str]] = {"ini", "conf"} 1abcdefgh

54 

55 def configure(self, **options: Unpack[TOMLOptions]) -> None: 1abcdefgh

56 """For the documentation of the options, see the TOMLOptions class.""" 

57 old_options = self.toml_options 

58 toml_encoders = options.get("encoders") or old_options.get("encoders") or [] 

59 cleanup_old_encoders = options.get("cleanup_old_encoders", False) 

60 

61 if cleanup_old_encoders: 

62 for encoder in self.toml_options.get("encoders") or []: 

63 unregister_encoder(encoder) 

64 

65 for encoder in toml_encoders: 

66 register_encoder(encoder) 

67 

68 def load(self, stream: IO[str]) -> Data: 1abcdefgh

69 """Load the data from the given stream.""" 

70 return load(stream) 

71 

72 def dump(self, data: Data, stream: IO[str]) -> None: 1abcdefgh

73 """Dump the data to the given stream.""" 

74 dump( 

75 data, 

76 stream, 

77 sort_keys=self.toml_options.get("sort_keys", False), 

78 )