-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
update.py
462 lines (355 loc) · 14 KB
/
update.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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
import dataclasses
import io
import itertools
import logging
import os
import pathlib
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
import textwrap
from collections.abc import Iterable, Iterator, Mapping, Sequence
from datetime import datetime, timezone
import click
import parver # type: ignore
import requests
IANA_LATEST_LOCATION = "https://www.iana.org/time-zones/repository/tzdata-latest.tar.gz"
SOURCE = "https://data.iana.org/time-zones/releases"
WORKING_DIR = pathlib.Path("tmp")
REPO_ROOT = pathlib.Path(__file__).parent
PKG_BASE = REPO_ROOT / "src"
TEMPLATES_DIR = REPO_ROOT / "templates"
SKIP_NEWS_HEADINGS = {
"Changes to code",
"Changes to build procedure",
}
def download_tzdb_tarballs(
version: str, base_url: str = SOURCE, working_dir: pathlib.Path = WORKING_DIR
) -> Sequence[pathlib.Path]:
"""Download the tzdata and tzcode tarballs."""
tzdata_file = f"tzdata{version}.tar.gz"
tzcode_file = f"tzcode{version}.tar.gz"
target_dir = working_dir / version / "download"
# mkdir -p target_dir
target_dir.mkdir(parents=True, exist_ok=True)
download_locations = []
for filename in [tzdata_file, tzcode_file]:
download_location = target_dir / filename
download_locations.append(download_location)
if download_location.exists():
logging.info("File %s already exists, skipping", download_location)
continue
url = f"{base_url}/{filename}"
logging.info("Downloading %s from %s", filename, url)
r = requests.get(url)
with open(download_location, "wb") as f:
f.write(r.content)
return download_locations
def retrieve_local_tarballs(
version: str, source_dir: pathlib.Path, working_dir: pathlib.Path = WORKING_DIR
) -> Sequence[pathlib.Path]:
"""Retrieve the tzdata and tzcode tarballs from a folder.
This is useful when building against a local, patched version of tzdb.
"""
tzdata_file = f"tzdata{version}.tar.gz"
tzcode_file = f"tzcode{version}.tar.gz"
target_dir = working_dir / version / "download"
# mkdir -p target_dir
target_dir.mkdir(parents=True, exist_ok=True)
dest_locations = []
for filename in [tzdata_file, tzcode_file]:
source_location = source_dir / filename
dest_location = target_dir / filename
if dest_location.exists():
logging.info("File %s exists, overwriting", dest_location)
shutil.copy(source_location, dest_location)
dest_locations.append(dest_location)
return dest_locations
def unpack_tzdb_tarballs(
download_locations: Sequence[pathlib.Path],
) -> pathlib.Path:
assert len(download_locations) == 2
assert download_locations[0].parent == download_locations[1].parent
base_dir = download_locations[0].parent.parent
target_dir = base_dir / "tzdb"
# Remove the directory and re-create it if it does not exist
if target_dir.exists():
shutil.rmtree(target_dir)
target_dir.mkdir()
for tarball in download_locations:
logging.info("Unpacking %s to %s", tarball, target_dir)
subprocess.run(
["tar", "-xf", os.fspath(tarball.absolute())],
cwd=target_dir,
check=True,
)
return target_dir
def load_zonefiles(
base_dir: pathlib.Path,
) -> tuple[Sequence[str], pathlib.Path]:
target_dir = base_dir.parent / "zoneinfo"
if target_dir.exists():
shutil.rmtree(target_dir)
with tempfile.TemporaryDirectory() as td:
td_path = pathlib.Path(td)
# First run the makefile, which does all kinds of other random stuff
subprocess.run(
["make", f"DESTDIR={td}", "ZFLAGS=-b slim", "install"],
cwd=base_dir,
check=True,
)
proc = subprocess.run(
["make", "zonenames"], cwd=base_dir, stdout=subprocess.PIPE, check=True
)
zonenames = list(map(str.strip, proc.stdout.decode("utf-8").split("\n")))
# Move the zoneinfo files into the target directory
src_dir = td_path / "usr" / "share" / "zoneinfo"
shutil.move(os.fspath(src_dir), os.fspath(target_dir))
return zonenames, target_dir
def create_package(version: str, zonenames: Sequence[str], zoneinfo_dir: pathlib.Path):
"""Creates the tzdata package."""
# Start out at rc0
base_version = parver.Version.parse(translate_version(version))
rc_version = base_version.replace(pre_tag="rc", pre=0)
package_version = str(rc_version)
# First remove the existing package contents
target_dir = PKG_BASE / "tzdata"
if target_dir.exists():
shutil.rmtree(target_dir)
data_dir = target_dir / "zoneinfo"
# Next move the zoneinfo file to the target location
shutil.move(os.fspath(zoneinfo_dir), data_dir)
# Generate the base __init__.py from a template
with open(TEMPLATES_DIR / "__init__.py.in", "r") as f_in:
contents = f_in.read()
contents = contents.replace("%%IANA_VERSION%%", f'"{version}"')
contents = contents.replace("%%PACKAGE_VERSION%%", f'"{package_version}"')
with open(target_dir / "__init__.py", "w") as f_out:
f_out.write(contents)
with open(REPO_ROOT / "VERSION", "w") as f:
f.write(package_version)
# Generate the "zones" file as a newline-delimited list
with open(target_dir / "zones", "w") as f:
f.write("\n".join(zonenames))
# Now recursively create __init__.py files in every directory we need to
for dirpath, _, filenames in os.walk(data_dir):
if "__init__.py" not in filenames:
init_file = pathlib.Path(dirpath) / "__init__.py"
init_file.touch()
def find_latest_version() -> str:
r = requests.get(IANA_LATEST_LOCATION)
fobj = io.BytesIO(r.content)
with tarfile.open(fileobj=fobj, mode="r:gz") as tf:
vfile = tf.extractfile("version")
assert vfile is not None, "version file is not a regular file"
version = vfile.read().decode("utf-8").strip()
assert re.match("\d{4}[a-z]$", version), version
target_dir = WORKING_DIR / version / "download"
target_dir.mkdir(parents=True, exist_ok=True)
fobj.seek(0)
with open(target_dir / f"tzdata{version}.tar.gz", "wb") as f:
f.write(fobj.read())
return version
def translate_version(iana_version: str) -> str:
"""Translates from an IANA version to a PEP 440 version string.
E.g. 2020a -> 2020.1
"""
if (
len(iana_version) < 5
or not iana_version[0:4].isdigit()
or not iana_version[4:].isalpha()
):
raise ValueError(
"IANA version string must be of the format YYYYx where YYYY represents the "
f"year and x is in [a-z], found: {iana_version}"
)
version_year = iana_version[0:4]
patch_letters = iana_version[4:]
# From tz-link.html:
#
# Since 1996, each version has been a four-digit year followed by
# lower-case letter (a through z, then za through zz, then zza through zzz,
# and so on).
if len(patch_letters) > 1 and not all(c == "z" for c in patch_letters[0:-1]):
raise ValueError(
f"Invalid IANA version number (only the last character may be a letter "
f"other than z), found: {iana_version}"
)
final_patch_number = ord(patch_letters[-1]) - ord("a") + 1
patch_number = (26 * (len(patch_letters) - 1)) + final_patch_number
return f"{version_year}.{patch_number:d}"
##
# News entry handling
@dataclasses.dataclass
class NewsEntry:
version: str
release_date: datetime
categories: Mapping[str, str]
def to_file(self) -> None:
fpath = pathlib.Path("news.d") / (self.version + ".md")
release_date = self.release_date.astimezone(timezone.utc)
translated_version = translate_version(self.version)
contents = [f"# Version {translated_version}"]
contents.append(
f"Upstream version {self.version} released {release_date.isoformat()}"
)
contents.append("")
for category, entry in self.categories.items():
contents.append(f"## {category}")
contents.append("")
contents.append(entry)
contents.append("")
with open(fpath, "wt") as f:
f.write(("\n".join(contents)).strip())
INDENT_RE = re.compile("[^ ]")
def get_indent(s: str) -> int:
s = s.rstrip()
if not s:
return 0
m = INDENT_RE.search(s)
assert m is not None
return m.span()[0]
def read_block(
lines: Iterator[str],
) -> tuple[Sequence[str], Iterator[str]]:
lines, peek = itertools.tee(lines)
while not (first_line := next(peek)):
next(lines)
block_indent = get_indent(first_line)
block = []
# The way this loop works: `peek` is always one line ahead of `lines`. It
# starts out where `lines` is pointing to the first non-empty line, and
# peek is the line after that. We know that if the body of the loop is
# reached, the next value in `lines` is part of the block.
#
# It is done this way so that we can return an iterable pointing at the
# first line *after* the block that we just read.
for line in peek:
block.append(next(lines))
if not line:
block.append(line)
continue
line_indent = get_indent(line)
if line_indent < block_indent:
# We've dedented, so this is the end of the block.
break
else:
# If we've exhausted `peek` because we're reading the last block in the
# file, we won't hit the `break` condition, but we'll still have a
# valid line in the `lines` queue.
block.append(next(lines))
return block, lines
def parse_categories(news_block: Sequence[str]) -> Mapping[str, str]:
blocks = iter(news_block)
output = {}
while True:
try:
while not (heading := next(blocks)):
pass
except StopIteration:
break
content_lines, blocks = read_block(blocks)
heading = heading.strip()
if heading in SKIP_NEWS_HEADINGS:
continue
# Merge the contents into paragraphs by grouping into consecutive blocks
# of non-empty lines, then joining those lines on a newline.
content_paragraphs: Iterable[str] = (
"\n".join(paragraph)
for _, paragraph in itertools.groupby(content_lines, key=bool)
)
# Now dedent each paragraph and wrap it to 80 characters. This needs to
# be done at the per-paragraph level, because `textwrap.wrap` doesn't
# recognize paragraph breaks.
content_paragraphs = map(textwrap.dedent, content_paragraphs)
content_paragraphs = map(
"\n".join,
(textwrap.wrap(paragraph, width=80) for paragraph in content_paragraphs),
)
# Finally we can join the paragraphs into a single string and trim
# whitespace from it
contents = "\n".join(content_paragraphs)
contents = contents.strip()
output[heading] = contents
return output
def read_news(tzdb_loc: pathlib.Path, version: str | None = None) -> NewsEntry:
release_re = re.compile("^Release (?P<version>\d{4}[a-z]) - (?P<date>.*$)")
with open(tzdb_loc / "NEWS", "rt") as f:
f_lines = map(str.rstrip, f)
for line in f_lines:
if ((m := release_re.match(line)) is not None) and (
version is None or m.group("version") == version
):
break
else:
if version is None:
message = "No releases found!"
else:
message = f"No release found with version {version}"
assert m is not None
version_date = datetime.strptime(m.group("date"), "%Y-%m-%d %H:%M:%S %z")
release_version = m.group("version")
release_contents, _ = read_block(f_lines)
# Now we further parse the contents of the news and filter out some
# irrelevant categories.
categories = parse_categories(release_contents)
return NewsEntry(release_version, version_date, categories)
def update_news(news_entry: NewsEntry):
# news.d contains fragments for each tzdata version, and the NEWS file
# is assembled by stitching these together each time. First thing we'll do
# is add a new fragment.
news_entry.to_file()
# Now go through and join all the files together
news_fragment_files = sorted(
pathlib.Path("news.d").glob("*.md"), key=lambda p: p.name, reverse=True
)
news_fragments = [p.read_text() for p in news_fragment_files]
with open("NEWS.md", "wt") as f:
f.write("\n\n---\n\n".join(news_fragments))
@click.command()
@click.option(
"--version", "-v", default=None, help="The version of the tzdata file to download"
)
@click.option(
"--source-dir",
"-s",
default=None,
help="A local source directory containing tarballs (must be used together with --version)",
type=click.Path(
exists=True, file_okay=False, dir_okay=True, path_type=pathlib.Path
), # type: ignore
)
@click.option(
"--news-only/--no-news-only",
help="Flag to disable data updates and only update the news entry",
)
def main(
version: str | None,
news_only: bool,
source_dir: pathlib.Path | None,
):
logging.basicConfig(level=logging.INFO)
if source_dir is not None:
if version is None:
logging.error(
"--source-dir specified without --version: "
"If using --source-dir, --version must also be used."
)
sys.exit(-1)
download_locations = retrieve_local_tarballs(version, source_dir)
else:
if version is None:
version = find_latest_version()
download_locations = download_tzdb_tarballs(version)
tzdb_location = unpack_tzdb_tarballs(download_locations)
# Update the news entry
news_entry = read_news(tzdb_location, version=version)
update_news(news_entry)
if not news_only:
zonenames, zonefile_path = load_zonefiles(tzdb_location)
create_package(version, zonenames, zonefile_path)
if __name__ == "__main__":
main()