cargo/ops/cargo_report/
util.rs

1//! Common utilities for `cargo report` commands.
2
3use std::ffi::OsStr;
4use std::path::PathBuf;
5
6use crate::CargoResult;
7use crate::GlobalContext;
8use crate::core::Workspace;
9use crate::util::BuildLogger;
10use crate::util::logger::RunId;
11
12/// Lists log files by calling a callback for each valid log file.
13///
14/// * Yield log files from new to old
15/// * If in a workspace, select only the log files associated with the workspace
16pub fn list_log_files(
17    gctx: &GlobalContext,
18    ws: Option<&Workspace<'_>>,
19) -> CargoResult<Box<dyn Iterator<Item = (PathBuf, RunId)>>> {
20    let log_dir = gctx.home().join("log");
21    let log_dir = log_dir.as_path_unlocked();
22
23    if !log_dir.exists() {
24        return Ok(Box::new(std::iter::empty()));
25    }
26
27    let walk = walkdir::WalkDir::new(log_dir)
28        .follow_links(true)
29        .sort_by(|a, b| a.file_name().cmp(b.file_name()).reverse())
30        .min_depth(1)
31        .max_depth(1)
32        .into_iter()
33        .filter_map(|entry| {
34            let entry = entry.ok()?;
35            let path = entry.path();
36
37            // We only accept JSONL/NDJSON files.
38            if !entry.file_type().is_file() {
39                return None;
40            }
41            if entry.path().extension() != Some(OsStr::new("jsonl")) {
42                return None;
43            }
44
45            // ...and the file name must follow RunId format
46            let run_id = path.file_stem()?.to_str()?.parse::<RunId>().ok()?;
47            Some((path.to_path_buf(), run_id))
48        });
49
50    let ws_run_id = ws.map(BuildLogger::generate_run_id);
51
52    let walk = walk.filter(move |(_, id)| {
53        ws_run_id
54            .as_ref()
55            .map_or(true, |ws_id| id.same_workspace(ws_id))
56    });
57
58    Ok(Box::new(walk))
59}