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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
use colored::*;
use cp437::{BufReader as CP437BufReader, Progress, ProgressUpdater};
use failure::Error;
use indicatif::ProgressBar;
#[allow(unused_imports)]
use log::{debug, error, info, trace, warn};
use serde::de::DeserializeOwned;
use std::fs::File;
use std::path::PathBuf;

mod df_world;
pub use df_world::*;
mod deserializers;
pub use deserializers::*;
pub mod converters;
pub use converters::*;

struct ProgressBarUpdater {
    read_size: u64,
    total_size: u64,
    progress_bar: ProgressBar,
}

impl ProgressUpdater for ProgressBarUpdater {
    fn update(&mut self, value: u64) {
        self.read_size += value;
        self.progress_bar.set_position(self.read_size);
        if self.read_size + 20000 >= self.total_size {
            self.progress_bar.finish_with_message("✔️");
        }
    }
}

fn read_xml_file<C: DeserializeOwned>(
    filename: &PathBuf,
    progress_bar: ProgressBar,
) -> Result<C, Error> {
    let file = File::open(filename)?;
    let metadata = file.metadata()?;
    let total_size = metadata.len();
    progress_bar.set_length(total_size);

    let bar_updater = ProgressBarUpdater {
        read_size: 0,
        total_size,
        progress_bar,
    };

    let progress: Progress<ProgressBarUpdater> = Progress {
        updater: bar_updater,
    };

    // let reader = BufReader::new(file); // UTF-8 Only
    let reader = CP437BufReader::new(file, progress); // CP437 Only
    let parsed_result = &mut quick_xml::de::Deserializer::from_reader(reader);
    let result: Result<C, _> = serde_path_to_error::deserialize(parsed_result);
    let parsed_object: C = match result {
        Ok(data) => data,
        Err(err) => {
            let path = err.path().to_string();
            error!("Error in: {}", path.red());
            if err.to_string().contains("Unexpected EOF during reading") {
                error!("Error: {} \nIn: {}", err, path);
                panic!("Unexpected EOF during importing.");
            }
            if err.to_string().contains("Expecting Start event") {
                panic!("File is empty.");
            }
            panic!("Error: {} \nIn: {}", err, path);
        }
    };
    Ok(parsed_object)
}

pub fn parse_legends<C: DeserializeOwned>(filename: &PathBuf, progress_bar: ProgressBar) -> C {
    match read_xml_file(filename, progress_bar) {
        Result::Ok(data) => data,
        Result::Err(err) => {
            error!("The {} file could not be parsed.", "legends".red());
            panic!("Error in legends: {:?}", err);
        }
    }
}