-
Notifications
You must be signed in to change notification settings - Fork 237
Expand file tree
/
Copy pathconfig_reader.py
More file actions
212 lines (164 loc) · 5.89 KB
/
config_reader.py
File metadata and controls
212 lines (164 loc) · 5.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
"""Configuration parser for YAML and JSON files."""
from __future__ import annotations
import json
import logging
import pathlib
import typing as t
import yaml
logger = logging.getLogger(__name__)
if t.TYPE_CHECKING:
from typing import TypeAlias
FormatLiteral = t.Literal["json", "yaml"]
RawConfigData: TypeAlias = dict[t.Any, t.Any]
class ConfigReader:
r"""Parse string data (YAML and JSON) into a dictionary.
>>> cfg = ConfigReader({ "session_name": "my session" })
>>> cfg.dump("yaml")
'session_name: my session\n'
>>> cfg.dump("json")
'{\n "session_name": "my session"\n}'
"""
def __init__(self, content: RawConfigData) -> None:
self.content = content
@staticmethod
def _load(fmt: FormatLiteral, content: str) -> dict[str, t.Any]:
"""Load raw config data and directly return it.
>>> ConfigReader._load("json", '{ "session_name": "my session" }')
{'session_name': 'my session'}
>>> ConfigReader._load("yaml", 'session_name: my session')
{'session_name': 'my session'}
"""
if fmt == "yaml":
return t.cast(
"dict[str, t.Any]",
yaml.load(
content,
Loader=yaml.SafeLoader,
),
)
if fmt == "json":
return t.cast("dict[str, t.Any]", json.loads(content))
msg = f"{fmt} not supported in configuration"
raise NotImplementedError(msg)
@classmethod
def load(cls, fmt: FormatLiteral, content: str) -> ConfigReader:
"""Load raw config data into a ConfigReader instance (to dump later).
>>> cfg = ConfigReader.load("json", '{ "session_name": "my session" }')
>>> cfg
<tmuxp._internal.config_reader.ConfigReader object at ...>
>>> cfg.content
{'session_name': 'my session'}
>>> cfg = ConfigReader.load("yaml", 'session_name: my session')
>>> cfg
<tmuxp._internal.config_reader.ConfigReader object at ...>
>>> cfg.content
{'session_name': 'my session'}
"""
return cls(
content=cls._load(
fmt=fmt,
content=content,
),
)
@classmethod
def _from_file(cls, path: pathlib.Path) -> dict[str, t.Any]:
r"""Load data from file path directly to dictionary.
**YAML file**
*For demonstration only,* create a YAML file:
>>> yaml_file = tmp_path / 'my_config.yaml'
>>> yaml_file.write_text('session_name: my session', encoding='utf-8')
24
*Read YAML file*:
>>> ConfigReader._from_file(yaml_file)
{'session_name': 'my session'}
**JSON file**
*For demonstration only,* create a JSON file:
>>> json_file = tmp_path / 'my_config.json'
>>> json_file.write_text('{"session_name": "my session"}', encoding='utf-8')
30
*Read JSON file*:
>>> ConfigReader._from_file(json_file)
{'session_name': 'my session'}
"""
assert isinstance(path, pathlib.Path)
logger.debug("loading config", extra={"tmux_config_path": str(path)})
content = path.open(encoding="utf-8").read()
if path.suffix in {".yaml", ".yml"}:
fmt: FormatLiteral = "yaml"
elif path.suffix == ".json":
fmt = "json"
else:
msg = f"{path.suffix} not supported in {path}"
raise NotImplementedError(msg)
return cls._load(
fmt=fmt,
content=content,
)
@classmethod
def from_file(cls, path: pathlib.Path) -> ConfigReader:
r"""Load data from file path.
**YAML file**
*For demonstration only,* create a YAML file:
>>> yaml_file = tmp_path / 'my_config.yaml'
>>> yaml_file.write_text('session_name: my session', encoding='utf-8')
24
*Read YAML file*:
>>> cfg = ConfigReader.from_file(yaml_file)
>>> cfg
<tmuxp._internal.config_reader.ConfigReader object at ...>
>>> cfg.content
{'session_name': 'my session'}
**JSON file**
*For demonstration only,* create a JSON file:
>>> json_file = tmp_path / 'my_config.json'
>>> json_file.write_text('{"session_name": "my session"}', encoding='utf-8')
30
*Read JSON file*:
>>> cfg = ConfigReader.from_file(json_file)
>>> cfg
<tmuxp._internal.config_reader.ConfigReader object at ...>
>>> cfg.content
{'session_name': 'my session'}
"""
return cls(content=cls._from_file(path=path))
@staticmethod
def _dump(
fmt: FormatLiteral,
content: RawConfigData,
indent: int = 2,
**kwargs: t.Any,
) -> str:
r"""Dump directly.
>>> ConfigReader._dump("yaml", { "session_name": "my session" })
'session_name: my session\n'
>>> ConfigReader._dump("json", { "session_name": "my session" })
'{\n "session_name": "my session"\n}'
"""
if fmt == "yaml":
return yaml.dump(
content,
indent=2,
default_flow_style=False,
Dumper=yaml.SafeDumper,
)
if fmt == "json":
return json.dumps(
content,
indent=2,
)
msg = f"{fmt} not supported in config"
raise NotImplementedError(msg)
def dump(self, fmt: FormatLiteral, indent: int = 2, **kwargs: t.Any) -> str:
r"""Dump via ConfigReader instance.
>>> cfg = ConfigReader({ "session_name": "my session" })
>>> cfg.dump("yaml")
'session_name: my session\n'
>>> cfg.dump("json")
'{\n "session_name": "my session"\n}'
"""
return self._dump(
fmt=fmt,
content=self.content,
indent=indent,
**kwargs,
)