Repository navigation
Expand file tree
/
Copy pathrelease.py
More file actions
executable file
·1765 lines (1592 loc) · 77.4 KB
/
Copy pathrelease.py
File metadata and controls
executable file
·1765 lines (1592 loc) · 77.4 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
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
#!/usr/bin/env python3
"""release.py — cut a new SpliceCraft release.
Usage: ./release.py 0.8.7
./release.py --bioconda-only # re-submit current recipe
Pure-Python replacement for the old release.sh. Same seven steps, same
ordering, same abort-on-failure semantics:
1. Bumps the version in BOTH pyproject.toml and splicecraft.py.
2. Runs the test suite (aborts on any failure).
3. Builds the package locally (aborts if twine check fails).
4. Syncs `conda-recipe/meta.yaml` (version + sha256 + run-deps) from
the just-built sdist + pyproject — keeps the in-repo recipe in
lockstep with PyPI so a bioconda PR is one click away.
5. Bundles ALL accumulated working-tree changes (version bump +
anything else the user has iterated on since the last release)
into a single ``Release v<version>`` commit, tags v<version>,
and pushes — then creates a GitHub Release for the tag (changelog
section as the body + the built wheel/sdist as assets; optional +
non-fatal, skipped cleanly when `gh` is absent/unauthed).
6. GitHub Actions (publish.yml) builds + uploads to PyPI from the tag.
7. Polls PyPI until the sdist is hosted, then forks
bioconda-recipes (if needed) and opens a PR with the recipe
update so end users can `conda install -c bioconda splicecraft`.
Sweep #18 (2026-05-21): the working tree no longer needs to be
clean before release. release.py prints a summary of pending
changes, then ``git add -A``'s them into the release commit. This
keeps the iteration cycle tight — the user accumulates work in the
tree and ships it all at release time instead of paying a commit
toll on every change. `.gitignore` is still in effect, so build
artefacts / caches / logs stay out of the release commit.
Prereqs (one-time, see README):
- Trusted Publishing configured at pypi.org for this project.
- `gh` CLI authenticated (`gh auth status`) — needed for the
bioconda fork + PR step. Skipped with a note if missing.
Aborts at the first error — every shelled-out step uses ``check=True`` so
a failed test / build / push raises ``CalledProcessError`` and the script
exits non-zero before tagging or pushing. Mirrors the old script's
``set -euo pipefail`` guarantee.
The whole thing takes ~2 minutes from run to "live on PyPI".
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
from pathlib import Path
from typing import NoReturn
REPO_ROOT = Path(__file__).resolve().parent
PYPROJECT = REPO_ROOT / "pyproject.toml"
SPLICECRAFT = REPO_ROOT / "splicecraft.py"
# The Claude Code plugin manifests. This repo doubles as a plugin marketplace
# (`claude plugin marketplace add Binomica-Labs/SpliceCraft`), and the plugin
# version is what `claude plugin update` compares against — leave it behind and
# installed copies never see an update.
PLUGIN_MANIFEST = REPO_ROOT / "plugin" / ".claude-plugin" / "plugin.json"
MARKETPLACE_MANIFEST = REPO_ROOT / ".claude-plugin" / "marketplace.json"
PLUGIN_SKILL = REPO_ROOT / "plugin" / "skills" / "splicecraft" / "SKILL.md"
CHANGELOG = REPO_ROOT / "CHANGELOG.md"
CONDA_RECIPE = REPO_ROOT / "conda-recipe" / "meta.yaml"
CITATION_CFF = REPO_ROOT / "CITATION.cff"
ZENODO_JSON = REPO_ROOT / ".zenodo.json"
# Upstream bioconda repository — the canonical channel every
# `conda install -c bioconda <pkg>` user pulls from. The release flow
# forks this into the maintainer's account, pushes a branch with the
# updated recipe, and opens a PR against this upstream repo. Once
# merged by a bioconda maintainer, bioconda's CI builds the package
# and uploads to anaconda.org/bioconda — that's how the recipe
# actually reaches end users.
BIOCONDA_UPSTREAM = "bioconda/bioconda-recipes"
BIOCONDA_RECIPE_SUBPATH = "recipes/splicecraft/meta.yaml"
PYPI_SDIST_URL_TPL = (
"https://pypi.io/packages/source/s/splicecraft/"
"splicecraft-{version}.tar.gz"
)
# Accept canonical X.Y.Z plus PEP-440 suffixes (rc1, post1, dev0, …).
_VERSION_RE = re.compile(r"^\d+\.\d+\.\d+([a-z0-9.-]*)?$")
# In-file regexes for the version bump. Both files live at the repo
# root; the regexes target the canonical lines that release.sh used to
# rewrite with `sed -i -E`.
_PYPROJECT_VERSION_RE = re.compile(
r'^(version\s*=\s*)"[^"]+"', re.MULTILINE,
)
_SPLICECRAFT_VERSION_RE = re.compile(
r'^(__version__\s*=\s*)"[^"]+"', re.MULTILINE,
)
# `"version": "X.Y.Z"` inside .claude-plugin/plugin.json (JSON, so the
# separator is a colon and the key is quoted).
_PLUGIN_VERSION_RE = re.compile(
r'^(\s*"version"\s*:\s*)"[^"]+"', re.MULTILINE,
)
# Citation metadata (the Zenodo DOI record + GitHub's "Cite this repository"
# button). Three files carry the version / release date and MUST move together
# with the bump above, or the archived record cites the wrong release:
# * CITATION.cff — `version:` + `date-released:` (YAML, unquoted / quoted)
# * .zenodo.json — `"version"` (JSON)
# * splicecraft.py — `_RELEASE_DATE` (drives the year in `--citation`)
# `^version:` is anchored so it can't match `cff-version:` on the line above.
_CFF_VERSION_RE = re.compile(r"^(version:\s*).+$", re.MULTILINE)
_CFF_DATE_RE = re.compile(r"^(date-released:\s*).+$", re.MULTILINE)
_ZENODO_VERSION_RE = re.compile(r'^(\s*"version"\s*:\s*)"[^"]*"', re.MULTILINE)
_RELEASE_DATE_RE = re.compile(r'^(_RELEASE_DATE\s*=\s*)"[^"]*"', re.MULTILINE)
# conda-recipe/meta.yaml uses jinja2-style `{% set version = "..." %}`
# at the top and a `sha256: <hex>` line under `source:`. The run-deps
# block under `requirements:` is a YAML list we rewrite wholesale from
# pyproject's `[project] dependencies` so the two never drift.
_CONDA_VERSION_RE = re.compile(
r'(\{%\s*set\s+version\s*=\s*)"[^"]+"(\s*%\})'
)
_CONDA_SHA256_RE = re.compile(
r'^(\s*sha256:\s*)[0-9a-fA-F]{64}', re.MULTILINE,
)
# ` run:` followed by one or more ` - <name> ...` list items, up to
# the next less-indented line. Captures the whole block for replacement.
_CONDA_RUN_BLOCK_RE = re.compile(
r"^ run:\n(?: -.*\n)+", re.MULTILINE,
)
# Match a single "package>=X.Y.Z" or "package" line inside pyproject's
# `dependencies = [ ... ]` array (PEP 621).
_PYPROJECT_DEPS_BLOCK_RE = re.compile(
r"^dependencies\s*=\s*\[\s*\n(.*?)^\]",
re.MULTILINE | re.DOTALL,
)
_PEP440_SPEC_RE = re.compile(r"^([A-Za-z0-9._-]+)\s*(.*)$")
def _heading(msg: str) -> None:
print(f"── {msg} ──", flush=True)
def _die(msg: str, code: int = 1) -> NoReturn:
print(f"Error: {msg}", file=sys.stderr)
sys.exit(code)
def _run(cmd: list[str], **kwargs) -> subprocess.CompletedProcess:
"""Run *cmd* with ``check=True`` so any non-zero exit aborts the
release. We deliberately do not capture stdout/stderr — the user
needs to see pytest / twine / git output as it streams."""
return subprocess.run(cmd, check=True, **kwargs)
def _upgrade_pyright() -> None:
"""Pull the newest pyright BEFORE the type-check runs.
``PYRIGHT_PYTHON_FORCE_VERSION=latest`` already makes the pyright BINARY
match the one CI resolves, but the pip *wrapper* stays pinned wherever it
was installed and prints "there is a new pyright version available" on
every single run — noise that trains you to skim past pyright's output,
which is the failure mode the gate exists to prevent. Upgrading first
means the checker that clears the release is the current one, and a
genuinely quiet run stays meaningful.
**Non-fatal by design.** Releasing offline has to work, so a failed
upgrade warns and the installed wrapper is used — the type-check itself
still runs and still gates. Set ``SPLICECRAFT_SKIP_PYRIGHT_UPGRADE=1`` to
skip the network round-trip entirely (a pinned or air-gapped env);
``SPLICECRAFT_SKIP_PYRIGHT=1`` skips this too, since it skips the check
this exists to feed.
"""
if os.environ.get("SPLICECRAFT_SKIP_PYRIGHT_UPGRADE", "").strip().lower() \
in ("1", "true", "yes"):
print(" SPLICECRAFT_SKIP_PYRIGHT_UPGRADE set — using the installed "
"pyright.")
return
_heading("Checking for a newer pyright")
before = _pyright_wrapper_version()
try:
proc = subprocess.run(
[sys.executable, "-m", "pip", "install", "--upgrade", "pyright"],
capture_output=True, text=True, timeout=180,
)
except (OSError, subprocess.SubprocessError) as exc:
print(f" Could not check for a newer pyright ({exc}) — continuing "
f"with {before or 'the installed version'}.")
return
if proc.returncode != 0:
lines = (proc.stderr or proc.stdout or "").strip().splitlines()
why = lines[-1] if lines else "no output"
have = before or "the installed version"
print(f" pyright upgrade check failed ({why}) — continuing with "
f"{have}.")
return
after = _pyright_wrapper_version()
if before and after and before != after:
print(f" pyright {before} → {after}")
else:
print(f" pyright {after or before or '?'} is current")
def _pyright_wrapper_version() -> str:
"""Installed version of the ``pyright`` pip wrapper, or "" if it can't be
read (not installed / metadata unavailable). Deliberately does NOT shell
out to ``pyright --version``: that downloads the node binary, which is the
slow, network-flaky step this check runs ahead of."""
try:
from importlib.metadata import PackageNotFoundError, version
return version("pyright")
except (ImportError, PackageNotFoundError):
return ""
except Exception: # noqa: BLE001 — advisory only
return ""
def _summarize_pending_changes() -> None:
"""Sweep #18 (2026-05-21): release.py now BUNDLES accumulated
work into the release commit instead of refusing to proceed.
Pre-sweep `_ensure_clean_tree` rejected any uncommitted changes;
the new flow lets the user accumulate iterative work in the
working tree between releases and ship it in a single
``Release vX.Y.Z`` commit. This function is informational only:
print the pending changes so the user can confirm visually
before the build/test/commit/push pipeline proceeds.
"""
result = subprocess.run(
["git", "status", "--porcelain"],
check=True, capture_output=True, text=True,
)
pending = result.stdout.strip()
if not pending:
return
print("─" * 61)
print(" Pending changes that will be bundled into this release:")
print("─" * 61)
subprocess.run(["git", "status", "--short"], check=False)
print()
# Pre-sweep #18 alias — kept around for any external invocation that
# imports release.py and calls the old name. New code should call
# ``_summarize_pending_changes`` directly.
_ensure_clean_tree = _summarize_pending_changes
def _ensure_tag_unused(version: str) -> None:
"""Refuse to proceed if the target tag already exists locally."""
rev = subprocess.run(
["git", "rev-parse", f"v{version}"],
capture_output=True, text=True,
)
if rev.returncode == 0:
_die(f"tag v{version} already exists.")
def _previous_release_ref() -> str | None:
"""Return the most recent SpliceCraft release tag (``vX.Y.Z``) for
bounding ``git log`` when drafting a changelog section. Falls back
to ``None`` if no such tag exists (first-ever release on a fresh
clone), in which case the caller emits a placeholder rather than
dumping the whole history.
"""
result = subprocess.run(
["git", "tag", "--list", "v*", "--sort=-v:refname"],
capture_output=True, text=True, check=False,
)
if result.returncode != 0:
return None
for line in result.stdout.splitlines():
tag = line.strip()
if tag:
return tag
return None
def _commits_since(ref: "str | None") -> list[str]:
"""Return the subject line of every non-merge commit since *ref*
(or every commit on the branch if *ref* is None / unknown).
Strips out the bookkeeping commits ("Release v…", standalone
"Changelog: …") that would clutter a user-facing summary.
"""
if ref is None:
rng = ["HEAD"]
else:
rng = [f"{ref}..HEAD"]
result = subprocess.run(
["git", "log", "--no-merges", "--pretty=format:%s", *rng],
capture_output=True, text=True, check=False,
)
if result.returncode != 0:
return []
out: list[str] = []
for ln in result.stdout.splitlines():
s = ln.strip()
if not s:
continue
low = s.lower()
if low.startswith("release v"):
continue
if low.startswith("changelog:"):
continue
out.append(s)
return out
def _draft_changelog_section(version: str) -> str:
"""Build a fresh ``## [<version>]`` section from the commits landed
since the previous release tag. Used by `_ensure_changelog_entry`
when no entry has been hand-written yet — guarantees the What's
New modal renders an up-to-date brief on every release, never a
stale one.
Commit subjects in this repo are descriptive enough to make a
reasonable user-facing summary; the maintainer is free to write a
richer entry by hand before running release.py and the auto-draft
will not overwrite it.
"""
import datetime as _dt
today = _dt.date.today().isoformat()
prev = _previous_release_ref()
commits = _commits_since(prev)
if commits:
bullets = "\n".join(f"* {c}" for c in commits)
provenance = (
f"_(auto-generated from commits since {prev})_"
if prev is not None else
"_(auto-generated changelog)_"
)
body = f"{provenance}\n\n{bullets}\n"
else:
# No commits since the last tag (e.g. a re-release of the same
# tree, or release.py is invoked twice). Still emit a heading
# so the modal has something to display rather than rendering
# the previous version as if it were current.
body = (
"_(auto-generated changelog — no notable commits found "
"since the previous release)_\n"
)
return (
f"## [{version}] — {today}\n\n"
f"{body}\n---\n\n"
)
def _insert_changelog_section(section: str) -> None:
"""Insert *section* at the top of ``CHANGELOG.md``, just below the
file's header + first ``---`` separator. Preserves all existing
entries verbatim. Caller has already confirmed the new version's
heading is absent.
"""
text = CHANGELOG.read_text(encoding="utf-8")
# Canonical file shape:
# # SpliceCraft Changelog
# <blank>
# ---
# <blank>
# ## [X.Y.Z] — …
# New sections insert between the leading `---` and the most
# recent `## [` heading. If the anchor is missing (mangled file),
# fall back to prepending immediately after the H1.
marker = "\n---\n\n"
idx = text.find(marker)
if idx == -1:
prefix, _, rest = text.partition("\n")
new_text = f"{prefix}\n\n{section}{rest}"
else:
split_at = idx + len(marker)
new_text = text[:split_at] + section + text[split_at:]
CHANGELOG.write_text(new_text, encoding="utf-8")
_AUTO_STUB_MARKER = (
"_(auto-generated changelog — no notable commits found "
"since the previous release)_"
)
def _promote_unreleased_to_version(version: str) -> bool:
"""Sweep #36 (2026-05-27): if the maintainer has been keeping a
`## [unreleased]` block updated with the real changelog content,
relabel that heading to `## [<version>] — <today>` so the rich
content becomes the new version's body. Returns True if a
promotion happened, False otherwise.
Why this exists: the prior flow auto-generated a fresh section
from `git log` commit subjects, but the user often accumulates
bullet-pointed `[unreleased]` content as they go and forgets to
hand-copy it into the new version heading before releasing.
Result: 0.9.27 / 0.9.28 / 0.9.29 all shipped with the
"no notable commits found" auto-stub even though substantial
work had landed. Auto-promotion makes the `[unreleased]` pocket
the source of truth.
Only the FIRST `## [unreleased]` heading is promoted — any
later ones (legacy duplicates from manual edits) stay put so
the maintainer can fold them in by hand.
"""
import datetime as _dt
text = CHANGELOG.read_text(encoding="utf-8")
# Anchor: heading starts at col 0, matches `## [unreleased]`
# case-insensitively to allow `[Unreleased]` too.
m = re.search(
r"^## \[unreleased\][^\n]*$",
text, flags=re.IGNORECASE | re.MULTILINE,
)
if m is None:
return False
today = _dt.date.today().isoformat()
new_heading = f"## [{version}] — {today}"
new_text = text[:m.start()] + new_heading + text[m.end():]
CHANGELOG.write_text(new_text, encoding="utf-8")
return True
def _changelog_section_body(version: str) -> str:
"""Return the body of `## [<version>]` (everything between that
heading and the next `## [` heading) so callers can inspect it.
Empty string if the heading isn't present.
"""
if not CHANGELOG.is_file():
return ""
text = CHANGELOG.read_text(encoding="utf-8")
head_re = re.compile(
rf"^## \[{re.escape(version)}\][^\n]*$",
re.MULTILINE,
)
m = head_re.search(text)
if not m:
return ""
tail = text[m.end():]
next_head = re.search(r"^## \[", tail, flags=re.MULTILINE)
return tail[:next_head.start()] if next_head else tail
def _section_has_real_content(body: str) -> bool:
"""Return True if *body* contains real changelog content (real
bullet points or sub-headings), False if it's empty / blank /
just the auto-stub marker. Drives the empty-stub refusal in
`_ensure_changelog_entry`.
Heuristic: strip the heading-trailing `---`, blank lines, and
the auto-stub marker; if anything substantive remains, accept.
`_draft_changelog_section`'s commit-bullet body has real `*`
bullets and passes; the no-notable-commits body strips to
empty and fails.
"""
text = body
text = text.replace(_AUTO_STUB_MARKER, "")
text = re.sub(r"^---\s*$", "", text, flags=re.MULTILINE)
text = text.strip()
return bool(text)
def _ensure_changelog_entry(version: str) -> None:
"""Make sure `CHANGELOG.md` carries a heading for the new version.
Resolution order (sweep #36, 2026-05-27):
1. If `## [<version>]` already exists, leave it alone — the
maintainer hand-wrote it.
2. Else, if `## [unreleased]` exists, relabel it. The pocket
is the source of truth for "what shipped this release".
3. Else, auto-generate a section from `git log
<previous tag>..HEAD` so the in-app What's New modal at
least lists the commits since the previous release.
After resolution, asserts the section body has real content
(anything beyond the no-notable-commits auto-stub). If it
doesn't, aborts with a clear message asking the maintainer to
populate the section first — the "0.9.29 shipped with an
empty stub" failure mode triggered this guard.
Missing `CHANGELOG.md` falls through with a friendlier
message than ``FileNotFoundError``. The resulting file is
added to the release commit downstream (see `add_targets` in
`main()`), so the file on disk and the modal stay in lockstep.
"""
if not CHANGELOG.is_file():
_die(f"{CHANGELOG.name} not found at {CHANGELOG}. "
"Add it before releasing.")
text = CHANGELOG.read_text(encoding="utf-8")
needle = f"## [{version}]"
if needle in text:
if not _section_has_real_content(
_changelog_section_body(version)
):
_die(
f"{CHANGELOG.name} has a hand-written `{needle}` "
f"heading but its body contains no real content "
f"(only the no-notable-commits stub or blanks). "
f"Populate it with the actual bug-fix / feature "
f"bullets before re-running release.py."
)
return
if _promote_unreleased_to_version(version):
print(
f" ↳ promoted `## [unreleased]` → `{needle}` in "
f"{CHANGELOG.name} (the pocket had queued content)"
)
else:
section = _draft_changelog_section(version)
_insert_changelog_section(section)
print(
f" ↳ auto-generated `{needle}` section in "
f"{CHANGELOG.name} (no hand-written entry, no "
f"`[unreleased]` pocket)"
)
if not _section_has_real_content(
_changelog_section_body(version)
):
_die(
f"{CHANGELOG.name} section for `{needle}` ended up "
f"empty (no `[unreleased]` content, no commits since "
f"the previous tag). Either: (a) hand-write the "
f"section with bullets describing what's in this "
f"release, or (b) add bullets under a "
f"`## [unreleased]` heading and re-run release.py. "
f"Refusing to ship a What's New modal with no real "
f"content."
)
def _bump_version_in_file(path: Path, pattern: re.Pattern[str],
new_version: str, label: str) -> None:
"""Substitute the canonical version line in *path* via regex. Raises
if zero substitutions happened — protects against the file's
formatting drifting (e.g., quotes changing) without us noticing."""
text = path.read_text(encoding="utf-8")
new_text, n = pattern.subn(rf'\1"{new_version}"', text)
if n == 0:
_die(f"failed to find version line in {label} ({path.name}).")
if n > 1:
# More than one match would mean we're rewriting something
# unintended; bail before clobbering it.
_die(f"found {n} version-line matches in {label}; refusing to "
f"bump (please simplify {path.name}).")
path.write_text(new_text, encoding="utf-8")
def _stamp_citation_metadata(new_version: str) -> str:
"""Stamp *new_version* + today's date into the citation metadata:
``CITATION.cff`` (version + date-released), ``.zenodo.json`` (version), and
``splicecraft.py``'s ``_RELEASE_DATE``.
These drive the permanent Zenodo/DataCite record for this release and the
`splicecraft --citation` output, so a missed stamp means a DOI that cites
the WRONG version forever. Every substitution is counted and a miss is
fatal — same contract as `_bump_version_in_file`. `tests/test_citation.py`
re-checks the result during the pytest gate below.
Returns the ISO date stamped, for the log line."""
import datetime as _dt # local import, matching this file's style
today = _dt.date.today().isoformat()
edits = [
(CITATION_CFF, _CFF_VERSION_RE, new_version, "CITATION.cff version"),
(CITATION_CFF, _CFF_DATE_RE, f"'{today}'", "CITATION.cff date-released"),
(ZENODO_JSON, _ZENODO_VERSION_RE, f'"{new_version}"', ".zenodo.json version"),
(SPLICECRAFT, _RELEASE_DATE_RE, f'"{today}"', "splicecraft.py _RELEASE_DATE"),
]
# PASS 1 — stage every substitution in memory and prove all four matched
# BEFORE a single byte lands. Writing file-by-file leaves a half-stamped
# tree when a later regex misses: CITATION.cff already bumped, .zenodo.json
# still on the old version, and the release dead in between. `staged` is
# keyed by path because CITATION.cff takes two edits that must compose.
staged: dict[Path, str] = {}
for path, pattern, value, label in edits:
if path not in staged:
if not path.exists():
_die(f"{path.name} is missing, so {label} cannot be stamped. "
f"Restore the file (git checkout {path.name}) before "
f"releasing — a release without citation metadata mints "
f"a DOI record with no version on it.")
staged[path] = path.read_text(encoding="utf-8")
new_text, n = pattern.subn(lambda m: m.group(1) + value, staged[path])
if n != 1:
_die(f"expected exactly 1 {label} line to rewrite, found {n} "
f"in {path.name}. Citation metadata would ship stale — "
f"fix the file (or the regex) before releasing.")
staged[path] = new_text
# PASS 2 — every substitution matched, so commit them all.
for path, text in staged.items():
path.write_text(text, encoding="utf-8")
# Read back — a wrong-encoding / silently-failed write here would put the
# wrong version on a permanent DOI, which cannot be taken back.
cff = CITATION_CFF.read_text(encoding="utf-8")
if f"\nversion: {new_version}\n" not in cff:
_die(f"CITATION.cff did not take version {new_version}.")
if f"date-released: '{today}'" not in cff:
_die(f"CITATION.cff did not take date-released {today}.")
try:
zen = json.loads(ZENODO_JSON.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
_die(f".zenodo.json is not valid JSON after the stamp: {exc}")
if zen.get("version") != new_version:
_die(f".zenodo.json version is {zen.get('version')!r}, expected "
f"{new_version!r}.")
if f'_RELEASE_DATE = "{today}"' not in SPLICECRAFT.read_text(encoding="utf-8"):
_die(f"splicecraft.py did not take _RELEASE_DATE {today}.")
return today
def _verify_bump(path: Path, new_version: str, var_name: str) -> None:
"""Read the file back and confirm the new version line is exactly
where we expect it. Catches odd encoding / line-ending issues that
would otherwise let a silently-failed bump through."""
text = path.read_text(encoding="utf-8")
expected = re.compile(
rf'^{re.escape(var_name)}\s*=\s*"{re.escape(new_version)}"',
re.MULTILINE,
)
if not expected.search(text):
_die(f"failed to update {path.name} (expected "
f'{var_name} = "{new_version}").')
def _bump_plugin_manifest(new_version: str) -> None:
"""Bump + validate the Claude Code plugin manifests.
Verification parses the JSON rather than regex-matching it back: a manifest
that stops being valid JSON doesn't fail loudly at release time, it fails
silently for every user who has `claude plugin marketplace add`ed this repo,
which is the worst place to find out. The skill file's existence is checked
for the same reason — a plugin whose only component has moved installs fine
and then does nothing.
"""
if not PLUGIN_MANIFEST.is_file():
_die(f"plugin manifest missing: {PLUGIN_MANIFEST}")
_bump_version_in_file(
PLUGIN_MANIFEST, _PLUGIN_VERSION_RE, new_version,
"plugin/.claude-plugin/plugin.json",
)
for manifest in (PLUGIN_MANIFEST, MARKETPLACE_MANIFEST):
try:
data = json.loads(manifest.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
_die(f"{manifest.name} is not readable as JSON after the bump "
f"({exc}) — installs from this marketplace would break.")
if not data.get("name"):
_die(f"{manifest.name} has no 'name' — the plugin id is immutable "
f"once published and must not go missing.")
stamped = json.loads(PLUGIN_MANIFEST.read_text(encoding="utf-8"))
if stamped.get("version") != new_version:
_die(f'failed to update plugin/.claude-plugin/plugin.json (expected version '
f'"{new_version}", found "{stamped.get("version")}").')
if not PLUGIN_SKILL.is_file():
_die(f"plugin skill missing: {PLUGIN_SKILL} — the plugin would install "
f"with no components.")
print(f" plugin/.claude-plugin/plugin.json → {new_version} "
f"(manifests parse, skill present)")
def _clean_build_artifacts() -> None:
"""``rm -rf dist/ build/ *.egg-info`` in pure Python."""
for d in ("dist", "build"):
shutil.rmtree(REPO_ROOT / d, ignore_errors=True)
for egg in REPO_ROOT.glob("*.egg-info"):
shutil.rmtree(egg, ignore_errors=True)
def _read_pyproject_runtime_deps() -> list[str]:
"""Extract the [project] dependencies array from pyproject.toml in
declaration order. Returns the raw PEP-440 specifiers (e.g.
``"textual>=8.2.6"``).
Regex-based to avoid a tomllib (3.11+) / tomli dependency — the
pyproject's dependency block uses one quoted string per line with
comments and blank lines interspersed, all of which we skip.
"""
text = PYPROJECT.read_text(encoding="utf-8")
m = _PYPROJECT_DEPS_BLOCK_RE.search(text)
if m is None:
_die("could not find `dependencies = [...]` in pyproject.toml.")
deps: list[str] = []
for line in m.group(1).splitlines():
stripped = line.strip()
if not stripped or stripped.startswith("#"):
continue
# Strip trailing comma + trailing inline comment.
no_comment = stripped.split("#", 1)[0].strip().rstrip(",").strip()
m2 = re.match(r'^"([^"]+)"$', no_comment)
if m2:
deps.append(m2.group(1))
if not deps:
_die("pyproject's dependencies array parsed empty — refusing "
"to wipe the conda recipe's run-deps.")
return deps
def _pep440_to_conda(spec: str) -> str:
"""Translate a single PEP-440 spec to conda's `pkg >=X.Y.Z` form.
Conda's recipe parser wants whitespace between the package name and
the version constraint; pyproject (PEP 508) accepts both styles but
we normalise here so the recipe stays consistent regardless of how
pyproject is written.
"""
m = _PEP440_SPEC_RE.match(spec.strip())
if not m:
return spec
name, rest = m.group(1), m.group(2).strip()
return f"{name} {rest}".strip() if rest else name
def _sha256_of(path: Path) -> str:
"""SHA-256 hex digest of a file, streamed in 64 KB chunks so we
don't load multi-MB sdists fully into RAM."""
h = hashlib.sha256()
with path.open("rb") as fh:
for chunk in iter(lambda: fh.read(64 * 1024), b""):
h.update(chunk)
return h.hexdigest()
def _sync_conda_recipe(new_version: str) -> None:
"""Rewrite ``conda-recipe/meta.yaml`` to match the just-built
release: bump version, regenerate sha256 from the local sdist
(hatchling produces deterministic sdists, so this matches what
PyPI will host), and rewrite the ``run:`` block from
pyproject.toml's runtime deps.
The recipe is the reference copy that lives in-repo; the canonical
bioconda copy at ``bioconda-recipes/recipes/splicecraft/`` still
needs a PR with the same bump, but having the local recipe always
pre-bumped means the PR is a one-shot copy-paste.
No-op if the recipe file is missing (older checkouts predate it).
"""
if not CONDA_RECIPE.is_file():
print(f"Note: {CONDA_RECIPE.relative_to(REPO_ROOT)} not present; "
"skipping conda recipe sync.")
return
sdists = sorted((REPO_ROOT / "dist").glob("*.tar.gz"))
if not sdists:
_die("no sdist found in dist/ — conda sha256 cannot be computed.")
if len(sdists) > 1:
_die(f"expected exactly one sdist in dist/, found {len(sdists)}.")
sdist = sdists[0]
sha256 = _sha256_of(sdist)
text = CONDA_RECIPE.read_text(encoding="utf-8")
text, n = _CONDA_VERSION_RE.subn(rf'\1"{new_version}"\2', text)
if n != 1:
_die(f"conda recipe: expected 1 `{{% set version = ... %}}` "
f"line, got {n}.")
text, n = _CONDA_SHA256_RE.subn(rf"\g<1>{sha256}", text)
if n != 1:
_die(f"conda recipe: expected 1 sha256 line, got {n}.")
pep_deps = _read_pyproject_runtime_deps()
# `python >=3.10` is always the first run-dep — keep it pinned to
# the value in pyproject.toml's `requires-python` rather than
# hard-coding so a future Python-floor bump stays in sync. Parsing
# the floor again here avoids a separate constant.
py_floor_m = re.search(
r'^requires-python\s*=\s*"\s*([^"]+?)\s*"',
PYPROJECT.read_text(encoding="utf-8"),
re.MULTILINE,
)
py_floor = (
py_floor_m.group(1).strip() if py_floor_m is not None else ">=3.10"
)
run_lines = [f" - python {py_floor}"]
run_lines.extend(f" - {_pep440_to_conda(d)}" for d in pep_deps)
new_run_block = " run:\n" + "\n".join(run_lines) + "\n"
text, n = _CONDA_RUN_BLOCK_RE.subn(new_run_block, text, count=1)
if n != 1:
_die("conda recipe: failed to rewrite the `run:` deps block "
"(expected ` run:` followed by ` - …` lines).")
CONDA_RECIPE.write_text(text, encoding="utf-8")
print(f" conda recipe → version {new_version}, sha256 {sha256[:16]}…, "
f"{len(pep_deps)} runtime deps from pyproject")
def _wait_for_pypi(new_version: str, timeout_s: int = 360) -> bool:
"""Poll PyPI until the new sdist is downloadable. Bioconda's bot
tries to fetch the sdist immediately when the PR opens; if PyPI's
Trusted Publishing pipeline hasn't finished yet, the first CI run
fails and the user has to re-trigger it manually. Polling here is
a 1-3 minute wait that avoids the dance entirely.
Returns True on success, False on timeout (in which case the
caller opens the PR anyway and the bot's automatic retry will
eventually pick up the sdist).
"""
import time
url = PYPI_SDIST_URL_TPL.format(version=new_version)
deadline = time.time() + timeout_s
print(f" Polling {url}")
while time.time() < deadline:
result = subprocess.run(
["curl", "-sIfL", "-o", "/dev/null", url],
capture_output=True,
)
if result.returncode == 0:
print(" sdist live on PyPI.")
return True
time.sleep(10)
print(f" Timed out after {timeout_s}s. Bioconda PR will open "
"anyway; their bot retries until the sdist is reachable.")
return False
def _gh_logged_in_user() -> "str | None":
"""Return the GitHub username the local `gh` CLI is authenticated
as, or None if `gh` isn't installed / authed (caller skips PR)."""
if not shutil.which("gh"):
return None
result = subprocess.run(
["gh", "api", "user", "--jq", ".login"],
capture_output=True, text=True,
)
if result.returncode != 0:
return None
name = result.stdout.strip()
return name or None
def _ensure_bioconda_fork(owner: str) -> None:
"""Ensure `<owner>/bioconda-recipes` exists. Forks the upstream if
it doesn't. Idempotent — `gh repo fork` is a no-op when the fork
already exists."""
result = subprocess.run(
["gh", "repo", "view", f"{owner}/bioconda-recipes"],
capture_output=True, text=True,
)
if result.returncode == 0:
return
print(f" Forking {BIOCONDA_UPSTREAM} → {owner}/bioconda-recipes")
_run(["gh", "repo", "fork", BIOCONDA_UPSTREAM,
"--clone=false", "--default-branch-only"])
def _version_tuple(v: str) -> tuple[int, ...]:
"""Parse 'X.Y.Z[.suffix]' into a comparable tuple. Non-numeric
suffix segments contribute their leading digits only (so 0.9.0rc1
sorts as (0, 9, 0, 1)) — good enough for the supersede check in
`_close_superseded_bioconda_prs`; the rich PEP-440 ordering isn't
needed because we only compare same-tool branches."""
parts: list[int] = []
for piece in v.split("."):
try:
parts.append(int(piece))
except ValueError:
digits = "".join(ch for ch in piece if ch.isdigit())
parts.append(int(digits) if digits else 0)
return tuple(parts)
def _close_superseded_bioconda_prs(owner: str, new_version: str) -> None:
"""Close any open splicecraft PRs in bioconda-recipes whose branch
targets a version OLDER than `new_version`. Same-version PRs are
left alone — `_submit_bioconda_pr`'s existing check handles those.
Why: bioconda reviewers are volunteers and a multi-PR stack for
the same software with sequential versions creates ambiguity ("is
one of these the canonical ask, or did the maintainer change
their mind?"). Closing supersedes with an explicit pointer makes
the queue obvious. Without this guard, every `release.py` invocation
piles on a new PR while leaving prior ones open — exactly what
happened during the 0.8.9 → 0.9.2 stretch where four "first
submission" PRs sat green for days while the maintainer waited
for the queue to clarify itself.
Branch convention: `splicecraft-<version>` (see
`_submit_bioconda_pr` below — both producer + this consumer).
Failures are non-fatal (`check=False`); the new PR opens regardless.
"""
import json as _json
result = subprocess.run(
["gh", "pr", "list",
"--repo", BIOCONDA_UPSTREAM,
"--author", owner,
"--state", "open",
"--search", "splicecraft in:title",
"--json", "number,headRefName,url",
"--limit", "20"],
capture_output=True, text=True, check=False,
)
if result.returncode != 0 or not result.stdout.strip():
return
try:
prs = _json.loads(result.stdout)
except _json.JSONDecodeError:
return
if not isinstance(prs, list):
return
new_tuple = _version_tuple(new_version)
for pr in prs:
branch = pr.get("headRefName", "") or ""
if not branch.startswith("splicecraft-"):
continue
pr_version = branch[len("splicecraft-"):]
if _version_tuple(pr_version) >= new_tuple:
# Equal or newer — leave alone. Same-version is handled
# by the existing branch-match check inside
# `_submit_bioconda_pr`; newer would mean something
# unexpected (manual PR ahead of release.py) and we'd
# rather not auto-close that.
continue
print(f" Closing superseded bioconda PR #{pr['number']} "
f"(v{pr_version} < v{new_version})")
comment_body = (
f"Superseded by the upcoming PR for v{new_version}. "
f"Closing to clear the queue so a maintainer only needs "
f"to review the latest — the recipe content for each "
f"interim version is functionally identical apart from "
f"version + sha256."
)
# Comment THEN close, both `check=False` — leaving them
# non-fatal so a transient gh / API hiccup doesn't block the
# release. Worst case: an older PR stays open and we manually
# close it later (the same situation as before this guard).
subprocess.run(
["gh", "pr", "comment", str(pr["number"]),
"--repo", BIOCONDA_UPSTREAM,
"--body", comment_body],
check=False, capture_output=True,
)
subprocess.run(
["gh", "pr", "close", str(pr["number"]),
"--repo", BIOCONDA_UPSTREAM],
check=False, capture_output=True,
)
def _submit_bioconda_pr(new_version: str) -> None:
"""Open (or update) a bioconda PR with the current recipe.
Steps:
1. Verify `gh` is authed; skip with a note if not.
2. Fork bioconda/bioconda-recipes if the maintainer's account
doesn't already host a fork.
3. Close any open splicecraft PRs at an older version so the
queue surfaces only the canonical ask
(`_close_superseded_bioconda_prs`).
4. Shallow-clone the fork to a temp dir, fast-forward its
master to upstream (so our branch is fresh).
5. Drop in `recipes/splicecraft/meta.yaml` from our in-repo
recipe (which `_sync_conda_recipe` just refreshed).
6. Branch, commit, force-push to the fork (force-with-lease so
a stale branch from a previous failed attempt doesn't block
us; per-version branches make collisions impossible across
releases).
7. Open the PR against the upstream master. If one for this
version already exists (re-run), print the URL and skip.
First-time submissions (no `recipes/splicecraft/` directory in
bioconda yet) and updates use the same flow; bioconda's bot
handles both transparently.
"""
if not CONDA_RECIPE.is_file():
print(f"Note: {CONDA_RECIPE.relative_to(REPO_ROOT)} not present; "
"skipping bioconda PR.")
return
owner = _gh_logged_in_user()
if owner is None:
print("Note: `gh` CLI not installed or not authenticated; "
"skipping bioconda PR. Run `gh auth login` and rerun "
"with --bioconda-only to publish to bioconda.")
return
print(f" gh authenticated as {owner}")
_ensure_bioconda_fork(owner)
_close_superseded_bioconda_prs(owner, new_version)
import tempfile
with tempfile.TemporaryDirectory(prefix="bioconda-pr-") as tmp:
clone = Path(tmp) / "bioconda-recipes"
# Shallow clone keeps the bioconda-recipes mega-repo manageable
# (it has 10K+ recipes and a multi-GB history).
_run([
"git", "clone", "--depth=1", "--single-branch",
"--branch=master",
f"https://github.com/{owner}/bioconda-recipes.git",
str(clone),
])
# Pull the latest upstream master into the shallow clone so
# our branch starts from current head, not the fork's
# potentially-stale snapshot.
_run(["git", "-C", str(clone), "remote", "add",
"upstream", f"https://github.com/{BIOCONDA_UPSTREAM}.git"])
_run(["git", "-C", str(clone), "fetch", "--depth=1",
"upstream", "master"])
_run(["git", "-C", str(clone), "reset", "--hard",
"upstream/master"])
recipe_dir = clone / "recipes" / "splicecraft"