plottery_project/
project_config.rs

1use std::{
2    fs::File,
3    io::{self, BufReader, Read, Write},
4    path::Path,
5};
6
7use anyhow::Result;
8use chrono::{DateTime, Utc};
9use serde::{Deserialize, Serialize};
10
11#[derive(Debug, Serialize, Deserialize, Clone)]
12pub struct ProjectConfig {
13    pub name: String,
14    pub created_date: DateTime<Utc>,
15    pub last_modified_date: DateTime<Utc>,
16}
17
18impl PartialEq for ProjectConfig {
19    fn eq(&self, other: &Self) -> bool {
20        self.name == other.name && self.created_date == other.created_date
21    }
22}
23
24impl ProjectConfig {
25    pub fn new(name: &str) -> Self {
26        Self {
27            name: name.to_string(),
28            created_date: Utc::now(),
29            last_modified_date: Utc::now(),
30        }
31    }
32
33    pub fn new_from_file(path: &Path) -> Result<Self> {
34        let file = File::open(path)?;
35        let mut reader = BufReader::new(file);
36
37        let mut contents = String::new();
38        reader.read_to_string(&mut contents)?;
39
40        Ok(serde_json::from_str(&contents)?)
41    }
42
43    pub fn save_to_file(&self, path: &Path) -> Result<()> {
44        let file = File::create(path)?;
45        let mut writer = io::BufWriter::new(file);
46
47        let contents = serde_json::to_string_pretty(&self)?;
48        writer.write_all(contents.as_bytes())?;
49
50        Ok(())
51    }
52
53    pub fn update_last_modified_date(&mut self) {
54        self.last_modified_date = Utc::now();
55    }
56}