Skip to main content

lean_ctx/core/workflow/
store.rs

1use crate::core::workflow::types::WorkflowRun;
2use std::path::PathBuf;
3
4fn active_workflow_path() -> Option<PathBuf> {
5    crate::core::data_dir::lean_ctx_data_dir()
6        .ok()
7        .map(|d| d.join("workflows").join("active.json"))
8}
9
10pub fn load_active() -> Result<Option<WorkflowRun>, String> {
11    let Some(path) = active_workflow_path() else {
12        return Ok(None);
13    };
14    let content = match std::fs::read_to_string(&path) {
15        Ok(c) => c,
16        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
17        Err(e) => return Err(format!("read {}: {e}", path.display())),
18    };
19    let run: WorkflowRun =
20        serde_json::from_str(&content).map_err(|e| format!("Invalid workflow JSON: {e}"))?;
21    Ok(Some(run))
22}
23
24pub fn save_active(run: &WorkflowRun) -> Result<(), String> {
25    let Some(path) = active_workflow_path() else {
26        return Err("No home directory available".to_string());
27    };
28    if let Some(parent) = path.parent() {
29        std::fs::create_dir_all(parent).map_err(|e| format!("mkdir failed: {e}"))?;
30    }
31    let json = serde_json::to_string_pretty(run).map_err(|e| format!("serialize failed: {e}"))?;
32    let tmp = path.with_extension("tmp");
33    std::fs::write(&tmp, json).map_err(|e| format!("write failed: {e}"))?;
34    std::fs::rename(&tmp, &path).map_err(|e| format!("rename failed: {e}"))?;
35    Ok(())
36}
37
38pub fn clear_active() -> Result<(), String> {
39    let Some(path) = active_workflow_path() else {
40        return Ok(());
41    };
42    match std::fs::remove_file(&path) {
43        Ok(()) => Ok(()),
44        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
45        Err(e) => Err(format!("remove {}: {e}", path.display())),
46    }
47}