1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
//! Shared JSON output assembly for CLI and programmatic consumers.
use std::path::Path;
use std::time::Duration;
use fallow_output::{
CHECK_SCHEMA_VERSION, CheckGroupedEntry, CheckGroupedOutput, CheckOutput, CheckOutputInput,
DUPES_SCHEMA_VERSION, DupesOutput, DupesOutputInput, GroupByMode, RootEnvelopeMode,
apply_config_fixable_to_duplicate_exports, build_check_output, build_dupes_output,
harmonize_multi_kind_suppress_line_actions as harmonize_typed_suppress_line_actions,
strip_root_prefix,
};
use fallow_types::duplicates::DuplicationReport;
use fallow_types::envelope::{
BaselineDeltas, BaselineMatch, ElapsedMs, Meta, RegressionResult, SchemaVersion, ToolVersion,
};
use fallow_types::output::NextStep;
use fallow_types::results::AnalysisResults;
use fallow_types::workspace::WorkspaceDiagnostic;
use crate::{DupesReportPayload, DuplicationGroup, DuplicationGrouping, ResultGroup};
/// Inputs for `fallow dead-code --format json` output assembly.
pub struct CheckJsonOutputInput<'a> {
/// Typed dead-code results to serialize.
pub results: &'a AnalysisResults,
/// Project root; its prefix is stripped from every path in the output.
pub root: &'a Path,
/// Analysis wall time, emitted as `elapsed_ms`.
pub elapsed: Duration,
/// Whether duplicate-export findings can be auto-fixed through config;
/// propagated onto their fix actions.
pub config_fixable: bool,
/// Optional explain metadata block for the envelope.
pub meta: Option<Meta>,
/// Caller-computed baseline and regression sections.
pub extras: CheckJsonExtraOutputs,
/// Non-fatal per-file diagnostics collected during the workspace walk.
pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
/// Suggested follow-up commands for the consumer.
pub next_steps: Vec<NextStep>,
/// Whether the root envelope carries a `kind` discriminant.
pub envelope_mode: RootEnvelopeMode,
/// Analysis run id stamped into telemetry metadata when present.
pub telemetry_analysis_run_id: Option<&'a str>,
}
/// Inputs for the dead-code JSON payload without a root envelope.
pub struct CheckJsonPayloadInput<'a> {
/// Typed dead-code results to serialize.
pub results: &'a AnalysisResults,
/// Project root; its prefix is stripped from every path in the output.
pub root: &'a Path,
/// Analysis wall time, emitted as `elapsed_ms`.
pub elapsed: Duration,
/// Whether duplicate-export findings can be auto-fixed through config;
/// propagated onto their fix actions.
pub config_fixable: bool,
/// Caller-computed baseline and regression sections.
pub extras: CheckJsonExtraOutputs,
/// Non-fatal per-file diagnostics collected during the workspace walk.
pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
}
/// Optional root sections for dead-code JSON envelopes.
///
/// These fields are part of the output contract, but they are computed by
/// caller-specific workflows such as baseline and regression gates.
#[derive(Debug, Clone, Default)]
pub struct CheckJsonExtraOutputs {
/// Per-category issue count changes against the matched baseline.
pub baseline_deltas: Option<BaselineDeltas>,
/// Which baseline snapshot the run was compared against.
pub baseline: Option<BaselineMatch>,
/// This run's view of that baseline: counts, advisory verdict and the
/// `--fail-on-stale-baseline` verdict.
pub baseline_staleness: Option<fallow_output::BaselineStaleness>,
/// Outcome of the regression gate against the baseline.
pub regression: Option<RegressionResult>,
/// Every gate this run evaluated. The programmatic route runs no CLI-layer
/// gate, so a caller that computes none leaves this `None` and the envelope
/// key stays absent. An empty set is never emitted: it would assert that
/// gates were evaluated and none tripped, which is a different claim.
pub gate_outcomes: Option<fallow_output::GateOutcomes>,
/// Every narrowing or shaping request this run received, absent when it
/// was asked for nothing. The programmatic route resolves no CLI flag and
/// leaves this `None`; an entry whose `status` is not `applied` means the
/// report is wider than what was asked for.
pub request_outcomes: Option<fallow_output::RequestOutcomes>,
}
struct CheckJsonEnvelopeInput<'a> {
results: &'a AnalysisResults,
elapsed: Duration,
config_fixable: bool,
meta: Option<Meta>,
extras: CheckJsonExtraOutputs,
workspace_diagnostics: Vec<WorkspaceDiagnostic>,
next_steps: Vec<NextStep>,
}
/// Inputs for grouped dead-code JSON output assembly.
pub struct GroupedCheckJsonOutputInput<'a> {
/// This run's view of the loaded baseline, for baseline runs.
pub baseline_staleness: Option<fallow_output::BaselineStaleness>,
/// Every gate this run evaluated. The programmatic route runs no CLI-layer
/// gate, so a caller that computes none leaves this `None` and the envelope
/// key stays absent. An empty set is never emitted: it would assert that
/// gates were evaluated and none tripped, which is a different claim.
pub gate_outcomes: Option<fallow_output::GateOutcomes>,
/// Every narrowing or shaping request this run received, absent when it
/// was asked for nothing. The programmatic route resolves no CLI flag and
/// leaves this `None`; an entry whose `status` is not `applied` means the
/// report is wider than what was asked for.
pub request_outcomes: Option<fallow_output::RequestOutcomes>,
/// Results already partitioned into groups, in output order.
pub groups: &'a [ResultGroup],
/// Ungrouped results, used for the envelope's `total_issues` count.
pub original: &'a AnalysisResults,
/// Project root; its prefix is stripped from every path in the output.
pub root: &'a Path,
/// Analysis wall time, emitted as `elapsed_ms`.
pub elapsed: Duration,
/// Grouping axis recorded as `grouped_by` in the envelope.
pub grouped_by: GroupByMode,
/// Whether duplicate-export findings can be auto-fixed through config;
/// propagated onto their fix actions per group.
pub config_fixable: bool,
/// Optional explain metadata block for the envelope.
pub meta: Option<Meta>,
/// Non-fatal per-file diagnostics collected during the workspace walk.
pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
/// Suggested follow-up commands for the consumer.
pub next_steps: Vec<NextStep>,
/// Whether the root envelope carries a `kind` discriminant.
pub envelope_mode: RootEnvelopeMode,
/// Analysis run id stamped into telemetry metadata when present.
pub telemetry_analysis_run_id: Option<&'a str>,
}
/// Inputs for `fallow dupes --format json` output assembly.
pub struct DuplicationJsonOutputInput<'a> {
/// This run's view of the loaded duplication baseline, for baseline runs.
pub baseline_staleness: Option<fallow_output::BaselineStaleness>,
/// Every gate this run evaluated. The programmatic route runs no CLI-layer
/// gate, so a caller that computes none leaves this `None` and the envelope
/// key stays absent. An empty set is never emitted: it would assert that
/// gates were evaluated and none tripped, which is a different claim.
pub gate_outcomes: Option<fallow_output::GateOutcomes>,
/// Every narrowing or shaping request this run received, absent when it
/// was asked for nothing. The programmatic route resolves no CLI flag and
/// leaves this `None`; an entry whose `status` is not `applied` means the
/// report is wider than what was asked for.
pub request_outcomes: Option<fallow_output::RequestOutcomes>,
/// Typed duplication report to serialize.
pub report: &'a DuplicationReport,
/// Project root; its prefix is stripped from every path in the output.
pub root: &'a Path,
/// Analysis wall time, emitted as `elapsed_ms`.
pub elapsed: Duration,
/// Whether each clone instance carries its verbatim source text.
pub include_fragments: bool,
/// Optional explain metadata block for the envelope.
pub meta: Option<Meta>,
/// Non-fatal per-file diagnostics collected during the workspace walk.
pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
/// Suggested follow-up commands for the consumer.
pub next_steps: Vec<NextStep>,
/// Whether the root envelope carries a `kind` discriminant.
pub envelope_mode: RootEnvelopeMode,
/// Analysis run id stamped into telemetry metadata when present.
pub telemetry_analysis_run_id: Option<&'a str>,
}
/// Inputs for grouped duplication JSON output assembly.
pub struct GroupedDuplicationJsonOutputInput<'a> {
/// This run's view of the loaded duplication baseline, for baseline runs.
pub baseline_staleness: Option<fallow_output::BaselineStaleness>,
/// Every gate this run evaluated. The programmatic route runs no CLI-layer
/// gate, so a caller that computes none leaves this `None` and the envelope
/// key stays absent. An empty set is never emitted: it would assert that
/// gates were evaluated and none tripped, which is a different claim.
pub gate_outcomes: Option<fallow_output::GateOutcomes>,
/// Every narrowing or shaping request this run received, absent when it
/// was asked for nothing. The programmatic route resolves no CLI flag and
/// leaves this `None`; an entry whose `status` is not `applied` means the
/// report is wider than what was asked for.
pub request_outcomes: Option<fallow_output::RequestOutcomes>,
/// Typed duplication report to serialize.
pub report: &'a DuplicationReport,
/// Precomputed grouping whose groups replace the flat `groups` array.
pub grouping: &'a DuplicationGrouping,
/// Project root; its prefix is stripped from every path in the output.
pub root: &'a Path,
/// Analysis wall time, emitted as `elapsed_ms`.
pub elapsed: Duration,
/// Whether each clone instance carries its verbatim source text.
pub include_fragments: bool,
/// Optional explain metadata block for the envelope.
pub meta: Option<Meta>,
/// Non-fatal per-file diagnostics collected during the workspace walk.
pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
/// Suggested follow-up commands for the consumer.
pub next_steps: Vec<NextStep>,
/// Whether the root envelope carries a `kind` discriminant.
pub envelope_mode: RootEnvelopeMode,
/// Analysis run id stamped into telemetry metadata when present.
pub telemetry_analysis_run_id: Option<&'a str>,
}
/// Build and serialize dead-code JSON through the API-owned output boundary.
///
/// # Errors
///
/// Returns a serde error when the typed envelope cannot be converted to JSON.
pub fn serialize_check_json(
input: CheckJsonOutputInput<'_>,
) -> Result<serde_json::Value, serde_json::Error> {
let envelope = build_check_json_envelope(CheckJsonEnvelopeInput {
results: input.results,
elapsed: input.elapsed,
config_fixable: input.config_fixable,
meta: input.meta,
extras: input.extras,
workspace_diagnostics: input.workspace_diagnostics,
next_steps: input.next_steps,
});
let mut output = fallow_output::serialize_check_json_output(
envelope,
input.envelope_mode,
input.telemetry_analysis_run_id,
)?;
strip_json_root_prefix(&mut output, input.root);
Ok(output)
}
/// Build a dead-code JSON payload without adding a root envelope.
///
/// # Errors
///
/// Returns a serde error when the typed envelope cannot be converted to JSON.
pub fn serialize_check_json_payload(
input: CheckJsonPayloadInput<'_>,
) -> Result<serde_json::Value, serde_json::Error> {
let envelope = build_check_json_envelope(CheckJsonEnvelopeInput {
results: input.results,
elapsed: input.elapsed,
config_fixable: input.config_fixable,
meta: None,
extras: input.extras,
workspace_diagnostics: input.workspace_diagnostics,
next_steps: Vec::new(),
});
let mut output = serde_json::to_value(envelope)?;
strip_json_root_prefix(&mut output, input.root);
Ok(output)
}
/// Build and serialize grouped dead-code JSON through the API output boundary.
///
/// # Errors
///
/// Returns a serde error when the typed envelope cannot be converted to JSON.
pub fn serialize_grouped_check_json(
input: GroupedCheckJsonOutputInput<'_>,
) -> Result<serde_json::Value, serde_json::Error> {
let entries = input
.groups
.iter()
.map(|group| {
let mut results = group.results.clone();
apply_config_fixable_to_duplicate_exports(&mut results, input.config_fixable);
harmonize_typed_suppress_line_actions(&mut results);
CheckGroupedEntry {
key: group.key.clone(),
owners: group.owners.clone(),
total_issues: results.total_issues(),
results,
}
})
.collect();
let envelope = CheckGroupedOutput {
request_outcomes: input.request_outcomes,
schema_version: SchemaVersion(CHECK_SCHEMA_VERSION),
version: ToolVersion(env!("CARGO_PKG_VERSION").to_string()),
elapsed_ms: ElapsedMs(input.elapsed.as_millis() as u64),
grouped_by: input.grouped_by,
total_issues: input.original.total_issues(),
groups: entries,
baseline_staleness: input.baseline_staleness,
gate_outcomes: input.gate_outcomes,
meta: input.meta,
workspace_diagnostics: input.workspace_diagnostics,
next_steps: input.next_steps,
};
let mut output = fallow_output::serialize_check_grouped_json_output(
envelope,
input.envelope_mode,
input.telemetry_analysis_run_id,
)?;
strip_json_root_prefix(&mut output, input.root);
Ok(output)
}
/// Build and serialize duplication JSON through the API-owned output boundary.
///
/// # Errors
///
/// Returns a serde error when the typed envelope cannot be converted to JSON.
pub fn serialize_duplication_json(
input: DuplicationJsonOutputInput<'_>,
) -> Result<serde_json::Value, serde_json::Error> {
let payload =
DupesReportPayload::from_report_with_fragments(input.report, input.include_fragments);
let envelope: DupesOutput<DupesReportPayload, DuplicationGroup> =
build_dupes_output(DupesOutputInput {
gate_outcomes: input.gate_outcomes,
request_outcomes: input.request_outcomes,
schema_version: DUPES_SCHEMA_VERSION,
version: env!("CARGO_PKG_VERSION").to_string(),
elapsed: input.elapsed,
report: payload,
clone_groups_shown: input.report.clone_groups_shown(),
clone_groups_omitted: input.report.clone_groups_omitted(),
clone_families_shown: input.report.clone_families_shown(),
clone_families_omitted: input.report.clone_families_omitted(),
grouped_by: None,
total_issues: None,
groups: None,
baseline_staleness: input.baseline_staleness,
meta: input.meta,
workspace_diagnostics: input.workspace_diagnostics,
next_steps: input.next_steps,
});
let mut output = fallow_output::serialize_dupes_json_output(
envelope,
input.envelope_mode,
input.telemetry_analysis_run_id,
)?;
let root_prefix = format!("{}/", input.root.display());
strip_root_prefix(&mut output, &root_prefix);
Ok(output)
}
/// Build and serialize grouped duplication JSON through the API output boundary.
///
/// # Errors
///
/// Returns a serde error when the typed envelope cannot be converted to JSON.
pub fn serialize_grouped_duplication_json(
input: GroupedDuplicationJsonOutputInput<'_>,
) -> Result<serde_json::Value, serde_json::Error> {
let root_prefix = format!("{}/", input.root.display());
let payload =
DupesReportPayload::from_report_with_fragments(input.report, input.include_fragments);
let envelope: DupesOutput<DupesReportPayload, DuplicationGroup> =
build_dupes_output(DupesOutputInput {
gate_outcomes: input.gate_outcomes,
request_outcomes: input.request_outcomes,
schema_version: DUPES_SCHEMA_VERSION,
version: env!("CARGO_PKG_VERSION").to_string(),
elapsed: input.elapsed,
report: payload,
clone_groups_shown: input.report.clone_groups_shown(),
clone_groups_omitted: input.report.clone_groups_omitted(),
clone_families_shown: input.report.clone_families_shown(),
clone_families_omitted: input.report.clone_families_omitted(),
grouped_by: Some(group_by_mode_from_label(input.grouping.mode)),
total_issues: Some(input.report.clone_groups.len()),
groups: None,
baseline_staleness: input.baseline_staleness,
meta: input.meta,
workspace_diagnostics: input.workspace_diagnostics,
next_steps: input.next_steps,
});
let mut output = fallow_output::serialize_dupes_json_output(
envelope,
input.envelope_mode,
input.telemetry_analysis_run_id,
)?;
strip_root_prefix(&mut output, &root_prefix);
let group_values = input
.grouping
.groups
.iter()
.map(|group| {
let mut value = if input.include_fragments {
serde_json::to_value(group)?
} else {
let mut stripped = group.clone();
stripped.strip_fragments();
serde_json::to_value(&stripped)?
};
strip_root_prefix(&mut value, &root_prefix);
Ok(value)
})
.collect::<Result<Vec<_>, serde_json::Error>>()?;
if let serde_json::Value::Object(ref mut map) = output {
map.insert("groups".to_string(), serde_json::Value::Array(group_values));
}
Ok(output)
}
fn build_check_json_envelope(input: CheckJsonEnvelopeInput<'_>) -> CheckOutput {
let mut output = build_check_output(CheckOutputInput {
schema_version: CHECK_SCHEMA_VERSION,
version: env!("CARGO_PKG_VERSION").to_string(),
elapsed: input.elapsed,
results: input.results.clone(),
config_fixable: input.config_fixable,
meta: input.meta,
workspace_diagnostics: input.workspace_diagnostics,
next_steps: input.next_steps,
});
output.baseline_deltas = input.extras.baseline_deltas;
output.baseline = input.extras.baseline;
output.baseline_staleness = input.extras.baseline_staleness;
output.regression = input.extras.regression;
output.gate_outcomes = input.extras.gate_outcomes;
output.request_outcomes = input.extras.request_outcomes;
output
}
fn strip_json_root_prefix(output: &mut serde_json::Value, root: &Path) {
let root_prefix = format!("{}/", root.display());
strip_root_prefix(output, &root_prefix);
}
fn group_by_mode_from_label(label: &str) -> GroupByMode {
match label {
"directory" => GroupByMode::Directory,
"package" => GroupByMode::Package,
"section" => GroupByMode::Section,
_ => GroupByMode::Owner,
}
}
#[cfg(test)]
mod tests {
use super::*;
use fallow_types::workspace::WorkspaceDiagnosticKind;
#[test]
fn grouped_check_json_carries_workspace_diagnostics_with_relative_paths() {
let root = Path::new("/project");
let output = serialize_grouped_check_json(GroupedCheckJsonOutputInput {
gate_outcomes: None,
request_outcomes: None,
baseline_staleness: None,
groups: &[],
original: &AnalysisResults::default(),
root,
elapsed: Duration::ZERO,
grouped_by: GroupByMode::Directory,
config_fixable: false,
meta: None,
workspace_diagnostics: vec![WorkspaceDiagnostic::new(
root,
root.join("src/unreadable.ts"),
WorkspaceDiagnosticKind::SourceReadFailure {
error: "permission denied".to_string(),
},
)],
next_steps: Vec::new(),
envelope_mode: RootEnvelopeMode::Tagged,
telemetry_analysis_run_id: None,
})
.expect("grouped check JSON serializes");
assert_eq!(
output["workspace_diagnostics"][0]["path"],
"src/unreadable.ts"
);
assert_eq!(
output["workspace_diagnostics"][0]["kind"],
"source-read-failure"
);
}
}