Skip to content

Commit

Permalink
Refactor Hbs Renderer interface
Browse files Browse the repository at this point in the history
  • Loading branch information
lukaspustina committed Jan 11, 2020
1 parent a876f3d commit b97dfdf
Show file tree
Hide file tree
Showing 4 changed files with 126 additions and 116 deletions.
2 changes: 1 addition & 1 deletion examples/md_report.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ fn main() {
let analysis = Analysis::new(Box::new(runner), &hostinfos, &config.commands);
let report = analysis.run().expect("failed to run analysis");

let renderer = renderer::MdRenderer::new(template);
let renderer = renderer::HbsRenderer::new(template);
let stdout = std::io::stdout();
let handle = stdout.lock();
renderer.render(&report, handle).expect("Failed to render to stdout");
Expand Down
25 changes: 22 additions & 3 deletions src/bin/usereport.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use exitfailure::ExitFailure;
use failure::ResultExt;
use failure::{ResultExt, format_err};
use indicatif::{ProgressBar, ProgressStyle};
use prettytable::{cell, format, row, Cell, Row, Table};
use std::{
Expand All @@ -9,7 +9,7 @@ use std::{
sync::mpsc::{self, Receiver, Sender},
};
use structopt::{clap, StructOpt};
use usereport::{renderer, renderer::OutputType, runner::ThreadRunner, Analysis, AnalysisReport, Config, Renderer};
use usereport::{renderer, runner::ThreadRunner, Analysis, AnalysisReport, Config, Renderer};

#[derive(Debug, StructOpt)]
#[structopt(name = "usereport", author, about, setting = clap::AppSettings::ColoredHelp)]
Expand Down Expand Up @@ -46,6 +46,25 @@ struct Opt {
show_commands: bool,
}

#[derive(Debug)]
pub enum OutputType {
JSON,
Markdown,
}

impl FromStr for OutputType {
type Err = failure::Error;

fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_ref() {
"json" => Ok(OutputType::JSON),
"markdown" => Ok(OutputType::Markdown),
"md" => Ok(OutputType::Markdown),
_ => Err(format_err!("failed to parse {} as output type", s)),
}
}
}

fn main() -> Result<(), ExitFailure> {
human_panic::setup_panic!();
env_logger::init();
Expand Down Expand Up @@ -173,7 +192,7 @@ fn render_to_stdout(report: &AnalysisReport, output_type: &OutputType) -> render

fn renderer<W: Write>(output_type: &OutputType) -> Box<dyn Renderer<W>> {
match output_type {
OutputType::Markdown => Box::new(renderer::MdRenderer::new(defaults::MD_TEMPLATE)),
OutputType::Markdown => Box::new(renderer::HbsRenderer::new(defaults::MD_TEMPLATE)),
OutputType::JSON => Box::new(renderer::JsonRenderer::new()),
}
}
Expand Down
64 changes: 37 additions & 27 deletions src/command.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use chrono::Local;
use log::{debug, trace};
use serde::{Deserialize, Serialize};
use std::{io::Read, time::Duration};
use subprocess::{Popen, PopenConfig, Redirection};
use chrono::Local;

/// Run a CLI command and store its stdout.
///
Expand Down Expand Up @@ -39,26 +39,26 @@ use chrono::Local;
/// ```
#[derive(Debug, Deserialize, PartialEq, Serialize, Clone)]
pub struct Command {
pub(crate) name: String,
pub(crate) title: Option<String>,
pub(crate) name: String,
pub(crate) title: Option<String>,
pub(crate) description: Option<String>,
pub(crate) command: String,
pub(crate) command: String,
#[serde(rename = "timeout")]
/// Timeout for command execution, defaults to 1 sec if not set
pub(crate) timeout_sec: Option<u64>,
pub(crate) links: Option<Vec<Link>>,
pub(crate) links: Option<Vec<Link>>,
}

impl Command {
/// Create new command with default values
pub fn new<T: Into<String>>(name: T, command: T) -> Command {
Command {
name: name.into(),
title: None,
name: name.into(),
title: None,
description: None,
command: command.into(),
command: command.into(),
timeout_sec: None,
links: None,
links: None,
}
}

Expand Down Expand Up @@ -121,7 +121,7 @@ impl Command {
Err(err) => {
return CommandResult::Error {
command: self,
reason: err.to_string(),
reason: err.to_string(),
};
}
};
Expand All @@ -137,23 +137,33 @@ impl Command {
let _ = p.stdout.as_ref().unwrap().read_to_string(&mut stdout); // TODO: unwrap is unsafe
debug!("stdout '{}'", stdout);

CommandResult::Success { command: self, run_time_ms, stdout }
CommandResult::Success {
command: self,
run_time_ms,
stdout,
}
}
Ok(Some(status)) => {
trace!("process successfully finished as {:?}", status);
CommandResult::Failed { command: self, run_time_ms }
CommandResult::Failed {
command: self,
run_time_ms,
}
}
Ok(None) => {
trace!("process timed out and will be killed");
self.terminate(&mut p);
CommandResult::Timeout { command: self, run_time_ms }
CommandResult::Timeout {
command: self,
run_time_ms,
}
}
Err(err) => {
trace!("process failed '{:?}'", err);
self.terminate(&mut p);
CommandResult::Error {
command: self,
reason: err.to_string(),
reason: err.to_string(),
}
}
}
Expand All @@ -170,31 +180,31 @@ impl Command {
#[derive(Debug, Deserialize, PartialEq, Serialize, Clone)]
pub struct Link {
pub(crate) name: String,
pub(crate) url: String,
pub(crate) url: String,
}

impl Link {
pub fn new<T: Into<String>>(name: T, url: T) -> Link {
Link {
name: name.into(),
url: url.into(),
url: url.into(),
}
}

pub fn name(&self) -> &str {
&self.name
}
pub fn name(&self) -> &str { &self.name }

pub fn url(&self) -> &str {
&self.url
}
pub fn url(&self) -> &str { &self.url }
}

/// Encapsulates a command execution result
#[derive(Debug, PartialEq, Serialize)]
pub enum CommandResult {
/// `Command` has been executed successfully and `String` contains stdout.
Success { command: Command, run_time_ms: u64, stdout: String },
Success {
command: Command,
run_time_ms: u64,
stdout: String,
},
/// `Command` failed to execute
Failed { command: Command, run_time_ms: u64 },
/// `Command` execution exceeded specified timeout
Expand All @@ -215,9 +225,9 @@ mod tests {
init();

#[cfg(target_os = "macos")]
let command = Command::new("true", r#"/usr/bin/true"#);
let command = Command::new("true", r#"/usr/bin/true"#);
#[cfg(target_os = "linux")]
let command = Command::new("true", r#"/bin/true"#);
let command = Command::new("true", r#"/bin/true"#);

let res = command.exec();

Expand All @@ -231,9 +241,9 @@ mod tests {
init();

#[cfg(target_os = "macos")]
let command = Command::new("false", r#"/usr/bin/false"#);
let command = Command::new("false", r#"/usr/bin/false"#);
#[cfg(target_os = "linux")]
let command = Command::new("false", r#"/bin/false"#);
let command = Command::new("false", r#"/bin/false"#);

let res = command.exec();

Expand Down
Loading

0 comments on commit b97dfdf

Please sign in to comment.