synta 0.3.2

ASN.1 parser, decoder, and encoder library with DER/BER support and C FFI
Documentation
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
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
#!/usr/bin/env python3
"""
release.py — update changelogs, optionally bump version, and publish a Rust workspace.

By default the script runs in preview mode: it validates inputs, updates
changelogs and version numbers in memory, runs cargo check, and prints a
summary — but makes no commits, tags, or publishes.  Pass --do-run to
execute the release for real.

Usage:
    ./contrib/release/release.py [VERSION] [OPTIONS]

    VERSION   Version to release (default: current workspace version).
              When omitted the script releases whatever version is already
              set in [workspace.package] — no Cargo.toml changes are made.
              When supplied and different from the current version, the
              workspace version and all inter-crate dep specs are bumped.

Options:
    --do-run          Execute the release: write files, commit, tag, and publish
    --no-publish      With --do-run: commit and tag, but skip cargo publish
    --skip-ci         Skip running contrib/ci/local-ci.sh (CI assumed green)
    --no-sign         Create an unsigned annotated tag instead of a signed one
    --delay SECS      Seconds to wait between cargo publish calls for crates.io
                      index propagation (default: 30)

Crate publish order and changelog locations are read from the sibling file
'publish-order' in the same directory as this script.
"""

from __future__ import annotations

import argparse
import contextlib
import re
import subprocess
import sys
import time
import urllib.error
import urllib.request
from datetime import date, datetime, timezone
from email.utils import parsedate_to_datetime
from pathlib import Path

# ---------------------------------------------------------------------------
# Terminal colours
# ---------------------------------------------------------------------------

RED    = "\033[0;31m"
GREEN  = "\033[0;32m"
YELLOW = "\033[1;33m"
BLUE   = "\033[0;34m"
BOLD   = "\033[1m"
NC     = "\033[0m"


def _use_color() -> bool:
    import os
    return sys.stdout.isatty() and os.environ.get("NO_COLOR", "") != "1"


def _c(code: str) -> str:
    return code if _use_color() else ""


def step(msg: str) -> None:
    print(f"\n{_c(BOLD)}{_c(BLUE)}{msg}{_c(NC)}", flush=True)


def ok(msg: str) -> None:
    print(f"  {_c(GREEN)}{_c(NC)}  {msg}", flush=True)


def warn(msg: str) -> None:
    # Intentionally stdout so output stays ordered when piped.
    print(f"  {_c(YELLOW)}!{_c(NC)}  {msg}", flush=True)


def die(msg: str) -> None:
    print(f"\n{_c(RED)}error:{_c(NC)} {msg}", file=sys.stderr, flush=True)
    sys.exit(1)


def info(msg: str) -> None:
    print(f"  {msg}", flush=True)


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

def find_repo_root() -> Path:
    """Walk upward from the script location to the Cargo.toml workspace root."""
    candidate = Path(__file__).resolve().parent.parent.parent
    if (candidate / "Cargo.toml").exists():
        return candidate
    p = Path.cwd().resolve()
    while p != p.parent:
        if (p / "Cargo.toml").exists():
            return p
        p = p.parent
    die("Could not locate workspace root (no Cargo.toml found).")


def load_publish_order(script_dir: Path) -> list[tuple[str, Path]]:
    """
    Parse the 'publish-order' file next to this script.

    Returns a list of (package_name, crate_path) pairs where:
      - package_name matches [package] name in the crate's Cargo.toml
      - crate_path   is the workspace-relative Path to the crate directory

    Use "." to refer to the workspace root crate.
    Blank lines and lines starting with '#' are ignored.
    """
    order_file = script_dir / "publish-order"
    if not order_file.exists():
        order_file = Path.cwd() / "publish-order"
    if not order_file.exists():
        die(f"Publish order file not found: {order_file}")

    root = find_repo_root()
    entries: list[tuple[str, Path]] = []
    for raw in order_file.read_text().splitlines():
        line = raw.strip()
        if not line or line.startswith("#"):
            continue
        crate_path = Path(line)
        pkg_name = crate_path.name
        if not pkg_name:
            # Root crate (".") — derive package name from its Cargo.toml
            pkg_name = get_workspace_name(root / crate_path)
        entries.append((pkg_name, crate_path))

    if not entries:
        die(f"No crate entries found in {order_file}")
    return entries


def run(cmd: list[str], *, cwd: Path | None = None) -> None:
    subprocess.run(cmd, cwd=cwd, check=True)


def capture(cmd: list[str], *, cwd: Path | None = None) -> str:
    return subprocess.run(cmd, cwd=cwd, check=True, text=True,
                          capture_output=True).stdout.strip()


def confirm(prompt: str) -> bool:
    try:
        answer = input(f"\n{_c(BOLD)}{prompt}{_c(NC)} [y/N] ").strip().lower()
    except (EOFError, KeyboardInterrupt):
        print()
        return False
    return answer in ("y", "yes")


# ---------------------------------------------------------------------------
# Version helpers
# ---------------------------------------------------------------------------

_VERSION_RE = re.compile(r"^\d+\.\d+\.\d+$")


def parse_version(v: str) -> tuple[int, int, int]:
    if not _VERSION_RE.match(v):
        die(f"Invalid version '{v}'; expected MAJOR.MINOR.PATCH (e.g. 0.2.0)")
    major, minor, patch = (int(x) for x in v.split("."))
    return major, minor, patch



