generated from maddoxwerts/Dockerized-Rust
88 lines
2 KiB
Rust
88 lines
2 KiB
Rust
// Libraries
|
|
use std::fs::File;
|
|
use std::io::Result;
|
|
|
|
use csv::{self, StringRecord};
|
|
use walkdir::WalkDir;
|
|
|
|
// Structures
|
|
pub struct Packager {
|
|
directory: String,
|
|
file_out: String,
|
|
}
|
|
|
|
// Implementations
|
|
impl Packager {
|
|
// Constructors
|
|
pub fn new(directory: String, file_out: String) -> Self {
|
|
Self {
|
|
directory,
|
|
file_out,
|
|
}
|
|
}
|
|
|
|
// Functions
|
|
fn read_csv(&self, path: &str) -> Result<Vec<StringRecord>> {
|
|
// Opening the File & Reading
|
|
let file = File::open(path)?;
|
|
let mut rdr = csv::Reader::from_reader(file);
|
|
|
|
// Creating a list of string records
|
|
let mut result: Vec<StringRecord> = Vec::new();
|
|
|
|
// Iterate through records
|
|
for record in rdr.records() {
|
|
result.push(record?);
|
|
}
|
|
|
|
// Ok!
|
|
Ok(result)
|
|
}
|
|
fn save(&self, records: Vec<StringRecord>) -> Result<()> {
|
|
// Writing to the path we want
|
|
let mut writer = csv::Writer::from_path(&self.file_out)?;
|
|
|
|
// Creating the Header
|
|
writer.write_record(&["Date", "Description", "Amount"])?;
|
|
|
|
// Adding all Records
|
|
for record in &records {
|
|
writer.write_record(record)?;
|
|
}
|
|
|
|
// Flushing!!
|
|
writer.flush()?;
|
|
|
|
// Ok!!
|
|
Ok(())
|
|
}
|
|
|
|
pub fn start(&self) -> Result<()> {
|
|
// Holding all Records
|
|
let mut records: Vec<StringRecord> = Vec::new();
|
|
|
|
// Using WalkDir to go through the Directory
|
|
for entry in WalkDir::new(&self.directory) {
|
|
// Reference the Path
|
|
let entry = entry?;
|
|
let path = entry.path();
|
|
|
|
// Is it a file?
|
|
if !path.is_file() {
|
|
continue;
|
|
}
|
|
|
|
// Reading the CSV from the Path
|
|
let file = self.read_csv(path.to_str().unwrap())?;
|
|
|
|
// Adding it to the record list
|
|
records.extend(file);
|
|
}
|
|
|
|
// Saving the Records
|
|
self.save(records)?;
|
|
|
|
// Ok!!
|
|
Ok(())
|
|
}
|
|
}
|