Skip to main content

garbage_code_hunter/trend/
history.rs

1//! History record storage and retrieval.
2
3use anyhow::{Context, Result};
4use serde::{Deserialize, Serialize};
5use std::fs;
6use std::path::PathBuf;
7
8/// A single scan history record.
9#[derive(Debug, Clone, Serialize, Deserialize)]
10pub struct HistoryRecord {
11    pub timestamp: String,
12    pub project_path: String,
13    pub overall_score: f64,
14    pub tools: Vec<ToolScore>,
15}
16
17/// Score for a single tool.
18#[derive(Debug, Clone, Serialize, Deserialize)]
19pub struct ToolScore {
20    pub name: String,
21    pub score: f64,
22    pub item_count: usize,
23}
24
25/// Get the history directory path (~/.garbage-code-hunter/history/).
26fn history_dir() -> Result<PathBuf> {
27    let home = dirs_home().context("Could not determine home directory")?;
28    let dir = home.join(".garbage-code-hunter").join("history");
29    fs::create_dir_all(&dir)?;
30    Ok(dir)
31}
32
33fn dirs_home() -> Option<PathBuf> {
34    std::env::var("HOME").ok().map(PathBuf::from)
35}
36
37/// Save a history record to disk.
38pub fn save(record: &HistoryRecord) -> Result<PathBuf> {
39    let dir = history_dir()?;
40    let filename = format!("{}.json", record.timestamp.replace(':', "-"));
41    let path = dir.join(&filename);
42    let json = serde_json::to_string_pretty(record)?;
43    fs::write(&path, json)?;
44    Ok(path)
45}
46
47/// Load all history records, sorted by timestamp ascending.
48pub fn load_all() -> Result<Vec<HistoryRecord>> {
49    let dir = match history_dir() {
50        Ok(d) => d,
51        Err(_) => return Ok(vec![]),
52    };
53
54    let mut records = Vec::new();
55    if !dir.exists() {
56        return Ok(records);
57    }
58
59    for entry in fs::read_dir(&dir)? {
60        let entry = entry?;
61        let path = entry.path();
62        if path.extension().is_some_and(|ext| ext == "json") {
63            if let Ok(content) = fs::read_to_string(&path) {
64                if let Ok(record) = serde_json::from_str::<HistoryRecord>(&content) {
65                    records.push(record);
66                }
67            }
68        }
69    }
70
71    records.sort_by(|a, b| a.timestamp.cmp(&b.timestamp));
72    Ok(records)
73}
74
75/// Load the last N records.
76pub fn load_last(n: usize) -> Result<Vec<HistoryRecord>> {
77    let all = load_all()?;
78    let start = all.len().saturating_sub(n);
79    Ok(all[start..].to_vec())
80}
81
82/// Load records since a given date (YYYY-MM-DD).
83pub fn load_since(date: &str) -> Result<Vec<HistoryRecord>> {
84    let all = load_all()?;
85    Ok(all
86        .into_iter()
87        .filter(|r| r.timestamp.as_str() >= date)
88        .collect())
89}
90
91/// Generate a timestamp string for now.
92pub fn now_timestamp() -> String {
93    let secs = std::time::SystemTime::now()
94        .duration_since(std::time::UNIX_EPOCH)
95        .unwrap_or_default()
96        .as_secs();
97    // Simple epoch -> datetime conversion
98    epoch_to_datetime(secs)
99}
100
101fn epoch_to_datetime(secs: u64) -> String {
102    let days = secs / 86400;
103    let time_of_day = secs % 86400;
104    let hour = time_of_day / 3600;
105    let minute = (time_of_day % 3600) / 60;
106    let second = time_of_day % 60;
107
108    // Days since 1970-01-01 to Y-M-D
109    let (y, m, d) = days_to_ymd(days);
110
111    format!(
112        "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
113        y, m, d, hour, minute, second
114    )
115}
116
117fn days_to_ymd(days: u64) -> (i64, u32, u32) {
118    // Simplified civil calendar from days since epoch
119    let z = days + 719468;
120    let era = z / 146097;
121    let doe = z - era * 146097;
122    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
123    let y = yoe as i64 + era as i64 * 400;
124    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
125    let mp = (5 * doy + 2) / 153;
126    let d = doy - (153 * mp + 2) / 5 + 1;
127    let m = if mp < 10 { mp + 3 } else { mp - 9 };
128    let y = if m <= 2 { y + 1 } else { y };
129    (y, m as u32, d as u32)
130}
131
132#[cfg(test)]
133mod tests {
134    use super::*;
135
136    #[test]
137    fn test_epoch_to_datetime() {
138        // 2024-01-15T14:30:00Z = 1705328400
139        let dt = epoch_to_datetime(1705328400);
140        assert!(dt.starts_with("2024-01-15"));
141    }
142
143    #[test]
144    fn test_now_timestamp() {
145        let ts = now_timestamp();
146        assert!(ts.contains("T"));
147        assert!(ts.ends_with("Z"));
148    }
149
150    #[test]
151    fn test_history_record_serde() {
152        let record = HistoryRecord {
153            timestamp: "2024-01-15T14:30:00Z".to_string(),
154            project_path: "/tmp/test".to_string(),
155            overall_score: 72.5,
156            tools: vec![
157                ToolScore {
158                    name: "code-hunter".to_string(),
159                    score: 65.0,
160                    item_count: 45,
161                },
162                ToolScore {
163                    name: "commit-roaster".to_string(),
164                    score: 80.0,
165                    item_count: 12,
166                },
167            ],
168        };
169        let json = serde_json::to_string(&record).unwrap();
170        let parsed: HistoryRecord = serde_json::from_str(&json).unwrap();
171        assert_eq!(parsed.overall_score, 72.5);
172        assert_eq!(parsed.tools.len(), 2);
173    }
174}