vibe_ticket/specs/
storage.rs1use crate::error::{ErrorContext, Result};
7use serde::{Serialize, de::DeserializeOwned};
8use std::fs;
9use std::path::{Path, PathBuf};
10
11pub trait DocumentStore {
13 fn save_json<T: Serialize>(&self, path: &Path, data: &T) -> Result<()> {
15 let content = serde_json::to_string_pretty(data).context("Failed to serialize document")?;
16 self.save_text(path, &content)
17 }
18
19 fn load_json<T: DeserializeOwned>(&self, path: &Path) -> Result<T> {
21 let content = self.load_text(path)?;
22 serde_json::from_str(&content)
23 .with_context(|| format!("Failed to parse JSON from: {}", path.display()))
24 }
25
26 fn save_text(&self, path: &Path, content: &str) -> Result<()>;
28
29 fn load_text(&self, path: &Path) -> Result<String>;
31
32 fn exists(&self, path: &Path) -> bool;
34
35 fn ensure_dir(&self, dir: &Path) -> Result<()>;
37
38 fn list_dirs(&self, path: &Path) -> Result<Vec<PathBuf>>;
40}
41
42pub struct FileSystemStore;
44
45impl DocumentStore for FileSystemStore {
46 fn save_text(&self, path: &Path, content: &str) -> Result<()> {
47 if let Some(parent) = path.parent() {
49 self.ensure_dir(parent)?;
50 }
51
52 fs::write(path, content)
53 .with_context(|| format!("Failed to write file: {}", path.display()))
54 }
55
56 fn load_text(&self, path: &Path) -> Result<String> {
57 fs::read_to_string(path).with_context(|| format!("Failed to read file: {}", path.display()))
58 }
59
60 fn exists(&self, path: &Path) -> bool {
61 path.exists()
62 }
63
64 fn ensure_dir(&self, dir: &Path) -> Result<()> {
65 fs::create_dir_all(dir)
66 .with_context(|| format!("Failed to create directory: {}", dir.display()))
67 }
68
69 fn list_dirs(&self, path: &Path) -> Result<Vec<PathBuf>> {
70 if !path.exists() {
71 return Ok(Vec::new());
72 }
73
74 let mut dirs = Vec::new();
75 let entries = fs::read_dir(path)
76 .with_context(|| format!("Failed to read directory: {}", path.display()))?;
77
78 for entry in entries {
79 let entry = entry.context("Failed to read directory entry")?;
80 let path = entry.path();
81 if path.is_dir() {
82 dirs.push(path);
83 }
84 }
85
86 Ok(dirs)
87 }
88}
89
90pub struct DocumentOperations<S: DocumentStore> {
92 store: S,
93 base_dir: PathBuf,
94}
95
96impl<S: DocumentStore> DocumentOperations<S> {
97 pub const fn new(store: S, base_dir: PathBuf) -> Self {
99 Self { store, base_dir }
100 }
101
102 pub fn get_subdir(&self, id: &str) -> PathBuf {
104 self.base_dir.join(id)
105 }
106
107 pub fn initialize(&self) -> Result<()> {
109 self.store.ensure_dir(&self.base_dir)
110 }
111
112 pub fn save_in_subdir<T: Serialize>(&self, id: &str, filename: &str, data: &T) -> Result<()> {
114 let subdir = self.get_subdir(id);
115 let path = subdir.join(filename);
116 self.store.save_json(&path, data)
117 }
118
119 pub fn load_from_subdir<T: DeserializeOwned>(&self, id: &str, filename: &str) -> Result<T> {
121 let subdir = self.get_subdir(id);
122 let path = subdir.join(filename);
123 self.store.load_json(&path)
124 }
125
126 pub fn save_text_in_subdir(&self, id: &str, filename: &str, content: &str) -> Result<()> {
128 let subdir = self.get_subdir(id);
129 let path = subdir.join(filename);
130 self.store.save_text(&path, content)
131 }
132
133 pub fn load_text_from_subdir(&self, id: &str, filename: &str) -> Result<Option<String>> {
135 let subdir = self.get_subdir(id);
136 let path = subdir.join(filename);
137
138 if !self.store.exists(&path) {
139 return Ok(None);
140 }
141
142 Ok(Some(self.store.load_text(&path)?))
143 }
144
145 pub fn list_subdirs(&self) -> Result<Vec<PathBuf>> {
147 self.store.list_dirs(&self.base_dir)
148 }
149
150 pub const fn base_dir(&self) -> &PathBuf {
152 &self.base_dir
153 }
154}
155
156#[cfg(test)]
157mod tests {
158 use super::*;
159 use std::collections::HashMap;
160
161 struct MockStore {
163 files: std::cell::RefCell<HashMap<PathBuf, String>>,
164 }
165
166 impl MockStore {
167 fn new() -> Self {
168 Self {
169 files: std::cell::RefCell::new(HashMap::new()),
170 }
171 }
172 }
173
174 impl DocumentStore for MockStore {
175 fn save_text(&self, path: &Path, content: &str) -> Result<()> {
176 self.files
177 .borrow_mut()
178 .insert(path.to_path_buf(), content.to_string());
179 Ok(())
180 }
181
182 fn load_text(&self, path: &Path) -> Result<String> {
183 self.files
184 .borrow()
185 .get(path)
186 .cloned()
187 .ok_or_else(|| crate::error::VibeTicketError::custom("File not found"))
188 }
189
190 fn exists(&self, path: &Path) -> bool {
191 self.files.borrow().contains_key(path)
192 }
193
194 fn ensure_dir(&self, _dir: &Path) -> Result<()> {
195 Ok(())
196 }
197
198 fn list_dirs(&self, _path: &Path) -> Result<Vec<PathBuf>> {
199 Ok(vec![])
200 }
201 }
202
203 #[test]
204 fn test_document_operations() {
205 let store = MockStore::new();
206 let ops = DocumentOperations::new(store, PathBuf::from("/test"));
207
208 #[derive(Serialize, serde::Deserialize, PartialEq, Debug)]
210 struct TestDoc {
211 name: String,
212 value: i32,
213 }
214
215 let doc = TestDoc {
216 name: "test".to_string(),
217 value: 42,
218 };
219
220 ops.save_in_subdir("id1", "test.json", &doc).unwrap();
221 let loaded: TestDoc = ops.load_from_subdir("id1", "test.json").unwrap();
222 assert_eq!(doc, loaded);
223
224 ops.save_text_in_subdir("id2", "test.txt", "Hello, World!")
226 .unwrap();
227 let text = ops.load_text_from_subdir("id2", "test.txt").unwrap();
228 assert_eq!(text, Some("Hello, World!".to_string()));
229
230 let missing = ops.load_text_from_subdir("id3", "missing.txt").unwrap();
232 assert_eq!(missing, None);
233 }
234}