55
66import argparse
77import json
8+ import os
89import re
910import subprocess
1011import sys
1112from pathlib import Path
1213
13- ROOT = Path (__file__ ).resolve ().parent .parent
14+ ROOT = Path (os . environ . get ( "DESKTOP_RELEASE_ROOT" , Path ( __file__ ).resolve ().parent .parent ))
1415CHANGELOG = ROOT / "CHANGELOG.md"
1516METADATA = ROOT / ".release" / "desktop-candidate.json"
1617SEMVER = re .compile (r"^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?$" )
18+ STABLE_TAG = re .compile (r"desktop-v([0-9]+)\.([0-9]+)\.([0-9]+)$" )
1719DESKTOP_PATHS = (
1820 "desktop/" ,
1921 "crates/buzz-core/" ,
@@ -54,30 +56,71 @@ def commit_list(range_spec: str, paths: tuple[str, ...] | None = None) -> list[d
5456 return [dict (zip (("sha" , "subject" ), line .split ("\0 " , 1 ))) for line in out .splitlines ()]
5557
5658
57- def stable_tags (base_sha : str ) -> list [tuple [int , str , str ]]:
58- tags : list [tuple [int , str , str ]] = []
59- for tag in git ("tag" , "--merged" , base_sha , "--list" ).splitlines ():
60- if not re .fullmatch (r"(?:desktop-)?v[0-9]+\.[0-9]+\.[0-9]+" , tag ):
59+ def gh_json (endpoint : str ) -> object :
60+ try :
61+ return json .loads (subprocess .check_output (
62+ ["gh" , "api" , endpoint ], cwd = ROOT , text = True
63+ ))
64+ except (subprocess .CalledProcessError , json .JSONDecodeError ) as error :
65+ raise SystemExit (f"cannot verify prior desktop release via GitHub: { error } " ) from error
66+
67+
68+ def stable_tags () -> list [tuple [tuple [int , int , int ], str , str ]]:
69+ tags : list [tuple [tuple [int , int , int ], str , str ]] = []
70+ aliases : dict [tuple [int , int , int ], list [tuple [str , str ]]] = {}
71+ for tag in git ("tag" , "--list" , "desktop-v*" ).splitlines ():
72+ match = STABLE_TAG .fullmatch (tag )
73+ if not match :
6174 continue
75+ version = tuple (map (int , match .groups ()))
6276 sha = git ("rev-list" , "-n" , "1" , tag )
63- distance = int (git ("rev-list" , "--count" , f"{ sha } ..{ base_sha } " ))
64- tags .append ((distance , tag , sha ))
77+ aliases .setdefault (version , []).append ((tag , sha ))
78+ for version , refs in aliases .items ():
79+ if len (refs ) != 1 :
80+ detail = ", " .join (f"{ tag } @{ sha } " for tag , sha in refs )
81+ raise SystemExit (f"ambiguous desktop release version { version } : { detail } " )
82+ tag , sha = refs [0 ]
83+ tags .append ((version , tag , sha ))
6584 return tags
6685
6786
68- def previous_tag (base_sha : str ) -> str :
69- tags = stable_tags (base_sha )
70- if not tags :
71- return ""
72- min_distance = min (item [0 ] for item in tags )
73- nearest = [item for item in tags if item [0 ] == min_distance ]
74- commits = {item [2 ] for item in nearest }
75- if len (commits ) != 1 :
76- detail = ", " .join (f"{ tag } @{ sha } " for _ , tag , sha in nearest )
77- raise SystemExit (f"ambiguous previous desktop release tags: { detail } " )
78- # During migration, prefer the namespaced tag when aliases share a commit.
79- nearest .sort (key = lambda item : (not item [1 ].startswith ("desktop-v" ), item [1 ]))
80- return nearest [0 ][1 ]
87+ def previous_release (version : str , repo : str ) -> dict [str , str ] | None :
88+ target = tuple (map (int , version .split ("-" , 1 )[0 ].split ("." )))
89+ tags = stable_tags ()
90+ newer = [item for item in tags if item [0 ] >= target ]
91+ if newer :
92+ detail = ", " .join (item [1 ] for item in newer )
93+ raise SystemExit (f"desktop release version must increase beyond existing tags: { detail } " )
94+ eligible = [item for item in tags if item [0 ] < target ]
95+ if not eligible :
96+ return None
97+ prior_version , tag , candidate_sha = max (eligible )
98+ try :
99+ metadata = json .loads (git ("show" , f"{ tag } :.release/desktop-candidate.json" ))
100+ except (subprocess .CalledProcessError , json .JSONDecodeError ) as error :
101+ raise SystemExit (f"prior release { tag } has invalid candidate metadata" ) from error
102+ expected = {
103+ "version" : "." .join (map (str , prior_version )),
104+ "tag" : tag ,
105+ }
106+ if any (metadata .get (key ) != value for key , value in expected .items ()):
107+ raise SystemExit (f"prior release { tag } metadata does not match its tag" )
108+ base_sha = metadata .get ("base_sha" )
109+ if not isinstance (base_sha , str ) or not re .fullmatch (r"[0-9a-f]{40}" , base_sha ):
110+ raise SystemExit (f"prior release { tag } has invalid base_sha" )
111+ pulls = gh_json (f"repos/{ repo } /commits/{ candidate_sha } /pulls" )
112+ matches = [pr for pr in pulls if pr .get ("merged_at" ) and (
113+ pr .get ("head" , {}).get ("sha" ) == candidate_sha
114+ or pr .get ("merge_commit_sha" ) == candidate_sha
115+ )]
116+ if len (matches ) != 1 or not matches [0 ].get ("merge_commit_sha" ):
117+ raise SystemExit (f"prior release { tag } does not identify exactly one merged release PR" )
118+ return {
119+ "tag" : tag ,
120+ "candidate_sha" : candidate_sha ,
121+ "base_sha" : base_sha ,
122+ "merge_sha" : matches [0 ]["merge_commit_sha" ],
123+ }
81124
82125
83126def bullet (commit : dict [str , str ], repo : str ) -> str :
@@ -91,24 +134,27 @@ def bullet(commit: dict[str, str], repo: str) -> str:
91134 return f"- { subject } ([`{ sha } `](https://github.com/{ repo } /commit/{ sha } ))"
92135
93136
94- def expected (base_sha : str , previous : str ) -> tuple [list [dict [str , str ]], list [dict [str , str ]]]:
95- # With no prior desktop tag, account for the repository's root commit too.
96- # A ``root..base`` range silently drops that first commit.
97- range_spec = f"{ previous } ..{ base_sha } " if previous else base_sha
98- all_commits = commit_list (range_spec )
99- relevant_shas = {c ["sha" ] for c in commit_list (range_spec , DESKTOP_PATHS )}
137+ def expected (base_sha : str , previous_base : str , previous_merge : str ) -> tuple [list [dict [str , str ]], list [dict [str , str ]]]:
138+ # Immutable candidate tags may live on side history after squash merge. The
139+ # prior candidate metadata is the ledger boundary; exclude only its known
140+ # squash commit so unrelated commits around that merge remain accounted for.
141+ range_spec = f"{ previous_base } ..{ base_sha } " if previous_base else base_sha
142+ all_commits = [c for c in commit_list (range_spec ) if c ["sha" ] != previous_merge ]
143+ relevant_shas = {c ["sha" ] for c in commit_list (range_spec , DESKTOP_PATHS )} - {previous_merge }
100144 relevant = [c for c in all_commits if c ["sha" ] in relevant_shas ]
101145 other = [c for c in all_commits if c ["sha" ] not in relevant_shas ]
102146 return relevant , other
103147
104148
105- def render (version : str , base_sha : str , previous : str , repo : str ) -> tuple [str , list [str ]]:
106- relevant , other = expected (base_sha , previous )
149+ def render (version : str , base_sha : str , previous : dict [str , str ] | None , repo : str ) -> tuple [str , list [str ]]:
150+ relevant , other = expected (
151+ base_sha , previous ["base_sha" ] if previous else "" , previous ["merge_sha" ] if previous else ""
152+ )
107153 lines = [f"## v{ version } " , "" , "### Desktop and shared changes" , "" ]
108154 lines += [bullet (c , repo ) for c in relevant ] or ["- None" ]
109155 lines += ["" , "### Other repository changes" , "" ]
110156 lines += [bullet (c , repo ) for c in other ] or ["- None" ]
111- compare_start = previous or git ("rev-list" , "--max-parents=0" , base_sha ).splitlines ()[0 ]
157+ compare_start = previous [ "tag" ] if previous else git ("rev-list" , "--max-parents=0" , base_sha ).splitlines ()[0 ]
112158 lines += ["" , f"[Compare { compare_start } ...desktop-v{ version } ](https://github.com/{ repo } /compare/{ compare_start } ...desktop-v{ version } )" ]
113159 return "\n " .join (lines ) + "\n " , [c ["sha" ] for c in relevant + other ]
114160
@@ -117,8 +163,8 @@ def generate(args: argparse.Namespace) -> None:
117163 if not SEMVER .fullmatch (args .version ):
118164 raise SystemExit (f"invalid semver: { args .version } " )
119165 base_sha = git ("rev-parse" , args .base )
120- previous = previous_tag (base_sha )
121166 repo = args .repo or re .sub (r".*github\.com[:/]" , "" , git ("remote" , "get-url" , "origin" )).removesuffix (".git" )
167+ previous = previous_release (args .version , repo )
122168 block , commits = render (args .version , base_sha , previous , repo )
123169 old = CHANGELOG .read_text () if CHANGELOG .exists () else "# Changelog\n "
124170 if not old .startswith ("# Changelog" ):
@@ -127,10 +173,12 @@ def generate(args: argparse.Namespace) -> None:
127173 CHANGELOG .write_text (f"# Changelog\n \n { block } \n { remainder } " )
128174 METADATA .parent .mkdir (parents = True , exist_ok = True )
129175 METADATA .write_text (json .dumps ({
130- "schema" : 1 ,
176+ "schema" : 2 ,
131177 "version" : args .version ,
132178 "base_sha" : base_sha ,
133- "previous_tag" : previous or None ,
179+ "previous_tag" : previous ["tag" ] if previous else None ,
180+ "previous_base_sha" : previous ["base_sha" ] if previous else None ,
181+ "previous_merge_sha" : previous ["merge_sha" ] if previous else None ,
134182 "tag" : f"desktop-v{ args .version } " ,
135183 "commit_count" : len (commits ),
136184 }, indent = 2 ) + "\n " )
@@ -157,14 +205,16 @@ def validate(args: argparse.Namespace) -> None:
157205 if missing :
158206 detail .append (f"missing required files: { ', ' .join (sorted (missing ))} " )
159207 raise SystemExit ("candidate is not version-only (" + "; " .join (detail ) + ")" )
160- previous = data ["previous_tag" ] or ""
161- actual_previous = previous_tag (data ["base_sha" ])
162- if previous != actual_previous :
163- raise SystemExit (
164- f"recorded previous tag { previous or '<none>' } does not match "
165- f"nearest release tag { actual_previous or '<none>' } "
166- )
167208 repo = args .repo or "block/buzz"
209+ previous = previous_release (version , repo )
210+ recorded_previous = {
211+ "tag" : data .get ("previous_tag" ),
212+ "base_sha" : data .get ("previous_base_sha" ),
213+ "merge_sha" : data .get ("previous_merge_sha" ),
214+ } if data .get ("previous_tag" ) else None
215+ expected_previous = {key : previous [key ] for key in ("tag" , "base_sha" , "merge_sha" )} if previous else None
216+ if recorded_previous != expected_previous :
217+ raise SystemExit ("recorded previous release ledger does not match immutable prior release" )
168218 expected_block , shas = render (version , data ["base_sha" ], previous , repo )
169219 text = CHANGELOG .read_text ()
170220 blocks = re .findall (rf"(?ms)^## v{ re .escape (version )} \n.*?(?=^## v|\Z)" , text )
0 commit comments