def get_current_version(root: Path) -> str:
    text = (root / "Cargo.toml").read_text()
    m = re.search(r'^\s*version\s*=\s*"([^"]+)"', text, re.MULTILINE)
    if not m:
        die("Could not find version = \"...\" in [workspace.package]")
    return m.group(1)


def get_workspace_name(root: Path) -> str:
    """Return the workspace name from [workspace.package] or the directory name."""
    text = (root / "Cargo.toml").read_text()
    m = re.search(r'^\s*name\s*=\s*"([^"]+)"', text, re.MULTILINE)
    return m.group(1) if m else root.name


# ---------------------------------------------------------------------------
# Commit scoring and changelog generation
# ---------------------------------------------------------------------------

def _kw_re(*keywords: str) -> re.Pattern:
    return re.compile(r'\b(?:' + '|'.join(re.escape(kw) for kw in keywords) + r')\b')


_KW_HIGH_RE = _kw_re(
    "security", "vulnerability", "critical", "breaking",
    "feat", "feature", "implement", "introduce",
    "initial", "fix", "bug", "rewrite", "redesign",
)
_KW_MED_RE = _kw_re(
    "refactor", "rework", "migrate", "remove", "delete", "deprecate",
    "add", "new",
)
_KW_LOW_RE = _kw_re(
    "perf", "optimize", "bench", "benchmark",
    "test", "tests", "spec",
)
_KW_PENALTY_RE = _kw_re(
    "whitespace", "indent", "typo", "spelling",
    "rustfmt", "clippy", "fmt", "format", "style",
    "readme", "comment", "chore", "bump", "workflow",
)
_DOC_RE  = re.compile(r'\b(docs?|documentation)\b')
_CI_RE   = re.compile(r'\b(ci|cd)\b')
_CONV_RE = re.compile(r'^(\w+)(?:\([^)]+\))?(!)?:\s+')

_SCORE_MIN = 5
_CATEGORY_ORDER = ["Security", "Added", "Changed", "Fixed", "Removed"]


def _score(subject: str, files: int, lines: int) -> int:
    subj = subject.lower()
    score = 0
    m = _CONV_RE.match(subject)
    if m and m.group(2):            # breaking change (!)
        score += 50
    if _KW_HIGH_RE.search(subj):
        score += 30
    elif _KW_MED_RE.search(subj):
        score += 15
    elif _KW_LOW_RE.search(subj):
        score += 5
    if _KW_PENALTY_RE.search(subj):
        score -= 25
    elif _DOC_RE.search(subj):
        score -= 20
    elif _CI_RE.search(subj):
        score -= 15
    if files >= 10:   score += 20
    elif files >= 5:  score += 12
    elif files >= 2:  score += 4
    if lines >= 500:  score += 20
    elif lines >= 100: score += 12
    elif lines >= 30:  score += 4
    return score


def _categorize(subject: str) -> str:
    subj = subject.lower()
    m = _CONV_RE.match(subject)
    if m:
        t = m.group(1).lower()
        if t in ("fix", "bugfix"):                 return "Fixed"
        if t in ("feat", "feature"):               return "Added"
        if t in ("refactor", "rework"):            return "Changed"
        if t in ("remove", "delete", "deprecate"): return "Removed"
        if t == "security":                        return "Security"
    if re.search(r'\b(?:fix(?:es|ed)?|bug|error|crash|broken)\b', subj):  return "Fixed"
    if re.search(r'\b(?:remov|delet|deprecat)', subj):                     return "Removed"
    if re.search(r'\b(?:security|vulnerabilit|cve)\b', subj):              return "Security"
    if re.search(r'\b(?:refactor|rework|migrat|reorgan|clean)\b', subj):   return "Changed"
    return "Added"


def _strip_pkg_prefix(subject: str, pkg_name: str) -> str:
    """Strip '<pkg-name>[/submod]: ' or '<dir>/<pkg-name>[/submod]: ' prefix."""
    pat = re.compile(
        r'^(?:[^/:]+/)?' + re.escape(pkg_name) + r'(?:/[^:]+)?:\s+',
        re.IGNORECASE,
    )
    return pat.sub('', subject)


def _subcrate_excludes(root: Path) -> list[str]:
    """
    Return git pathspec exclude tokens for every immediate sub-crate directory.

    Used when querying the workspace-root crate (".") so that commits that
    only touch synta-certificate/, synta-python/, etc. are not attributed to
    the top-level synta crate's changelog.
    """
    excludes = []
    for child in sorted(root.iterdir()):
        if child.is_dir() and (child / "Cargo.toml").exists():
            excludes.append(f":(exclude){child.name}/")
    return excludes


def _find_predecessor_paths(root: Path, rel_path: Path) -> list[Path]:
    """
    Return old directory paths that git renamed into rel_path.

    Uses the Cargo.toml inside the crate as a representative file to find
    rename records (R-status lines) in git history.  --follow works for
    individual files, so this gives us the pre-move directory root.
    """
    probe = rel_path / "Cargo.toml"
    result = subprocess.run(
        ["git", "log", "--follow", "--name-status", "--diff-filter=R",
         "--format=", "--", str(probe)],
        cwd=root, capture_output=True, text=True,
    )
    depth = len(rel_path.parts)
    predecessors: list[Path] = []
    seen: set[str] = set()
    for line in result.stdout.splitlines():
        if not line.startswith("R"):
            continue
        parts = line.split("\t")
        if len(parts) < 3:
            continue
        old_file = Path(parts[1])
        if len(old_file.parts) < depth:
            continue
        old_dir = Path(*old_file.parts[:depth])
        key = str(old_dir)
        if key not in seen and old_dir != rel_path:
            seen.add(key)
            predecessors.append(old_dir)
    return predecessors


