Skip to main content

cli_tutor/
progress.rs

1use anyhow::Result;
2use serde::{Deserialize, Serialize};
3use std::collections::HashMap;
4use std::fs;
5use std::path::PathBuf;
6
7#[derive(Debug, Clone, Serialize, Deserialize, Default)]
8pub struct ModuleProgress {
9    pub completed: Vec<String>,
10    pub attempted: Vec<String>,
11    // timed_challenge.TIMER.3 — best solve time per exercise (milliseconds)
12    #[serde(default)]
13    pub best_times: HashMap<String, u64>,
14}
15
16#[derive(Debug, Clone, Serialize, Deserialize, Default)]
17pub struct Progress {
18    #[serde(flatten)]
19    pub modules: HashMap<String, ModuleProgress>,
20}
21
22impl Progress {
23    pub fn load() -> Self {
24        match Self::try_load() {
25            Ok(p) => p,
26            Err(e) => {
27                // progress_tracking.LOAD.2 — warn and start fresh on corrupt file
28                eprintln!("Warning: could not load progress file: {e}. Starting fresh.");
29                Self::default()
30            }
31        }
32    }
33
34    fn try_load() -> Result<Self> {
35        let path = progress_path()?;
36        if !path.exists() {
37            // progress_tracking.LOAD.1 — missing file → fresh start, no error
38            return Ok(Self::default());
39        }
40        let content = fs::read_to_string(&path)?;
41        let p: Self = serde_json::from_str(&content)?;
42        Ok(p)
43    }
44
45    pub fn save(&self) -> Result<()> {
46        let path = progress_path()?;
47        if let Some(parent) = path.parent() {
48            fs::create_dir_all(parent)?;
49        }
50        let json = serde_json::to_string_pretty(self)?;
51        fs::write(&path, json)?;
52        Ok(())
53    }
54
55    pub fn mark_completed(&mut self, module: &str, exercise_id: &str) {
56        let entry = self.modules.entry(module.to_string()).or_default();
57        if !entry.completed.contains(&exercise_id.to_string()) {
58            entry.completed.push(exercise_id.to_string());
59        }
60        entry.attempted.retain(|id| id != exercise_id);
61    }
62
63    pub fn mark_attempted(&mut self, module: &str, exercise_id: &str) {
64        let entry = self.modules.entry(module.to_string()).or_default();
65        if !entry.completed.contains(&exercise_id.to_string())
66            && !entry.attempted.contains(&exercise_id.to_string())
67        {
68            entry.attempted.push(exercise_id.to_string());
69        }
70    }
71
72    pub fn is_completed(&self, module: &str, exercise_id: &str) -> bool {
73        self.modules
74            .get(module)
75            .map(|p| p.completed.iter().any(|id| id == exercise_id))
76            .unwrap_or(false)
77    }
78
79    // timed_challenge.TIMER.3 — record best solve time; only keeps the fastest
80    pub fn record_time(&mut self, module: &str, exercise_id: &str, ms: u64) {
81        let entry = self.modules.entry(module.to_string()).or_default();
82        let best = entry.best_times.entry(exercise_id.to_string()).or_insert(u64::MAX);
83        if ms < *best {
84            *best = ms;
85        }
86    }
87
88    pub fn best_time(&self, module: &str, exercise_id: &str) -> Option<u64> {
89        self.modules
90            .get(module)
91            .and_then(|p| p.best_times.get(exercise_id).copied())
92            .filter(|&ms| ms < u64::MAX)
93    }
94}
95
96fn progress_path() -> Result<PathBuf> {
97    let base = dirs_base()?;
98    Ok(base.join("cli-tutor").join("progress.json"))
99}
100
101fn dirs_base() -> Result<PathBuf> {
102    // XDG_DATA_HOME or ~/.local/share
103    if let Ok(xdg) = std::env::var("XDG_DATA_HOME") {
104        return Ok(PathBuf::from(xdg));
105    }
106    let home = std::env::var("HOME")?;
107    Ok(PathBuf::from(home).join(".local").join("share"))
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113    use std::sync::atomic::{AtomicU64, Ordering};
114
115    static TEST_COUNTER: AtomicU64 = AtomicU64::new(0);
116
117    // Use XDG_DATA_HOME with a unique temp dir to avoid racing on HOME across parallel tests.
118    fn with_xdg_data<F: FnOnce(PathBuf)>(f: F) {
119        let n = TEST_COUNTER.fetch_add(1, Ordering::Relaxed);
120        let tmp =
121            std::env::temp_dir().join(format!("cli-tutor-prog-test-{}-{}", std::process::id(), n));
122        std::fs::create_dir_all(&tmp).unwrap();
123        f(tmp.clone());
124        let _ = std::fs::remove_dir_all(&tmp);
125    }
126
127    fn load_from(xdg_data: &PathBuf) -> Progress {
128        let path = xdg_data.join("cli-tutor").join("progress.json");
129        if !path.exists() {
130            return Progress::default();
131        }
132        let content = std::fs::read_to_string(&path).unwrap_or_default();
133        serde_json::from_str(&content).unwrap_or_default()
134    }
135
136    fn save_to(p: &Progress, xdg_data: &PathBuf) {
137        let path = xdg_data.join("cli-tutor").join("progress.json");
138        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
139        let json = serde_json::to_string_pretty(p).unwrap();
140        std::fs::write(&path, json).unwrap();
141    }
142
143    #[test]
144    fn fresh_start_on_missing_file() {
145        with_xdg_data(|dir| {
146            let p = load_from(&dir);
147            assert!(p.modules.is_empty());
148        });
149    }
150
151    #[test]
152    fn save_and_round_trip() {
153        with_xdg_data(|dir| {
154            let mut p = Progress::default();
155            p.mark_completed("grep", "grep.1");
156            save_to(&p, &dir);
157
158            let loaded = load_from(&dir);
159            assert!(loaded.is_completed("grep", "grep.1"));
160        });
161    }
162
163    #[test]
164    fn fresh_start_on_corrupt_file() {
165        with_xdg_data(|dir| {
166            let path = dir.join("cli-tutor").join("progress.json");
167            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
168            std::fs::write(&path, "{{invalid json").unwrap();
169
170            let content = std::fs::read_to_string(&path).unwrap();
171            let result: Result<Progress, _> = serde_json::from_str(&content);
172            assert!(
173                result.is_err(),
174                "Expected corrupt file to fail deserialization"
175            );
176
177            // Progress::load() itself falls back to default on error
178            let p = Progress::default();
179            assert!(p.modules.is_empty());
180        });
181    }
182
183    #[test]
184    fn mark_completed_deduplicates() {
185        let mut p = Progress::default();
186        p.mark_completed("grep", "grep.1");
187        p.mark_completed("grep", "grep.1");
188        assert_eq!(p.modules["grep"].completed.len(), 1);
189    }
190}