88import sys
99from pathlib import Path
1010
11- from ci_lint .cargo_messages import load_artifacts_file
11+ from ci_lint .cargo_messages import JsonValue , load_artifacts_file
1212from ci_lint .cargo_scan import discover_workspace
1313from ci_lint .finding import Status
14+ from ci_lint .github_api import default_fetch
1415from ci_lint .plan import Plan , PlanError , build_act_event , compute_plan
1516from ci_lint .precheck import (
1617 has_violations ,
1920 run_precheck ,
2021 write_step_summary ,
2122)
23+ from ci_lint .reuse import ReuseResult , compute_reuse , empty_result
2224from ci_lint .runtime .gate import compute_gate
2325from ci_lint .runtime .gate import render_text as render_gate_text
2426from ci_lint .runtime .gate import to_json_dict as gate_to_json_dict
@@ -61,6 +63,104 @@ def _sha_from_event(event: dict[str, object]) -> str | None:
6163 return None
6264
6365
66+ def _head_sha_from_event (event : dict [str , object ]) -> str | None :
67+ pr = event .get ("pull_request" )
68+ if isinstance (pr , dict ):
69+ head = pr .get ("head" )
70+ if isinstance (head , dict ) and isinstance (head .get ("sha" ), str ):
71+ return head ["sha" ]
72+ return None
73+
74+
75+ def _compute_reuse_for_plan (plan : Plan , event_name : str , event : dict [str , object ]) -> ReuseResult :
76+ """Round-3A brief, Part 2. Only ever makes a network call for the
77+ `pull_request` event, and only when GITHUB_TOKEN, GITHUB_REPOSITORY,
78+ and the PR's head SHA (from the event payload) are all available --
79+ otherwise (any other event, or missing credentials/context) returns a
80+ deterministic "reuse nothing" result with no I/O, so this is always
81+ network-free in unit tests and on push/schedule/workflow_dispatch."""
82+
83+ lane_digests = dict (plan .lane_digests )
84+ if event_name != "pull_request" :
85+ return empty_result (lane_digests )
86+ token = os .environ .get ("GITHUB_TOKEN" )
87+ repo_slug = os .environ .get ("GITHUB_REPOSITORY" )
88+ head_sha = _head_sha_from_event (event )
89+ if not token or not repo_slug or not head_sha :
90+ return empty_result (lane_digests )
91+ result = compute_reuse (
92+ repo = repo_slug ,
93+ head_sha = head_sha ,
94+ current_run_id = os .environ .get ("GITHUB_RUN_ID" ),
95+ lane_digests = lane_digests ,
96+ fetch = default_fetch ,
97+ token = token ,
98+ )
99+ if result .warning :
100+ print (f"ci-lint: { result .warning } " , file = sys .stderr )
101+ return result
102+
103+
104+ def _plan_github_output_lines (plan : Plan , reuse_result : ReuseResult | None ) -> list [str ]:
105+ payload = plan .to_json_dict ()
106+ compact = json .dumps (payload , separators = ("," , ":" ))
107+ platforms_json = json .dumps ([p .id for p in plan .platforms ])
108+ cross_platforms_json = json .dumps ([p .id for p in plan .platforms if p .group != "linux" ])
109+ suites_json = json .dumps (list (plan .suites ))
110+ dylint_targets_json = json .dumps (list (plan .dylint_targets ))
111+ platform_lanes_json = json .dumps ([pl .to_json_dict () for pl in plan .platform_lanes ], separators = ("," , ":" ))
112+ fast_suites_json = json .dumps (list (plan .fast_suites ), separators = ("," , ":" ))
113+ lane_digests_json = json .dumps (dict (plan .lane_digests ), separators = ("," , ":" ))
114+
115+ lines = [
116+ f"plan={ compact } " ,
117+ f"platforms_json={ platforms_json } " ,
118+ f"cross_platforms_json={ cross_platforms_json } " ,
119+ f"suites_json={ suites_json } " ,
120+ f"dylint_targets_json={ dylint_targets_json } " ,
121+ f"needs_platform_lanes={ 'true' if plan .needs_platform_lanes else 'false' } " ,
122+ f"mergeable={ 'true' if plan .mergeable else 'false' } " ,
123+ # Round-3A brief, Part 1.
124+ f"platform_lanes_json={ platform_lanes_json } " ,
125+ f"fast_suites_json={ fast_suites_json } " ,
126+ f"lane_digests_json={ lane_digests_json } " ,
127+ ]
128+
129+ if reuse_result is not None :
130+ reused_platform_ids = {
131+ key .split (":" , 1 )[1 ]
132+ for key , entry in reuse_result .reuse .items ()
133+ if key .startswith ("platform:" ) and entry is not None
134+ }
135+ platform_lanes_todo = [
136+ pl .to_json_dict () for pl in plan .platform_lanes if pl .id not in reused_platform_ids
137+ ]
138+ reuse_json = json .dumps (reuse_result .to_json_dict (), separators = ("," , ":" ))
139+ platform_lanes_todo_json = json .dumps (platform_lanes_todo , separators = ("," , ":" ))
140+ fast_reused = reuse_result .reuse .get ("fast" ) is not None
141+ dylint_reused = reuse_result .reuse .get ("dylint" ) is not None
142+ lines .extend (
143+ [
144+ # Round-3A brief, Part 2.
145+ f"reuse_json={ reuse_json } " ,
146+ f"platform_lanes_todo_json={ platform_lanes_todo_json } " ,
147+ f"fast_reused={ 'true' if fast_reused else 'false' } " ,
148+ f"dylint_reused={ 'true' if dylint_reused else 'false' } " ,
149+ ]
150+ )
151+
152+ return lines
153+
154+
155+ def _write_plan_github_output (plan : Plan , reuse_result : ReuseResult | None ) -> None :
156+ gh_out = os .environ .get ("GITHUB_OUTPUT" )
157+ if not gh_out :
158+ return
159+ with open (gh_out , "a" , encoding = "utf-8" ) as fh :
160+ for line in _plan_github_output_lines (plan , reuse_result ):
161+ fh .write (line + "\n " )
162+
163+
64164def _cmd_precheck (args : argparse .Namespace ) -> int :
65165 repo_root = Path (args .repo ).resolve ()
66166 event = _load_event (args .event )
@@ -74,19 +174,29 @@ def _cmd_precheck(args: argparse.Namespace) -> int:
74174 print (render_text (result ))
75175 write_step_summary (result )
76176
77- if args .plan_out :
177+ if args .plan_out or args . github_output :
78178 ci , _ = load_ci_toml (repo_root )
79179 if ci is not None :
180+ event_name = "pull_request" if title else "push"
80181 try :
81182 plan = compute_plan (
82183 ci ,
83- event_name = "pull_request" if title else "push" ,
184+ event_name = event_name ,
84185 title = title ,
85186 dispatch_sha = _sha_from_event (event ),
187+ repo_root = repo_root ,
86188 )
87- Path (args .plan_out ).write_text (json .dumps (plan .to_json_dict (), indent = 2 ), encoding = "utf-8" )
88189 except PlanError as exc :
89190 print (f"ci-lint plan: { exc } " , file = sys .stderr )
191+ else :
192+ reuse_result = _compute_reuse_for_plan (plan , event_name , event ) if args .reuse else None
193+ if args .plan_out :
194+ payload = plan .to_json_dict ()
195+ if reuse_result is not None :
196+ payload ["reuse" ] = reuse_result .to_json_dict ()
197+ Path (args .plan_out ).write_text (json .dumps (payload , indent = 2 ), encoding = "utf-8" )
198+ if args .github_output :
199+ _write_plan_github_output (plan , reuse_result )
90200
91201 return 1 if has_violations (result ) else 0
92202
@@ -110,13 +220,22 @@ def _cmd_plan(args: argparse.Namespace) -> int:
110220
111221 try :
112222 plan = compute_plan (
113- ci , event_name = event_name , title = title , ref = args .ref , dispatch_sha = dispatch_sha
223+ ci ,
224+ event_name = event_name ,
225+ title = title ,
226+ ref = args .ref ,
227+ dispatch_sha = dispatch_sha ,
228+ repo_root = repo_root ,
114229 )
115230 except PlanError as exc :
116231 print (f"ci-lint plan: { exc } " , file = sys .stderr )
117232 return 1
118233
234+ reuse_result = _compute_reuse_for_plan (plan , event_name , event ) if args .reuse else None
235+
119236 payload = plan .to_json_dict ()
237+ if reuse_result is not None :
238+ payload ["reuse" ] = reuse_result .to_json_dict ()
120239 text = json .dumps (payload , indent = 2 )
121240 if args .out :
122241 Path (args .out ).write_text (text , encoding = "utf-8" )
@@ -126,23 +245,7 @@ def _cmd_plan(args: argparse.Namespace) -> int:
126245 Path (args .act ).write_text (json .dumps (build_act_event (title ), indent = 2 ), encoding = "utf-8" )
127246
128247 if args .github_output :
129- gh_out = os .environ .get ("GITHUB_OUTPUT" )
130- if gh_out :
131- compact = json .dumps (payload , separators = ("," , ":" ))
132- platforms_json = json .dumps ([p .id for p in plan .platforms ])
133- cross_platforms_json = json .dumps (
134- [p .id for p in plan .platforms if p .group != "linux" ]
135- )
136- suites_json = json .dumps (list (plan .suites ))
137- dylint_targets_json = json .dumps (list (plan .dylint_targets ))
138- with open (gh_out , "a" , encoding = "utf-8" ) as fh :
139- fh .write (f"plan={ compact } \n " )
140- fh .write (f"platforms_json={ platforms_json } \n " )
141- fh .write (f"cross_platforms_json={ cross_platforms_json } \n " )
142- fh .write (f"suites_json={ suites_json } \n " )
143- fh .write (f"dylint_targets_json={ dylint_targets_json } \n " )
144- fh .write (f"needs_platform_lanes={ 'true' if plan .needs_platform_lanes else 'false' } \n " )
145- fh .write (f"mergeable={ 'true' if plan .mergeable else 'false' } \n " )
248+ _write_plan_github_output (plan , reuse_result )
146249
147250 return 0
148251
@@ -221,7 +324,28 @@ def _cmd_gate(args: argparse.Namespace) -> int:
221324 print ("ci-lint gate: --plan and --needs must both be JSON objects" , file = sys .stderr )
222325 return 1
223326
224- report = compute_gate (plan , needs )
327+ reuse : dict [str , JsonValue ] | None = None
328+ if args .reuse :
329+ try :
330+ with open (args .reuse , encoding = "utf-8" ) as fh :
331+ reuse_raw = json .load (fh )
332+ except (OSError , json .JSONDecodeError ) as exc :
333+ print (f"ci-lint gate: cannot read --reuse { args .reuse !r} : { exc } " , file = sys .stderr )
334+ return 1
335+ if not isinstance (reuse_raw , dict ):
336+ print ("ci-lint gate: --reuse must be a JSON object" , file = sys .stderr )
337+ return 1
338+ reuse = reuse_raw
339+
340+ event = _load_event (args .event )
341+ head_sha = _head_sha_from_event (event )
342+ token = os .environ .get ("GITHUB_TOKEN" )
343+ repo_slug = os .environ .get ("GITHUB_REPOSITORY" )
344+ fetch = default_fetch if token and repo_slug else None
345+
346+ report = compute_gate (
347+ plan , needs , reuse = reuse , head_sha = head_sha , fetch = fetch , token = token , repo = repo_slug
348+ )
225349 print (json .dumps (gate_to_json_dict (report ), indent = 2 ) if args .json else render_gate_text (report ))
226350 if report .not_mergeable_message :
227351 print (report .not_mergeable_message , file = sys .stderr )
@@ -242,6 +366,16 @@ def build_parser() -> argparse.ArgumentParser:
242366 p_precheck .add_argument ("--event" , default = None )
243367 p_precheck .add_argument ("--title" , default = None )
244368 p_precheck .add_argument ("--plan-out" , default = None )
369+ p_precheck .add_argument (
370+ "--github-output" ,
371+ action = "store_true" ,
372+ help = "also write the plan's $GITHUB_OUTPUT keys (same as 'ci_lint plan --github-output')" ,
373+ )
374+ p_precheck .add_argument (
375+ "--reuse" ,
376+ action = "store_true" ,
377+ help = "compute title-edit reuse (round-3A Part 2) and include it in --plan-out/--github-output" ,
378+ )
245379 p_precheck .add_argument ("--json" , action = "store_true" )
246380 p_precheck .set_defaults (func = _cmd_precheck )
247381
@@ -255,6 +389,12 @@ def build_parser() -> argparse.ArgumentParser:
255389 p_plan .add_argument ("--github-output" , action = "store_true" )
256390 p_plan .add_argument ("--act" , default = None )
257391 p_plan .add_argument ("--sha" , default = None )
392+ p_plan .add_argument (
393+ "--reuse" ,
394+ action = "store_true" ,
395+ help = "look up title-edit reuse for pull_request events (round-3A Part 2); "
396+ "requires GITHUB_TOKEN + GITHUB_REPOSITORY and the event's PR head SHA, else reuses nothing" ,
397+ )
258398 p_plan .set_defaults (func = _cmd_plan )
259399
260400 p_units = sub .add_parser ("units" , help = "compile-unit count + RUST-011 from a cargo --message-format=json run" )
@@ -292,6 +432,17 @@ def build_parser() -> argparse.ArgumentParser:
292432 p_gate .add_argument ("--repo" , default = "." )
293433 p_gate .add_argument ("--plan" , required = True )
294434 p_gate .add_argument ("--needs" , required = True )
435+ p_gate .add_argument (
436+ "--reuse" ,
437+ default = None ,
438+ help = "path to the plan's reuse map JSON (round-3A Part 3; from "
439+ "'ci_lint plan --reuse's reuse_json/--out \" reuse\" key)" ,
440+ )
441+ p_gate .add_argument (
442+ "--event" ,
443+ default = None ,
444+ help = "pull_request event JSON, to read the PR head SHA for reuse re-verification" ,
445+ )
295446 p_gate .add_argument ("--json" , action = "store_true" )
296447 p_gate .set_defaults (func = _cmd_gate )
297448
0 commit comments