def _git_log_commits(
    root: Path, rel_path: Path, since_ref: str | None
) -> list[tuple[str, str]]:
    """
    Return [(hash, subject)] for non-merge commits that touch rel_path,
    including any predecessor paths found via rename detection.
    """
    paths = [rel_path] + _find_predecessor_paths(root, rel_path)
    range_arg = f"{since_ref}..HEAD" if since_ref else "HEAD"
    seen_hashes: set[str] = set()
    commits: list[tuple[str, str]] = []
    for path in paths:
        # When scanning the workspace root, exclude sub-crate directories so
        # that commits touching only synta-certificate/ etc. are not attributed
        # to the top-level crate.
        exclude = _subcrate_excludes(root) if str(path) == "." else []
        result = subprocess.run(
            ["git", "log", "--no-merges", "--format=%H\t%s",
             range_arg, "--", str(path)] + exclude,
            cwd=root, capture_output=True, text=True,
        )
        for line in result.stdout.splitlines():
            if "\t" not in line:
                continue
            h, subj = line.split("\t", 1)
            h = h.strip()
            if h not in seen_hashes:
                seen_hashes.add(h)
                commits.append((h, subj.strip()))
    return commits


def _git_numstat(
    root: Path, rel_path: Path, since_ref: str | None
) -> dict[str, tuple[int, int]]:
    """
    Return {hash: (files_changed, total_lines)} for commits touching rel_path,
    including any predecessor paths found via rename detection.
    """
    paths = [rel_path] + _find_predecessor_paths(root, rel_path)
    range_arg = f"{since_ref}..HEAD" if since_ref else "HEAD"
    stats: dict[str, tuple[int, int]] = {}
    for path in paths:
        exclude = _subcrate_excludes(root) if str(path) == "." else []
        result = subprocess.run(
            ["git", "log", "--no-merges", "--numstat", "--format=__C__ %H",
             range_arg, "--", str(path)] + exclude,
            cwd=root, capture_output=True, text=True,
        )
        current: str | None = None
        files = added = removed = 0
        for line in result.stdout.splitlines():
            if line.startswith("__C__ "):
                if current is not None and current not in stats:
                    stats[current] = (files, added + removed)
                current = line[6:].strip()
                files = added = removed = 0
            elif current and "\t" in line:
                parts = line.split("\t", 2)
                if len(parts) == 3:
                    a_s, r_s, _ = parts
                    added   += int(a_s) if a_s.isdigit() else 0
                    removed += int(r_s) if r_s.isdigit() else 0
                    files   += 1
        if current is not None and current not in stats:
            stats[current] = (files, added + removed)
    return stats


def generate_changelog_entries(
    root: Path, crate_rel_path: Path, pkg_name: str, since_ref: str | None
) -> dict[str, list[str]]:
    """Return {category: [bullet, ...]} for commits that score >= _SCORE_MIN."""
    commits = _git_log_commits(root, crate_rel_path, since_ref)
    if not commits:
        return {}
    numstat = _git_numstat(root, crate_rel_path, since_ref)

    entries: dict[str, list[str]] = {}
    seen: set[str] = set()
    for h, subject in commits:
        files, lines = numstat.get(h, (0, 0))
        if _score(subject, files, lines) < _SCORE_MIN:
            continue
        clean = _strip_pkg_prefix(subject, pkg_name)
        clean = _CONV_RE.sub('', clean)      # strip "feat: " / "fix(scope): "
        clean = clean[:1].upper() + clean[1:] if clean else clean
        if not clean or clean in seen:
            continue
        seen.add(clean)
        cat = _categorize(subject)
        entries.setdefault(cat, []).append(clean)
    return entries


def format_changelog_body(entries: dict[str, list[str]]) -> str:
    """Format categorized entries as Keep-a-Changelog ### sections."""
    lines: list[str] = []
    for cat in _CATEGORY_ORDER:
        if cat not in entries:
            continue
        lines += [f"### {cat}", ""]
        lines += [f"- {b}" for b in entries[cat]]
        lines.append("")
    return "\n".join(lines).rstrip("\n") + "\n" if lines else ""


def _fill_section_body(text: str, header_pat: re.Pattern, new_body: str) -> str:
    """
    Replace the body of the first section matched by header_pat with new_body.
    The section runs from the line after the header to the next '## ' or EOF.
    """
    m = header_pat.search(text)
    if m is None:
        return text
    pos = m.end()                   # right after the header line (past its \n)
    nxt = text.find('\n## ', pos)
    body_end = nxt if nxt >= 0 else len(text)
    return text[:pos] + "\n" + new_body.rstrip("\n") + "\n" + text[body_end:]


# ---------------------------------------------------------------------------
# File mutation helpers
# ---------------------------------------------------------------------------

