Skip to content

Commit

Permalink
Clearing output, changing directories
Browse files Browse the repository at this point in the history
  • Loading branch information
pmikolajczyk41 committed Jun 20, 2023
1 parent 56eb529 commit 6255bd2
Show file tree
Hide file tree
Showing 10 changed files with 199 additions and 149 deletions.
18 changes: 8 additions & 10 deletions drink-cli/src/app_state.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use std::{env, path::PathBuf};

use drink::Sandbox;
use ratatui::text::Line;
use sp_runtime::AccountId32;

#[derive(Clone, Eq, PartialEq, Hash, Debug, Default)]
Expand All @@ -9,26 +11,21 @@ pub struct ChainInfo {
pub current_contract_address: Option<AccountId32>,
}

#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug, Default)]
pub enum Mode {
#[default]
Managing,
Editing,
}

impl Default for Mode {
fn default() -> Self {
Mode::Managing
}
}

#[derive(Clone, Eq, PartialEq, Hash, Debug)]
#[derive(Clone, Eq, PartialEq, Debug)]
pub struct UiState {
pub pwd: PathBuf,
pub mode: Mode,

pub user_input: String,

pub output: Vec<String>,
pub output: Vec<Line<'static>>,
pub output_offset: u16,
}

Expand All @@ -44,8 +41,9 @@ impl Default for UiState {
}
}

#[derive(Clone, Eq, PartialEq, Hash, Debug, Default)]
#[derive(Default)]
pub struct AppState {
pub sandbox: Sandbox,
pub chain_info: ChainInfo,
pub ui_state: UiState,
}
9 changes: 7 additions & 2 deletions drink-cli/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,19 @@ use clap::Parser;

#[derive(Parser)]
pub enum CliCommand {
#[clap(alias = "c")]
Clear,
#[clap(alias = "cd")]
ChangeDir {
path: String,
},

#[clap(alias = "b")]
Build,
#[clap(alias = "d")]
Deploy,
CallGet,
CallFlip,
#[clap(alias = "e")]
Exit,
}

#[cfg(test)]
Expand Down
99 changes: 94 additions & 5 deletions drink-cli/src/executor.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,101 @@
use std::{env, process::Command};

use anyhow::Result;
use clap::Parser;
use sp_runtime::AccountId32;

use crate::app_state::AppState;
use crate::{app_state::AppState, cli::CliCommand};

pub fn execute(app_state: &mut AppState) -> Result<()> {
let command = app_state.ui_state.user_input.clone();
app_state
.ui_state
.output
.push(format!("Executing: {}", command));
app_state.print_command(&command);

let command = command
.split_ascii_whitespace()
.map(|a| a.trim())
.collect::<Vec<_>>();
let cli_command = match CliCommand::try_parse_from([vec![""], command].concat()) {
Ok(cli_command) => cli_command,
Err(_) => {
app_state.print_error("Invalid command");
return Ok(());
}
};

match cli_command {
CliCommand::Clear => {
app_state.ui_state.output.clear();
app_state.ui_state.output_offset = 0;
}
CliCommand::ChangeDir { path } => {
let target_dir = app_state.ui_state.pwd.join(path);
match env::set_current_dir(target_dir) {
Ok(_) => {
app_state.ui_state.pwd =
env::current_dir().expect("Failed to get current directory");
app_state.print("Directory changed");
}
Err(err) => app_state.print_error(&err.to_string()),
}
}

CliCommand::Build => {
build_contract(app_state);
}
CliCommand::Deploy => {
// account_id = Some(deploy_contract(&mut sandbox));
app_state.chain_info.deployed_contracts += 1;
app_state.chain_info.current_contract_address = Some(AccountId32::new([0; 32]));
}
CliCommand::CallGet => {
// let account_id = match account_id {
// Some(ref account_id) => account_id.clone(),
// None => {
// eprintln!("Contract not deployed");
// continue;
// }
// };
//
// let result = sandbox.call_contract(account_id, "get".to_string());
// println!("Contract called successfully.\n\n{result}")
}
CliCommand::CallFlip => {}
}

Ok(())
}

fn build_contract(app_state: &mut AppState) {
let output = Command::new("cargo-contract")
.arg("contract")
.arg("build")
.arg("--release")
.output()
.expect("Failed to execute 'cargo contract' command");

if output.status.success() {
app_state.print("Contract built successfully");
} else {
let stderr = String::from_utf8_lossy(&output.stderr);
app_state.print_error(&format!(
"Error executing 'cargo contract' command:\n{stderr}"
));
}
}

// fn deploy_contract(sandbox: &mut Sandbox) -> AccountId32 {
// println!("Deploying contract...");
//
// let contract_bytes_path = env::current_dir()
// .expect("Failed to get current directory")
// .join(CONTRACT_DIR)
// .join("target/ink/example.wasm");
// let contract_bytes = std::fs::read(contract_bytes_path).expect("Failed to read contract bytes");
//
// let account_id = sandbox.deploy_contract(contract_bytes);
//
// println!("Contract deployed successfully");
//
// account_id
// }
//
105 changes: 0 additions & 105 deletions drink-cli/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
use std::{env, process::Command};

use anyhow::Result;
use drink::Sandbox;
use sp_runtime::AccountId32;

use crate::ui::run_ui;

