graphviz_rust/
cmd.rs

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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
//! Utilities for executing the [`dot` command line executable].
//!
//! *Important*: users should have the `dot` command line executable installed.
//! A download can be found here: <https://graphviz.org/download/>.
//!
//! Additional information on controlling the output can be found in the `graphviz`
//! docs on [layouts] and [output formats].
//!
//! [layouts]: https://graphviz.org/docs/layouts/
//! [output formats]:https://graphviz.org/docs/outputs/
//! # Example:
//! ```no_run
//! use dot_structures::*;
//! use dot_generator::*;
//! use graphviz_rust::attributes::*;
//! use graphviz_rust::cmd::{CommandArg, Format};
//! use graphviz_rust::exec;
//! use graphviz_rust::printer::{PrinterContext,DotPrinter};
//!
//! fn graph_to_output(){
//!     let mut g = graph!(id!("id");
//!             node!("nod"),
//!             subgraph!("sb";
//!                edge!(node_id!("a") => subgraph!(;
//!                   node!("n";
//!                   NodeAttributes::color(color_name::black), NodeAttributes::shape(shape::egg))
//!               ))
//!           ),
//!           edge!(node_id!("a1") => node_id!(esc "a2"))
//!     );
//!     let graph_svg = exec(g, &mut PrinterContext::default(), vec![
//!         CommandArg::Format(Format::Svg),
//!     ]).unwrap();
//! }
//!
//! fn graph_to_file(){
//!        let mut g = graph!(id!("id"));
//!        let mut ctx = PrinterContext::default();
//!        ctx.always_inline();
//!        let empty = exec(g, &mut ctx, vec![
//!           CommandArg::Format(Format::Svg),
//!           CommandArg::Output("1.svg".to_string())
//!       ]);
//! }
//! ```
//!
//! [`dot` command line executable]: https://graphviz.org/doc/info/command.html
use std::{
    io::{self, ErrorKind, Write},
    process::{Command, Output},
};

use tempfile::NamedTempFile;

pub(crate) fn exec(graph: String, args: Vec<CommandArg>) -> io::Result<Vec<u8>> {
    let args = args.into_iter().map(|a| a.prepare()).collect();
    temp_file(graph).and_then(|f| {
        let path = f.path().to_string_lossy().to_string();
        do_exec(path, args).and_then(|o| {
            if o.status.code().map(|c| c != 0).unwrap_or(true) {
                let mes = String::from_utf8_lossy(&o.stderr).to_string();
                Err(std::io::Error::new(ErrorKind::Other, mes))
            } else {
                Ok(o.stdout)
            }
        })
    })
}

fn do_exec(input: String, args: Vec<String>) -> io::Result<Output> {
    let mut command = Command::new("dot");

    for arg in args {
        command.arg(arg);
    }
    command.arg(input).output()
}

fn temp_file(ctx: String) -> io::Result<NamedTempFile> {
    let mut file = NamedTempFile::new()?;
    file.write_all(ctx.as_bytes()).map(|_x| file)
}

/// Commandline arguments that can be passed to executable.
///
/// The list of possible commands can be found here:
/// <https://graphviz.org/doc/info/command.html>.
pub enum CommandArg {
    /// any custom argument.
    ///
    /// _Note_: it does not manage any prefixes and thus '-' or the prefix must
    /// be passed as well.
    Custom(String),
    /// Regulates the output file with -o prefix
    Output(String),
    /// [`Layouts`] in cmd
    ///
    /// [`Layouts`]: https://graphviz.org/docs/layouts/
    Layout(Layout),
    /// [`Output`] formats in cmd
    ///
    /// [`Output`]:https://graphviz.org/docs/outputs/
    Format(Format),
}

impl From<Layout> for CommandArg {
    fn from(value: Layout) -> Self {
        CommandArg::Layout(value)
    }
}

impl From<Format> for CommandArg {
    fn from(value: Format) -> Self {
        CommandArg::Format(value)
    }
}

impl CommandArg {
    fn prepare(&self) -> String {
        match self {
            CommandArg::Custom(s) => s.clone(),
            CommandArg::Output(p) => format!("-o{}", p),
            CommandArg::Layout(l) => format!("-K{}", format!("{:?}", l).to_lowercase()),
            CommandArg::Format(f) => {
                let str = match f {
                    Format::Xdot12 => "xdot1.2".to_string(),
                    Format::Xdot14 => "xdot1.4".to_string(),
                    Format::ImapNp => "imap_np".to_string(),
                    Format::CmapxNp => "cmapx_np".to_string(),
                    Format::DotJson => "dot_json".to_string(),
                    Format::XdotJson => "xdot_json".to_string(),
                    Format::PlainExt => "plain-ext".to_string(),
                    _ => format!("{:?}", f).to_lowercase(),
                };
                format!("-T{}", str)
            }
        }
    }
}

/// Various algorithms for projecting abstract graphs into a space for
/// visualization
///
/// <https://graphviz.org/docs/layouts/>
#[derive(Debug, Copy, Clone)]
pub enum Layout {
    Dot,
    Neato,
    Twopi,
    Circo,
    Fdp,
    Asage,
    Patchwork,
    Sfdp,
}

/// Various graphic and data formats for end user, web, documents and other
/// applications.
///
/// <https://graphviz.org/docs/outputs/>
#[derive(Debug, Copy, Clone)]
pub enum Format {
    Bmp,
    Cgimage,
    Canon,
    Dot,
    Gv,
    Xdot,
    Xdot12,
    Xdot14,
    Eps,
    Exr,
    Fig,
    Gd,
    Gd2,
    Gif,
    Gtk,
    Ico,
    Cmap,
    Ismap,
    Imap,
    Cmapx,
    ImapNp,
    CmapxNp,
    Jpg,
    Jpeg,
    Jpe,
    Jp2,
    Json,
    Json0,
    DotJson,
    XdotJson,
    Pdf,
    Pic,
    Pct,
    Pict,
    Plain,
    PlainExt,
    Png,
    Pov,
    Ps,
    Ps2,
    Psd,
    Sgi,
    Svg,
    Svgz,
    Tga,
    Tif,
    Tiff,
    Tk,
    Vml,
    Vmlz,
    Vrml,
    Vbmp,
    Webp,
    Xlib,
    X11,
}

#[cfg(test)]
mod tests {
    use dot_generator::*;
    use dot_structures::*;

    use crate::printer::{DotPrinter, PrinterContext};

    use super::{exec, CommandArg, Format};

    #[test]
    fn error_test() {
        let g = graph!(id!("id"));
        let mut ctx = PrinterContext::default();
        ctx.always_inline();
        let empty = exec(
            g.print(&mut ctx),
            vec![
                Format::Svg.into(),
                CommandArg::Output("missing/1.svg".to_string()),
            ],
        );
        assert!(empty.is_err())
    }
}