def bump_crate_spec_versions(root: Path, new_version: str) -> list[Path]:
    """
    Update the Version: field in all packaging spec files:

    - rust2rpm-generated rust-synta*.spec in each crate directory
    - hand-maintained *.spec.in templates under contrib/packages/
      (synta.spec.in, python3-synta.spec.in)

    Returns the list of changed files.
    """
    changed: list[Path] = []

    for spec in sorted(root.glob("**/rust-synta*.spec")):
        if any(part in ("target", ".cargo", "vendor") for part in spec.parts):
            continue
        text = spec.read_text()
        new_text = re.sub(
            r'^(Version:\s*)\S+',
            lambda m: m.group(1) + new_version,
            text,
            count=1,
            flags=re.MULTILINE,
        )
        if new_text != text:
            spec.write_text(new_text)
            changed.append(spec)

    packages_dir = root / "contrib" / "packages"
    if packages_dir.is_dir():
        for spec_in in sorted(packages_dir.glob("*.spec.in")):
            text = spec_in.read_text()
            new_text = re.sub(
                r'^(Version:\s*)\S+',
                lambda m: m.group(1) + new_version,
                text,
                count=1,
                flags=re.MULTILINE,
            )
            if new_text != text:
                spec_in.write_text(new_text)
                changed.append(spec_in)

    return changed


def bump_workspace_version(root: Path, old: str, new: str) -> None:
    path = root / "Cargo.toml"
    text = path.read_text()
    new_text = re.sub(
        r'^(\s*version\s*=\s*)"' + re.escape(old) + r'"',
        lambda m: m.group(1) + f'"{new}"',
        text,
        count=1,
        flags=re.MULTILINE,
    )
    if new_text == text:
        die(f"Could not replace version '{old}' in Cargo.toml")
    path.write_text(new_text)


def _get_workspace_member_dirs(root: Path) -> list[Path]:
    """Parse [workspace.members] and return all non-root member relative paths."""
    text = (root / "Cargo.toml").read_text()
    m = re.search(r'members\s*=\s*\[([^\]]+)\]', text, re.DOTALL)
    if not m:
        return []
    paths = []
    for raw in re.findall(r'"([^"]+)"', m.group(1)):
        if raw and raw != ".":
            paths.append(Path(raw))
    return paths


def bump_crate_package_versions(
    root: Path, publish_order: list[tuple[str, Path]], new: str
) -> list[Path]:
    """
    Update the [package] version field in ALL workspace member crates' Cargo.toml.

    Covers every crate in [workspace.members], not just those in publish_order,
    so that internal-only crates (e.g. synta-python-common) stay version-consistent
    with the rest of the workspace and cargo check does not fail.

    Uses count=1 so that only the first 'version = "..."' line is replaced,
    which is always the [package] version (dependency version specs come later
    in the file and are handled separately by bump_dep_version_specs).

    Returns the list of files that were changed.
    """
    # Build the ordered list: publish_order members first, then any workspace
    # members that are not in publish_order (e.g. internal rlib helpers).
    order_paths = {str(rel_path) for _, rel_path in publish_order}
    all_paths = [rel_path for _, rel_path in publish_order if str(rel_path) != "."]
    for mp in _get_workspace_member_dirs(root):
        if str(mp) not in order_paths:
            all_paths.append(mp)

    changed: list[Path] = []
    for rel_path in all_paths:
        toml = root / rel_path / "Cargo.toml"
        if not toml.exists():
            continue
        text = toml.read_text()
        new_text = re.sub(
            r'^(\s*version\s*=\s*)"[^"]*"',
            lambda m: m.group(1) + f'"{new}"',
            text,
            count=1,
            flags=re.MULTILINE,
        )
        if new_text != text:
            toml.write_text(new_text)
            changed.append(toml)
    return changed


def bump_dep_version_specs(root: Path, new_version: str) -> list[Path]:
    """
    Update version specs for workspace-internal crate deps in every Cargo.toml.

    Handles both inline format:
        synta = { path = "..", version = "0.1.0" }
    and multi-line section format:
        [dev-dependencies.synta-certificate]
        path    = "../synta-certificate"
        version = "0.1.2"

    A dep is considered workspace-internal when its path starts with '.' (i.e.
    it is a relative path pointing inside the workspace).  The version spec is
    set to new_version regardless of its previous value, so patch-level bumps
    (0.1.2 → 0.1.3) are handled correctly even though the Cargo semver spec
    ('0.1') remains the same.

    Also updates pyproject.toml [project] version if the file exists.

    Returns the list of changed files.
    """
    _INLINE_WS_PATH = re.compile(r'\bpath\s*=\s*"\.[^"]*"')
    _VER_SUB = re.compile(r'(\bversion\s*=\s*)"[^"]*"')

    changed: list[Path] = []

    for toml in sorted(root.rglob("Cargo.toml")):
        if any(part in ("target", ".cargo", "vendor") for part in toml.parts):
            continue
        text = toml.read_text()
        lines = text.splitlines(keepends=True)
        new_lines: list[str] = []
        in_ws_section = False   # inside a [dep.crate-name] section with ws path
        modified = False

        for line in lines:
            # Any section header resets the multi-line-section state.
            if re.match(r'^\s*\[', line):
                in_ws_section = False

            if _INLINE_WS_PATH.search(line):
                # Inline dep: path and version on the same line.
                new_line = _VER_SUB.sub(
                    lambda m: m.group(1) + f'"{new_version}"', line
                )
                if new_line != line:
                    modified = True
                line = new_line
                in_ws_section = True   # version may also appear on next line

            elif re.match(r'^\s*path\s*=\s*"\.[^"]*"', line):
                # Multi-line section: path= on its own line.
                in_ws_section = True

            elif in_ws_section and re.match(r'^\s*version\s*=\s*"', line):
                # Multi-line section: version= line after a workspace path.
                new_line = _VER_SUB.sub(
                    lambda m: m.group(1) + f'"{new_version}"', line
                )
                if new_line != line:
                    modified = True
                line = new_line

            new_lines.append(line)

        if modified:
            toml.write_text("".join(new_lines))
            changed.append(toml)

    # Keep all pyproject.toml [project] versions in sync with the workspace.
    for pyproject in sorted(root.rglob("pyproject.toml")):
        if any(part in ("target", ".cargo", "vendor") for part in pyproject.parts):
            continue
        text = pyproject.read_text()
        new_text = re.sub(
            r'^(\s*version\s*=\s*)"[^"]*"',
            lambda m: m.group(1) + f'"{new_version}"',
            text, count=1, flags=re.MULTILINE,
        )
        if new_text != text:
            pyproject.write_text(new_text)
            changed.append(pyproject)

    return changed