Expand All @@ -11,107 +7,6 @@ mod cli;
mod executor;
mod ui;

const CONTRACT_DIR: &str = "../example/";

fn main() -> Result<()> {
run_ui()
}

// fn main() -> Result<(), Box<dyn Error>> {
// let mut sandbox = Sandbox::new();
// let mut account_id = None;
//
// loop {
// println!();
//
// let mut user_input = String::new();
// io::stdin()
// .read_line(&mut user_input)
// .expect("Failed to get user input");
//
// let cli_command = match CliCommand::try_parse_from(["", user_input.trim()]) {
// Ok(cli_command) => cli_command,
// Err(_) => {
// eprintln!("Invalid command");
// continue;
// }
// };
//
// match cli_command {
// CliCommand::Build => {
// build_contract();
// }
// CliCommand::Deploy => {
// account_id = Some(deploy_contract(&mut sandbox));
// }
// CliCommand::CallGet => {
// let account_id = match account_id {
// Some(ref account_id) => account_id.clone(),
// None => {
// eprintln!("Contract not deployed");
// continue;
// }
// };
//
// let result = sandbox.call_contract(account_id, "get".to_string());
// println!("Contract called successfully.\n\n{result}")
// }
// CliCommand::CallFlip => {
// let account_id = match account_id {
// Some(ref account_id) => account_id.clone(),
// None => {
// eprintln!("Contract not deployed");
// continue;
// }
// };
//
// let result = sandbox.call_contract(account_id, "flip".to_string());
// println!("Contract called successfully.\n\n{result}")
// }
// CliCommand::Exit => {
// println!("Exit");
// break;
// }
// }
// }
//
// Ok(())
// }

fn build_contract() {
println!("Building contract...");

let current_dir = env::current_dir().expect("Failed to get current directory");
let contract_path = current_dir.join(CONTRACT_DIR);
env::set_current_dir(contract_path).expect("Failed to change directory");

let output = Command::new("cargo-contract")
.arg("contract")
.arg("build")
.arg("--release")
.output()
.expect("Failed to execute 'cargo contract' command");

if output.status.success() {
println!("Contract built successfully");
} else {
let stderr = String::from_utf8_lossy(&output.stderr);
eprintln!("Error executing 'cargo contract' command:\n{}", stderr);
}
}

fn deploy_contract(sandbox: &mut Sandbox) -> AccountId32 {
println!("Deploying contract...");

let contract_bytes_path = env::current_dir()
.expect("Failed to get current directory")
.join(CONTRACT_DIR)
.join("target/ink/example.wasm");
let contract_bytes = std::fs::read(contract_bytes_path).expect("Failed to read contract bytes");

let account_id = sandbox.deploy_contract(contract_bytes);

println!("Contract deployed successfully");

account_id
}
34 changes: 27 additions & 7 deletions drink-cli/src/ui/footer.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use ratatui::{
layout::Alignment,
style::{Color, Modifier, Style},
text::{Line, Span},
widgets::{Block, BorderType, Borders, Paragraph, Widget},
};

Expand All @@ -11,12 +13,30 @@ pub(super) fn build(app_state: &AppState) -> impl Widget {
.borders(Borders::ALL)
.border_type(BorderType::Rounded);

let instruction = match app_state.ui_state.mode {
Mode::Managing => "Press 'q' to quit. Press `i` to enter editing mode",
Mode::Editing => "Press 'Esc' to quit editing mode",
};
let instruction: Line = match app_state.ui_state.mode {
Mode::Managing => vec![
Span::raw("Press "),
Span::styled("'q'", Style::default().fg(Color::Yellow)),
Span::raw(" to quit. Press "),
Span::styled("'i'", Style::default().fg(Color::Yellow)),
Span::raw(" to enter editing mode"),
],
Mode::Editing => vec![
Span::raw("Press "),
Span::styled("'Esc'", Style::default().fg(Color::Yellow)),
Span::raw(" to quit editing mode"),
],
}
.into();

Paragraph::new(format!("{instruction}\nMade by Aleph Zero Foundation"))
.alignment(Alignment::Center)
.block(base)
Paragraph::new(vec![
instruction,
Span::styled(
"Made by Aleph Zero Foundation",
Style::default().add_modifier(Modifier::ITALIC),
)
.into(),
])
.alignment(Alignment::Center)
.block(base)
}
1 change: 0 additions & 1 deletion drink-cli/src/ui/layout.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use ratatui::{
backend::Backend,
layout::{Constraint, Direction, Layout},
widgets::{Block, BorderType, Borders},
Frame,
};

Expand Down
6 changes: 3 additions & 3 deletions drink-cli/src/ui/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ mod current_env;
mod footer;
mod layout;
mod output;
mod print;
mod user_input;

use std::{io, io::Stdout, thread::sleep};
use std::{io, io::Stdout};

use anyhow::{anyhow, Result};
use crossterm::{
Expand All @@ -15,11 +16,10 @@ use crossterm::{
};
use layout::layout;
use ratatui::backend::CrosstermBackend;
use sp_runtime::Saturating;

use crate::{
app_state::{
AppState, Mode,
AppState,
Mode::{Editing, Managing},
},
executor::execute,
Expand Down
Loading

0 comments on commit 6255bd2

Please sign in to comment.