Skip to main content

fallow_api/
combined_output.rs

1//! Combined JSON output assembly shared by CLI and programmatic consumers.
2
3use 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
20/// Dead-code section inputs for a bare combined JSON report.
21pub struct CombinedCheckJsonSection<'a> {
22    /// Typed dead-code results serialized into the `check` section.
23    pub results: &'a AnalysisResults,
24    /// Project root; its prefix is stripped from paths inside the section.
25    pub root: &'a Path,
26    /// Dead-code analysis wall time, emitted as the section's `elapsed_ms`.
27    pub elapsed: Duration,
28    /// Whether duplicate-export findings can be auto-fixed through config;
29    /// propagated onto their fix actions.
30    pub config_fixable: bool,
31    /// Caller-computed baseline and regression sections.
32    pub extras: CheckJsonExtraOutputs,
33}
34
35/// Inputs for bare `fallow --format json` output assembly.
36pub struct CombinedJsonOutputInput<'a> {
37    /// Applied refs for exact workspace package roots.
38    pub package_baselines: Vec<fallow_output::PackageBaselineStatus>,
39    /// Every gate this run evaluated, absent when it evaluated none. The
40    /// programmatic route runs no CLI-layer gate and leaves this `None`.
41    pub gate_outcomes: Option<fallow_output::GateOutcomes>,
42    /// Every narrowing or shaping request this run received, absent when it
43    /// was asked for nothing. The programmatic route resolves no CLI flag and
44    /// leaves this `None`; an entry whose `status` is not `applied` means the
45    /// report is wider than what was asked for.
46    pub request_outcomes: Option<fallow_output::RequestOutcomes>,
47
48    /// Dead-code section; `None` omits `check` from the envelope.
49    pub check: Option<CombinedCheckJsonSection<'a>>,
50    /// Duplication section; `None` omits `dupes` from the envelope.
51    pub dupes: Option<&'a DupesReportPayload>,
52    /// Health section; `None` omits `health` from the envelope.
53    pub health: Option<&'a HealthReport>,
54    /// Project root; its prefix is stripped from paths in every section.
55    pub root: &'a Path,
56    /// Total wall time across sections, emitted as the root `elapsed_ms`.
57    pub elapsed: Duration,
58    /// Emit per-section explain metadata under `meta`.
59    pub explain: bool,
60    /// Type-aware pass metadata, merged into the check section's meta even
61    /// when `explain` is off.
62    pub type_aware: Option<fallow_types::envelope::TypeAwareMeta>,
63    /// Workspace, source-discovery, and analysis-stage diagnostics for the
64    /// run: the same list the standalone envelopes carry, emitted on the
65    /// combined root and omitted when empty. The root is the only carrier, so
66    /// a run that skips a section still reports them (issue #2366).
67    pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
68    /// Suggested follow-up commands for the consumer.
69    pub next_steps: Vec<NextStep>,
70    /// Analysis run id stamped into telemetry metadata when present.
71    pub telemetry_analysis_run_id: Option<&'a str>,
72    /// Each analysis that the run skips, with the reason. The CLI leaves it
73    /// empty.
74    pub skipped: Vec<fallow_output::SkippedAnalysis>,
75}
76
77/// Build and serialize bare combined JSON through the API output boundary.
78///
79/// # Errors
80///
81/// Returns a serde error when any typed section cannot be converted to JSON.
82pub 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
163/// Build a combined duplication section without adding a nested root envelope.
164///
165/// # Errors
166///
167/// Returns a serde error when the typed duplication payload cannot be
168/// serialized.
169pub 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
182/// Build a combined health section without adding a nested root envelope.
183///
184/// # Errors
185///
186/// Returns a serde error when the typed health payload cannot be serialized.
187pub 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                    override_comment_line: None,
311                    max_file_lines: None,
312                },
313                vec![HealthFindingAction {
314                    kind: HealthFindingActionType::SuppressLine,
315                    auto_fixable: false,
316                    description: "Suppress with an inline comment above the function declaration"
317                        .to_string(),
318                    note: None,
319                    comment: Some("// fallow-ignore-next-line complexity".to_string()),
320                    placement: Some("above-function-declaration".to_string()),
321                    target_path: None,
322                }],
323                None,
324            )],
325            ..HealthReport::default()
326        };
327
328        let output = serialize_combined_json(CombinedJsonOutputInput {
329            package_baselines: Vec::new(),
330            gate_outcomes: None,
331            request_outcomes: None,
332            check: Some(CombinedCheckJsonSection {
333                results: &results,
334                root,
335                elapsed: Duration::ZERO,
336                config_fixable: false,
337                extras: crate::CheckJsonExtraOutputs::default(),
338            }),
339            dupes: None,
340            health: Some(&health),
341            root,
342            elapsed: Duration::ZERO,
343            explain: false,
344            type_aware: None,
345            workspace_diagnostics: Vec::new(),
346            next_steps: Vec::new(),
347            telemetry_analysis_run_id: None,
348            skipped: Vec::new(),
349        })
350        .expect("combined JSON");
351
352        assert_eq!(
353            output["check"]["unused_exports"][0]["actions"][1]["comment"],
354            "// fallow-ignore-next-line unused-export, complexity"
355        );
356        assert_eq!(
357            output["health"]["findings"][0]["actions"][0]["comment"],
358            "// fallow-ignore-next-line unused-export, complexity"
359        );
360    }
361
362    fn combined_json_with_diagnostics(
363        root: &std::path::Path,
364        include_check: bool,
365        workspace_diagnostics: Vec<WorkspaceDiagnostic>,
366    ) -> serde_json::Value {
367        let results = AnalysisResults::default();
368        serialize_combined_json(CombinedJsonOutputInput {
369            package_baselines: Vec::new(),
370            gate_outcomes: None,
371            request_outcomes: None,
372            check: include_check.then(|| CombinedCheckJsonSection {
373                results: &results,
374                root,
375                elapsed: Duration::ZERO,
376                config_fixable: false,
377                extras: crate::CheckJsonExtraOutputs::default(),
378            }),
379            dupes: None,
380            health: None,
381            root,
382            elapsed: Duration::ZERO,
383            explain: false,
384            type_aware: None,
385            workspace_diagnostics,
386            next_steps: Vec::new(),
387            telemetry_analysis_run_id: None,
388            skipped: Vec::new(),
389        })
390        .expect("combined JSON")
391    }
392
393    fn malformed_yaml_diagnostic(root: &std::path::Path) -> WorkspaceDiagnostic {
394        WorkspaceDiagnostic::new(
395            root,
396            root.join("pnpm-workspace.yaml"),
397            WorkspaceDiagnosticKind::MalformedPnpmWorkspaceYaml {
398                error: "could not find expected ':'".to_owned(),
399            },
400        )
401    }
402
403    /// Issue #2366: the combined root carries the diagnostics it is given,
404    /// root-relative like the standalone envelopes, and omits the array when
405    /// there are none. The `check` section never grows its own copy, so the
406    /// document has exactly one carrier.
407    #[test]
408    fn combined_root_carries_workspace_diagnostics_root_relative_or_omits_them() {
409        let root = std::path::Path::new("/project");
410        let output =
411            combined_json_with_diagnostics(root, true, vec![malformed_yaml_diagnostic(root)]);
412        assert_eq!(
413            output["workspace_diagnostics"][0]["kind"],
414            "malformed-pnpm-workspace-yaml"
415        );
416        assert_eq!(
417            output["workspace_diagnostics"][0]["path"],
418            "pnpm-workspace.yaml"
419        );
420        assert!(
421            output["check"].is_object(),
422            "the check section is present, so the absence check below is not vacuous: {output}"
423        );
424        assert!(
425            output["check"].get("workspace_diagnostics").is_none(),
426            "the check section is not a second carrier: {output}"
427        );
428
429        let empty = combined_json_with_diagnostics(root, true, Vec::new());
430        assert!(
431            empty.get("workspace_diagnostics").is_none(),
432            "an empty list is omitted from the combined root: {empty}"
433        );
434    }
435
436    /// Issue #2366: the carrier does not depend on which sections ran, so a
437    /// combined run without a `check` section (`--skip check`, `--only health`,
438    /// `--only dupes`) still reports the diagnostics.
439    #[test]
440    fn combined_root_carries_workspace_diagnostics_without_a_check_section() {
441        let root = std::path::Path::new("/project");
442        let output =
443            combined_json_with_diagnostics(root, false, vec![malformed_yaml_diagnostic(root)]);
444        assert!(
445            output.get("check").is_none(),
446            "this run has no check section: {output}"
447        );
448        assert_eq!(
449            output["workspace_diagnostics"][0]["kind"],
450            "malformed-pnpm-workspace-yaml"
451        );
452        assert_eq!(
453            output["workspace_diagnostics"][0]["path"],
454            "pnpm-workspace.yaml"
455        );
456    }
457}