From 20a076b7c50147be86f5bc11b3d260845132233b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krzysztof=20Jagie=C5=82=C5=82o?= Date: Wed, 4 Aug 2021 14:26:10 +0200 Subject: [PATCH] Accept filepaths through the CLI (#12) --- src/cli/src/main.rs | 35 +++++++++++++++++++++++++++++++---- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/src/cli/src/main.rs b/src/cli/src/main.rs index cf42ad3..937dc68 100644 --- a/src/cli/src/main.rs +++ b/src/cli/src/main.rs @@ -1,8 +1,10 @@ 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"); @@ -10,9 +12,17 @@ const PKG_VERSION: &str = env!("CARGO_PKG_VERSION"); const PKG_AUTHORS: &str = env!("CARGO_PKG_AUTHORS"); fn read_from_stdin() -> io::Result { - 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 { + let path = Path::new(path); + let mut handle = File::open(&path)?; + let mut buffer = String::new(); handle.read_to_string(&mut buffer)?; Ok(buffer) } @@ -23,13 +33,30 @@ fn render(input: &str) -> Result { } 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),