Skip to content

Commit

Permalink
Add option to print output as JSON (#9)
Browse files Browse the repository at this point in the history
Make StatusContext struct serializable using serde so that it can be serialized to JSON. 
Added command line option that lets users print output as JSON. 
The new command line option must be set along with the verbose flag.
  • Loading branch information
omkhegde authored Feb 19, 2021
1 parent e875ab0 commit 62e32c0
Show file tree
Hide file tree
Showing 6 changed files with 55 additions and 37 deletions.
2 changes: 1 addition & 1 deletion cfn-guard/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ edition = "2018"
[dependencies]
nom = "5.1.2"
nom_locate = "2.0.0"
indexmap = "1.6.0"
indexmap = { version = "1.6.0", features = ["serde-1"] }
regex = "1.3.9"
simple_logger = "1.3.0"
clap = "2.29.0"
Expand Down
4 changes: 3 additions & 1 deletion cfn-guard/src/commands/tracker.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
use crate::rules::{Evaluate, EvaluationContext, Result, Status, EvaluationType, path_value::PathAwareValue};
use nom::lib::std::fmt::Formatter;
use serde::{Serialize};

#[derive(Debug)]
#[derive(Serialize, Debug)]
pub(super) struct StatusContext {
pub(super) eval_type: EvaluationType,
pub(super) context: String,
#[serde(skip_serializing)]
pub(super) msg: Option<String>,
pub(super) from: Option<PathAwareValue>,
pub(super) to: Option<PathAwareValue>,
Expand Down
70 changes: 41 additions & 29 deletions cfn-guard/src/commands/validate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ impl Command for Validate {
.help("sort by last modified times within a directory"))
.arg(Arg::with_name("verbose").long("verbose").short("v").required(false)
.help("verbose logging"))
.arg(Arg::with_name("print-json").long("print-json").short("p").required(false)
.help("Print output in json format"))
}

fn execute(&self, app: &ArgMatches<'_>) -> Result<()> {
Expand All @@ -67,6 +69,7 @@ impl Command for Validate {
false
};

let print_json = app.is_present("print-json");

let files = get_files(file, cmp)?;
let data_files = get_files(data, cmp)?;
Expand All @@ -83,7 +86,7 @@ impl Command for Validate {
},

Ok(rules) => {
evaluate_against_data_files(&data_files, &rules, verbose)?
evaluate_against_data_files(&data_files, &rules, verbose, print_json)?
}
}
}
Expand All @@ -96,7 +99,8 @@ impl Command for Validate {
#[derive(Debug)]
struct ConsoleReporter<'r> {
root_context: StackTracker<'r>,
verbose: bool
verbose: bool,
print_json: bool
}

