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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
#![warn(clippy::all)]
#![warn(missing_docs)]
#![warn(rustdoc::missing_doc_code_examples)]
#![warn(clippy::missing_docs_in_private_items)]
#![doc = include_str!("../README.md")]

use bollard::container::{Config, RemoveContainerOptions};
use bollard::Docker;
use std::collections::HashMap;
use std::str::FromStr;

use bollard::exec::{CreateExecOptions, StartExecResults};
use bollard::image::CreateImageOptions;
use futures_util::stream::StreamExt;
use futures_util::TryStreamExt;

/// Contains the workspace that resulted from running the octave command in `eval`
#[derive(Debug)]
pub struct OctaveResults {
    scalars: HashMap<String, f64>,
    matrices: HashMap<String, Vec<Vec<f64>>>,
}

impl OctaveResults {
    /// Get a scalar by name
    pub fn get_scalar_named(&self, name: &str) -> Option<&f64> {
        self.scalars.get(name)
    }
    /// Get a matrix by name
    pub fn get_matrix_named(&self, name: &str) -> Option<&Vec<Vec<f64>>> {
        self.matrices.get(name)
    }
}

impl From<String> for OctaveResults {
    fn from(output: String) -> Self {
        let mut results = OctaveResults {
            scalars: Default::default(),
            matrices: Default::default(),
        };

        let split_output = output.split("\n");
        let mut name: String = "".to_owned();
        let mut currently_building: String = "".to_owned();
        let mut matrix: Vec<Vec<f64>> = vec![];
        let mut current_row: usize = 0;
        let mut max_rows: usize = 0;
        let mut columns: usize = 0;
        for line in split_output {
            if currently_building.len() == 0 {
                if line.starts_with("# Created") {
                    continue;
                } else if line.starts_with("# name: ") {
                    name = line.to_string().replace("# name: ", "").replace("\n", "")
                } else if line.starts_with("# type: ") {
                    currently_building = line.to_string().replace("# type: ", "").replace("\n", "")
                }
            } else {
                if currently_building == "scalar" && !line.is_empty() {
                    results
                        .scalars
                        .insert(name.clone(), f64::from_str(line).unwrap());
                    currently_building = "".to_owned();
                } else if currently_building == "matrix" && !line.is_empty() {
                    if line.starts_with("# rows: ") {
                        let current_row = 0;
                        max_rows =
                            usize::from_str(&*line.to_string().replace("# rows: ", "")).unwrap();
                    } else if line.starts_with("# columns: ") {
                        columns =
                            usize::from_str(&*line.to_string().replace("# columns: ", "")).unwrap();
                    } else {
                        if current_row == max_rows {
                            results.matrices.insert(name.clone(), matrix.clone());
                            currently_building = "".to_owned();
                        } else if !line.is_empty() {
                            let mut this_row = vec![];
                            for elem in line.split(" ") {
                                if elem.is_empty() {
                                    continue;
                                } else {
                                    this_row.push(f64::from_str(elem).unwrap());
                                }
                            }
                            matrix.push(this_row);
                            current_row += 1;
                        }
                    }
                }
            }
        }

        results
    }
}

/// Evaluate lines of Octave code
/// ```
/// use mocktave::eval;
/// let should_be_seven = eval("a = 5+2");
/// assert_eq!(*(should_be_seven.get_scalar_named("a").unwrap()), 7_f64);
/// ```
#[tokio::main]
pub async fn eval(input: &str) -> OctaveResults {
    const IMAGE: &str = "mtmiller/octave:latest";
    let docker = Docker::connect_with_socket_defaults().unwrap();

    docker
        .create_image(
            Some(CreateImageOptions {
                from_image: IMAGE,
                ..Default::default()
            }),
            None,
            None,
        )
        .try_collect::<Vec<_>>()
        .await
        .expect("Could not create image.");

    let alpine_config = Config {
        image: Some(IMAGE),
        tty: Some(true),
        ..Default::default()
    };

    let id = docker
        .create_container::<&str, &str>(None, alpine_config)
        .await
        .expect("Could not create container.")
        .id;
    docker
        .start_container::<String>(&id, None)
        .await
        .expect("Could not start container.");

    // non interactive
    let exec = docker
        .create_exec(
            &id,
            CreateExecOptions {
                attach_stdout: Some(true),
                attach_stderr: Some(true),
                cmd: Some(vec![
                    "octave",
                    "--eval",
                    &(input.to_string() + ";save(\"-\", \"*\");"),
                ]),
                ..Default::default()
            },
        )
        .await
        .expect("Could not create command to execute.")
        .id;

    let mut output_text = vec!["".to_string(); 0];

    if let StartExecResults::Attached { mut output, .. } = docker
        .start_exec(&exec, None)
        .await
        .expect("Execution of command failed.")
    {
        while let Some(Ok(msg)) = output.next().await {
            output_text.push(msg.to_string());
            // print!("{}", msg);
        }
    } else {
        unreachable!();
    }

    docker
        .remove_container(
            &id,
            Some(RemoveContainerOptions {
                force: true,
                ..Default::default()
            }),
        )
        .await
        .expect("Could not remove container.");

    OctaveResults::from(output_text.join(""))
}