33import fcntl
44import json
55import re
6+ import shlex
67import subprocess
78import uuid
9+ from datetime import datetime , timezone
10+ from importlib .metadata import PackageNotFoundError , distribution
811from pathlib import Path
12+ from urllib .parse import unquote , urlparse
913from xml .etree import ElementTree as ET
1014
1115from . import __version__
@@ -142,8 +146,170 @@ def standalone(svg):
142146 )
143147
144148
145- def build_bundle (root ):
146- """Rebuild shareable artifacts from retained results, without GitHub access."""
149+ def now ():
150+ return datetime .now (timezone .utc ).isoformat ()
151+
152+
153+ def local_checkout ():
154+ """Find a development checkout, including when running in a uvx environment."""
155+ candidates = [Path (__file__ ).resolve ().parents [2 ]]
156+ try :
157+ direct = json .loads (distribution ("abench" ).read_text ("direct_url.json" ) or "{}" )
158+ url = urlparse (direct .get ("url" , "" ))
159+ if url .scheme == "file" and url .netloc in ("" , "localhost" ):
160+ candidates .append (Path (unquote (url .path )))
161+ except (ValueError , OSError , PackageNotFoundError ):
162+ pass
163+ return next (
164+ (
165+ str (p )
166+ for p in candidates
167+ if (p / "pyproject.toml" ).is_file () and (p / "src/abench" ).is_dir ()
168+ ),
169+ None ,
170+ )
171+
172+
173+ def write_launcher (bundle , checkout ):
174+ launcher = bundle / "publish.sh"
175+ fallback = ""
176+ if checkout :
177+ quoted = shlex .quote (checkout )
178+ fallback = f"""if command -v uvx >/dev/null 2>&1 && [ -f { quoted } /pyproject.toml ]; then
179+ exec uvx --refresh --from { quoted } abench publish "$suite_dir" "$@"
180+ fi
181+ """
182+ launcher .write_text (
183+ """#!/bin/sh
184+ # Permanent, safe-to-repeat abench publication launcher. No credentials stored.
185+ set -eu
186+ publication_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P)
187+ suite_dir=$(dirname -- "$publication_dir")
188+ if command -v abench >/dev/null 2>&1; then
189+ exec abench publish "$suite_dir" "$@"
190+ fi
191+ """
192+ + fallback
193+ + """echo 'Cannot find abench. Install a version with PR publishing support, or restore the recorded checkout and install uv.' >&2
194+ exit 127
195+ """
196+ )
197+ launcher .chmod (0o755 )
198+
199+
200+ STATUS_LABELS = {
201+ "prepared" : "Not published" ,
202+ "failed" : "Publication failed" ,
203+ "posting" : "Publication outcome uncertain" ,
204+ "uncertain" : "Publication outcome uncertain" ,
205+ "published" : "Published" ,
206+ "missing" : "Previously published comment not found" ,
207+ }
208+
209+
210+ def save_status (bundle , state ):
211+ """JSON is authoritative; the Markdown file is a readable projection."""
212+ write_json (bundle / "state.json" , state )
213+ label = STATUS_LABELS .get (state ["status" ], state ["status" ])
214+ target = state ["target" ]
215+ lines = [
216+ "# Publication status" ,
217+ "" ,
218+ f"**{ label } **" ,
219+ "" ,
220+ f"Target: https://github.com/{ target ['repository' ]} /pull/{ target ['pr' ]} " ,
221+ f"Last publication attempt: { state .get ('last_attempt_at' , 'Never recorded' )} " ,
222+ ]
223+ if state .get ("comment_url" ):
224+ lines += ["" , f"[Open the recorded GitHub comment]({ state ['comment_url' ]} )" ]
225+ if state .get ("last_verified_at" ):
226+ lines += [f"Last GitHub check: { state ['last_verified_at' ]} " ]
227+ if state .get ("error" ):
228+ lines += ["" , f"Last error: { cell (state ['error' ])} " ]
229+ if state .get ("verification_error" ):
230+ lines += [
231+ "" ,
232+ f"GitHub verification failed: { cell (state ['verification_error' ])} " ,
233+ ]
234+ if state ["status" ] in ("posting" , "uncertain" ):
235+ lines += [
236+ "" ,
237+ "GitHub may have accepted the comment. Retry checks for the existing comment before posting again." ,
238+ ]
239+ command = shlex .quote (str (bundle / "publish.sh" ))
240+ lines += [
241+ "" ,
242+ "Publish or retry (safe to repeat):" ,
243+ "" ,
244+ "```sh" ,
245+ command ,
246+ "```" ,
247+ "" ,
248+ "Preview with `--dry-run`; inspect local status with `--status`; check GitHub with `--verify`." ,
249+ "" ,
250+ "This file records local knowledge; use --verify to check whether the comment still exists." ,
251+ ]
252+ (bundle / "STATUS.md" ).write_text ("\n " .join (lines ) + "\n " )
253+
254+
255+ def completion (bundle , state ):
256+ if state ["status" ] == "published" :
257+ print (f"Results published: { state ['comment_url' ]} " )
258+ elif state ["status" ] in ("posting" , "uncertain" ):
259+ print ("Results saved; publication outcome uncertain." )
260+ else :
261+ print ("Results saved but not published." )
262+ print (f"Publication status: { bundle / 'STATUS.md' } " )
263+ if state ["status" ] != "published" :
264+ print (f"Publish / retry: { shlex .quote (str (bundle / 'publish.sh' ))} " )
265+
266+
267+ def find_comment (state ):
268+ target = state ["target" ]
269+ pages = json .loads (
270+ gh (
271+ "api" ,
272+ f"repos/{ target ['repository' ]} /issues/{ target ['pr' ]} /comments" ,
273+ "--hostname" ,
274+ "github.com" ,
275+ "--paginate" ,
276+ "--slurp" ,
277+ )
278+ )
279+ marker = f"<!-- abench:{ state ['id' ]} -->"
280+ return next (
281+ (
282+ c
283+ for page in pages
284+ for c in page
285+ if marker in (c .get ("body" ) or "" ) or c ["id" ] == state .get ("comment_id" )
286+ ),
287+ None ,
288+ )
289+
290+
291+ def verify_publication (bundle , state ):
292+ """Read GitHub only; never recreate or edit a comment during verification."""
293+ try :
294+ found = find_comment (state )
295+ except (ValueError , OSError ) as error :
296+ state ["verification_error" ] = str (error )
297+ save_status (bundle , state )
298+ raise
299+ state ["last_verified_at" ] = now ()
300+ state .pop ("verification_error" , None )
301+ if found :
302+ state .update (
303+ status = "published" , comment_id = found ["id" ], comment_url = found ["html_url" ]
304+ )
305+ state .pop ("error" , None )
306+ elif state .get ("comment_url" ):
307+ state ["status" ] = "missing"
308+ save_status (bundle , state )
309+
310+
311+ def prepare_publication (root ):
312+ """Create local publication controls without reading benchmark measurements."""
147313 plan = read_json (root / "suite.json" )
148314 if not plan :
149315 raise ValueError (f"No suite.json in { root } " )
@@ -160,7 +326,20 @@ def build_bundle(root):
160326 raise ValueError ("Publication target differs from the saved publication state" )
161327 if not state :
162328 state = {"target" : config , "id" : str (uuid .uuid4 ()), "status" : "prepared" }
329+ state ["checkout" ] = local_checkout ()
163330 write_json (state_path , state )
331+ if "checkout" not in state :
332+ state ["checkout" ] = local_checkout ()
333+ save_status (bundle , state )
334+ write_launcher (bundle , state .get ("checkout" ))
335+ return bundle , state
336+
337+
338+ def build_bundle (root ):
339+ """Rebuild shareable artifacts from retained results, without GitHub access."""
340+ bundle , state = prepare_publication (root )
341+ plan = read_json (root / "suite.json" )
342+ config = state ["target" ]
164343 marker = f"<!-- abench:{ state ['id' ]} -->"
165344 runs = []
166345 names = []
@@ -240,8 +419,6 @@ def elapsed(run):
240419 "" ,
241420 "" ,
242421 "Valid runs only. Mean ± population standard deviation across worker executions, not confidence intervals. Parallel component times must not be summed as wall time." ,
243- "" ,
244- "The interactive HTML report and JSON remain in the experiment output directory." ,
245422 ]
246423 (bundle / "comment.md" ).write_text ("\n " .join (lines ) + "\n " )
247424 xmax = (
@@ -280,7 +457,7 @@ def elapsed(run):
280457 return bundle , state
281458
282459
283- def publish (root , * , dry_run = False ):
460+ def publish (root , * , dry_run = False , status_only = False , verify = False ):
284461 """Publish once per suite; recover a successful comment after a lost response."""
285462 root = Path (root ).expanduser ().resolve ()
286463 if not (root / "suite.json" ).is_file ():
@@ -290,30 +467,30 @@ def publish(root, *, dry_run=False):
290467 fcntl .flock (lock , fcntl .LOCK_EX | fcntl .LOCK_NB )
291468 except BlockingIOError as error :
292469 raise ValueError ("Publication is already running for this suite" ) from error
470+ if status_only or verify :
471+ bundle , state = prepare_publication (root )
472+ if verify :
473+ verify_publication (bundle , state )
474+ print ((bundle / "STATUS.md" ).read_text ())
475+ return state .get ("comment_url" )
293476 bundle , state = build_bundle (root )
294477 if dry_run :
295478 print (f"Publication preview: { bundle / 'comment.md' } " )
479+ completion (bundle , state )
296480 return None
481+ if state .get ("status" ) == "missing" :
482+ raise ValueError (
483+ "The previously published comment was not found on GitHub; not reposting automatically. See publication/STATUS.md."
484+ )
297485 if state .get ("comment_url" ):
298- print ( f"Already published: { state [ 'comment_url' ] } " )
486+ completion ( bundle , state )
299487 return state ["comment_url" ]
300488 try :
489+ state ["last_attempt_at" ] = now ()
490+ save_status (bundle , state )
301491 config = state ["target" ]
302492 current = preflight (config )
303- marker = f"<!-- abench:{ state ['id' ]} -->"
304- comments = json .loads (
305- gh (
306- "api" ,
307- f"repos/{ config ['repository' ]} /issues/{ config ['pr' ]} /comments" ,
308- "--hostname" ,
309- "github.com" ,
310- "--paginate" ,
311- "--slurp" ,
312- )
313- )
314- found = next (
315- (c for page in comments for c in page if marker in c ["body" ]), None
316- )
493+ found = find_comment (state )
317494 if not found :
318495 snapshot = read_json (root / "suite.json" ).get ("publication_pr" , {})
319496 body = (bundle / "comment.md" ).read_text ()
@@ -332,8 +509,8 @@ def publish(root, *, dry_run=False):
332509 # Resolve relative image references from the bundle, including
333510 # output directories containing spaces or Markdown punctuation.
334511 (bundle / "upload.md" ).write_text (body )
335- state [ " status" ] = "posting"
336- write_json (bundle / "state.json" , state )
512+ state . update ( status = "posting" , last_attempt_at = now ())
513+ save_status (bundle , state )
337514 url = gh (
338515 "pr" ,
339516 "comment" ,
@@ -356,16 +533,26 @@ def publish(root, *, dry_run=False):
356533 found = {"id" : int (match [1 ]), "html_url" : match [0 ]}
357534 state .update (
358535 status = "published" ,
536+ published_at = state .get ("published_at" ) or now (),
359537 comment_id = found ["id" ],
360538 comment_url = found ["html_url" ],
361539 )
362540 state .pop ("error" , None )
363- write_json (bundle / "state.json" , state )
364- except (ValueError , OSError ) as error :
365- state .update (status = "failed" , error = str (error ))
366- write_json (bundle / "state.json" , state )
541+ save_status (bundle , state )
542+ except (ValueError , OSError , KeyboardInterrupt ) as error :
543+ state .update (
544+ status = "uncertain"
545+ if state ["status" ] in ("posting" , "uncertain" )
546+ else "failed" ,
547+ error = str (error ) or "Publication interrupted" ,
548+ last_attempt_at = state .get ("last_attempt_at" ) or now (),
549+ )
550+ save_status (bundle , state )
551+ completion (bundle , state )
552+ if isinstance (error , KeyboardInterrupt ):
553+ raise
367554 raise ValueError (
368- f"{ error } \n Results retained. Retry: abench publish { root } "
555+ f"{ error } \n Results retained. Retry: { shlex . quote ( str ( bundle / 'publish.sh' )) } "
369556 ) from error
370- print ( f"Published: { state [ 'comment_url' ] } " )
557+ completion ( bundle , state )
371558 return state ["comment_url" ]
0 commit comments