fn colored_string(status: Option<Status>) -> ColoredString {
Expand Down Expand Up @@ -155,42 +159,50 @@ pub(super) fn print_context(cxt: &StatusContext, depth: usize) {
}

impl<'r, 'loc> ConsoleReporter<'r> {
fn new(root: StackTracker<'r>, verbose: bool) -> Self {
fn new(root: StackTracker<'r>, verbose: bool, print_json: bool) -> Self {
ConsoleReporter {
root_context: root,
verbose,
print_json,
}
}

fn report(self) {
print!("{}", "Summary Report".underline());
let stack = self.root_context.stack();
let top = stack.first().unwrap();
println!(" Overall File Status = {}", colored_string(top.status));

let longest = top.children.iter()
.max_by(|f, s| {
(*f).context.len().cmp(&(*s).context.len())
})
.map(|elem| elem.context.len())
.unwrap_or(20);

for container in &top.children {
print!("{}", container.context);
let container_level = container.context.len();
let spaces = longest - container_level + 4;
for _idx in 0..spaces {
print!(" ");
}
println!("{}", colored_string(container.status));
}

if self.verbose {
println!("Evaluation Tree");
for each in &top.children {
print_context(each, 1);
}
if self.verbose && self.print_json {
let serialized_user = serde_json::to_string_pretty(&top.children).unwrap();
println!("{}", serialized_user);
}
else {
print!("{}", "Summary Report".underline());
println!(" Overall File Status = {}", colored_string(top.status));

let longest = top.children.iter()
.max_by(|f, s| {
(*f).context.len().cmp(&(*s).context.len())
})
.map(|elem| elem.context.len())
.unwrap_or(20);

for container in &top.children {
print!("{}", container.context);
let container_level = container.context.len();
let spaces = longest - container_level + 4;
for _idx in 0..spaces {
print!(" ");
}
println!("{}", colored_string(container.status));
}

if self.verbose {
println!("Evaluation Tree");
for each in &top.children {
print_context(each, 1);
}
}
}
}
}

Expand Down Expand Up @@ -237,7 +249,7 @@ impl<'r> ConsoleReporter<'r> {

}

fn evaluate_against_data_files(data_files: &[PathBuf], rules: &RulesFile<'_>, verbose: bool) -> Result<()> {
fn evaluate_against_data_files(data_files: &[PathBuf], rules: &RulesFile<'_>, verbose: bool, print_json: bool) -> Result<()> {
let mut iterator = iterate_over(data_files, |content, _| {
match serde_json::from_str::<serde_json::Value>(&content) {
Ok(value) => PathAwareValue::try_from(value),
Expand All @@ -254,7 +266,7 @@ fn evaluate_against_data_files(data_files: &[PathBuf], rules: &RulesFile<'_>, ve
Ok(root) => {
let root_context = RootScope::new(rules, &root);
let stacker = StackTracker::new(&root_context);
let reporter = ConsoleReporter::new(stacker, verbose);
let reporter = ConsoleReporter::new(stacker, verbose, print_json);
rules.evaluate(&root, &reporter)?;
reporter.report();
}
Expand Down
5 changes: 3 additions & 2 deletions cfn-guard/src/rules/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,11 @@ use colored::*;
use crate::rules::path_value::PathAwareValue;
use nom::lib::std::convert::TryFrom;
use crate::rules::errors::ErrorKind;
use serde::{Serialize};

pub(crate) type Result<R> = std::result::Result<R, Error>;

#[derive(Debug, Clone, PartialEq, Copy)]
#[derive(Debug, Clone, PartialEq, Copy, Serialize)]
pub(crate) enum Status {
PASS,
FAIL,
Expand Down Expand Up @@ -49,7 +50,7 @@ impl TryFrom<&str> for Status {
}
}

#[derive(Debug, Clone, PartialEq, Copy)]
#[derive(Debug, Clone, PartialEq, Copy, Serialize)]
pub(crate) enum EvaluationType {
File,
Rule,
Expand Down
7 changes: 4 additions & 3 deletions cfn-guard/src/rules/path_value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,9 @@ use super::{EvaluationContext, Evaluate, Status};
use std::cmp::Ordering;
use crate::rules::evaluate::AutoReport;
use crate::rules::EvaluationType;
use serde::{Serialize};

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)]
pub(crate) struct Path(pub(crate) String);

impl std::fmt::Display for Path {
Expand Down Expand Up @@ -103,14 +104,14 @@ impl Path {
}
}

#[derive(PartialEq, Debug, Clone)]
#[derive(PartialEq, Debug, Clone, Serialize)]
pub(crate) struct MapValue {
keys: Vec<PathAwareValue>,
values: indexmap::IndexMap<String, PathAwareValue>,
}


#[derive(Debug, Clone)]
#[derive(Debug, Clone, Serialize)]
pub(crate) enum PathAwareValue {
Null(Path),
String((Path, String)),
Expand Down
4 changes: 3 additions & 1 deletion cfn-guard/src/rules/values.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ use nom::lib::std::fmt::Formatter;
use crate::rules::errors::{Error};
use crate::rules::parser::Span;

use serde::{Serialize};

#[derive(PartialEq, Debug, Clone, Hash, Copy)]
pub enum CmpOperator {
Eq,
Expand Down Expand Up @@ -112,7 +114,7 @@ impl Hash for Value {
//
// .X in r(10, 20]
// .X in r(10, 20)
#[derive(PartialEq, Debug, Clone)]
#[derive(PartialEq, Debug, Clone, Serialize)]
pub struct RangeType<T: PartialOrd> {
pub upper: T,
pub lower: T,
Expand Down

0 comments on commit 62e32c0

Please sign in to comment.