Repository navigation
Expand file tree
/
Copy pathgenerate_encodings.py
More file actions
703 lines (587 loc) · 29.1 KB
/
Copy pathgenerate_encodings.py
File metadata and controls
703 lines (587 loc) · 29.1 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
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
#!/usr/bin/env python3
# Regenerates encodings/*.tbl and the README table from Python's
# stdlib codecs. Hand-authored .tbl files (no generated header) are
# left alone.
# Run from anywhere:
# python3 scripts/generate_encodings.py (re)writes encodings/ and README.md
# python3 scripts/generate_encodings.py --check verifies both, writes nothing
import argparse
import codecs
import encodings.aliases
import hashlib
import os
import posixpath
import re
import sys
from typing import NamedTuple
REPO_ROOT = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
ENCODINGS_DIR = os.path.join(REPO_ROOT, "encodings", "builtin")
README_PATH = os.path.join(REPO_ROOT, "README.md")
INCLUDES_DIR = "includes"
# Every file this script writes starts with this line; a file without it is left alone.
GENERATED_COMMENT = "# Generated by ImHex-Patterns/scripts/generate_encodings.py"
FILE_TABLE_START = "<!-- generate_encodings.py: start of File encodings table -->"
FILE_TABLE_END = "<!-- generate_encodings.py: end of File encodings table -->"
GENERATED_STRING_TABLE_START = "<!-- generate_encodings.py: start of Generated encodings table -->"
GENERATED_STRING_TABLE_END = "<!-- generate_encodings.py: end of Generated encodings table -->"
# codec -> (display name, description), both hand-curated; the name is a label, not the filename.
CODEC_ENCODINGS = {
"ascii": ("ASCII", "Basic 7-bit encoding for English text"),
"big5": ("Big5", "Encoding for Traditional Chinese text"),
"big5hkscs": ("Big5-HKSCS", "Extended Big5 encoding with the Hong Kong Supplementary Character Set"),
"cp037": ("IBM 037", "Extended Binary Coded Decimal Interchange Code"),
"cp1250": ("Windows 1250", "Windows encoding for Central European languages (Polish, Czech, Hungarian, and others)"),
"cp1251": ("Windows 1251", "Windows encoding for Cyrillic languages (Russian, Bulgarian, Serbian, and others)"),
"cp1252": ("Windows 1252", "Windows encoding for Western European languages (English, French, German, and others)"),
"cp1253": ("Windows 1253", "Windows encoding for the Greek language"),
"cp1254": ("Windows 1254", "Windows encoding for the Turkish language"),
"cp1255": ("Windows 1255", "Windows encoding for the Hebrew language"),
"cp1256": ("Windows 1256", "Windows encoding for the Arabic language"),
"cp1257": ("Windows 1257", "Windows encoding for Baltic languages (Estonian, Latvian, Lithuanian)"),
"cp1258": ("Windows 1258", "Windows encoding for the Vietnamese language"),
"cp437": ("IBM 437", "Original IBM PC encoding, with box-drawing and symbol characters"),
"cp775": ("IBM 775", "DOS encoding for Baltic languages (Estonian, Latvian, Lithuanian)"),
"cp850": ("IBM 850", "DOS encoding for Western European languages (English, French, German, and others)"),
"cp852": ("IBM 852", "DOS encoding for Central European languages (Polish, Czech, Hungarian, and others)"),
"cp855": ("IBM 855", "DOS encoding for Cyrillic languages (Russian, Bulgarian, Serbian, and others)"),
"cp857": ("IBM 857", "DOS encoding for the Turkish language"),
"cp860": ("IBM 860", "DOS encoding for the Portuguese language"),
"cp861": ("IBM 861", "DOS encoding for the Icelandic language"),
"cp862": ("IBM 862", "DOS encoding for the Hebrew language"),
"cp863": ("IBM 863", "DOS encoding for the Canadian French language"),
"cp864": ("IBM 864", "DOS encoding for the Arabic language"),
"cp865": ("IBM 865", "DOS encoding for Nordic languages (Danish, Norwegian, and others)"),
"cp866": ("IBM 866", "DOS encoding for Cyrillic languages (Russian and others)"),
"cp869": ("IBM 869", "DOS encoding for the Greek language"),
"cp874": ("Windows 874", "Windows encoding for the Thai language"),
"cp932": ("Windows 31J", "Shift-JIS with Microsoft/NEC/IBM extensions (aka MS932/CP932)"),
"euc_jp": ("EUC-JP", "Extended Unix Code encoding for the Japanese language"),
"euc_kr": ("EUC-KR", "Extended Unix Code encoding for the Korean language"),
"gb2312": ("GB2312", "Older encoding for Simplified Chinese text"),
"gbk": ("GBK", "Encoding for Simplified Chinese text"),
"iso8859_2": ("ISO 8859-2", "ISO encoding for Central European languages (Polish, Czech, Hungarian, and others)"),
"iso8859_3": ("ISO 8859-3", "ISO encoding for South European languages (Turkish, Maltese, Esperanto)"),
"iso8859_4": ("ISO 8859-4", "ISO encoding for North European languages (Estonian, Latvian, Lithuanian, Greenlandic, Sami)"),
"iso8859_5": ("ISO 8859-5", "ISO encoding for Cyrillic languages (Russian, Bulgarian, Serbian, and others)"),
"iso8859_6": ("ISO 8859-6", "ISO encoding for the Arabic language"),
"iso8859_7": ("ISO 8859-7", "ISO encoding for the Greek language"),
"iso8859_8": ("ISO 8859-8", "ISO encoding for the Hebrew language"),
"iso8859_9": ("ISO 8859-9", "ISO encoding for the Turkish language"),
"iso8859_10": ("ISO 8859-10", "ISO encoding for Nordic languages (Icelandic, Sami, and others)"),
"iso8859_11": ("ISO 8859-11", "ISO encoding for the Thai language"),
"iso8859_13": ("ISO 8859-13", "ISO encoding for Baltic languages (Estonian, Latvian, Lithuanian)"),
"iso8859_14": ("ISO 8859-14", "ISO encoding for Celtic languages (Irish Gaelic, Scottish Gaelic, Welsh, Breton)"),
"iso8859_15": ("ISO 8859-15", "ISO encoding for Western European languages, a revision of ISO-8859-1 adding the Euro sign"),
"iso8859_16": ("ISO 8859-16", "ISO encoding for South-Eastern European languages (Romanian, and others), includes the Euro sign"),
"koi8_r": ("KOI8-R", "Cyrillic KOI8-R encoding (Russian characters)"),
"koi8_u": ("KOI8-U", "Cyrillic KOI8-U encoding (Ukrainian characters)"),
"latin_1": ("ISO 8859-1", "ISO encoding for Western European languages (English, French, German, and others)"),
"mac_arabic": ("Mac OS Arabic", "Classic Mac OS encoding for the Arabic language"),
"mac_croatian": ("Mac OS Croatian", "Classic Mac OS encoding for the Croatian language"),
"mac_cyrillic": ("Mac OS Cyrillic", "Classic Mac OS encoding for Cyrillic languages (Russian, Bulgarian, Serbian, and others)"),
"mac_farsi": ("Mac OS Farsi", "Classic Mac OS encoding for the Persian (Farsi) language"),
"mac_greek": ("Mac OS Greek", "Classic Mac OS encoding for the Greek language"),
"mac_iceland": ("Mac OS Icelandic", "Classic Mac OS encoding for the Icelandic language"),
"mac_latin2": ("Mac OS Central European", "Classic Mac OS encoding for Central European languages (Czech, Slovak, Hungarian, Polish, and others)"),
"mac_roman": ("Mac OS Roman", "Classic Mac OS encoding for Western European languages"),
"mac_romanian": ("Mac OS Romanian", "Classic Mac OS encoding for the Romanian language"),
"mac_turkish": ("Mac OS Turkish", "Classic Mac OS encoding for the Turkish language"),
"shift_jis": ("Shift_JIS", "Encoding for Japanese text"),
"tis_620": ("TIS-620", "Thai national standard character encoding"),
}
# Encodings derived from another encoding's entries (source, key_filter) plus overrides.
DERIVED_ENCODINGS = {
"jis_x0201": {
"name": "JIS X 0201",
"description": "JIS X 0201 encoding (half-width katakana and Roman set)",
"aliases": ["X0201"],
"source": "shift_jis",
"key_filter": lambda k: len(k) == 2,
"overrides": {"5C": "¥", "7E": "‾"},
},
}
# Aliases missing from Python's table. is_useful_alias() still applies.
EXTRA_ALIASES = {
"cp874": ["ms874", "windows_874"],
"cp932": ["windows_31j"],
"gbk": ["windows-936"],
"iso8859_8": ["iso_8859_8_e", "iso_8859_8_i"],
}
# Minimum overlap for a shared table to be worth creating at all.
MIN_SHARED_ENTRIES = 48
# Friendly names for shared tables, keyed by content hash; unlisted tables use the hash instead.
KNOWN_SHARED_NAMES = {
"30a1371392fa": "arabic_common",
"0e166e4cc71e": "baltic",
"26547374c76a": "box_drawing",
"8da30839c26c": "central_european",
"333c7d4a7806": "cjk_symbols",
"7032f8c44e34": "dos_latin",
"d4a14d7516bd": "greek",
"e9ab4a6a1d2c": "halfwidth_katakana",
"4fa454d63732": "iso8859_latin",
"293ab09ade86": "iso8859_western",
"73f090c0b0f0": "japanese_kanji",
"733be1b6d236": "koi8",
"c8d8be2c999e": "latin_greek_math",
"ef502e17ae0e": "mac_central_european",
"9d4c91e34171": "mac_latin",
"ee297dd4450f": "mac_rtl",
"4adec219b5e9": "nordic",
"f6a9c1205582": "simplified_chinese",
"f03083f77bbc": "traditional_chinese",
"f90e30177902": "windows_latin",
}
def encodings_path(*parts):
"""Absolute path for a name under encodings/, like ascii.tbl."""
return os.path.join(ENCODINGS_DIR, *parts)
def is_useful_alias(alias):
"""False for aliases too terse to mean anything on their own, like
"1250", "csBig5", or "l1"."""
a = alias.lower()
return not (a.isdigit() or a.startswith("cs") or re.fullmatch(r"l\d+", a))
def normalize(name):
"""Filename stem for a codec or alias name: lowercase only, so every
name maps predictably to its own file. Separators are left alone,
so "iso8859-1" and "iso_8859_1" are two files."""
return name.lower()
def stem_for(key):
"""Filename stem for a codec or derived key. Never the display name."""
if key in CODEC_ENCODINGS:
return normalize(codecs.lookup(key).name)
return normalize(key)
def library_aliases_for(codec_name):
target = codecs.lookup(codec_name).name
found = set()
for alias, module_name in encodings.aliases.aliases.items():
try:
if codecs.lookup(module_name).name == target:
found.add(alias)
except LookupError:
continue
return sorted(found)
def format_value(c):
if len(c) == 1 and not c.isprintable():
cp = ord(c)
return f"\\u{cp:04X}" if cp <= 0xFFFF else f"\\U{cp:08X}"
return c
def gen_codec_entries(codec_name):
entries = {}
for b0 in range(0x100):
key1 = bytes([b0])
try:
entries[key1.hex().upper()] = key1.decode(codec_name)
continue
except UnicodeDecodeError:
pass
for b1 in range(0x100):
key2 = bytes([b0, b1])
try:
entries[key2.hex().upper()] = key2.decode(codec_name)
except UnicodeDecodeError:
continue
if codec_name == "euc_jp" and b0 == 0x8F: # JIS X 0212 supplementary plane
for b1 in range(0x100):
for b2 in range(0x100):
key3 = bytes([b0, b1, b2])
try:
entries[key3.hex().upper()] = key3.decode(codec_name)
except UnicodeDecodeError:
continue
return entries
def find_bases(full_by_stem):
"""Largest safe superset for each stem, or None. A base must never
redefine a value the includer defines. ImHex leaves conflicts between
multiple -include targets undefined. Smallest-first order avoids cycles."""
bases = {}
processed = {}
for stem in sorted(full_by_stem, key=lambda s: (len(full_by_stem[s]), s)):
entries = full_by_stem[stem]
best_stem, best_size = None, -1
for other_stem, other_entries in processed.items():
if len(other_entries) <= best_size:
continue
if all(entries.get(k) == v for k, v in other_entries.items()):
best_stem, best_size = other_stem, len(other_entries)
bases[stem] = best_stem
processed[stem] = entries
return bases
def dump_entries(entries):
lines = [f"{k}={format_value(entries[k])}"
for k in sorted(entries, key=lambda k: (len(k), int(k, 16)))]
return "\n".join(lines)
def build_primary_body(name, description, include, entries):
lines = [GENERATED_COMMENT, f"-name {name}"]
if description:
lines.append(f"-description {description}")
if include:
lines.append(f"-include {include}")
body = dump_entries(entries)
if body:
lines.append(body)
return "\n".join(lines) + "\n"
def build_include_body(description, include, entries):
"""Like build_primary_body, but no -name. Lives in
encodings/includes/, not meant to be selected directly."""
lines = [GENERATED_COMMENT, f"# {description}"]
if include:
lines.append(f"-include {include}")
body = dump_entries(entries)
if body:
lines.append(body)
return "\n".join(lines) + "\n"
def build_alias_body(primary_stem):
return f"{GENERATED_COMMENT}\n-alias {primary_stem}\n"
def useful_aliases(key, aliases):
"""Aliases worth a file: useful, and not the primary's own stem.
Near-misses like "iso8859_1" next to "iso8859-1" are kept."""
stem = stem_for(key)
return sorted({normalize(a) for a in aliases
if is_useful_alias(a) and normalize(a) != stem})
def aliases_for(codec):
"""Every name a codec answers to, besides its own stem. The codec
key counts as one: "iso8859_2" looks up "iso8859-2"."""
names = {codec} | set(library_aliases_for(codec)) | set(EXTRA_ALIASES.get(codec, []))
return useful_aliases(codec, names)
class EncodingSpec(NamedTuple):
key: str
name: str
description: str
aliases: list
def all_encodings():
"""EncodingSpec for every generated primary file."""
items = [EncodingSpec(codec, name, description, aliases_for(codec))
for codec, (name, description) in CODEC_ENCODINGS.items()]
items += [EncodingSpec(key, cfg["name"], cfg["description"], useful_aliases(key, cfg["aliases"]))
for key, cfg in DERIVED_ENCODINGS.items()]
return items
def shared_stem(entries):
"""Name for a de-dup table: a friendly name if this content is
recognized, otherwise the content hash itself."""
digest = hashlib.sha256(dump_entries(entries).encode()).hexdigest()[:12]
return KNOWN_SHARED_NAMES.get(digest, digest)
def discover_shared_bases(real_full):
"""Pairs encodings that mostly agree into shared de-dup tables. Each
switches to at most one, only if it beats its current base; a stem
already used as a base, like ascii, never switches itself.
Returns (entries by shared stem, {shared stem: (a, b)}, {stem: base})."""
real_bases = find_bases(real_full)
fixed = {b for b in real_bases.values() if b is not None}
def base_size(stem):
base = real_bases[stem]
return len(real_full[base]) if base else 0
pool = sorted(real_full)
candidates = []
for i, a in enumerate(pool):
for b in pool[i + 1:]:
if a in fixed and b in fixed:
continue
da, db = real_full[a], real_full[b]
agree = {k: v for k, v in da.items() if db.get(k) == v}
if len(agree) < MIN_SHARED_ENTRIES:
continue
improves = (a not in fixed and len(agree) > base_size(a)) or \
(b not in fixed and len(agree) > base_size(b))
if improves:
candidates.append((len(agree), a, b, agree))
candidates.sort(key=lambda c: (-c[0], c[1], c[2]))
claimed = set()
shared_entries, shared_sources = {}, {}
for _size, a, b, agree in candidates:
switchable = [s for s in (a, b) if s not in fixed and s not in claimed
and len(agree) > base_size(s)]
if not switchable:
continue
stem = shared_stem(agree)
shared_entries[stem] = agree
shared_sources[stem] = (a, b)
for s in switchable:
real_bases[s] = stem
claimed.add(s)
return shared_entries, shared_sources, real_bases
def build_entries():
entries_by_key = {codec: gen_codec_entries(codec) for codec in CODEC_ENCODINGS}
for key, cfg in DERIVED_ENCODINGS.items():
entries = {k: v for k, v in entries_by_key[cfg["source"]].items()
if cfg["key_filter"](k)}
entries.update(cfg["overrides"])
entries_by_key[key] = entries
stems = {key: stem_for(key) for key in entries_by_key}
real_full = {stems[key]: entries_by_key[key] for key in entries_by_key}
shared_entries, shared_sources, bases = discover_shared_bases(real_full)
# a shared table can itself -include a real base, e.g. ascii
trial = {**real_full, **shared_entries}
shared_bases = find_bases(trial)
bases.update({stem: shared_bases[stem] for stem in shared_entries})
full = {**real_full, **shared_entries}
# Drop shared tables with too few users or too little content of their own.
changed = True
while changed:
changed = False
counts = {}
for base in bases.values():
if base is not None:
counts[base] = counts.get(base, 0) + 1
for stem in list(shared_entries):
base = bases.get(stem)
entries = full[stem]
own = entries if base is None else \
{k: v for k, v in entries.items() if k not in full[base]}
if counts.get(stem, 0) >= 2 and len(own) >= MIN_SHARED_ENTRIES:
continue
redirect_to = base
for s, b in list(bases.items()):
if b == stem:
bases[s] = redirect_to
del shared_entries[stem]
del shared_sources[stem]
del full[stem]
del bases[stem]
changed = True
return stems, full, bases, shared_sources
def check_known_shared_names(full, shared_sources):
"""Problems for KNOWN_SHARED_NAMES entries no shared table produces
anymore, e.g. after a codec change shifts the pairing and strands a
stale hash -> name mapping."""
produced = {hashlib.sha256(dump_entries(full[stem]).encode()).hexdigest()[:12]
for stem in shared_sources}
stale = sorted(set(KNOWN_SHARED_NAMES) - produced)
if not stale:
return []
entries = ", ".join(f"{digest} ({KNOWN_SHARED_NAMES[digest]})" for digest in stale)
return [f"KNOWN_SHARED_NAMES has stale entries no longer produced by any shared table: {entries}"]
def is_codepage(entries):
"""True if every key is one byte and every value is one codepoint
(what #pragma encoding accepts)."""
return all(len(k) == 2 for k in entries) and all(len(v) == 1 for v in entries.values())
def natural_sort_key(name):
"""Sorts number groups by value, so "ISO-8859-2" comes before
"ISO-8859-10"."""
return [int(chunk) if chunk.isdigit() else chunk.casefold()
for chunk in re.split(r"(\d+)", name)]
class ReadmeRow(NamedTuple):
name: str
link: str
description: str
entries: int
aliases: list
def readme_rows(stems, full):
file_encodings, generated_string = [], []
for spec in all_encodings():
stem = stems[spec.key]
entries = full[stem]
row = ReadmeRow(spec.name, f"{stem}.tbl", spec.description, len(entries), spec.aliases)
(file_encodings if is_codepage(entries) else generated_string).append(row)
by_name = lambda row: natural_sort_key(row.name)
file_encodings.sort(key=by_name)
generated_string.sort(key=by_name)
return file_encodings, generated_string
def build_readme_table(rows):
lines = ["| Name | Path | Description | Entries | Aliases |",
"|------|------|-------------|---------|---------|"]
for row in rows:
alias_text = ", ".join(f"`{a}`" for a in row.aliases) if row.aliases else "(none)"
full_link = f"encodings/{row.link}"
path = f"[`{full_link}`]({full_link})"
lines.append(f"| {row.name} | {path} | {row.description} | {row.entries} | {alias_text} |")
return "\n".join(lines) + "\n"
def apply_table(content, start, end, table):
pattern = re.compile(re.escape(start) + r"\n.*?\n" + re.escape(end), re.DOTALL)
replacement = f"{start}\n{table}{end}"
new_content, count = pattern.subn(replacement, content, count=1)
if count == 0:
raise SystemExit(f"README.md: markers not found (expected {start!r})")
return new_content
def file_path(stem, shared_stems):
""".tbl file path to write stem to."""
if stem in shared_stems:
return f"{INCLUDES_DIR}/{stem}.tbl"
return f"{stem}.tbl"
def relative_include(includer_stem, target_stem, shared_stems):
"""-include value naming target_stem's file, relative to includer_stem's
own file. file_path() returns "/"-separated paths, so posixpath (not
os.path) preserves that on Windows too."""
includer_dir = posixpath.dirname(file_path(includer_stem, shared_stems))
target = file_path(target_stem, shared_stems)
return posixpath.relpath(target, includer_dir) if includer_dir else target
def shared_dependents(full, bases, shared_stems):
"""Map each shared stem to every real stem that -includes it,
directly or through a chain of other shared stems."""
dependents = {s: set() for s in shared_stems}
for real_stem in full:
if real_stem in shared_stems:
continue
stem = bases.get(real_stem)
while stem is not None:
if stem not in dependents:
break
dependents[stem].add(real_stem)
stem = bases.get(stem)
return dependents
def build_shared_base_files(full, shared_sources, bases):
""".tbl files for the pairs discover_shared_bases() found, written
under encodings/includes/."""
shared_stems = set(shared_sources)
dependents = shared_dependents(full, bases, shared_stems)
files = {}
for stem in shared_sources:
names = ", ".join(sorted(dependents[stem]))
base_stem = bases[stem]
entries = full[stem]
own = entries if base_stem is None else \
{k: v for k, v in entries.items() if k not in full[base_stem]}
description = f"{len(entries)} entries shared by {names}"
include = relative_include(stem, base_stem, shared_stems) if base_stem else None
files[file_path(stem, shared_stems)] = build_include_body(description, include, own)
return files
def all_files(stems, full, bases, shared_stems):
encodings_ = all_encodings()
primary_names = {stems[spec.key] + ".tbl" for spec in encodings_}
files = {}
alias_targets = {}
for spec in encodings_:
stem = stems[spec.key]
entries = full[stem]
base_stem = bases[stem]
own = entries if base_stem is None else \
{k: v for k, v in entries.items() if k not in full[base_stem]}
if stem + ".tbl" in files:
raise SystemExit(f"primary collision: two encodings both normalize to {stem}.tbl")
include = relative_include(stem, base_stem, shared_stems) if base_stem else None
files[stem + ".tbl"] = build_primary_body(spec.name, spec.description, include, own)
for alias in spec.aliases:
alias_fname = normalize(alias) + ".tbl"
if alias_fname == stem + ".tbl":
continue
# An alias stub must never replace a real table.
if alias_fname in primary_names:
raise SystemExit(f"alias collision: {stem}'s alias {alias_fname} is "
"another encoding's own file")
if alias_fname in alias_targets and alias_targets[alias_fname] != stem:
raise SystemExit(f"alias collision: {alias_fname} wants both "
f"{alias_targets[alias_fname]} and {stem}")
alias_targets[alias_fname] = stem
files[alias_fname] = build_alias_body(stem)
return files
def has_generated_header(path):
try:
with open(path, encoding="utf-8", newline="") as f:
return f.readline().rstrip("\n") == GENERATED_COMMENT
except (FileNotFoundError, UnicodeDecodeError):
return False
def existing_tbl_paths():
"""Every .tbl path on disk, under encodings/ and encodings/includes/."""
paths = {encodings_path(f) for f in os.listdir(encodings_path()) if f.endswith(".tbl")}
if os.path.isdir(encodings_path(INCLUDES_DIR)):
paths |= {encodings_path(INCLUDES_DIR, f)
for f in os.listdir(encodings_path(INCLUDES_DIR)) if f.endswith(".tbl")}
return paths
def check_no_hand_authored_conflicts(expected_paths, all_paths, generated_paths):
"""Exits if a wanted path is held by a file with no generated header:
never overwrite a hand-authored file."""
conflicts = sorted((expected_paths & all_paths) - generated_paths)
if not conflicts:
return
for path in conflicts:
print(f"generate_encodings.py: {path} exists but has no generated-file "
"header, so it looks hand-authored - rename it or the encoding "
"it collides with", file=sys.stderr)
sys.exit(1)
def build_expected(stems, full, bases, shared_sources):
"""Every path this script produces, mapped to its expected content:
every .tbl file plus README.md."""
shared_stems = set(shared_sources)
tbl_files = all_files(stems, full, bases, shared_stems)
tbl_files.update(build_shared_base_files(full, shared_sources, bases))
expected = {encodings_path(name): content for name, content in tbl_files.items()}
with open(README_PATH, encoding="utf-8", newline="") as f:
readme_expected = f.read()
file_encodings, generated_string = readme_rows(stems, full)
readme_expected = apply_table(readme_expected, FILE_TABLE_START, FILE_TABLE_END,
build_readme_table(file_encodings))
readme_expected = apply_table(readme_expected, GENERATED_STRING_TABLE_START, GENERATED_STRING_TABLE_END,
build_readme_table(generated_string))
expected[README_PATH] = readme_expected
return expected
def sync_files(expected, existing):
"""Compares expected {path: content} against the paths this script
already owns. Returns (missing, mismatched, extra) path lists."""
missing = sorted(set(expected) - existing)
extra = sorted(existing - set(expected))
mismatched = []
for path in sorted(set(expected) & existing):
with open(path, encoding="utf-8", newline="") as f:
current = f.read()
if current != expected[path]:
mismatched.append(path)
return missing, mismatched, extra
def sync_report(expected, missing, mismatched, extra, check):
"""In check mode, diagnoses each problem. Otherwise writes each change
and removes what is no longer expected. Either way: one line per path,
then a one-line summary. Returns whether there was anything to report."""
prefix = "generate_encodings.py --check:"
if check:
for path in sorted(missing):
print(f"{prefix} missing {path}", file=sys.stderr)
for path in sorted(mismatched):
print(f"{prefix} out of date {path}", file=sys.stderr)
for path in extra:
print(f"{prefix} unexpected {path} (not produced by generate_encodings.py)", file=sys.stderr)
else:
for path in sorted(missing):
with open(path, "w", encoding="utf-8", newline="") as f:
f.write(expected[path])
print(f"created {path}")
for path in sorted(mismatched):
with open(path, "w", encoding="utf-8", newline="") as f:
f.write(expected[path])
print(f"updated {path}")
for path in extra:
os.remove(path)
print(f"removed {path}")
total = len(missing) + len(mismatched) + len(extra)
if not total:
return False
if check:
summary = count_summary([
("missing", len(missing)),
("out of date", len(mismatched)),
("unexpected", len(extra))])
noun = "problem" if total == 1 else "problems"
print(f"{prefix} {total} {noun} ({summary})", file=sys.stderr)
else:
summary = count_summary([
("new", len(missing)),
("updated", len(mismatched)),
("removed", len(extra))])
print(f"wrote {total} files, {summary}")
return True
def count_summary(labeled_counts):
"""Joins non-zero (label, count) pairs like "2 new, 1 removed"."""
return ", ".join(f"{n} {label}" for label, n in labeled_counts if n)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--check", action="store_true",
help="verify encodings/ and README.md match, write nothing")
args = parser.parse_args()
stems, full, bases, shared_sources = build_entries()
expected = build_expected(stems, full, bases, shared_sources)
all_tbl_paths = existing_tbl_paths()
generated_paths = {p for p in all_tbl_paths if has_generated_header(p)}
check_no_hand_authored_conflicts(set(expected), all_tbl_paths, generated_paths)
existing = generated_paths | {README_PATH}
missing, mismatched, extra = sync_files(expected, existing)
prefix = "generate_encodings.py --check:" if args.check else "generate_encodings.py:"
other_problems = check_known_shared_names(full, shared_sources)
for problem in other_problems:
print(f"{prefix} {problem}", file=sys.stderr)
if not (missing or mismatched or extra or other_problems):
print(f"{len(existing)} files are up to date")
return
if not args.check:
os.makedirs(encodings_path(INCLUDES_DIR), exist_ok=True)
found_problems = sync_report(expected, missing, mismatched, extra, args.check) or other_problems
if args.check:
sys.exit(1 if found_problems else 0)
if __name__ == "__main__":
main()