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
//! It allows to execute cmd engine passing extra parameters
//!
//! *It is important*: to execute it properly it needs to have an [`executable package`] on the system
//!
//! The extra information can be found in [`layouts`] and [`outputs`]
//!
//! [`layouts`]: https://graphviz.org/docs/layouts/
//! [`outputs`]:https://graphviz.org/docs/outputs/
//! [`executable package`]: https://graphviz.org/download/
//! # 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())
//!        ]).unwrap();
//!
//!  }
//! ```
use std::{
    io::{self, Write},
    process::{Command, Output},
};

use tempfile::NamedTempFile;

pub(crate) fn exec(graph: String, args: Vec<CommandArg>) -> io::Result<String> {
    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).map(|o| {
            if o.status.code().map(|c| c != 0).unwrap_or(true) {
                String::from_utf8_lossy(&*o.stderr).to_string()
            } else {
                String::from_utf8_lossy(&*o.stdout).to_string()
            }
        })
    })
}

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)
}

/// Command arguments that can be passed to exec.
/// The list of possible [`commands`]
///
/// [`commands`]: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 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)
            }
        }
    }
}

#[derive(Debug, Copy, Clone)]
pub enum Layout {
    Dot,
    Neato,
    Twopi,
    Circo,
    Fdp,
    Asage,
    Patchwork,
    Sfdp,
}

#[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,
}