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.
56///
57/// # Errors
58///
59/// Returns an error when the config does not resolve or the journal cannot
60/// be removed.
61pub fn remove_finished_mutation_journal(
62    analysis: &AnalysisOptions,
63    report: &fallow_output::MutationReport,
64) -> Result<bool, ProgrammaticError> {
65    if report.completion.status != fallow_output::MutationCompletionStatus::Complete
66        || report.runner.is_none()
67    {
68        return Ok(false);
69    }
70    let path = super::journal::Journal::path(&cache_dir(analysis)?.join("mutation"));
71    match std::fs::remove_file(&path) {
72        Ok(()) => Ok(true),
73        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
74        Err(error) => Err(cache_error(format!(
75            "failed to remove {}: {error}",
76            path.display()
77        ))),
78    }
79}
80
81/// Saves the JSON `report` of a run as the last report of the project, and
82/// returns its path. The write goes to a temporary file first, so a reader
83/// never sees half a report.
84///
85/// # Errors
86///
87/// Returns an error when the config does not resolve or the cache directory
88/// cannot be written.
89pub fn save_last_mutation_report(
90    analysis: &AnalysisOptions,
91    report: &serde_json::Value,
92) -> Result<PathBuf, ProgrammaticError> {
93    let cache_dir = cache_dir(analysis)?;
94    ignore_cache_dir(&cache_dir).map_err(|error| cache_error(error.to_string()))?;
95    let dir = cache_dir.join("mutation");
96    std::fs::create_dir_all(&dir).map_err(|error| cache_error(error.to_string()))?;
97    let bytes = serde_json::to_vec(report)
98        .map_err(|error| cache_error(format!("failed to serialize the report: {error}")))?;
99    let path = dir.join(LAST_REPORT_FILE);
100    let temporary = dir.join(format!("{LAST_REPORT_FILE}.{}.tmp", std::process::id()));
101    std::fs::write(&temporary, bytes)
102        .and_then(|()| std::fs::rename(&temporary, &path))
103        .map_err(|error| {
104            let _ = std::fs::remove_file(&temporary);
105            cache_error(format!("failed to save {}: {error}", path.display()))
106        })?;
107    Ok(path)
108}
109
110/// The cached witnesses of a project, read once for a `tasks` batch.
111pub struct MutationWitnessStore {
112    witnesses: super::recorded_args::witnesses::WitnessMap,
113    now: u64,
114}
115
116impl MutationWitnessStore {
117    /// The arguments and the result of each side of the witness of
118    /// `mutant_id` with the input `input_id`. `None` when the cache no
119    /// longer has them (7 days).
120    pub fn values(
121        &self,
122        mutant_id: &str,
123        input_id: &str,
124    ) -> Option<(
125        Vec<serde_json::Value>,
126        fallow_output::MutationWitnessSide,
127        fallow_output::MutationWitnessSide,
128    )> {
129        let stored = super::recorded_args::witnesses::fresh_witness(
130            &self.witnesses,
131            mutant_id,
132            input_id,
133            self.now,
134        )?;
135        let side = |side: &super::recorded_args::witnesses::StoredSide| {
136            Some(fallow_output::MutationWitnessSide {
137                outcome: serde_json::from_value(serde_json::Value::String(side.outcome.clone()))
138                    .ok()?,
139                value: side.value.clone(),
140                text: side.text.clone(),
141            })
142        };
143        Some((
144            stored.args.clone(),
145            side(&stored.original)?,
146            side(&stored.mutant)?,
147        ))
148    }
149}
150
151/// The cached witnesses of the project of `analysis`. `None` when the config
152/// cannot load.
153pub fn mutation_witness_store(analysis: &AnalysisOptions) -> Option<MutationWitnessStore> {
154    let cache_dir = cache_dir(analysis).ok()?;
155    Some(MutationWitnessStore {
156        witnesses: super::recorded_args::witnesses::read_witnesses(&cache_dir),
157        now: super::recorded_args::now_secs(),
158    })
159}