pytools-rs 0.1.1

Miscellaneous tools referenced by DSL compilers/scientific-computing toolchains.
Documentation
// Copyright (c) 2022 Kaushik Kulkarni
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

use std::io::Write;
use std::process::Command;
use tempfile::NamedTempFile;

/// Valid visualzation modes for [`show_dot`].
#[derive(Clone)]
pub enum DotOutputT {
    /// Open as a new tab in the system's default browser. Recommended for
    /// graphs with large number of nodes.
    Browser,
    /// Save the graph as a SVG file on the filesystem.
    SVG(String),
    /// Open an Xwindow displaying the graph. Recommended for graphs with small
    /// number of nodes.
    XWindow,
}

pub trait ConvertibleToDotOutputT {
    fn to_dot_output_t(self) -> DotOutputT;
}

impl ConvertibleToDotOutputT for DotOutputT {
    fn to_dot_output_t(self) -> DotOutputT {
        self
    }
}

impl ConvertibleToDotOutputT for &str {
    fn to_dot_output_t(self) -> DotOutputT {
        match self {
            "xwindow" => DotOutputT::XWindow,
            "browser" => DotOutputT::Browser,
            x if x.ends_with(".svg") => DotOutputT::SVG(x[..x.len() - 4].to_string()),
            _ => panic!("Can be one of xwindow or browser"),
        }
    }
}

/// Visualize a graph written according to the [graphviz](https://www.graphviz.org/)
/// specification.
///
/// # Arguments
///
/// * `dot_code` - the [DOT](https://graphviz.org/doc/info/lang.html) code.
/// * `output_to` - how to visualize the graph. See [`DotOutputT`].
pub fn show_dot<T1: ToString, T2: ConvertibleToDotOutputT>(dot_code: T1, output_to: T2) {
    let mut fp = NamedTempFile::new().unwrap();
    writeln!(fp, "{}", dot_code.to_string()).unwrap();
    let (_file, fpath) = fp.keep().unwrap();

    match output_to.to_dot_output_t() {
        DotOutputT::XWindow => {
            let output = Command::new("dot").arg("-Tx11")
                                            .arg(fpath.to_str().unwrap())
                                            .output()
                                            .expect("could not run 'dot'");
            if !output.status.success() {
                panic!("dot exited with error: {}",
                       String::from_utf8_lossy(&output.stderr));
            }
        }
        DotOutputT::SVG(fname) => {
            let output = Command::new("dot").arg("-Tsvg")
                                            .arg(fpath.to_str().unwrap())
                                            .arg("-o")
                                            .arg(fname.as_str())
                                            .output()
                                            .expect("could not run 'dot'");
            if !output.status.success() {
                panic!("dot exited with error: {}",
                       String::from_utf8_lossy(&output.stderr));
            }
        }
        DotOutputT::Browser => unimplemented!("Browser output not yet supported"),
    }
}