summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 03bcff358a51b7c914154b408d0b98f09332ba1f (plain)
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
pub mod qif;

use qif::*;
use std::{
    error::Error,
    ffi::{OsStr, OsString},
    fs::File,
    io::{prelude::*, *},
    path::PathBuf,
    result::Result,
};
use structopt::StructOpt;

fn parse_filepath(str: &OsStr) -> Result<PathBuf, OsString> {
    let path: PathBuf = ::std::convert::From::from(str);
    if path.is_file() {
        Ok(path)
    } else {
        Err(str.to_os_string())
    }
}

#[derive(StructOpt, Debug)]
#[structopt(
    name = "Qif Parser",
    about = "Qif file preprocessor to decrease duplication when importing to gnucash"
)]
struct CliArgs {
    /// Files to preprocess
    #[structopt(parse(try_from_os_str = parse_filepath))]
    files: Vec<PathBuf>,
}

fn main() -> Result<(), Box<dyn Error>> {
    let args = CliArgs::from_args();

    for filepath in &args.files {
        let file = File::open(filepath)?;
        let file_reader = BufReader::new(file);
        let mut lines = file_reader.lines();

        if let Some(header_line) = lines.next() {
            let mut qif_file = QifFile::new(header_line?);
            let mut next_entry = Vec::new();

            for line_result in lines {
                let line = line_result?;
                if line == String::from("^") {
                    let new_qif_entry = QifEntry::new(&next_entry)?;
                    qif_file.push(new_qif_entry);
                    next_entry.clear();
                } else {
                    next_entry.push(line);
                }
            }

            let mut file = File::create(filepath)?;
            writeln!(file, "{}", qif_file)?;
        } else {
            println!("{} was empty", filepath.display());
        }
    }
    println!("Processed {} files", args.files.len());
    Ok(())
}