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