Skip to main content

fallow_api/mutation/
last_report.rs

1//! The saved report of the last mutation run, which `fallow mutation
2//! inspect` reads when no `--report` is given.
3//!
4//! Each run saves its full JSON report to
5//! `<cache dir>/mutation/last-report.json`. The cache directory has a
6//! `.gitignore` with `*`, so the saved report never makes the worktree dirty.
7//! `fallow mutation inspect` reads this file when the caller names no report.
8
9use std::path::PathBuf;
10
11use crate::analysis_context::resolve_programmatic_analysis_context;
12use crate::{AnalysisOptions, ProgrammaticError};
13
14/// The file name of the saved report below `<cache dir>/mutation`.
15const LAST_REPORT_FILE: &str = "last-report.json";
16
17fn cache_error(message: String) -> ProgrammaticError {
18    ProgrammaticError::new(message, 2).with_code("FALLOW_MUTATION_CACHE_WRITE_FAILED")
19}
20
21/// The cache directory of the project config: the directory that a run uses.
22fn cache_dir(analysis: &AnalysisOptions) -> Result<PathBuf, ProgrammaticError> {
23    resolve_programmatic_analysis_context(analysis)?;
24    let run =
25        crate::run::resolve_programmatic_run(analysis, &crate::run::ProgrammaticEntry::Mutation)?;
26    Ok(run.settings().cache_dir.value().clone())
27}
28
29/// The path of the saved report of the last run of the project.
30///
31/// # Errors
32///
33/// Returns an error when the root or the config does not resolve.
34pub fn last_mutation_report_path(analysis: &AnalysisOptions) -> Result<PathBuf, ProgrammaticError> {
35    Ok(cache_dir(analysis)?.join("mutation").join(LAST_REPORT_FILE))
36}
37
38/// Removes the outcome journal of the project when `report` is complete,
39/// and returns true when it removed a journal. Call it after the report is
40/// saved: the saved report then holds each result. A partial or failed run
41/// keeps the journal, so `--resume` can continue it. A run that started no
42/// test runner (`runner` is absent) did not write or check the journal, so
43/// the journal can belong to an interrupted run of another scope, and it
44/// stays. The journal is removed only when this run wrote it: a newer run of
45/// the project can own the journal file by now.
46///
47/// # Errors
48///
49/// Returns an error when the config does not resolve or the journal cannot
50/// be removed.
51pub fn remove_finished_mutation_journal(
52    analysis: &AnalysisOptions,
53    report: &fallow_output::MutationReport,
54) -> Result<bool, ProgrammaticError> {
55    if report.completion.status != fallow_output::MutationCompletionStatus::Complete
56        || report.runner.is_none()
57    {
58        return Ok(false);
59    }
60    let Some(run_id) = report.journal_run_id.as_deref() else {
61        return Ok(false);
62    };
63    let mutation_cache = cache_dir(analysis)?.join("mutation");
64    super::journal::Journal::remove_owned(&mutation_cache, run_id).map_err(|error| {
65        cache_error(format!(
66            "failed to remove {}: {error}",
67            super::journal::Journal::path(&mutation_cache).display()
68        ))
69    })
70}
71
72/// Saves the JSON `report` of a run as the last report of the project, and
73/// returns its path. The write goes to a temporary file first, so a reader
74/// never sees half a report.
75///
76/// # Errors
77///
78/// Returns an error when the config does not resolve or the cache directory
79/// cannot be written.
80pub fn save_last_mutation_report(
81    analysis: &AnalysisOptions,
82    report: &serde_json::Value,
83) -> Result<PathBuf, ProgrammaticError> {
84    let cache_dir = cache_dir(analysis)?;
85    super::ignore_cache_dir(&cache_dir).map_err(|error| cache_error(error.to_string()))?;
86    let dir = cache_dir.join("mutation");
87    std::fs::create_dir_all(&dir).map_err(|error| cache_error(error.to_string()))?;
88    let bytes = serde_json::to_vec(report)
89        .map_err(|error| cache_error(format!("failed to serialize the report: {error}")))?;
90    let path = dir.join(LAST_REPORT_FILE);
91    let temporary = dir.join(format!("{LAST_REPORT_FILE}.{}.tmp", std::process::id()));
92    std::fs::write(&temporary, bytes)
93        .and_then(|()| std::fs::rename(&temporary, &path))
94        .map_err(|error| {
95            let _ = std::fs::remove_file(&temporary);
96            cache_error(format!("failed to save {}: {error}", path.display()))
97        })?;
98    Ok(path)
99}
100
101/// The cached witnesses of a project, read once for a `tasks` batch.
102pub struct MutationWitnessStore {
103    witnesses: super::recorded_args::witnesses::WitnessMap,
104    now: u64,
105}
106
107impl MutationWitnessStore {
108    /// The arguments and the result of each side of the witness of
109    /// `mutant_id` with the input `input_id`. `None` when the cache no
110    /// longer has them (7 days).
111    pub fn values(
112        &self,
113        mutant_id: &str,
114        input_id: &str,
115    ) -> Option<(
116        Vec<serde_json::Value>,
117        fallow_output::MutationWitnessSide,
118        fallow_output::MutationWitnessSide,
119    )> {
120        let stored = super::recorded_args::witnesses::fresh_witness(
121            &self.witnesses,
122            mutant_id,
123            input_id,
124            self.now,
125        )?;
126        let side = |side: &super::recorded_args::witnesses::StoredSide| {
127            Some(fallow_output::MutationWitnessSide {
128                outcome: serde_json::from_value(serde_json::Value::String(side.outcome.clone()))
129                    .ok()?,
130                value: side.value.clone(),
131                text: side.text.clone(),
132            })
133        };
134        Some((
135            stored.args.clone(),
136            side(&stored.original)?,
137            side(&stored.mutant)?,
138        ))
139    }
140}
141
142/// The cached witnesses of the project of `analysis`. `None` when the config
143/// cannot load.
144pub fn mutation_witness_store(analysis: &AnalysisOptions) -> Option<MutationWitnessStore> {
145    let cache_dir = cache_dir(analysis).ok()?;
146    Some(MutationWitnessStore {
147        witnesses: super::recorded_args::witnesses::read_witnesses(&cache_dir),
148        now: super::recorded_args::now_secs(),
149    })
150}