summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: c6f797a052fd200fd4858b7e46d12924b69b4bcb (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
extern crate regex;
#[macro_use] extern crate lazy_static;
extern crate structopt;
#[macro_use] extern crate structopt_derive;

pub mod qif;

use structopt::StructOpt;

use qif::*;
use std::io::prelude::*;
use std::io::*;

use std::ffi::{OsString, OsStr};
use std::path::PathBuf;
use std::result::Result;

use std::fs::File;

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 {
    #[structopt(help = "Files to preprocess", required, parse(try_from_os_str="parse_filepath"))]
    files: Vec<PathBuf>
}

fn main() -> Result<(), Box<Error>> {
    let args = CliArgs::from_args();
    
    for filepath in &args.files {
        let qif_result = {
            let file = File::open(filepath)?;
            let file_reader = BufReader::new(file);
            let mut lines = file_reader.lines();
            
            let mut qif_file = QifFile::new(lines.next().unwrap()?);
            let mut next_entry = Vec::new();

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

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