podal/src/file/env.rs

39 lines
1.1 KiB
Rust
Raw Normal View History

use crate::params::Args;
use crate::prelude::*;
use std::fs::{File, OpenOptions};
use std::io::Write;
pub type FileOpenFn = Box<dyn Fn(&str) -> Result<File>>;
pub type FileAppendLineFn = Box<dyn Fn(&str, &str) -> Result<()>>;
pub struct FileEnv {
pub open: FileOpenFn,
pub append_line: FileAppendLineFn,
}
impl FileEnv {
pub fn create(a: &Args) -> Self {
let open_dir = a.downloads.clone();
let append_dir = a.downloads.clone();
Self {
open: Box::new(move |file_name| {
let path = format!("{}/{}", &open_dir, file_name);
let file = File::open(path)?;
Ok(file)
}),
append_line: Box::new(move |file_name, line| {
let path = format!("{}/{}", &append_dir, file_name);
let mut file = OpenOptions::new()
.write(true)
.append(true)
.create(true)
.open(path)
.unwrap();
writeln!(file, "{}", line)?;
Ok(())
}),
}
}
}