1use std::path::Path;
4use std::time::Duration;
5
6use fallow_output::{
7 COMBINED_SCHEMA_VERSION, CombinedMeta, CombinedOutput, HealthReport, check_meta, dupes_meta,
8 harmonize_dead_code_health_suppress_line_actions, health_meta, retain_reported_rules,
9 serialize_combined_json_output, strip_root_prefix,
10};
11use fallow_types::envelope::{ElapsedMs, SchemaVersion, ToolVersion};
12use fallow_types::output::NextStep;
13use fallow_types::results::AnalysisResults;
14use fallow_types::workspace::WorkspaceDiagnostic;
15
16use crate::{
17 CheckJsonExtraOutputs, CheckJsonPayloadInput, DupesReportPayload, serialize_check_json_payload,
18};
19
20pub struct CombinedCheckJsonSection<'a> {
22 pub results: &'a AnalysisResults,
24 pub root: &'a Path,
26 pub elapsed: Duration,
28 pub config_fixable: bool,
31 pub extras: CheckJsonExtraOutputs,
33}
34
35pub struct CombinedJsonOutputInput<'a> {
37 pub package_baselines: Vec<fallow_output::PackageBaselineStatus>,
39 pub gate_outcomes: Option<fallow_output::GateOutcomes>,
42 pub request_outcomes: Option<fallow_output::RequestOutcomes>,
47
48 pub check: Option<CombinedCheckJsonSection<'a>>,
50 pub dupes: Option<&'a DupesReportPayload>,
52 pub health: Option<&'a HealthReport>,
54 pub root: &'a Path,
56 pub elapsed: Duration,
58 pub explain: bool,
60 pub type_aware: Option<fallow_types::envelope::TypeAwareMeta>,
63 pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
68 pub next_steps: Vec<NextStep>,
70 pub telemetry_analysis_run_id: Option<&'a str>,
72 pub skipped: Vec<fallow_output::SkippedAnalysis>,
75}
76
77pub fn serialize_combined_json(
83 input: CombinedJsonOutputInput<'_>,
84) -> Result<serde_json::Value, serde_json::Error> {
85 let mut check_results = input.check.as_ref().map(|section| section.results.clone());
86 let mut health_report = input.health.cloned();
87 harmonize_dead_code_health_suppress_line_actions(
88 check_results.as_mut(),
89 health_report.as_mut(),
90 );
91
92 let check = if let Some(section) = input.check {
93 if let Some(results) = check_results.as_ref() {
94 Some(serialize_combined_check_json(section, results)?)
95 } else {
96 None
97 }
98 } else {
99 None
100 };
101 let dupes = serialize_combined_dupes_json(input.dupes, input.root)?;
102 let health = serialize_combined_health_json(health_report.as_ref(), input.root)?;
103
104 let mut meta = input
105 .explain
106 .then(|| combined_meta_for_output(check.is_some(), dupes.is_some(), health.is_some()));
107 if let Some(type_aware) = input.type_aware {
108 let combined_meta = meta.get_or_insert(CombinedMeta {
109 check: None,
110 dupes: None,
111 health: None,
112 telemetry: None,
113 });
114 let check_meta = combined_meta
115 .check
116 .get_or_insert_with(fallow_types::envelope::Meta::default);
117 check_meta.type_aware = Some(type_aware);
118 }
119 if let (Some(results), Some(check_meta)) = (
120 check_results.as_ref(),
121 meta.as_mut().and_then(|meta| meta.check.as_mut()),
122 ) {
123 retain_reported_rules(check_meta, [results]);
124 }
125
126 let output = CombinedOutput {
127 package_baselines: input.package_baselines,
128 schema_version: SchemaVersion(COMBINED_SCHEMA_VERSION),
129 version: ToolVersion(env!("CARGO_PKG_VERSION").to_string()),
130 elapsed_ms: ElapsedMs(elapsed_ms_for_output(input.elapsed)),
131 gate_outcomes: input.gate_outcomes,
132 request_outcomes: input.request_outcomes,
133 meta,
134 check,
135 dupes,
136 health,
137 workspace_diagnostics: input.workspace_diagnostics,
138 next_steps: input.next_steps,
139 skipped: input.skipped,
140 };
141
142 let mut value = serialize_combined_json_output(output, input.telemetry_analysis_run_id)?;
143 if let Some(diagnostics) = value.get_mut("workspace_diagnostics") {
144 strip_root_prefix(diagnostics, &format!("{}/", input.root.display()));
145 }
146 Ok(value)
147}
148
149fn serialize_combined_check_json(
150 section: CombinedCheckJsonSection<'_>,
151 results: &AnalysisResults,
152) -> Result<serde_json::Value, serde_json::Error> {
153 serialize_check_json_payload(CheckJsonPayloadInput {
154 results,
155 root: section.root,
156 elapsed: section.elapsed,
157 config_fixable: section.config_fixable,
158 extras: section.extras,
159 workspace_diagnostics: Vec::new(),
160 })
161}
162
163pub fn serialize_combined_dupes_json(
170 dupes: Option<&DupesReportPayload>,
171 root: &Path,
172) -> Result<Option<serde_json::Value>, serde_json::Error> {
173 let Some(payload) = dupes else {
174 return Ok(None);
175 };
176 let mut json = serde_json::to_value(payload)?;
177 let root_prefix = format!("{}/", root.display());
178 strip_root_prefix(&mut json, &root_prefix);
179 Ok(Some(json))
180}
181
182pub fn serialize_combined_health_json(
188 health: Option<&HealthReport>,
189 root: &Path,
190) -> Result<Option<serde_json::Value>, serde_json::Error> {
191 let Some(report) = health else {
192 return Ok(None);
193 };
194 let mut json = serde_json::to_value(report)?;
195 let root_prefix = format!("{}/", root.display());
196 strip_root_prefix(&mut json, &root_prefix);
197 Ok(Some(json))
198}
199
200fn elapsed_ms_for_output(elapsed: Duration) -> u64 {
201 u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX)
202}
203
204fn combined_meta_for_output(
205 include_check: bool,
206 include_dupes: bool,
207 include_health: bool,
208) -> CombinedMeta {
209 CombinedMeta {
210 check: include_check.then(check_meta),
211 dupes: include_dupes.then(dupes_meta),
212 health: include_health.then(health_meta),
213 telemetry: None,
214 }
215}
216
217#[cfg(test)]
218mod tests {
219 use std::time::Duration;
220
221 use fallow_output::{
222 ComplexityViolation, ExceededThreshold, FindingSeverity, HealthFinding, HealthReport,
223 };
224 use fallow_types::output_dead_code::UnusedExportFinding;
225 use fallow_types::output_health::{HealthFindingAction, HealthFindingActionType};
226 use fallow_types::results::{AnalysisResults, UnusedExport};
227 use fallow_types::workspace::{WorkspaceDiagnostic, WorkspaceDiagnosticKind};
228
229 use super::{CombinedCheckJsonSection, CombinedJsonOutputInput, serialize_combined_json};
230
231 #[test]
232 fn combined_json_root_contains_stable_envelope_fields() {
233 let root = serialize_combined_json(CombinedJsonOutputInput {
234 package_baselines: Vec::new(),
235 gate_outcomes: None,
236 request_outcomes: None,
237 check: None,
238 dupes: None,
239 health: None,
240 root: std::path::Path::new("."),
241 elapsed: Duration::from_millis(42),
242 explain: false,
243 type_aware: None,
244 workspace_diagnostics: Vec::new(),
245 next_steps: Vec::new(),
246 telemetry_analysis_run_id: None,
247 skipped: Vec::new(),
248 })
249 .expect("combined JSON root");
250
251 assert_eq!(
252 root.get("kind").and_then(serde_json::Value::as_str),
253 Some("combined")
254 );
255 assert_eq!(
256 root.get("elapsed_ms").and_then(serde_json::Value::as_u64),
257 Some(42)
258 );
259 assert!(root.get("schema_version").is_some());
260 assert!(root.get("version").is_some());
261 }
262
263 #[test]
264 fn combined_json_harmonizes_dead_code_and_health_suppress_actions_before_serialization() {
265 let root = std::path::Path::new("/project");
266 let path = root.join("src/shared.ts");
267 let mut results = AnalysisResults::default();
268 results
269 .unused_exports
270 .push(UnusedExportFinding::with_actions(UnusedExport {
271 path: path.clone(),
272 export_name: "value".to_string(),
273 is_type_only: false,
274 line: 7,
275 col: 0,
276 span_start: 0,
277 is_re_export: false,
278 deprecated: false,
279 deprecated_reason: None,
280 }));
281 let health = HealthReport {
282 findings: vec![HealthFinding::new(
283 ComplexityViolation {
284 path,
285 name: "expensive".to_string(),
286 line: 7,
287 col: 0,
288 cyclomatic: 22,
289 standard_cyclomatic: None,
290 cognitive: 18,
291 line_count: 40,
292 param_count: 1,
293 react_hook_count: 0,
294 react_jsx_max_depth: 0,
295 react_prop_count: 0,
296 react_hook_profile: None,
297 exceeded: ExceededThreshold::Both,
298 effective_severity: None,
299 severity: FindingSeverity::High,
300 crap: None,
301 mutation: None,
302 coverage_pct: None,
303 coverage_tier: None,
304 coverage_source: None,
305 inherited_from: None,
306 component_rollup: None,
307 contributions: Vec::new(),
308 effective_thresholds: None,
309 threshold_source: None,
310 max_file_lines: None,
311 },
312 vec![HealthFindingAction {
313 kind: HealthFindingActionType::SuppressLine,
314 auto_fixable: false,
315 description: "Suppress with an inline comment above the function declaration"
316 .to_string(),
317 note: None,
318 comment: Some("// fallow-ignore-next-line complexity".to_string()),
319 placement: Some("above-function-declaration".to_string()),
320 target_path: None,
321 }],
322 None,
323 )],
324 ..HealthReport::default()
325 };
326
327 let output = serialize_combined_json(CombinedJsonOutputInput {
328 package_baselines: Vec::new(),
329 gate_outcomes: None,
330 request_outcomes: None,
331 check: Some(CombinedCheckJsonSection {
332 results: &results,
333 root,
334 elapsed: Duration::ZERO,
335 config_fixable: false,
336 extras: crate::CheckJsonExtraOutputs::default(),
337 }),
338 dupes: None,
339 health: Some(&health),
340 root,
341 elapsed: Duration::ZERO,
342 explain: false,
343 type_aware: None,
344 workspace_diagnostics: Vec::new(),
345 next_steps: Vec::new(),
346 telemetry_analysis_run_id: None,
347 skipped: Vec::new(),
348 })
349 .expect("combined JSON");
350
351 assert_eq!(
352 output["check"]["unused_exports"][0]["actions"][1]["comment"],
353 "// fallow-ignore-next-line unused-export, complexity"
354 );
355 assert_eq!(
356 output["health"]["findings"][0]["actions"][0]["comment"],
357 "// fallow-ignore-next-line unused-export, complexity"
358 );
359 }
360
361 fn combined_json_with_diagnostics(
362 root: &std::path::Path,
363 include_check: bool,
364 workspace_diagnostics: Vec<WorkspaceDiagnostic>,
365 ) -> serde_json::Value {
366 let results = AnalysisResults::default();
367 serialize_combined_json(CombinedJsonOutputInput {
368 package_baselines: Vec::new(),
369 gate_outcomes: None,
370 request_outcomes: None,
371 check: include_check.then(|| CombinedCheckJsonSection {
372 results: &results,
373 root,
374 elapsed: Duration::ZERO,
375 config_fixable: false,
376 extras: crate::CheckJsonExtraOutputs::default(),
377 }),
378 dupes: None,
379 health: None,
380 root,
381 elapsed: Duration::ZERO,
382 explain: false,
383 type_aware: None,
384 workspace_diagnostics,
385 next_steps: Vec::new(),
386 telemetry_analysis_run_id: None,
387 skipped: Vec::new(),
388 })
389 .expect("combined JSON")
390 }
391
392 fn malformed_yaml_diagnostic(root: &std::path::Path) -> WorkspaceDiagnostic {
393 WorkspaceDiagnostic::new(
394 root,
395 root.join("pnpm-workspace.yaml"),
396 WorkspaceDiagnosticKind::MalformedPnpmWorkspaceYaml {
397 error: "could not find expected ':'".to_owned(),
398 },
399 )
400 }
401
402 #[test]
407 fn combined_root_carries_workspace_diagnostics_root_relative_or_omits_them() {
408 let root = std::path::Path::new("/project");
409 let output =
410 combined_json_with_diagnostics(root, true, vec![malformed_yaml_diagnostic(root)]);
411 assert_eq!(
412 output["workspace_diagnostics"][0]["kind"],
413 "malformed-pnpm-workspace-yaml"
414 );
415 assert_eq!(
416 output["workspace_diagnostics"][0]["path"],
417 "pnpm-workspace.yaml"
418 );
419 assert!(
420 output["check"].is_object(),
421 "the check section is present, so the absence check below is not vacuous: {output}"
422 );
423 assert!(
424 output["check"].get("workspace_diagnostics").is_none(),
425 "the check section is not a second carrier: {output}"
426 );
427
428 let empty = combined_json_with_diagnostics(root, true, Vec::new());
429 assert!(
430 empty.get("workspace_diagnostics").is_none(),
431 "an empty list is omitted from the combined root: {empty}"
432 );
433 }
434
435 #[test]
439 fn combined_root_carries_workspace_diagnostics_without_a_check_section() {
440 let root = std::path::Path::new("/project");
441 let output =
442 combined_json_with_diagnostics(root, false, vec![malformed_yaml_diagnostic(root)]);
443 assert!(
444 output.get("check").is_none(),
445 "this run has no check section: {output}"
446 );
447 assert_eq!(
448 output["workspace_diagnostics"][0]["kind"],
449 "malformed-pnpm-workspace-yaml"
450 );
451 assert_eq!(
452 output["workspace_diagnostics"][0]["path"],
453 "pnpm-workspace.yaml"
454 );
455 }
456}