fallow_api/mutation/
last_report.rs1use std::path::{Path, PathBuf};
10
11use crate::analysis_context::resolve_programmatic_analysis_context;
12use crate::{AnalysisOptions, ProgrammaticError};
13
14const LAST_REPORT_FILE: &str = "last-report.json";
16
17pub 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
32fn cache_dir(analysis: &AnalysisOptions) -> Result<PathBuf, ProgrammaticError> {
34 let resolved = resolve_programmatic_analysis_context(analysis)?;
35 let project = fallow_engine::project_config::config_for_project_with_load_options(
36 resolved.root(),
37 resolved.config_path().as_deref(),
38 fallow_config::ConfigLoadOptions {
39 allow_remote_extends: resolved.allow_remote_extends(),
40 },
41 )
42 .map_err(|error| {
43 ProgrammaticError::new(format!("failed to load config: {error}"), 2)
44 .with_code("FALLOW_CONFIG_LOAD_FAILED")
45 .with_context("analysis.configPath")
46 })?;
47 Ok(project.config.cache_dir)
48}
49
50pub fn last_mutation_report_path(analysis: &AnalysisOptions) -> Result<PathBuf, ProgrammaticError> {
56 Ok(cache_dir(analysis)?.join("mutation").join(LAST_REPORT_FILE))
57}
58
59pub fn save_last_mutation_report(
68 analysis: &AnalysisOptions,
69 report: &serde_json::Value,
70) -> Result<PathBuf, ProgrammaticError> {
71 let cache_dir = cache_dir(analysis)?;
72 ignore_cache_dir(&cache_dir).map_err(|error| cache_error(error.to_string()))?;
73 let dir = cache_dir.join("mutation");
74 std::fs::create_dir_all(&dir).map_err(|error| cache_error(error.to_string()))?;
75 let bytes = serde_json::to_vec(report)
76 .map_err(|error| cache_error(format!("failed to serialize the report: {error}")))?;
77 let path = dir.join(LAST_REPORT_FILE);
78 let temporary = dir.join(format!("{LAST_REPORT_FILE}.{}.tmp", std::process::id()));
79 std::fs::write(&temporary, bytes)
80 .and_then(|()| std::fs::rename(&temporary, &path))
81 .map_err(|error| {
82 let _ = std::fs::remove_file(&temporary);
83 cache_error(format!("failed to save {}: {error}", path.display()))
84 })?;
85 Ok(path)
86}