blob: c6e1f63ecf913bf337b69a555387a76446b6335b (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
use std::path::{Path, PathBuf};
use crate::transaction::{Category, Transaction};
#[derive(Debug)]
pub struct Store {
root: PathBuf,
transactions: Vec<Transaction>,
new_transactions: Vec<Transaction>,
}
impl Store {
//TODO Result
pub fn open(root: PathBuf) -> Option<Self> {
Some(Self {
transactions: Self::open_dir(&root)?,
new_transactions: Vec::new(),
root,
})
}
//TODO check if hash matches
//TODO Result
//TODO overkill? maybe we can use subfolders later on
fn open_dir(dir: &Path) -> Option<Vec<Transaction>> {
let mut res = Vec::new();
for entry in std::fs::read_dir(dir).ok()? {
let entry = entry.ok()?;
if entry.file_type().ok()?.is_dir() {
let mut transactions = Self::open_dir(&entry.path())?;
res.append(&mut transactions);
} else {
res.push(Transaction::open(&entry.path())?);
}
}
Some(res)
}
pub fn push(&mut self, transaction: Transaction) {
self.new_transactions.push(transaction);
}
pub fn write(&self) -> std::io::Result<()> {
for transaction in &self.new_transactions {
let mut path = self.root.clone();
path.push(format!("{}", transaction.id()));
transaction.write(&path)?;
}
Ok(())
}
pub fn transactions(&self) -> &[Transaction] {
&self.transactions
}
pub fn categories(&self) -> Vec<Category> {
let mut categories: Vec<_> = self
.transactions
.iter()
.map(|t| t.category.clone())
.collect();
categories.sort();
categories.dedup();
categories
}
}
|