gclone/src/cache.rs

75 lines
1.6 KiB
Rust

use std::path::PathBuf;
use std::fs::File;
use std::io::{Write, BufRead, BufReader};
use walkdir::WalkDir;
use crate::{Result, GIT_DIR};
pub struct Cache(Vec<String>);
impl Cache {
pub fn generate() -> Cache {
Cache(WalkDir::new(&*GIT_DIR)
.max_depth(3)
.into_iter()
.filter_map(|x| x.ok())
.map(|x| x.path().display().to_string())
.collect())
}
pub fn read() -> Result<Cache> {
let mut path = PathBuf::from(&*GIT_DIR);
path.push(".cdgcache");
let file = File::open(&path)?;
let file = BufReader::new(file);
let mut values = vec![];
for line in file.lines() {
if let Ok(l) = line {
values.push(l);
}
}
Ok(Cache(values))
}
pub fn read_or_generate() -> Cache {
match Cache::read() {
Ok(c) => c,
Err(_) => Cache::generate(),
}
}
pub fn write(&self) -> Result<()> {
let mut path = PathBuf::from(&*GIT_DIR);
path.push(".cdgcache");
let mut file = File::create(path)?;
for line in &self.0 {
writeln!(file, "{}", line)?;
}
Ok(())
}
pub fn find(&self, dirname: &str) -> Vec<String> {
let dirname = &format!("/{}", dirname);
let mut matches = vec![];
for line in &self.0 {
if line.ends_with(dirname) {
matches.push(line.clone());
}
}
matches
}
pub fn append(&mut self, value: String) {
self.0.push(value);
}
}