Skip to content

Commit

Permalink
Accept filepaths through the CLI (#12)
Browse files Browse the repository at this point in the history
  • Loading branch information
kjagiello authored Aug 4, 2021
1 parent 91cf3f2 commit 20a076b
Showing 1 changed file with 31 additions and 4 deletions.
35 changes: 31 additions & 4 deletions src/cli/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,28 @@
extern crate clap;

use clap::App;
use clap::{App, Arg};
use diagram_base::TransformError;
use std::fs::File;
use std::io::{self, Read};
use std::path::Path;
use std::process;

const PKG_NAME: &str = env!("CARGO_PKG_NAME");
const PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
const PKG_AUTHORS: &str = env!("CARGO_PKG_AUTHORS");

fn read_from_stdin() -> io::Result<String> {
let mut buffer = String::new();
let stdin = io::stdin();
let mut handle = stdin.lock();
let mut buffer = String::new();
handle.read_to_string(&mut buffer)?;
Ok(buffer)
}

fn read_from_path(path: &str) -> io::Result<String> {
let path = Path::new(path);
let mut handle = File::open(&path)?;
let mut buffer = String::new();
handle.read_to_string(&mut buffer)?;
Ok(buffer)
}
Expand All @@ -23,13 +33,30 @@ fn render(input: &str) -> Result<String, TransformError> {
}

fn main() -> io::Result<()> {
App::new(PKG_NAME)
let matches = App::new(PKG_NAME)
.version(PKG_VERSION)
.about("Diagrams as code")
.author(PKG_AUTHORS)
.arg(
Arg::with_name("PATH")
.help("Path to the .diag file to generate diagram for (- for STDIN).")
.required(false)
.index(1),
)
.get_matches();

let input = read_from_stdin()?;
let input = {
let path = matches.value_of("PATH").unwrap_or("-");
let (verbose_path, result) = match path {
"-" => ("STDIN", read_from_stdin()),
path => (path, read_from_path(path)),
};
result.unwrap_or_else(|e| {
eprintln!("{}: {}", verbose_path, e);
process::exit(1);
})
};

let output = render(input.as_str());
match output {
Ok(repr) if !repr.is_empty() => println!("{}", repr),
Expand Down

0 comments on commit 20a076b

Please sign in to comment.