/
files.py
275 lines (204 loc) · 8.87 KB
/
files.py
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
# load/write ../../languoids/tree/**/md.ini
import configparser
import functools
import logging
import os
import typing
from ._globals import ROOT
from . import _globals
from . import _tools
from . import fields as _fields
__all__ = ['set_root', 'get_repo_root',
'iterfiles',
'roundtrip', 'write_files']
TREE_IN_ROOT = _tools.path_from_filename('languoids', 'tree')
BASENAME = 'md.ini'
log = logging.getLogger(__name__)
def set_root(repo_root, *, resolve=False,
treepath=TREE_IN_ROOT):
"""Set and return default root for glottolog lanugoid directory tree."""
log.info('set_root: %r', repo_root)
if repo_root is None:
raise ValueError(f'missing repo_root path: {repo_root!r}')
repo_path = _tools.path_from_filename(repo_root)
if resolve:
repo_path = repo_path.resolve(strict=False)
ROOT.path = repo_path / _tools.path_from_filename(treepath)
return ROOT
def get_repo_root(root,
*, treepath=TREE_IN_ROOT):
repo_root = _tools.path_from_filename(root)
for _ in treepath.parts:
repo_root = repo_root.parent
return repo_root
class ConfigParser(configparser.ConfigParser):
"""Conservative ConfigParser with encoding header."""
_basename = BASENAME
_header = '# -*- coding: {encoding} -*-\n'
_newline = '\r\n'
_init_defaults = {'delimiters': ('=',),
'comment_prefixes': ('#',),
'interpolation': None}
@classmethod
def from_file(cls, filename, *, encoding=_tools.ENCODING, **kwargs):
path = _tools.path_from_filename(filename)
if path.name != cls._basename:
raise RuntimeError(f'unexpected filename {path!r}'
f' (must end with {cls._basename})')
inst = cls(**kwargs)
with path.open(encoding=encoding) as f:
inst.read_file(f)
return inst
def __init__(self, *, defaults=None, **kwargs):
for k, v in self._init_defaults.items():
kwargs.setdefault(k, v)
super().__init__(defaults=defaults, **kwargs)
def to_file(self, filename, *, encoding=_tools.ENCODING):
path = _tools.path_from_filename(filename)
with path.open('wt', encoding=encoding, newline=self._newline) as f:
f.write(self._header.format(encoding=encoding))
self.write(f)
class FileInfo(typing.NamedTuple):
"""Triple of ((<path_part>, ...), <ConfigParser object>, <DirEntry object>)."""
path: _globals.PathType
config: ConfigParser
dentry: os.DirEntry
@classmethod
def from_dentry(cls, dentry: os.DirEntry,
*, path_slice: slice = slice(None)):
path = _tools.path_from_filename(dentry)
config = ConfigParser.from_file(path)
return cls(path.parts[path_slice], config, dentry)
def iterfiles(root=ROOT,
*, progress_after: int =_tools.PROGRESS_AFTER
) -> typing.Iterator[FileInfo]:
"""Yield triples of ((<path_part>, ...), <ConfigParser object>, <DirEntry object>)."""
root = _tools.path_from_filename(root).resolve()
log.info(f'start parsing {BASENAME} files from %r', root)
msg = f'%s {BASENAME} files parsed'
make_fileinfo = functools.partial(FileInfo.from_dentry,
path_slice=slice(len(root.parts), -1))
n = 0
for n, dentry in enumerate(_tools.walk_scandir(root), 1):
yield make_fileinfo(dentry)
if not (n % progress_after):
log.info(msg, f'{n:_d}')
log.info(f'%s {BASENAME} files total', f'{n:_d}')
def roundtrip(root=ROOT, *, replace=False,
progress_after: int = _tools.PROGRESS_AFTER) -> int:
"""Do a load/save cycle with all config files."""
triples = iterfiles(root,progress_after=progress_after)
raw_records = raw_records_from_files(triples)
return write_files(raw_records, root, _join_lines=False,
replace=replace,
progress_after=progress_after)
RawRecordType = typing.Mapping[str, typing.Mapping[str, str]]
RawRecordItem = typing.Tuple[_globals.PathType, RawRecordType]
def raw_records_from_files(triples: typing.Iterable[FileInfo],
*, _default_section: str = configparser.DEFAULTSECT
) -> typing.Iterator[RawRecordItem]:
for path, cfg, _ in triples:
raw_record = {name: dict(section) for name, section in cfg.items()
if name != _default_section}
yield path, raw_record
RecordsType = typing.Union[typing.Iterable[_globals.RecordItem],
typing.Iterable[RawRecordItem]]
def write_files(records: RecordsType, root=ROOT,
*, replace: bool = False,
progress_after=_tools.PROGRESS_AFTER,
basename: str = BASENAME,
_join_lines: bool = True) -> int:
"""Write ((<path_part>, ...), <dict of dicts>) pairs to root."""
root = _tools.path_from_filename(root)
log.info(f'start writing {basename} files into %r', root)
if replace:
log.warning(f'replace present {basename} files')
joined_records = map(join_lines_inplace, records) if _join_lines else records
load_config = ConfigParser.from_file
files_written = 0
for path_tuple, raw_record in joined_records:
path = root.joinpath(*path_tuple + (basename,))
cfg = load_config(path)
if replace:
cfg.clear()
changed = update_config(cfg, raw_record,
quiet=replace)
if changed:
if not replace:
log.info('write cfg.to_file(%r)', path)
cfg.to_file(path)
files_written += 1
if not (files_written % progress_after):
log.info(f'%s {basename} files written', f'{files_written:_d}')
log.info(f'%s {basename} files written total', f'{files_written:_d}')
return files_written
def join_lines_inplace(record_item: _globals.RecordItem,
*, is_lines=_fields.is_lines) -> RawRecordItem:
path, record = record_item
for name, section in record.items():
for option in section:
if is_lines(name, option):
lines = [''] + section[option]
section[option] = '\n'.join(lines)
return path, record
def update_config(cfg: ConfigParser,
raw_record: RawRecordType,
*, quiet: bool = False,
is_lines=_fields.is_lines,
core_sections=_fields.CORE_SECTIONS,
keep_empty_sections=_fields.KEEP_EMPTY_SECTIONS,
keep_empty_options=_fields.KEEP_EMPTY_OPTIONS,
sorted_sections=_fields.sorted_sections,
sorted_options=_fields.sorted_options) -> bool:
changed = False
old_sections = set(cfg.sections())
old_empty = {s for s in old_sections if not any(v for _, v in cfg.items(s))}
new_sections = {sec for sec, s in raw_record.items() if s}
leave = (old_empty - new_sections) & keep_empty_sections
drop = old_sections - core_sections - leave - new_sections
if drop:
drop = sorted_sections(drop)
log.debug('cfg.remove_section(s) for s in %r', drop)
for s in drop:
cfg.remove_section(s)
changed = True
add = new_sections - old_sections
if add:
add = sorted_sections(add)
if not quiet:
log.debug('cfg.add_section(s) for s in %r', add)
for s in add:
cfg.add_section(s)
changed = True
for section in sorted_sections(raw_record):
s = raw_record[section]
if section not in old_sections or section in core_sections:
pass
elif section in leave:
continue
else:
old_options = {o for o in cfg.options(section)
if (section, o) not in keep_empty_options}
new_options = {k for k, v in s.items() if v}
drop_options = old_options - new_options
if drop_options:
drop_options = sorted_options(section, drop_options)
log.debug('cfg.remove_option(%r, o) for o in %r',
section, drop_options)
for o in drop_options:
cfg.remove_option(section, o)
changed = True
for option in sorted_options(section, s):
value = s[option]
if value is None or (not value and is_lines(section, option)):
continue
old = cfg.get(section, option, fallback=None)
if old == value:
continue
if not quiet:
if old is None:
log.debug('cfg add option (%r, %r)', section, option)
log.debug('cfg.set_option(%r, %r, %r)', section, option, value)
cfg.set(section, option, value)
changed = True
return changed