wsb/scrap/
scrap_common.rs1use crate::prelude::*;
2use chrono::{DateTime, Utc};
3use std::fs;
4
5#[derive(Debug, Serialize, Deserialize)]
6pub struct ScrapMetadata {
7 pub version: u32,
8 pub entries: HashMap<String, ScrapEntry>,
9}
10
11#[derive(Debug, Serialize, Deserialize, Clone)]
12pub struct ScrapEntry {
13 pub original_path: PathBuf,
14 pub scrapped_at: DateTime<Utc>,
15 pub scrapped_name: String,
16}
17
18impl ScrapMetadata {
19 pub fn new() -> Self {
20 Self {
21 version: 1,
22 entries: HashMap::new(),
23 }
24 }
25
26 pub fn load(scrap_dir: &Path) -> Result<Self> {
27 let metadata_path = scrap_dir.join(".metadata.json");
28 if !metadata_path.exists() {
29 return Ok(Self::new());
30 }
31
32 let content = fs::read_to_string(&metadata_path).context("Failed to read metadata file")?;
33
34 serde_json::from_str(&content).context("Failed to parse metadata file")
35 }
36
37 pub fn save(&self, scrap_dir: &Path) -> Result<()> {
38 let metadata_path = scrap_dir.join(".metadata.json");
39 let content = serde_json::to_string_pretty(self).context("Failed to serialize metadata")?;
40
41 fs::write(&metadata_path, content).context("Failed to write metadata file")?;
42
43 Ok(())
44 }
45
46 pub fn add_entry(&mut self, scrapped_name: &str, original_path: PathBuf) {
47 self.entries.insert(
48 scrapped_name.to_string(),
49 ScrapEntry {
50 original_path,
51 scrapped_at: Utc::now(),
52 scrapped_name: scrapped_name.to_string(),
53 },
54 );
55 }
56
57 pub fn remove_entry(&mut self, scrapped_name: &str) -> Option<ScrapEntry> {
58 self.entries.remove(scrapped_name)
59 }
60
61 pub fn get_entry(&self, scrapped_name: &str) -> Option<&ScrapEntry> {
62 self.entries.get(scrapped_name)
63 }
64}