gnuplot_wrapper/
script.rs

1use std::{fs::File, io::Write};
2
3use crate::command::Command;
4
5/// Gnuplot script
6#[derive(Debug)]
7pub struct Script {
8    commands: Vec<String>,
9    path: Option<String>
10}
11
12impl Script {
13    /// Create script
14    pub fn new() -> Self {
15        return Script {
16            commands: Vec::new(),
17            path: None
18        };
19    }
20
21    /// Add command
22    pub fn add_raw_command(&mut self, command: &str) {
23        self.commands.push(command.to_owned() + "\n");
24    }
25
26    /// Add command
27    pub fn add_command(&mut self, command: impl Command) {
28        self.commands.push(command.to_raw() + "\n");
29    }
30
31    /// Insert empty line in script
32    pub fn br(&mut self) {
33        self.commands.push("\n".to_owned());
34    }
35
36    /// Save script
37    pub fn save(&mut self, path: &str) {
38        self.path = Some(path.to_owned());
39        let mut file: File = File::create_new(&path).expect(&format!("Error when creating file: {}", path));
40        for command in &self.commands {
41            file.write_fmt(format_args!("{}", command)).expect(&format!("Error when writing to file: {}", path));
42        }
43        file.flush().expect(&format!("Error when flushing file: {}", path));
44    }
45
46    /// Get script path
47    pub fn get_path(&self) -> Option<String> {
48        return self.path.clone();
49    }
50
51    /// Get printed script
52    pub fn get_string(&self) -> String {
53        let mut script: String = String::new();
54        for line in &self.commands {
55            script.push_str(&line);
56        }
57        return script;
58    }
59}