Skip to main content

qutonium/exports/
export.rs

1use crate::{
2  core::suiter::Suite,
3  exports::json::JSON,
4};
5
6
7use std::{
8  fs,
9  io::Write,
10  path::Path,
11};
12
13
14pub trait Exporter {
15  fn new (data: Suite) -> Self;
16  fn parse (self) -> Self;
17  fn path (self, pathname: String) -> Self;
18}
19
20
21#[derive(Clone, Copy, Debug)]
22pub enum ExportMode {
23  JSON,
24}
25
26
27#[derive(Debug)]
28pub struct ExportConfig {
29  pub data: Suite,
30  pub filename: &'static str,
31  pub pathname: &'static str,
32}
33
34
35impl Clone for ExportConfig {
36  fn clone (&self) -> Self {
37    ExportConfig {
38      data: self.data.clone(),
39      filename: self.filename.clone(),
40      pathname: self.pathname.clone(),
41    }
42  }
43}
44
45
46#[derive(Debug)]
47pub struct Export {
48  pub config: ExportConfig,
49  pub exports: Vec<String>,
50  pub mode: ExportMode,
51}
52
53
54impl Export {
55  pub fn new (config: ExportConfig) -> Self {
56    Export {
57      config,
58      exports: vec![],
59      mode: ExportMode::JSON,
60    }
61  }
62
63  pub fn mode (mut self, mode: ExportMode) -> Self {
64    self.mode = mode;
65    self
66  }
67
68  // TODO: refacto!
69  pub fn to_json (mut self) {
70    println!("\ncreating json...");
71
72    let config = self.config.clone();
73    let path = format!("{}/{}", config.pathname, config.filename);
74    let json = JSON::new(config.data).path(path).parse();
75
76    self.exports.push(json.output.clone());
77
78    if let Some(parent) = Path::new(&json.pathname).parent() {
79      if !parent.exists() {
80        fs::create_dir_all(parent)
81        .unwrap_or_else(|_| panic!("Could not create {:?}", json.pathname));
82      }
83    }
84
85    let mut file = fs::File::create(&json.pathname)
86    .expect("Could not create output file");
87
88    file.write_all(self.exports[ExportMode::JSON as usize].as_bytes())
89    .expect("Could not output to file");
90
91    println!("created json in {}", &json.pathname);
92  }
93}