def update_changelog(
    path: Path,
    new_version: str,
    today: str,
    root: Path,
    crate_rel_path: Path,
    pkg_name: str,
    since_ref: str | None,
) -> str:
    """
    Generate changelog entries from git history, then either:
      - Rename [Unreleased] → [new_version] — today and fill its body, or
      - Fill the body of an existing [new_version] section.

    Returns "renamed" | "filled" | "up_to_date" | "no_unreleased" | "missing".
    """
    if not path.exists():
        return "missing"

    entries = generate_changelog_entries(root, crate_rel_path, pkg_name, since_ref)
    body = format_changelog_body(entries) if entries else ""

    text = path.read_text()
    unreleased_pat = re.compile(r"^##\s+\[[Uu]nreleased\][^\n]*\n", re.MULTILINE)
    versioned_pat  = re.compile(
        r"^##\s+\[" + re.escape(new_version) + r"\][^\n]*\n", re.MULTILINE
    )

    # Check for an existing [VERSION] section first.  If it is already present
    # and non-empty, leave it untouched — the author has written a human-friendly
    # summary and we must not overwrite it with auto-generated bullets.
    # Only fill the body when the section exists but is completely empty
    # (e.g. a placeholder added manually before the release).
    if versioned_pat.search(text):
        m = versioned_pat.search(text)
        pos = m.end()
        nxt = text.find('\n## ', pos)
        existing_body = text[pos: nxt if nxt >= 0 else len(text)].strip()
        if not existing_body and body:
            new_text = _fill_section_body(text, versioned_pat, body)
            if new_text != text:
                path.write_text(new_text)
                return "filled"
        return "up_to_date"

    if unreleased_pat.search(text):
        m = unreleased_pat.search(text)
        pos = m.end()
        nxt = text.find('\n## ', pos)
        existing_body = text[pos: nxt if nxt >= 0 else len(text)].strip()
        if not existing_body and body:
            # Only overwrite with auto-generated bullets when the section is
            # blank; otherwise the author's human-friendly prose is preserved.
            text = _fill_section_body(text, unreleased_pat, body)
        # Rename [Unreleased] → [new_version] — today
        new_header = f"## [{new_version}] — {today}\n"
        text = unreleased_pat.sub(new_header, text, count=1)
        # Prepend a fresh empty [Unreleased] section
        text = text.replace(new_header, f"## [Unreleased]\n\n\n{new_header}", 1)
        path.write_text(text)
        return "renamed"

    return "no_unreleased"


# ---------------------------------------------------------------------------
# Git helpers
# ---------------------------------------------------------------------------

def find_last_tag(root: Path) -> str | None:
    """Return the most recent annotated/lightweight tag, or None if none exist."""
    result = subprocess.run(
        ["git", "describe", "--tags", "--abbrev=0"],
        cwd=root, capture_output=True, text=True,
    )
    return result.stdout.strip() if result.returncode == 0 else None

def assert_clean_tree(root: Path) -> None:
    # Only tracked changes (M, A, D, R, C, U) matter for the release commit.
    # Untracked files (??) and ignored files (!!) do not affect what gets
    # committed or published, so we skip them.
    status = capture(["git", "status", "--porcelain"], cwd=root)
    tracked = [l for l in status.splitlines() if not l.startswith("??") and not l.startswith("!!")]
    if tracked:
        die(
            "Working tree has uncommitted changes.\n"
            "  Commit or stash them before running release.py.\n"
            + "\n".join(tracked)
        )


def git_commit(root: Path, version: str, files: list[Path]) -> bool:
    """Stage files and commit. Returns True if a commit was made, False if nothing changed."""
    run(["git", "add", "--"] + [str(f) for f in files], cwd=root)
    lock = root / "Cargo.lock"
    if lock.exists():
        run(["git", "add", str(lock)], cwd=root)
    staged = capture(["git", "diff", "--cached", "--name-only"], cwd=root)
    if not staged:
        return False
    run(["git", "commit", "-s", "-m", f"release: v{version}"], cwd=root)
    return True


def tag_exists(root: Path, version: str) -> bool:
    result = subprocess.run(
        ["git", "tag", "-l", f"v{version}"],
        cwd=root, capture_output=True, text=True,
    )
    return bool(result.stdout.strip())


def git_tag(root: Path, version: str, *, sign: bool) -> None:
    tag = f"v{version}"
    flag = "-s" if sign else "-a"
    run(["git", "tag", flag, tag, "-m", f"Release {tag}"], cwd=root)


