aoc_toolkit/application/progress/
store.rs1use std::fs::{self, File};
2use std::io::{self, Write};
3use std::path::{Path, PathBuf};
4
5use tempfile::NamedTempFile;
6
7use super::{LocalProgress, LocalProgressError};
8use crate::application::run::ProgressReport;
9use crate::project::Language;
10
11pub struct LocalProgressStore {
13 directory: PathBuf,
14 filename: &'static str,
15}
16
17#[derive(Debug, thiserror::Error)]
18pub enum LocalProgressStoreError {
19 #[error("Cannot access local progress at {path}: {source}")]
20 Io {
21 path: PathBuf,
22 #[source]
23 source: io::Error,
24 },
25
26 #[error(transparent)]
27 Snapshot(#[from] LocalProgressError),
28}
29
30impl LocalProgressStore {
31 #[must_use]
32 pub fn new(project_root: &Path, language: Language) -> Self {
33 let filename = match language {
34 Language::Rust => "rust.json",
35 };
36
37 Self {
38 directory: project_root.join(".aoc-toolkit").join("progress"),
39 filename,
40 }
41 }
42
43 pub fn load(&self) -> Result<LocalProgress, LocalProgressStoreError> {
49 let path = self.directory.join(self.filename);
50
51 match fs::read(&path) {
52 Ok(bytes) => Ok(LocalProgress::from_json(&bytes)?),
53 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(LocalProgress::default()),
54 Err(source) => Err(io_error(&path, source)),
55 }
56 }
57
58 pub fn record(&self, report: &ProgressReport) -> Result<(), LocalProgressStoreError> {
64 if report.days.iter().all(|day| day.parts.is_empty()) {
65 return Ok(());
66 }
67
68 fs::create_dir_all(&self.directory).map_err(|source| io_error(&self.directory, source))?;
69
70 let path = self.directory.join(self.filename);
71 let lock_path = path.with_extension("lock");
72 let lock = File::options()
73 .read(true)
74 .write(true)
75 .create(true)
76 .truncate(false)
77 .open(&lock_path)
78 .map_err(|source| io_error(&lock_path, source))?;
79 lock.lock().map_err(|source| io_error(&lock_path, source))?;
80
81 let mut progress = self.load()?;
82 progress.record(report);
83 let bytes = progress.to_json()?;
84
85 let mut temporary = NamedTempFile::new_in(&self.directory)
86 .map_err(|source| io_error(&self.directory, source))?;
87 temporary
88 .write_all(&bytes)
89 .map_err(|source| io_error(&path, source))?;
90 temporary
91 .as_file()
92 .sync_all()
93 .map_err(|source| io_error(&path, source))?;
94 temporary
95 .persist(&path)
96 .map_err(|error| io_error(&path, error.error))?;
97
98 Ok(())
99 }
100}
101
102fn io_error(path: &Path, source: io::Error) -> LocalProgressStoreError {
103 LocalProgressStoreError::Io {
104 path: path.to_path_buf(),
105 source,
106 }
107}
108
109#[cfg(test)]
110mod tests {
111 use std::fs;
112
113 use tempfile::tempdir;
114
115 use super::{LocalProgressStore, LocalProgressStoreError};
116 use crate::application::run::{
117 DayFailure, DayProgress, PartProgress, PartStatus, ProgressReport,
118 };
119 use crate::project::Language;
120
121 fn report(parts: Vec<PartProgress>, day_error: Option<DayFailure>) -> ProgressReport {
122 ProgressReport {
123 schema_version: 1,
124 days: vec![DayProgress {
125 year: 2025,
126 day: 3,
127 parts,
128 day_error,
129 }],
130 }
131 }
132
133 #[test]
134 fn merges_runs_into_the_project_snapshot() {
135 let root = tempdir().unwrap();
136 let store = LocalProgressStore::new(root.path(), Language::Rust);
137
138 store
139 .record(&report(
140 vec![PartProgress {
141 part: 1,
142 status: PartStatus::Succeeded,
143 }],
144 None,
145 ))
146 .unwrap();
147 store
148 .record(&report(
149 vec![PartProgress {
150 part: 2,
151 status: PartStatus::Panicked,
152 }],
153 None,
154 ))
155 .unwrap();
156
157 let reopened = LocalProgressStore::new(root.path(), Language::Rust);
158 let progress = reopened.load().unwrap();
159
160 assert_eq!(
161 progress.part_status(2025, 3, 1),
162 Some(PartStatus::Succeeded)
163 );
164 assert_eq!(progress.part_status(2025, 3, 2), Some(PartStatus::Panicked));
165 }
166
167 #[test]
168 fn creates_no_snapshot_when_no_parts_ran() {
169 let root = tempdir().unwrap();
170 let store = LocalProgressStore::new(root.path(), Language::Rust);
171
172 store
173 .record(&report(Vec::new(), Some(DayFailure::Panic)))
174 .unwrap();
175
176 assert!(!root.path().join(".aoc-toolkit").exists());
177 }
178
179 #[test]
180 fn preserves_an_invalid_snapshot_when_recording_fails() {
181 let root = tempdir().unwrap();
182 let store = LocalProgressStore::new(root.path(), Language::Rust);
183 let directory = root.path().join(".aoc-toolkit").join("progress");
184 let path = directory.join("rust.json");
185 fs::create_dir_all(directory).unwrap();
186 fs::write(&path, b"invalid JSON").unwrap();
187
188 let result = store.record(&report(
189 vec![PartProgress {
190 part: 1,
191 status: PartStatus::Succeeded,
192 }],
193 None,
194 ));
195
196 assert!(matches!(result, Err(LocalProgressStoreError::Snapshot(_))));
197 assert_eq!(fs::read(path).unwrap(), b"invalid JSON");
198 }
199}