Skip to main content

flow_core/
state.rs

1use serde::{Deserialize, Serialize};
2use std::path::{Path, PathBuf};
3
4#[derive(Debug, Clone, Serialize, Deserialize, Default)]
5pub struct State {
6    pub current_project: Option<String>,
7    pub recent_projects: Vec<String>,
8    pub worktrees: Vec<WorktreeState>,
9}
10
11#[derive(Debug, Clone, Serialize, Deserialize)]
12pub struct WorktreeState {
13    pub name: String,
14    pub path: PathBuf,
15    pub branch: String,
16    pub created_at: u64,
17}
18
19impl State {
20    /// Load state from the state directory.
21    ///
22    /// # Errors
23    ///
24    /// Returns an error if the state file exists but cannot be read.
25    pub fn load(state_dir: &Path) -> Result<Self, crate::FlowError> {
26        let state_path = state_dir.join("state.toml");
27
28        if state_path.exists() {
29            let content = std::fs::read_to_string(&state_path)?;
30            Ok(toml::from_str(&content).unwrap_or_default())
31        } else {
32            Ok(Self::default())
33        }
34    }
35
36    /// Save state to the state directory.
37    ///
38    /// # Errors
39    ///
40    /// Returns an error if the state cannot be serialized or written.
41    pub fn save(&self, state_dir: &Path) -> Result<(), crate::FlowError> {
42        std::fs::create_dir_all(state_dir)?;
43        let state_path = state_dir.join("state.toml");
44        let content =
45            toml::to_string_pretty(self).map_err(|e| crate::FlowError::Git(e.to_string()))?;
46        std::fs::write(state_path, content)?;
47        Ok(())
48    }
49}