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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
// # Mech Program
#![allow(dead_code)]
#![allow(warnings)]

// ## Prelude
#![feature(extern_prelude)]
#![feature(get_mut_unchecked)]

extern crate core;
extern crate libloading;
extern crate reqwest;
extern crate indexmap;

#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate serde_json;
extern crate serde;
#[macro_use]
extern crate crossbeam_channel;
#[macro_use]
extern crate lazy_static;

extern crate time;

extern crate mech_core;
use mech_core::*;
extern crate mech_syntax;
use mech_syntax::formatter::Formatter;
extern crate mech_utilities;
extern crate colored;
extern crate websocket;

use colored::*;
use libloading::Library;
use std::io::copy;
use std::fs::{OpenOptions, File, canonicalize, create_dir};
use std::path::{Path, PathBuf};
use crossbeam_channel::Sender;
use crossbeam_channel::Receiver;
use reqwest::StatusCode;

// ## Modules

pub mod program;
pub mod persister;
pub mod runloop;

// ## Exported Modules

pub use self::program::{Program};
pub use self::runloop::{ProgramRunner, RunLoop, ClientMessage};
pub use self::persister::{Persister};

pub fn format_errors(errors: &Vec<MechError>) -> String {
  let mut formatted_errors = "".to_string();
  let plural = if errors.len() == 1 {
    ""
  } else {
    "s"
  };
  let error_notice = format!("🐛 Found {} Error{}:\n", &errors.len(), plural);
  formatted_errors = format!("{}\n{}\n\n", formatted_errors, error_notice);
  for error in errors {
    formatted_errors = format!("{}{}\n\n", formatted_errors, "───────────────────────────────────────────────────────────────────".truecolor(246,192,78));
    match &error.kind {
      MechErrorKind::ParserError(ast,report,msg) => { formatted_errors = format!("{}{}", formatted_errors, msg);}
      MechErrorKind::MissingTable(table_id) => {
        formatted_errors = format!("{} Missing table: {}\n", formatted_errors, error.msg);
      }
      _ => {
        formatted_errors = format!("{}\n{:?}\n", formatted_errors, error);
      }
    }
  }
  formatted_errors = format!("{}\n{}",formatted_errors, "───────────────────────────────────────────────────────────────────\n\n".truecolor(246,192,78));
  formatted_errors
}

pub fn download_machine(machine_name: &str, name: &str, path_str: &str, ver: &str, outgoing: Option<crossbeam_channel::Sender<ClientMessage>>) -> Result<Library,MechError> {
  create_dir("machines");

  let machine_file_path = format!("machines/{}",machine_name);
  {
    let path = Path::new(path_str);
    // Download from the web
    if path.to_str().unwrap().starts_with("https") {
      match outgoing {
        Some(ref sender) => {sender.send(ClientMessage::String(format!("{} {} v{}", "[Downloading]".truecolor(153,221,85), name, ver)));}
        None => (),
      }
      let machine_url = format!("{}/{}", path_str, machine_name);
      match reqwest::get(machine_url.as_str()) {
        Ok(mut response) => {
          match response.status() {
            StatusCode::OK => {
              let mut dest = File::create(machine_file_path.clone())?;
              copy(&mut response, &mut dest)?;
            },
            _ => {
              match outgoing {
                Some(sender) => {sender.send(ClientMessage::String(format!("{} Failed to download {} v{}", "[Error]".bright_red(), name, ver)));}
                None => (),
              }
            },
          }
        }
        Err(_) => {
          match outgoing {
            Some(sender) => {sender.send(ClientMessage::String(format!("{} Failed to download {} v{}", "[Error]".bright_red(), name, ver)));}
            None => (),
          }
        }
      }

    // Load from a local directory
    } else {
      match outgoing {
        Some(sender) => {sender.send(ClientMessage::String(format!("{} {} v{}", "[Loading]".truecolor(153,221,85), name, ver)));}
        None => (),
      }
      let machine_path = format!("{}{}", path_str, machine_name);
      let path = Path::new(&machine_path);
      let mut dest = File::create(machine_file_path.clone())?;
      let mut f = File::open(path)?;
      copy(&mut f, &mut dest)?;
    }
  }
  let machine_file_path = format!("machines/{}",machine_name);
  let message = format!("Can't load library {:?}", machine_file_path);
  match unsafe{Library::new(machine_file_path)} {
    Ok(machine) => Ok(machine),
    Err(err) => Err(MechError{msg: "".to_string(), id: 1273, kind: MechErrorKind::GenericError(format!("{:?}",message))}),
  }
}