Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add open browser feature #44

Merged
merged 2 commits into from
Nov 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .rustfmt.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Basic
edition = "2021"
hard_tabs = true
max_width = 100
max_width = 140
tab_spaces = 4

# Imports
Expand Down
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ comfy-table = { version = "7.0.1" }
ratatui = { version = "0.23.0", features = ["all-widgets"] }
crossterm = { version = "0.27.0" }
array-bytes = { version = "6.1.0" }
open = { version = "5.0.0" }
# polkadot
sp-core = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" }
sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" }
Expand Down
7 changes: 7 additions & 0 deletions src/app/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,13 @@ pub enum ApplicationCommand {
#[arg(name = "network", long)]
network: Network,
},
/// Open block, extrinsic with default browser.
OpenWithBrowser {
#[arg(name = "block-hash", long)]
block_hash: Option<String>,
#[arg(name = "extrinsic-hash", long)]
extrinsic_hash: Option<String>,
},
/// Display dashboard information.
DashBoard,
/// Clean the history.
Expand Down
43 changes: 8 additions & 35 deletions src/app/dashboard/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,7 @@ use std::{collections::VecDeque, io, sync::Arc};
// crates.io
use crossterm::event::{read, Event, KeyCode, KeyEventKind};
use ratatui::{
prelude::{
text::Line, Backend, Color, Constraint, Direction, Frame, Layout, Rect, Span, Style,
Terminal,
},
prelude::{text::Line, Backend, Color, Constraint, Direction, Frame, Layout, Rect, Span, Style, Terminal},
style::Stylize,
widgets::*,
};
Expand Down Expand Up @@ -81,23 +78,12 @@ impl<CI: ChainInfo> DashBoard<CI> {
.types()
.types
.iter()
.find(|ty| {
ty.ty.path
== Path::from_segments_unchecked(vec![
"frame_system".to_string(),
"EventRecord".to_string(),
])
})
.find(|ty| ty.ty.path == Path::from_segments_unchecked(vec!["frame_system".to_string(), "EventRecord".to_string()]))
.map(|ty| ty.id)
.unwrap();

let ty_mut = metadata.types_mut();
let vec_event_records_ty = Type::new(
Path::default(),
vec![],
TypeDefSequence::new(event_records_type_id.into()),
vec![],
);
let vec_event_records_ty = Type::new(Path::default(), vec![], TypeDefSequence::new(event_records_type_id.into()), vec![]);
let vec_event_records_type_id = ty_mut.types.len() as u32;
ty_mut
.types
Expand All @@ -109,11 +95,7 @@ impl<CI: ChainInfo> DashBoard<CI> {

if let Ok(storage_data) = self.events_rev.try_recv() {
for data in storage_data {
let value = decode_as_type(
&mut data.0.as_ref(),
vec_event_records_type_id,
self.metadata.types(),
);
let value = decode_as_type(&mut data.0.as_ref(), vec_event_records_type_id, self.metadata.types());

if let Ok(event_records) = value {
match event_records.value {
Expand All @@ -124,16 +106,11 @@ impl<CI: ChainInfo> DashBoard<CI> {
match record.value {
ValueDef::Composite(inner) => match inner {
Composite::Named(v) => {
let event_values: Vec<Value<u32>> = v
.into_iter()
.filter(|d| d.0 == "event")
.map(|d| d.1)
.collect();
let event_values: Vec<Value<u32>> =
v.into_iter().filter(|d| d.0 == "event").map(|d| d.1).collect();

for event in event_values {
if self.events.items.len()
== self.events.items.capacity()
{
if self.events.items.len() == self.events.items.capacity() {
self.events.items.pop_front();
} else {
self.events.items.push_back(event);
Expand Down Expand Up @@ -180,11 +157,7 @@ impl<CI: ChainInfo> DashBoard<CI> {
}
}

pub async fn run_dashboard<B, CI>(
client: Arc<RpcClient<CI>>,
terminal: &mut Terminal<B>,
mut dash_board: DashBoard<CI>,
) -> io::Result<()>
pub async fn run_dashboard<B, CI>(client: Arc<RpcClient<CI>>, terminal: &mut Terminal<B>, mut dash_board: DashBoard<CI>) -> io::Result<()>
where
B: Backend,
CI: ChainInfo,
Expand Down
10 changes: 2 additions & 8 deletions src/app/dashboard/tab_blocks.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
// crates.io
use ratatui::{
prelude::{
text::Line, Backend, Color, Constraint, Direction, Frame, Layout, Modifier, Rect, Span,
Style,
},
prelude::{text::Line, Backend, Color, Constraint, Direction, Frame, Layout, Modifier, Rect, Span, Style},
widgets::*,
};
use sp_core::Encode;
Expand Down Expand Up @@ -94,10 +91,7 @@ where
// Extrinsics
items.push(ListItem::new("Extrinsic => ".to_string()));
for (i, e) in b.extrinsics().iter().enumerate() {
items.push(ListItem::new(format!(
" ext{i} => {:?}",
CI::Hashing::hash(&e.encode())
)));
items.push(ListItem::new(format!(" ext{i} => {:?}", CI::Hashing::hash(&e.encode()))));
}

let l = List::new(items).block(block);
Expand Down
5 changes: 1 addition & 4 deletions src/app/dashboard/tab_events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,7 @@ where
{
let mut text = "".to_string();
for e in &app.events.items {
text.push_str(&format!(
"{}\n",
serde_json::to_string(e).unwrap_or("Decode Error Occurred.".to_string())
));
text.push_str(&format!("{}\n", serde_json::to_string(e).unwrap_or("Decode Error Occurred.".to_string())));
}
let l = Paragraph::new(text)
.wrap(Wrap { trim: true })
Expand Down
47 changes: 8 additions & 39 deletions src/app/helper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,7 @@ pub struct Config {

const ESCAPE_CHAR: Option<char> = Some('\\');
const fn default_break_chars(c: char) -> bool {
matches!(
c,
' ' | '\t'
| '\n' | '"' | '\\'
| '\'' | '`' | '@'
| '$' | '>' | '<'
| '=' | ';' | '|'
| '&' | '{' | '('
| '\0'
)
matches!(c, ' ' | '\t' | '\n' | '"' | '\\' | '\'' | '`' | '@' | '$' | '>' | '<' | '=' | ';' | '|' | '&' | '{' | '(' | '\0')
}

/// Create a line editor.
Expand Down Expand Up @@ -133,11 +124,7 @@ impl<H: Hinter> Highlighter for EditorHelper<H> {
Owned(format!("\x1b[1m{hint}\x1b[m"))
}

fn highlight_candidate<'c>(
&self,
candidate: &'c str,
_completion: CompletionType,
) -> Cow<'c, str> {
fn highlight_candidate<'c>(&self, candidate: &'c str, _completion: CompletionType) -> Cow<'c, str> {
Owned(candidate.to_string())
}
}
Expand All @@ -154,27 +141,17 @@ impl<H: Hinter> Hinter for EditorHelper<H> {
impl<H: Hinter> Completer for EditorHelper<H> {
type Candidate = Pair;

fn complete(
&self,
line: &str,
pos: usize,
_ctx: &Context<'_>,
) -> rustyline::Result<(usize, Vec<Self::Candidate>)> {
fn complete(&self, line: &str, pos: usize, _ctx: &Context<'_>) -> rustyline::Result<(usize, Vec<Self::Candidate>)> {
println!();
let (start, mut word) = extract_word(line, pos, ESCAPE_CHAR, default_break_chars);
let prefixes = shell_words::split(&line[..pos]).unwrap();

let mut candidates = Vec::new();
if let Some(command) =
prefix_command(&self.command, prefixes.iter().map(String::as_str).peekable())
{
if let Some(command) = prefix_command(&self.command, prefixes.iter().map(String::as_str).peekable()) {
candidates = command
.get_subcommands()
.cloned()
.map(|i| Pair {
display: i.get_name().to_owned(),
replacement: i.get_name().to_owned(),
})
.map(|i| Pair { display: i.get_name().to_owned(), replacement: i.get_name().to_owned() })
.filter(|c| c.display.starts_with(word) && word != command.get_name())
.collect();

Expand All @@ -199,21 +176,14 @@ impl<H: Hinter> Completer for EditorHelper<H> {
}
}

fn prefix_command<'s, I: Iterator<Item = &'s str>>(
command: &Command,
mut prefixes: iter::Peekable<I>,
) -> Option<Command> {
fn prefix_command<'s, I: Iterator<Item = &'s str>>(command: &Command, mut prefixes: iter::Peekable<I>) -> Option<Command> {
if let Some(prefix) = prefixes.next() {
for subcommand in command.get_subcommands() {
if subcommand.get_name() == prefix
|| subcommand.get_display_name().unwrap_or_default() == prefix
|| subcommand.get_all_aliases().any(|s| s == prefix)
{
return if prefixes.peek().is_none() {
Some(subcommand.clone())
} else {
prefix_command(subcommand, prefixes)
};
return if prefixes.peek().is_none() { Some(subcommand.clone()) } else { prefix_command(subcommand, prefixes) };
}
}
}
Expand Down Expand Up @@ -245,8 +215,7 @@ pub fn metadata_path() -> Result<PathBuf, AppError> {

/// Print the app welcome message.
pub fn print_welcome_message() {
const INTRODUCTION: &str =
"This is the all-in-one substrate command assistant, the Polkadot Apps CLI edition.";
const INTRODUCTION: &str = "This is the all-in-one substrate command assistant, the Polkadot Apps CLI edition.";
const USAGE: &str = "
Tips:
- `usage` to ask help.
Expand Down
9 changes: 2 additions & 7 deletions src/app/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,6 @@ mod command;
mod dashboard;
mod helper;

pub use command::{
AccountInfoCommand, AppCommand, ApplicationCommand, ChainCommand, RpcCommand, RuntimeCommand,
};
pub use command::{AccountInfoCommand, AppCommand, ApplicationCommand, ChainCommand, RpcCommand, RuntimeCommand};
pub use dashboard::{run_dashboard, DashBoard};
pub use helper::{
app_root_path, create_editor, history_path, metadata_path, print_welcome_message, Config,
EditorHelper, POLKADOT_CLI,
};
pub use helper::{app_root_path, create_editor, history_path, metadata_path, print_welcome_message, Config, EditorHelper, POLKADOT_CLI};
Loading