# ---------------------------------------------------------------------------
# Cargo helpers
# ---------------------------------------------------------------------------

def crate_published(pkg: str, version: str) -> bool:
    """Return True if pkg@version is already visible on crates.io."""
    url = f"https://crates.io/api/v1/crates/{pkg}/{version}"
    req = urllib.request.Request(url, headers={"User-Agent": "release.py/1 (crate publish check)"})
    try:
        urllib.request.urlopen(req, timeout=15)
        return True
    except urllib.error.HTTPError as e:
        if e.code == 404:
            return False
        raise
    except urllib.error.URLError:
        return False


def cargo_publish_dry_run(root: Path, pkg: str) -> bool:
    with _no_dev_deps(root, pkg):
        result = subprocess.run(
            ["cargo", "publish", "--dry-run", "--allow-dirty", "--registry", "crates-io", "-p", pkg],
            cwd=root, check=False,
        )
        return result.returncode == 0


_RATE_LIMIT_RE = re.compile(
    r"Please try again after\s+([A-Za-z]+,\s+\d+\s+[A-Za-z]+\s+\d+\s+[\d:]+\s+GMT)",
    re.IGNORECASE,
)
_MAX_RATE_RETRIES = 3

_DEV_DEPS_RE = re.compile(
    r'\n\[dev-dependencies\].*?(?=\n\[|\Z)',
    re.DOTALL,
)


def _crate_manifest(root: Path, pkg: str) -> Path:
    """Return the Cargo.toml path for the named workspace member."""
    candidate = root / pkg / "Cargo.toml"
    if candidate.exists():
        return candidate
    return root / "Cargo.toml"


@contextlib.contextmanager
def _no_dev_deps(root: Path, pkg: str):
    """
    Temporarily strip [dev-dependencies] from the crate's Cargo.toml.

    cargo package (called internally by cargo publish) resolves ALL
    dependencies including dev-deps, even though they are stripped from the
    published Cargo.toml.  When workspace-member dev-deps haven't been
    published yet (e.g. synta → synta-certificate circular order), cargo
    fails during the packaging step.  Stripping [dev-dependencies] before
    packaging and restoring it after breaks the cycle safely.
    """
    manifest = _crate_manifest(root, pkg)
    original = manifest.read_text()
    patched = _DEV_DEPS_RE.sub('', original)
    if patched == original:
        yield
        return
    manifest.write_text(patched)
    try:
        yield
    finally:
        manifest.write_text(original)


def cargo_publish_one(root: Path, pkg: str) -> None:
    """
    Run cargo publish for a single package, retrying automatically on 429.

    Parses 'Please try again after <RFC 2822 date>' from cargo's output and
    sleeps until that moment before retrying.  Gives up after _MAX_RATE_RETRIES
    attempts and re-raises the last error.
    """
    with _no_dev_deps(root, pkg):
        for attempt in range(1, _MAX_RATE_RETRIES + 1):
            result = subprocess.run(
                ["cargo", "publish", "--allow-dirty",
                 "--registry", "crates-io", "-p", pkg],
                cwd=root, stderr=subprocess.PIPE, text=True,
            )
            if result.returncode == 0:
                return

            stderr = result.stderr
            print(stderr, end="", flush=True)   # show cargo's output as usual

            m = _RATE_LIMIT_RE.search(stderr)
            if m and attempt < _MAX_RATE_RETRIES:
                retry_after_str = m.group(1)
                try:
                    retry_at = parsedate_to_datetime(retry_after_str)
                except Exception:
                    retry_at = None

                now = datetime.now(timezone.utc)
                if retry_at and retry_at > now:
                    wait_secs = int((retry_at - now).total_seconds()) + 5
                else:
                    wait_secs = 60

                warn(f"Rate-limited by crates.io; waiting {wait_secs}s before retry "
                     f"({attempt}/{_MAX_RATE_RETRIES})")
                _sleep_with_dots(wait_secs)
                continue

            # Non-recoverable error or retries exhausted
            raise subprocess.CalledProcessError(result.returncode,
                                                ["cargo", "publish", "-p", pkg])


def _sleep_with_dots(seconds: int) -> None:
    print(f"  Sleeping {seconds}s", end="", flush=True)
    for _ in range(0, seconds, 5):
        time.sleep(min(5, seconds))
        print(".", end="", flush=True)
    print(flush=True)


def wait_for_propagation(seconds: int, pkg: str) -> None:
    print(f"  Waiting {seconds}s for crates.io to index {pkg}", end="", flush=True)
    for remaining in range(seconds, 0, -5):
        time.sleep(min(5, remaining))
        print(".", end="", flush=True)
    print()


# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------

