Skip to main content

rstask_core/
local_state.rs

1// Local state management for context and ID mapping
2use crate::Result;
3use crate::error::RstaskError;
4use crate::query::Query;
5use std::collections::HashMap;
6use std::path::{Path, PathBuf};
7
8pub type IdsMap = HashMap<String, i32>;
9
10/// Local state including context
11#[derive(Debug, Clone)]
12pub struct LocalState {
13    pub context: Query,
14    state_file: PathBuf,
15}
16
17impl LocalState {
18    /// Load state from file or create default
19    pub fn load(state_file: &Path) -> Self {
20        let context = if let Ok(data) = std::fs::read(state_file) {
21            bincode::deserialize(&data).unwrap_or_default()
22        } else {
23            Query::default()
24        };
25
26        LocalState {
27            context,
28            state_file: state_file.to_path_buf(),
29        }
30    }
31
32    /// Set the context
33    pub fn set_context(&mut self, context: Query) -> Result<()> {
34        if !context.ids.is_empty() {
35            return Err(RstaskError::Parse("context cannot contain IDs".to_string()));
36        }
37
38        if !context.text.is_empty() {
39            return Err(RstaskError::Parse(
40                "context cannot contain text".to_string(),
41            ));
42        }
43
44        self.context = context;
45        Ok(())
46    }
47
48    /// Get the current context
49    pub fn get_context(&self) -> &Query {
50        &self.context
51    }
52
53    /// Save state to file
54    pub fn save(&self) -> Result<()> {
55        if let Some(parent) = self.state_file.parent() {
56            std::fs::create_dir_all(parent)?;
57        }
58        let data = bincode::serialize(&self.context)?;
59        std::fs::write(&self.state_file, data)?;
60        Ok(())
61    }
62}
63
64pub fn load_ids(ids_file: &Path) -> IdsMap {
65    if let Ok(data) = std::fs::read(ids_file) {
66        bincode::deserialize(&data).unwrap_or_default()
67    } else {
68        HashMap::new()
69    }
70}
71
72pub fn save_ids(ids_file: &Path, ids: &IdsMap) -> Result<()> {
73    if let Some(parent) = ids_file.parent() {
74        std::fs::create_dir_all(parent)?;
75    }
76    let data = bincode::serialize(ids)?;
77    std::fs::write(ids_file, data)?;
78    Ok(())
79}
80
81pub fn load_state(state_file: &Path) -> Option<Query> {
82    if let Ok(data) = std::fs::read(state_file) {
83        bincode::deserialize(&data).ok()
84    } else {
85        None
86    }
87}
88
89pub fn save_state(state_file: &Path, query: &Query) -> Result<()> {
90    if let Some(parent) = state_file.parent() {
91        std::fs::create_dir_all(parent)?;
92    }
93    let data = bincode::serialize(query)?;
94    std::fs::write(state_file, data)?;
95    Ok(())
96}