use std::io;
use serde_json::{Value, json};
use super::{Entry, RunResult, SCHEMA_VERSION};
use crate::classify::Provenance;
use crate::delete::Outcome;
fn outcome_value(outcome: &Outcome) -> Value {
match outcome {
Outcome::Removed => json!({ "status": "removed" }),
Outcome::Detached => json!({ "status": "detached" }),
Outcome::WouldRemove => json!({ "status": "would_remove" }),
Outcome::Refused(refusal) => json!({
"status": "refused",
"reason": refusal.code(),
"detail": refusal.to_string(),
}),
Outcome::PartiallyRemoved {
freed,
remaining,
failure,
} => json!({
"status": "partially_removed",
"reason": failure.kind().code(),
"detail": failure.to_string(),
"freed_bytes": freed,
"remaining_bytes": remaining,
"os_error": failure.os_error(),
"os_message": failure.os_message(),
}),
Outcome::Failed(failure) => json!({
"status": "failed",
"reason": failure.kind().code(),
"detail": failure.to_string(),
"os_error": failure.os_error(),
"os_message": failure.os_message(),
}),
}
}
fn entry_value(entry: &Entry) -> Value {
json!({
"path": entry.path.display().to_string(),
"ecosystem": entry.ecosystem(),
"artifact": entry.artifact(),
"bytes": entry.bytes,
"unreadable_directories": entry.unreadable,
"reclaimed_bytes": entry.reclaimed_bytes(),
"source": match &entry.finding.provenance {
Provenance::Anchored { .. } => "marker",
Provenance::Included { .. } => "config-include",
Provenance::Cache { .. } => "cache",
Provenance::Tagged => "tagged",
},
"marker_dir": match &entry.finding.provenance {
Provenance::Anchored { marker_dir, .. } => Some(marker_dir.display().to_string()),
Provenance::Included { .. } | Provenance::Cache { .. } | Provenance::Tagged => None,
},
"include_pattern": match &entry.finding.provenance {
Provenance::Anchored { .. } | Provenance::Cache { .. } | Provenance::Tagged => None,
Provenance::Included { pattern } => Some(pattern.as_str()),
},
"outcome": outcome_value(&entry.outcome),
})
}
#[must_use]
pub fn document(result: &RunResult) -> Value {
let totals = result.totals();
json!({
"schema_version": SCHEMA_VERSION,
"dry_run": result.dry_run,
"roots": result.roots.iter().map(|root| root.display().to_string()).collect::<Vec<_>>(),
"artifacts": result.entries.iter().map(entry_value).collect::<Vec<_>>(),
"skipped": result
.skip_reasons()
.map(|(path, reason)| json!({
"path": path.display().to_string(),
"reason": reason.code(),
"detail": reason.to_string(),
}))
.collect::<Vec<_>>(),
"walk_errors": result
.failures
.iter()
.map(|failure| json!({
"path": failure.path.as_ref().map(|path| path.display().to_string()),
"detail": failure.message,
"transient": failure.transient,
"inaccessible": failure.inaccessible,
}))
.collect::<Vec<_>>(),
"totals": {
"reclaimed": totals.reclaimed,
"bytes": totals.bytes,
"skipped": totals.skipped,
"refused": totals.refused,
"failed": totals.failed,
"partial": totals.partial,
"partial_bytes": totals.partial_bytes,
"dependencies": totals.dependencies,
"detached": totals.detached,
"unmeasured": totals.unmeasured,
},
"elapsed_ms": u64::try_from(result.timings.total.as_millis()).unwrap_or(u64::MAX),
"git": result.git.as_ref().map(crate::git::document),
"timings_us": {
"total": micros(result.timings.total),
"scan": micros(result.timings.scan),
"policy": micros(result.timings.policy),
"size": micros(result.timings.size),
"delete": micros(result.timings.delete),
"git": micros(result.timings.git),
},
})
}
fn micros(duration: std::time::Duration) -> u64 {
u64::try_from(duration.as_micros()).unwrap_or(u64::MAX)
}
pub fn render(result: &RunResult, out: &mut impl io::Write) -> io::Result<()> {
serde_json::to_writer_pretty(&mut *out, &document(result))?;
writeln!(out)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::classify::SkipReason;
use crate::delete::Refusal;
use crate::report::fixtures::{entry, result};
use crate::scan::Skipped;
fn document_for_tests() -> Value {
let mut result = result(
vec![
entry("/projects/api/target", "rust.target", 4_200_000_000, Outcome::Removed),
entry(
"/projects/link/target",
"rust.target",
0,
Outcome::Refused(Refusal::Symlink),
),
entry(
"/projects/locked/obj",
"dotnet.obj",
900,
Outcome::Failed(crate::report::fixtures::failure(std::io::ErrorKind::PermissionDenied)),
),
],
false,
);
result.skipped_count = 1;
result.skips = vec![Skipped {
path: std::path::PathBuf::from("/projects/data/target"),
reason: SkipReason::NoMarker {
ecosystem: "rust",
markers: &["Cargo.toml"],
},
}];
result.sort();
document(&result)
}
#[test]
fn should_render_the_documented_shape() {
insta::assert_json_snapshot!(document_for_tests());
}
#[test]
fn should_mark_a_tagged_removal_with_its_own_source() {
let result = crate::report::fixtures::result(
vec![crate::report::fixtures::tagged(
"/tmp/enterprise-pro-target",
27_000_000_000,
Outcome::Removed,
)],
false,
);
let artifact = document(&result)["artifacts"][0].clone();
assert_eq!(artifact["source"], serde_json::json!("tagged"));
assert_eq!(artifact["ecosystem"], serde_json::json!("tagged"));
assert_eq!(artifact["artifact"], Value::Null);
assert_eq!(artifact["marker_dir"], Value::Null);
assert_eq!(artifact["include_pattern"], Value::Null);
}
#[test]
fn should_mark_an_unanchored_removal_as_config_sourced() {
let result = crate::report::fixtures::result(
vec![crate::report::fixtures::included(
"/scratch/build-junk",
"~/scratch/build-junk",
1024,
Outcome::Removed,
)],
false,
);
let artifact = document(&result)["artifacts"][0].clone();
assert_eq!(artifact["source"], serde_json::json!("config-include"));
assert_eq!(artifact["ecosystem"], Value::Null);
assert_eq!(artifact["artifact"], Value::Null);
assert_eq!(artifact["marker_dir"], Value::Null);
assert_eq!(artifact["include_pattern"], serde_json::json!("~/scratch/build-junk"));
}
#[test]
fn should_mark_which_walk_errors_were_only_interruptions() {
let mut result = crate::report::fixtures::result(Vec::new(), true);
result.failures = vec![
crate::scan::WalkFailure {
path: Some(std::path::PathBuf::from("/projects/locked")),
message: "Permission denied (os error 13)".to_owned(),
transient: false,
inaccessible: false,
},
crate::scan::WalkFailure {
path: Some(std::path::PathBuf::from("/projects/containers")),
message: "Interrupted system call (os error 4)".to_owned(),
transient: true,
inaccessible: false,
},
];
let errors = document(&result)["walk_errors"].clone();
assert_eq!(errors[0]["transient"], serde_json::json!(false));
assert_eq!(errors[1]["transient"], serde_json::json!(true));
}
#[test]
fn should_flag_inaccessible_directories_and_carry_their_path() {
let mut result = crate::report::fixtures::result(Vec::new(), true);
result.failures = vec![crate::scan::WalkFailure {
path: Some(std::path::PathBuf::from("/home/Library/Weather")),
message: "Operation not permitted (os error 1)".to_owned(),
transient: false,
inaccessible: true,
}];
let error = document(&result)["walk_errors"][0].clone();
assert_eq!(error["inaccessible"], serde_json::json!(true));
assert_eq!(error["path"], serde_json::json!("/home/Library/Weather"));
}
#[test]
fn should_carry_the_schema_version() {
assert_eq!(document_for_tests()["schema_version"], SCHEMA_VERSION);
}
#[test]
fn should_expose_enum_like_reason_codes() {
let document = document_for_tests();
assert_eq!(document["artifacts"][1]["outcome"]["reason"], "symlink");
assert_eq!(document["artifacts"][2]["outcome"]["reason"], "permission_denied");
assert_eq!(document["skipped"][0]["reason"], "no_marker");
}
#[test]
fn the_artifact_reclaimed_bytes_sum_to_the_totals() {
let document = document_for_tests();
let summed: u64 = document["artifacts"]
.as_array()
.expect("artifacts is an array")
.iter()
.map(|artifact| artifact["reclaimed_bytes"].as_u64().expect("a byte count"))
.sum();
assert_eq!(summed, document["totals"]["bytes"].as_u64().expect("a byte count"));
}
#[test]
fn should_agree_with_the_human_totals() {
let document = document_for_tests();
assert_eq!(document["totals"]["reclaimed"], 1);
assert_eq!(document["totals"]["bytes"], 4_200_000_000_u64);
assert_eq!(document["totals"]["refused"], 1);
assert_eq!(document["totals"]["failed"], 1);
}
#[test]
fn should_write_valid_json() {
let mut buffer = Vec::new();
let result = result(Vec::new(), true);
render(&result, &mut buffer).expect("writing to a Vec cannot fail");
let parsed: Value = serde_json::from_slice(&buffer).expect("the output parses");
assert_eq!(parsed["dry_run"], true);
}
}