def parse_args() -> argparse.Namespace:
    p = argparse.ArgumentParser(
        description="Two-phase release tool: prepare (changelog+tag) then publish to crates.io.",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=(
            "Typical release flow:\n"
            "\n"
            "  Phase 1 — prepare (on release branch):\n"
            "  %(prog)s               # preview: inspect changelog + version changes\n"
            "  %(prog)s 0.2.0         # preview: bump to 0.2.0\n"
            "  %(prog)s --do-run      # commit changelogs + tag; print push instructions\n"
            "  %(prog)s --do-run 0.2.0             # bump version, commit, tag\n"
            "  %(prog)s --do-run --skip-ci          # skip local-ci.sh\n"
            "\n"
            "  Phase 2 — publish (on main, after PR merge):\n"
            "  %(prog)s --publish-only              # preview: show what would be published\n"
            "  %(prog)s --do-run --publish-only     # publish all crates to crates.io\n"
        ),
    )
    p.add_argument("version", nargs="?", default=None,
                   help="Version to release (default: current workspace version)")
    p.add_argument("--do-run",       action="store_true",
                   help="Execute the phase (default: preview only)")
    p.add_argument("--publish-only", action="store_true",
                   help="Phase 2: skip prepare, publish crates to crates.io. "
                        "Run on main after the release PR has been merged and pulled.")
    p.add_argument("--skip-ci",      action="store_true",
                   help="Phase 1: skip running local-ci.sh all")
    p.add_argument("--no-sign",      action="store_true",
                   help="Phase 1: create an unsigned annotated tag (when GPG unavailable)")
    p.add_argument("--delay", type=int, default=30, metavar="SECS",
                   help="Phase 2: seconds between cargo publish calls (default: 30)")
    return p.parse_args()


def _do_publish(
    root: Path,
    publish_order: list[tuple[str, Path]],
    new_version: str,
    workspace_name: str,
    delay: int,
) -> None:
    """Publish all crates in order, skipping those already on crates.io."""
    step(f"Publishing {len(publish_order)} crates to crates.io")
    for i, (pkg, _) in enumerate(publish_order):
        prefix = f"[{i + 1}/{len(publish_order)}]"
        if crate_published(pkg, new_version):
            ok(f"{prefix} {pkg} v{new_version} already on crates.io — skipping")
            continue
        info(f"{prefix} cargo publish -p {pkg}")
        cargo_publish_one(root, pkg)
        ok(f"{pkg} published")
        if i < len(publish_order) - 1:
            wait_for_propagation(delay, pkg)

    step("Release complete")
    ok(f"{workspace_name} v{new_version} is live on crates.io")


