Skip to content

Commit

Permalink
Table for config
Browse files Browse the repository at this point in the history
  • Loading branch information
kevin-valerio committed Sep 27, 2024
1 parent eb77c7b commit b8862ee
Show file tree
Hide file tree
Showing 8 changed files with 237 additions and 189 deletions.
98 changes: 0 additions & 98 deletions src/cli/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,25 +15,6 @@ use crate::{
};
use anyhow::Context;
use frame_support::weights::Weight;
use ratatui::{
layout::Rect,
style::{
Color,
Modifier,
Style,
},
text::{
Line,
Span,
},
widgets::{
Block,
Borders,
List,
ListItem,
},
Frame,
};
use serde_derive::{
Deserialize,
Serialize,
Expand Down Expand Up @@ -182,85 +163,6 @@ impl TryFrom<&PathBuf> for Configuration {
}

impl Configuration {
pub fn render_config(&self, f: &mut Frame, area: Rect) {
// Helper function to create list items for optional fields
fn format_option<'a, T: std::fmt::Debug>(
label: &'a str,
option: &'a Option<T>,
) -> ListItem<'a> {
let opt = format!("{:?}", option)
.replace("Some", "")
.trim_start_matches('(')
.trim_end_matches(')')
.to_string();

let opt_2 = opt
.trim_start_matches("\"")
.trim_end_matches("\"")
.to_string();

ListItem::new(Line::from(vec![
Span::raw(format!("{}: ", label)),
Span::styled(opt_2, Style::default().fg(Color::Yellow)),
]))
}

let items = vec![
format_option("\nCores used", &self.cores),
ListItem::new(Line::from(vec![
Span::raw("Using Honggfuzz: "),
Span::styled(
format!("{}", self.use_honggfuzz),
Style::default().fg(Color::Yellow),
),
])),
format_option("Deployer address", &self.deployer_address),
format_option("Max messages per exec", &self.max_messages_per_exec),
format_option("Report path", &self.report_path),
ListItem::new(Line::from(vec![
Span::raw("Fuzzing origin: "),
Span::styled(
format!("{}", self.fuzz_origin),
Style::default().fg(Color::Yellow),
),
])),
format_option("Default gas limit", &self.default_gas_limit),
format_option("Storage deposit limit", &self.storage_deposit_limit),
format_option("Instantiate initial value", &self.instantiate_initial_value),
format_option("Constructor payload", &self.constructor_payload),
ListItem::new(Line::from(vec![
Span::raw("Verbose mode: "),
Span::styled(
format!("{}", self.verbose),
Style::default().fg(Color::Yellow),
),
])),
format_option(
"Path to instrumented contract",
&self.instrumented_contract_path,
),
format_option("Fuzz output folder", &self.fuzz_output),
ListItem::new(Line::from(vec![
Span::raw("Custom UI: "),
Span::styled(
format!("{}", self.show_ui),
Style::default().fg(Color::Yellow),
),
])),
];

let config_list = List::new(items)
.block(
Block::default()
.borders(Borders::ALL)
.title("Configuration"),
)
.style(Style::default().fg(Color::White))
.highlight_style(Style::default().add_modifier(Modifier::BOLD))
.highlight_symbol("> ");

f.render_widget(config_list, area);
}
pub fn should_fuzz_origin(&self) -> OriginFuzzingOption {
match self.fuzz_origin {
true => EnableOriginFuzzing,
Expand Down
62 changes: 35 additions & 27 deletions src/cli/ui/chart.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
use chrono::DateTime;
use ratatui::{
layout::Constraint,
layout::{
Alignment,
Constraint,
},
style::{
Color,
Style,
Expand All @@ -24,10 +28,8 @@ pub struct ChartManager<'a> {
}

impl<'a> ChartManager<'a> {
pub fn new(corpus_counter: &'a [(f64, f64)]) -> Self {
Self {
f64_array: corpus_counter,
}
pub fn new(f64_array: &'a [(f64, f64)]) -> Self {
Self { f64_array }
}

fn get_x_values(&self) -> Vec<f64> {
Expand All @@ -45,45 +47,49 @@ impl<'a> ChartManager<'a> {
fn find_min(values: &[f64]) -> f64 {
values.iter().cloned().fold(f64::INFINITY, f64::min)
}

pub fn get_first_x(&self) -> String {
fn timestamp_to_str(unix_timestamp: f64) -> String {
DateTime::from_timestamp(unix_timestamp as i64, 0)
.unwrap()
.format("%Y-%m-%d %H:%M:%S")
.to_string()
}
pub fn get_first_x(&self) -> f64 {
let x_values = self.get_x_values();
format!("{:.1}", Self::find_min(&x_values))
Self::find_min(&x_values)
}

pub fn get_middle_x(&self) -> String {
pub fn get_middle_x(&self) -> f64 {
let x_values = self.get_x_values();
let min_x = Self::find_min(&x_values);
let max_x = Self::find_max(&x_values);
format!("{:.1}", (min_x + max_x) / 2.0)
(min_x + max_x) / 2.0
}

pub fn get_max_x(&self) -> String {
pub fn get_max_x(&self) -> f64 {
let x_values = self.get_x_values();
format!("{:.1}", Self::find_max(&x_values))
Self::find_max(&x_values)
}

pub fn get_first_y(&self) -> String {
pub fn get_first_y(&self) -> f64 {
let y_values = self.get_y_values();
format!("{:.1}", Self::find_min(&y_values))
Self::find_min(&y_values)
}

pub fn get_middle_y(&self) -> String {
pub fn get_middle_y(&self) -> f64 {
let y_values = self.get_y_values();
let min_y = Self::find_min(&y_values);
let max_y = Self::find_max(&y_values);
format!("{:.1}", (min_y + max_y) / 2.0)
(min_y + max_y) / 2.0
}

fn get_max_y(&self) -> String {
fn get_max_y(&self) -> f64 {
let y_values = self.get_y_values();
format!("{:.1}", Self::find_max(&y_values))
Self::find_max(&y_values)
}

pub fn create_chart(&self) -> Chart {
let dataset = vec![Dataset::default()
.name("Number of entries")
.marker(Marker::Dot)
.marker(Marker::Braille)
.graph_type(GraphType::Line)
.style(Style::default().fg(Color::Cyan))
.data(self.f64_array)];
Expand All @@ -93,27 +99,29 @@ impl<'a> ChartManager<'a> {
Block::bordered().title(
Title::default()
.content("Corpus evolution over time".cyan().bold())
.alignment(ratatui::layout::Alignment::Center),
.alignment(Alignment::Center),
),
)
.x_axis(
Axis::default()
.title("Time")
.style(Style::default().fg(Color::Gray))
.bounds([self.get_first_x(), self.get_max_x()])
.labels([
self.get_first_x().bold(),
Span::from(self.get_middle_x()),
self.get_max_x().bold(),
Self::timestamp_to_str(self.get_first_x()).bold(),
Span::from(Self::timestamp_to_str(self.get_middle_x())),
Self::timestamp_to_str(self.get_max_x()).bold(),
]),
)
.y_axis(
Axis::default()
.title("Number of entries")
.style(Style::default().fg(Color::Gray))
.bounds([self.get_first_y(), self.get_max_y()])
.labels([
self.get_first_y().bold(),
Span::from(self.get_middle_y()),
self.get_max_y().bold(),
self.get_first_y().to_string().bold(),
Span::from(self.get_middle_y().to_string()),
self.get_max_y().to_string().bold(),
]),
)
.legend_position(Some(LegendPosition::TopLeft))
Expand Down
139 changes: 139 additions & 0 deletions src/cli/ui/configtable.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
use crate::cli::config::Configuration;
use ratatui::{
layout::{
Constraint,
Rect,
},
prelude::{
Color,
Modifier,
Style,
Stylize,
},
style::palette::{
tailwind,
tailwind::Palette,
},
widgets::{
Block,
Borders,
HighlightSpacing,
Row,
Table,
},
Frame,
};

const PALETTE: Palette = tailwind::RED;
struct TableColors {
buffer_bg: Color,
header_bg: Color,
header_fg: Color,
row_fg: Color,
selected_style_fg: Color,
normal_row_color: Color,
alt_row_color: Color,
}

impl TableColors {
const fn new(color: &Palette) -> Self {
Self {
buffer_bg: tailwind::SLATE.c950,
header_bg: color.c900,
header_fg: tailwind::SLATE.c200,
row_fg: tailwind::SLATE.c200,
selected_style_fg: color.c400,
normal_row_color: tailwind::SLATE.c950,
alt_row_color: tailwind::SLATE.c900,
}
}
}

impl Configuration {
pub fn render_config(&self, f: &mut Frame, area: Rect) {
// Helper function to format optional fields
fn format_option<T: std::fmt::Debug>(option: &Option<T>) -> String {
match option {
Some(value) => {
format!("{:?}", value)
.trim_matches(|c| c == '"' || c == '(' || c == ')')
.to_string()
}
None => "-".to_string(),
}
}

let colors = TableColors::new(&PALETTE);

let x = &format_option(&self.instantiate_initial_value);
let x1 = &format_option(&self.cores);
let x2 = &self.use_honggfuzz.to_string();
let x3 = &format_option(&self.deployer_address);
let x4 = &format_option(&self.max_messages_per_exec);
let x5 = &format_option(&self.report_path);
let x6 = &self.fuzz_origin.to_string();
let x7 = &format_option(&self.default_gas_limit);
let x8 = &format_option(&self.storage_deposit_limit);
let x9 = &format_option(&self.constructor_payload);
let x10 = &self.verbose.to_string();
let x11 = &self
.instrumented_contract_path
.clone()
.unwrap_or_default()
.to_string();
let x12 = &format_option(&self.fuzz_output);
let x13 = &self.show_ui.to_string();
let items = vec![
Row::new(vec!["Cores used", x1]),
Row::new(vec!["Using Honggfuzz", x2]),
Row::new(vec!["Deployer address", x3]),
Row::new(vec!["Max messages per exec", x4]),
Row::new(vec!["Report path", x5]),
Row::new(vec!["Fuzzing origin", x6]),
Row::new(vec!["Default gas limit", x7]),
Row::new(vec!["Storage deposit limit", x8]),
Row::new(vec!["Instantiate initial value", x]),
Row::new(vec!["Constructor payload", x9]),
Row::new(vec!["Verbose mode", x10]),
Row::new(vec!["Path to instrumented contract", x11]),
Row::new(vec!["Fuzz output folder", x12]),
Row::new(vec!["Custom UI", x13]),
];

let rows = items.iter().enumerate().map(|(i, row)| {
let color = match i % 2 {
0 => colors.normal_row_color,
_ => colors.alt_row_color,
};
row.clone()
.style(Style::new().fg(colors.row_fg).bg(color))
.height(1)
});

let selected_style = Style::default()
.add_modifier(Modifier::REVERSED)
.fg(colors.selected_style_fg);
let header_style = Style::default().fg(colors.header_fg).bg(colors.header_bg);

let table = Table::new(rows, [Constraint::Length(5), Constraint::Length(5)])
.header(
Row::new(vec!["Setting", "Value"])
.style(header_style)
.bold(),
)
.block(
Block::default()
.borders(Borders::ALL)
.title("Configuration"),
)
.highlight_style(selected_style)
.widths([Constraint::Percentage(40), Constraint::Percentage(60)])
.column_spacing(1)
.highlight_style(Style::default().add_modifier(Modifier::BOLD))
.highlight_symbol("> ")
.bg(colors.buffer_bg)
.highlight_spacing(HighlightSpacing::Always);

f.render_widget(table, area);
}
}
1 change: 1 addition & 0 deletions src/cli/ui/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ pub mod custom;
pub mod ratatui;

pub mod chart;
mod configtable;
pub mod monitor;
2 changes: 1 addition & 1 deletion src/cli/ui/monitor/corpus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ mod tests {
let data = watcher.data();

assert_eq!(data.len(), 2);
assert_eq!(data[0].y, 2.0);
assert_eq!(data[1].y, 1.0);
}

#[test]
Expand Down
Loading

0 comments on commit b8862ee

Please sign in to comment.