extracted append_line to FileEnv

This commit is contained in:
Paul Campbell 2023-07-29 20:13:28 +01:00
parent 95ed1735e7
commit f5974acd25
3 changed files with 20 additions and 16 deletions

View file

@ -1,13 +1,26 @@
use std::fs::File; use std::fs::{File, OpenOptions};
use std::io::Write;
pub struct FileEnv { pub struct FileEnv {
pub open: FileOpen, pub open: FileOpen,
pub append_line: FileAppendLine,
} }
impl Default for FileEnv { impl Default for FileEnv {
fn default() -> Self { fn default() -> Self {
Self { Self {
open: |path| File::open(path), open: |path| File::open(path),
append_line: |file_name, line| {
let mut file = OpenOptions::new()
.write(true)
.append(true)
.create(true)
.open(file_name)
.unwrap();
writeln!(file, "{}", line)?;
Ok(())
},
} }
} }
} }
pub type FileOpen = fn(path: &str) -> std::io::Result<File>; pub type FileOpen = fn(path: &str) -> std::io::Result<File>;
pub type FileAppendLine = fn(paht: &str, line: &str) -> std::io::Result<()>;

View file

@ -1,19 +1,10 @@
use crate::file::FileEnv;
use crate::prelude::*; use crate::prelude::*;
use std::fs::OpenOptions;
use std::io::prelude::*;
use super::Link; use super::Link;
pub fn add(link: &Link, file_name: &str) -> Result<()> { pub fn add(link: &Link, file_name: &str, e: &FileEnv) -> Result<()> {
let mut file = OpenOptions::new() (e.append_line)(file_name, &link.href)?;
.write(true)
.append(true)
.create(true)
.open(file_name)
.unwrap();
writeln!(file, "{}", link.href)?;
Ok(()) Ok(())
} }
@ -43,7 +34,7 @@ mod tests {
length: None, length: None,
}; };
//when //when
add(&link, &file_name)?; add(&link, &file_name, &FileEnv::default())?;
//then //then
let content: Vec<String> = read_text_file(&file_name)?; let content: Vec<String> = read_text_file(&file_name)?;
@ -72,7 +63,7 @@ mod tests {
length: None, length: None,
}; };
//when //when
add(&link, &file_name)?; add(&link, &file_name, &FileEnv::default())?;
//then //then
let content: Vec<String> = read_text_file(&file_name)?; let content: Vec<String> = read_text_file(&file_name)?;

View file

@ -29,7 +29,7 @@ pub fn run(subscriptions: &str, history: &str, site: &str, e: Env) -> Result<()>
if !history::find(&link, history, &e.file)? { if !history::find(&link, history, &e.file)? {
println!("Downloading {}: {}", &channel_name, entry.title().as_str()); println!("Downloading {}: {}", &channel_name, entry.title().as_str());
(e.fetch.download)(&link)?; (e.fetch.download)(&link)?;
history::add(&link, history)?; history::add(&link, history, &e.file)?;
} }
} }
} }