def main() -> None:
    args = parse_args()

    script_dir = Path(__file__).resolve().parent
    root = find_repo_root()
    today = date.today().isoformat()
    workspace_name = get_workspace_name(root)

    publish_order = load_publish_order(script_dir)

    # ── Pre-flight (both phases) ──────────────────────────────────────────────
    step("Pre-flight checks")

    assert_clean_tree(root)
    ok("Working tree is clean")

    branch = capture(["git", "rev-parse", "--abbrev-ref", "HEAD"], cwd=root)
    if branch in ("main", "master"):
        ok(f"On branch {branch}")
    else:
        warn(f"Current branch is '{branch}', not main/master — proceed with caution")

    old_version = get_current_version(root)
    new_version = args.version if args.version is not None else old_version
    if args.version is not None:
        parse_version(new_version)  # validate format

    for pkg, rel_path in publish_order:
        if not (root / rel_path).is_dir():
            die(f"Crate path not found: {rel_path} (package '{pkg}')")
    ok(f"{len(publish_order)} crates verified from publish-order")

    # ═════════════════════════════════════════════════════════════════════════
    # Phase 2 — publish-only
    # ═════════════════════════════════════════════════════════════════════════
    if args.publish_only:
        if branch not in ("main", "master"):
            die(f"--publish-only must run on main/master (currently on '{branch}'). "
                "Pull main after the PR is merged, then retry.")

        if not tag_exists(root, new_version):
            die(f"Tag v{new_version} not found — run the prepare phase first "
                "(release.py --do-run), push the tag, merge the PR, then retry.")
        ok(f"Tag v{new_version} confirmed")

        step("Summary")
        info(f"  Version : {new_version}")
        info(f"  Crates  : {', '.join(p for p, _ in publish_order)}")
        info(f"  Delay   : {args.delay}s between publishes")

        # In preview mode, run a dry-run publish check as a safety net.
        if not args.do_run:
            step(f"Verifying {publish_order[0][0]} with cargo publish --dry-run")
            if cargo_publish_dry_run(root, publish_order[0][0]):
                ok(f"{publish_order[0][0]}: dry-run publish succeeded")
            else:
                die(f"{publish_order[0][0]}: dry-run publish failed — fix before publishing")
            print(f"\n{_c(YELLOW)}Preview only — re-run with --do-run to publish.{_c(NC)}")
            sys.exit(0)

        if not confirm(f"Publish {workspace_name} v{new_version} to crates.io?"):
            print("Aborted.")
            sys.exit(1)

        _do_publish(root, publish_order, new_version, workspace_name, args.delay)
        return

    # ═════════════════════════════════════════════════════════════════════════
    # Phase 1 — prepare: changelogs, version bump, check, CI, tag
    # ═════════════════════════════════════════════════════════════════════════
    bumping = (new_version != old_version)

    if bumping:
        ok(f"Version: {old_version}{new_version}")
    else:
        ok(f"Releasing current version {new_version} (no version bump)")

    # ── Find git range for changelog generation ───────────────────────────────
    since_ref = find_last_tag(root)
    if since_ref:
        ok(f"Changelog range: {since_ref}..HEAD")
    else:
        ok("No previous tag — changelog will use full history")

    # ── Changelog update ──────────────────────────────────────────────────────
    step("Updating changelogs")

    cl_statuses: dict[Path, str] = {}
    for pkg, rel_path in publish_order:
        cl_path = root / rel_path / "CHANGELOG.md"
        status = update_changelog(
            cl_path, new_version, today,
            root, rel_path, pkg, since_ref,
        )
        cl_statuses[cl_path] = status
        rel = cl_path.relative_to(root)
        if status == "renamed":
            ok(f"{rel}: [Unreleased] → [{new_version}] — {today}")
        elif status == "filled":
            ok(f"{rel}: [{new_version}] body generated from git history")
        elif status == "up_to_date":
            ok(f"{rel}: [{new_version}] body already up to date")
        elif status == "no_unreleased":
            warn(f"{rel}: no [Unreleased] or [{new_version}] section — skipping")
        elif status == "missing":
            warn(f"{rel}: CHANGELOG.md not found")

    renamed = [p for p, s in cl_statuses.items() if s in ("renamed", "filled")]
    if not renamed:
        info("No changelogs updated")

    # ── Version bump ──────────────────────────────────────────────────────────
    if bumping:
        step("Bumping version")

        bump_workspace_version(root, old_version, new_version)
        ok(f"Cargo.toml: version = \"{new_version}\"")

        crate_tomls = bump_crate_package_versions(root, publish_order, new_version)
        for p in crate_tomls:
            ok(f"{p.relative_to(root)}: [package] version → \"{new_version}\"")

        dep_tomls = bump_dep_version_specs(root, new_version)
        if dep_tomls:
            for p in dep_tomls:
                ok(f"{p.relative_to(root)}: dep version specs → \"{new_version}\"")

        all_specs = bump_crate_spec_versions(root, new_version)
        for p in all_specs:
            ok(f"{p.relative_to(root)}: Version: → \"{new_version}\"")

        changed_tomls = crate_tomls + dep_tomls + all_specs
    else:
        changed_tomls = []

    # ── cargo check ───────────────────────────────────────────────────────────
    step("Running cargo check --workspace")
    run(["cargo", "check", "--workspace"], cwd=root)
    ok("cargo check passed")

    # ── CI ────────────────────────────────────────────────────────────────────
    if not args.skip_ci:
        step("Running local-ci.sh all")
        try:
            run(["bash", str(root / "contrib" / "ci" / "local-ci.sh"),
                 "--no-deps", "all"], cwd=root)
        except subprocess.CalledProcessError:
            die("CI failed — fix the failing jobs before releasing\n"
                "  Re-run with --skip-ci to bypass once CI is known green")
        ok("CI passed")
    else:
        warn("Skipping CI (--skip-ci)")

    # ── Dry-run publish check ─────────────────────────────────────────────────
    step(f"Verifying {publish_order[0][0]} with cargo publish --dry-run")
    if cargo_publish_dry_run(root, publish_order[0][0]):
        ok(f"{publish_order[0][0]}: dry-run publish succeeded")
    else:
        die(f"{publish_order[0][0]}: dry-run publish failed — fix before releasing")

    # ── Summary ───────────────────────────────────────────────────────────────
    commit_files = (
        ([root / "Cargo.toml"] if bumping else [])
        + changed_tomls
        + renamed
    )

    already_tagged = tag_exists(root, new_version)

    step("Summary")
    info(f"  Version   : {new_version}" + (f"  (bumped from {old_version})" if bumping else "  (no bump)"))
    info(f"  Date      : {today}")
    if already_tagged:
        info(f"  Tag       : v{new_version}  (already exists — will skip)")
    else:
        info(f"  Tag       : v{new_version}  ({'signed' if not args.no_sign else 'unsigned annotated'})")
    info(f"  Changelogs: {len(renamed)}/{len(publish_order)} updated")
    info(f"  Commit    : {'yes — ' + str(len(commit_files)) + ' file(s)' if commit_files else 'none (tag HEAD directly)'}")
    info(f"  Crates    : {', '.join(p for p, _ in publish_order)}")

    if not args.do_run:
        print(f"\n{_c(YELLOW)}Preview only — re-run with --do-run to commit and tag.{_c(NC)}")
        if bumping or renamed:
            print("  Inspect pending changes with:  git diff")
        sys.exit(0)

    # ── Confirm ───────────────────────────────────────────────────────────────
    if not confirm(f"Commit changelogs and tag v{new_version}?"):
        print("Aborted. Working-tree changes are preserved.")
        sys.exit(1)

    # ── Commit + tag ──────────────────────────────────────────────────────────
    step("Committing and tagging")
    if commit_files:
        if git_commit(root, new_version, commit_files):
            ok(f"Committed: release: v{new_version}")
        else:
            ok("Changelogs already up to date — tagging current HEAD")
    else:
        ok("No file changes — tagging current HEAD")

    if already_tagged:
        warn(f"Tag v{new_version} already exists — skipping")
    else:
        try:
            git_tag(root, new_version, sign=not args.no_sign)
        except subprocess.CalledProcessError:
            die(
                f"Failed to create tag v{new_version}.\n"
                "  If GPG signing failed (expired key or no pinentry), retry with:\n"
                f"    release.py --do-run --no-sign"
            )
        ok(f"Tagged: v{new_version}")

    step("Prepare complete — next steps")
    info(f"  1. Push the branch and tag:")
    info(f"       git push origin {branch} --tags")
    info(f"  2. Open a pull request and wait for it to be merged.")
    info(f"  3. Pull main locally:")
    info(f"       git checkout main && git pull")
    info(f"  4. Publish to crates.io:")
    info(f"       release.py --do-run --publish-only")


if __name__ == "__main__":
    main()