vibe_ticket/storage/
file.rs1use std::fs;
2use std::path::PathBuf;
3use std::sync::Arc;
4
5use crate::cache::TicketCache;
6use crate::core::{Ticket, TicketId};
7
8use crate::error::{ErrorContext, Result, VibeTicketError};
9
10#[derive(Clone)]
15pub struct FileStorage {
16 base_dir: PathBuf,
18 pub(crate) cache: Arc<TicketCache>,
20}
21
22impl FileStorage {
23 pub fn new(base_dir: impl Into<PathBuf>) -> Self {
25 Self {
26 base_dir: base_dir.into(),
27 cache: Arc::new(TicketCache::with_default_ttl()),
28 }
29 }
30
31 fn tickets_dir(&self) -> PathBuf {
33 self.get_path("tickets")
34 }
35
36 pub(crate) fn ticket_path(&self, id: &TicketId) -> PathBuf {
38 self.tickets_dir().join(format!("{id}.yaml"))
39 }
40
41 fn active_ticket_path(&self) -> PathBuf {
43 self.get_path("active_ticket")
44 }
45
46 fn active_tickets_path(&self) -> PathBuf {
48 self.get_path("active_tickets.yaml")
49 }
50
51 fn state_path(&self) -> PathBuf {
53 self.get_path("state.yaml")
54 }
55
56 fn get_path(&self, name: &str) -> PathBuf {
58 self.base_dir.join(name)
59 }
60
61 pub fn ensure_directories(&self) -> Result<()> {
63 fs::create_dir_all(self.tickets_dir()).context("Failed to create tickets directory")?;
64 Ok(())
65 }
66
67 pub fn save_ticket(&self, ticket: &Ticket) -> Result<()> {
69 self.ensure_directories()?;
70
71 let path = self.ticket_path(&ticket.id);
72
73 let _lock =
75 super::FileLock::acquire(&path, Some("save_ticket".to_string())).map_err(|e| {
76 VibeTicketError::custom(format!("Failed to acquire lock for saving ticket: {e}"))
77 })?;
78
79 let yaml = serde_yaml::to_string(ticket).context("Failed to serialize ticket")?;
80
81 fs::write(&path, yaml)
82 .with_context(|| format!("Failed to write ticket to {}", path.display()))?;
83
84 self.cache.invalidate_ticket(&ticket.id);
86
87 Ok(())
88 }
89
90 pub fn load_ticket(&self, id: &TicketId) -> Result<Ticket> {
92 if let Some(ticket) = self.cache.get_ticket(id) {
94 return Ok(ticket);
95 }
96
97 let path = self.ticket_path(id);
98
99 if !path.exists() {
100 return Err(VibeTicketError::TicketNotFound { id: id.to_string() });
101 }
102
103 let _lock =
105 super::FileLock::acquire(&path, Some("load_ticket".to_string())).map_err(|e| {
106 VibeTicketError::custom(format!("Failed to acquire lock for loading ticket: {e}"))
107 })?;
108
109 let yaml = fs::read_to_string(&path)
110 .with_context(|| format!("Failed to read ticket from {}", path.display()))?;
111
112 let ticket: Ticket = serde_yaml::from_str(&yaml).context("Failed to deserialize ticket")?;
113
114 self.cache.cache_ticket(&ticket);
116
117 Ok(ticket)
118 }
119
120 pub fn load_all_tickets(&self) -> Result<Vec<Ticket>> {
122 if let Some(tickets) = self.cache.get_all_tickets() {
124 return Ok(tickets);
125 }
126
127 let tickets_dir = self.tickets_dir();
128
129 if !tickets_dir.exists() {
130 return Ok(Vec::new());
131 }
132
133 let mut tickets = Vec::new();
134
135 for entry in fs::read_dir(&tickets_dir).context("Failed to read tickets directory")? {
136 let entry = entry.context("Failed to read directory entry")?;
137 let path = entry.path();
138
139 if path.extension().and_then(|s| s.to_str()) == Some("yaml") {
140 let yaml = fs::read_to_string(&path)
141 .with_context(|| format!("Failed to read {}", path.display()))?;
142
143 match serde_yaml::from_str::<Ticket>(&yaml) {
144 Ok(ticket) => tickets.push(ticket),
145 Err(e) => {
146 eprintln!(
148 "Warning: Failed to load ticket from {}: {e}",
149 path.display()
150 );
151 },
152 }
153 }
154 }
155
156 self.cache.cache_all_tickets(&tickets);
158
159 Ok(tickets)
160 }
161
162 pub fn delete_ticket(&self, id: &TicketId) -> Result<()> {
164 let path = self.ticket_path(id);
165
166 if !path.exists() {
167 return Err(VibeTicketError::TicketNotFound { id: id.to_string() });
168 }
169
170 let _lock =
172 super::FileLock::acquire(&path, Some("delete_ticket".to_string())).map_err(|e| {
173 VibeTicketError::custom(format!("Failed to acquire lock for deleting ticket: {e}"))
174 })?;
175
176 fs::remove_file(&path)
177 .with_context(|| format!("Failed to delete ticket at {}", path.display()))?;
178
179 self.cache.invalidate_ticket(id);
181
182 Ok(())
183 }
184
185 pub fn set_active_ticket(&self, id: &TicketId) -> Result<()> {
187 let path = self.active_ticket_path();
188
189 let _lock = super::FileLock::acquire(&path, Some("set_active_ticket".to_string()))
191 .map_err(|e| {
192 VibeTicketError::custom(format!(
193 "Failed to acquire lock for setting active ticket: {e}"
194 ))
195 })?;
196
197 fs::write(&path, id.to_string()).context("Failed to write active ticket")?;
198 Ok(())
199 }
200
201 pub fn get_active_ticket(&self) -> Result<Option<TicketId>> {
203 let path = self.active_ticket_path();
204
205 if !path.exists() {
206 return Ok(None);
207 }
208
209 let content = fs::read_to_string(&path).context("Failed to read active ticket")?;
210
211 let id = TicketId::parse_str(content.trim()).context("Failed to parse active ticket ID")?;
212
213 Ok(Some(id))
214 }
215
216 pub fn clear_active_ticket(&self) -> Result<()> {
218 let path = self.active_ticket_path();
219
220 if path.exists() {
221 let _lock = super::FileLock::acquire(&path, Some("clear_active_ticket".to_string()))
223 .map_err(|e| {
224 VibeTicketError::custom(format!(
225 "Failed to acquire lock for clearing active ticket: {e}"
226 ))
227 })?;
228
229 fs::remove_file(&path).context("Failed to clear active ticket")?;
230 }
231
232 Ok(())
233 }
234
235 pub fn add_active_ticket(&self, id: &TicketId) -> Result<()> {
240 let path = self.active_tickets_path();
241
242 let _lock = super::FileLock::acquire(&path, Some("add_active_ticket".to_string()))
244 .map_err(|e| {
245 VibeTicketError::custom(format!(
246 "Failed to acquire lock for adding active ticket: {e}"
247 ))
248 })?;
249
250 let mut active_ids = if path.exists() {
252 let content = fs::read_to_string(&path).context("Failed to read active tickets")?;
253 serde_yaml::from_str::<Vec<String>>(&content)
254 .context("Failed to parse active tickets")?
255 .into_iter()
256 .filter_map(|s| TicketId::parse_str(&s).ok())
257 .collect::<Vec<_>>()
258 } else {
259 Vec::new()
260 };
261
262 if !active_ids.contains(id) {
264 active_ids.push(id.clone());
265 }
266
267 let yaml = serde_yaml::to_string(
269 &active_ids
270 .iter()
271 .map(|id| id.to_string())
272 .collect::<Vec<_>>(),
273 )
274 .context("Failed to serialize active tickets")?;
275
276 fs::write(&path, yaml).context("Failed to write active tickets")?;
277
278 Ok(())
279 }
280
281 pub fn remove_active_ticket(&self, id: &TicketId) -> Result<()> {
283 let path = self.active_tickets_path();
284
285 if !path.exists() {
286 return Ok(()); }
288
289 let _lock = super::FileLock::acquire(&path, Some("remove_active_ticket".to_string()))
291 .map_err(|e| {
292 VibeTicketError::custom(format!(
293 "Failed to acquire lock for removing active ticket: {e}"
294 ))
295 })?;
296
297 let content = fs::read_to_string(&path).context("Failed to read active tickets")?;
299 let mut active_ids = serde_yaml::from_str::<Vec<String>>(&content)
300 .context("Failed to parse active tickets")?
301 .into_iter()
302 .filter_map(|s| TicketId::parse_str(&s).ok())
303 .collect::<Vec<_>>();
304
305 active_ids.retain(|tid| tid != id);
307
308 if active_ids.is_empty() {
309 fs::remove_file(&path).context("Failed to remove active tickets file")?;
311 } else {
312 let yaml = serde_yaml::to_string(
314 &active_ids
315 .iter()
316 .map(|id| id.to_string())
317 .collect::<Vec<_>>(),
318 )
319 .context("Failed to serialize active tickets")?;
320
321 fs::write(&path, yaml).context("Failed to write active tickets")?;
322 }
323
324 Ok(())
325 }
326
327 pub fn get_all_active_tickets(&self) -> Result<Vec<TicketId>> {
332 let mut active_ids = Vec::new();
333
334 let new_path = self.active_tickets_path();
336 if new_path.exists() {
337 let content = fs::read_to_string(&new_path).context("Failed to read active tickets")?;
338 active_ids = serde_yaml::from_str::<Vec<String>>(&content)
339 .context("Failed to parse active tickets")?
340 .into_iter()
341 .filter_map(|s| TicketId::parse_str(&s).ok())
342 .collect();
343 } else {
344 if let Some(id) = self.get_active_ticket()? {
346 active_ids.push(id);
347 }
348 }
349
350 Ok(active_ids)
351 }
352
353 pub fn ticket_exists_with_slug(&self, slug: &str) -> Result<bool> {
355 let tickets = self.load_all_tickets()?;
356 Ok(tickets.iter().any(|t| t.slug == slug))
357 }
358
359 pub fn find_ticket_by_slug(&self, slug: &str) -> Result<Option<Ticket>> {
361 let tickets = self.load_all_tickets()?;
362 Ok(tickets.into_iter().find(|t| t.slug == slug))
363 }
364}
365
366#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
368pub struct ProjectState {
369 pub name: String,
371
372 pub description: Option<String>,
374
375 pub created_at: chrono::DateTime<chrono::Utc>,
377
378 pub updated_at: chrono::DateTime<chrono::Utc>,
380
381 pub ticket_count: u64,
383}
384
385impl FileStorage {
386 pub fn save_state(&self, state: &ProjectState) -> Result<()> {
388 let path = self.state_path();
389 let yaml = serde_yaml::to_string(state).context("Failed to serialize project state")?;
390
391 fs::write(&path, yaml).context("Failed to write project state")?;
392
393 Ok(())
394 }
395
396 pub fn load_state(&self) -> Result<ProjectState> {
398 let path = self.state_path();
399
400 if !path.exists() {
401 return Err(VibeTicketError::ProjectNotInitialized);
402 }
403
404 let yaml = fs::read_to_string(&path).context("Failed to read project state")?;
405
406 let state: ProjectState =
407 serde_yaml::from_str(&yaml).context("Failed to deserialize project state")?;
408
409 Ok(state)
410 }
411}
412
413#[cfg(test)]
414mod tests {
415 use super::*;
416 use tempfile::TempDir;
417
418 fn create_test_storage() -> (FileStorage, TempDir) {
419 let temp_dir = TempDir::new().unwrap();
420 let storage = FileStorage::new(temp_dir.path());
421 (storage, temp_dir)
422 }
423
424 #[test]
425 fn test_save_and_load_ticket() {
426 let (storage, _temp) = create_test_storage();
427 let mut ticket = Ticket::new("test-ticket", "Test Ticket");
428 ticket.description = "Test description".to_string();
429
430 storage.save_ticket(&ticket).unwrap();
431 let loaded = storage.load_ticket(&ticket.id).unwrap();
432
433 assert_eq!(loaded.slug, ticket.slug);
434 assert_eq!(loaded.title, ticket.title);
435 assert_eq!(loaded.description, ticket.description);
436 }
437
438 #[test]
439 fn test_load_all_tickets() {
440 let (storage, _temp) = create_test_storage();
441
442 let first_ticket = Ticket::new("ticket-1", "Ticket 1");
443 let second_ticket = Ticket::new("ticket-2", "Ticket 2");
444
445 storage.save_ticket(&first_ticket).unwrap();
446 storage.save_ticket(&second_ticket).unwrap();
447
448 let all_tickets = storage.load_all_tickets().unwrap();
449 assert_eq!(all_tickets.len(), 2);
450 }
451
452 #[test]
453 fn test_active_ticket() {
454 let (storage, _temp) = create_test_storage();
455 let ticket = Ticket::new("test", "Test");
456
457 storage.save_ticket(&ticket).unwrap();
458 storage.set_active_ticket(&ticket.id).unwrap();
459
460 let active_id = storage.get_active_ticket().unwrap();
461 assert_eq!(active_id, Some(ticket.id));
462
463 storage.clear_active_ticket().unwrap();
464 let active_id = storage.get_active_ticket().unwrap();
465 assert_eq!(active_id, None);
466 }
467}
468#[cfg(test)]
470#[path = "concurrent_tests.rs"]
471mod concurrent_tests;