Skip to content

Commit

Permalink
add strategy pattern to commands
Browse files Browse the repository at this point in the history
  • Loading branch information
orelvis15 committed Jul 4, 2022
1 parent 7a123ff commit 675928b
Show file tree
Hide file tree
Showing 18 changed files with 147 additions and 111 deletions.
1 change: 0 additions & 1 deletion config/config_remote.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
version = "0.0.1"

[update]
last_cvm_version = "0.0.1"
version_pattern = "v{version}"
name_pattern = "cvm-{arch}.tar.gz"
file_name = "cvm.tar.gz"
Expand Down
21 changes: 10 additions & 11 deletions src/config/remote_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ pub fn get_remote_config() -> Result<RemoteConfig, Message> {
Ok(parse_file)
}

#[derive(Deserialize, Debug, Clone)]
#[derive(Deserialize, Debug, Clone, Default)]
pub struct RemoteConfig {
pub general: General,
pub update: Update,
Expand All @@ -30,18 +30,18 @@ pub struct RemoteConfig {
pub services_item: Vec<Services>,
}

#[derive(Deserialize, Debug, Clone)]
#[derive(Deserialize, Debug, Clone, Default)]
pub struct Binaries {
pub required_files: Vec<String>,
pub others_files: Vec<String>,
}

#[derive(Deserialize, Debug, Clone)]
#[derive(Deserialize, Debug, Clone, Default)]
pub struct General {
pub version: String,
}

#[derive(Deserialize, Debug, Clone)]
#[derive(Deserialize, Debug, Clone, Default)]
pub struct Init {
pub git_assets: String,
pub ghcup_url: String,
Expand All @@ -62,15 +62,15 @@ pub struct Init {
pub haskell_cabal_version: String,
}

#[derive(Deserialize, Debug, Clone)]
#[derive(Deserialize, Debug, Clone, Default)]
pub struct ConfigFileItem {
pub url: String,
pub name: String,
pub folder_key: String,
pub pattern_sed: String,
}

#[derive(Deserialize, Debug, Clone)]
#[derive(Deserialize, Debug, Clone, Default)]
pub struct Dependencies {
pub macos: Vec<String>,
pub debian: Vec<String>,
Expand All @@ -84,7 +84,7 @@ pub struct Dependencies {
pub rhel_8: Vec<String>,
}

#[derive(Deserialize, Debug, Clone)]
#[derive(Deserialize, Debug, Clone, Default)]
pub struct BuildCardanoNode {
pub cnode_repository: String,
pub cnode_release: String,
Expand All @@ -93,22 +93,21 @@ pub struct BuildCardanoNode {
pub cnode_ported_libsodium_data: String,
}

#[derive(Deserialize, Debug, Clone)]
#[derive(Deserialize, Debug, Clone, Default)]
pub struct StructureFolderItem {
pub key: String,
pub name: String,
pub parent: String,
}

#[derive(Deserialize, Debug, Clone)]
#[derive(Deserialize, Debug, Clone, Default)]
pub struct Update {
pub last_cvm_version: String,
pub version_pattern: String,
pub name_pattern: String,
pub file_name: String,
}

#[derive(Deserialize, Debug, Clone)]
#[derive(Deserialize, Debug, Clone, Default)]
pub struct Services {
pub url: String,
pub file: String,
Expand Down
51 changes: 19 additions & 32 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
extern crate core;

use std::io::stdout;
use crossterm::style::Stylize;
use message::message::{MessageData, Message};
use subcommands::subcommands_impl;
use crate::subcommands::subcommand::Command;
use crate::subcommands::subcommand_strategy::CommandStrategy;
use subcommands::subcommands_impl::init::Init;
use subcommands::subcommands_impl::install::Install;
use subcommands::subcommands_impl::list::List;
use subcommands::subcommands_impl::start::Start;
use subcommands::subcommands_impl::stop::Stop;
use crate::message::message::MessageKind;
use crate::subcommands_impl::clean::Clean;
use crate::subcommands_impl::config::Config;
use crate::subcommands_impl::r#use::Use;
Expand All @@ -18,6 +17,7 @@ use crate::subcommands_impl::update::Update;
use crate::task::task::Success;
use crate::term::term::Term;
use crate::utils::url_build::url_build;
use crate::utils::version_utils::get_last_cvm_version;

mod task;
mod config;
Expand All @@ -31,50 +31,39 @@ mod term;
const VERSION: &str = env!("CARGO_PKG_VERSION");

fn main() {
let config = config::remote_config::get_remote_config();

if let Err(error) = &config {
error.print();
return;
}
let config = config.unwrap();

let mut term = Term { stdout: stdout() };

let _ =show_update_alert(&config.update.last_cvm_version, &VERSION.to_string());
let _ = show_update_alert(VERSION.to_string());

let args = subcommands::commands_config::command_config();

let result = match args.subcommand() {
Some(("init", matches)) => {
Init::start(matches, &config, &mut term)
Init::start(matches)
}
Some(("install", matches)) => {
Install::start(matches, &config, &mut term)
Install::start(matches)
}
Some(("use", matches)) => {
Use::start(matches, &config, &mut term)
Use::start(matches)
}
Some(("remove", matches)) => {
Remove::start(matches, &config, &mut term)
Remove::start(matches)
}
Some(("clean", matches)) => {
Clean::start(matches, &config, &mut term)
Clean::start(matches)
}
Some(("list", matches)) => {
List::start(matches, &config, &mut term)
List::start(matches)
}
Some(("update", matches)) => {
Update::start(matches, &config, &mut term)
Update::start(matches)
}
Some(("start", matches)) => {
Start::start(matches, &config, &mut term)
Start::start(matches)
}
Some(("stop", matches)) => {
Stop::start(matches, &config, &mut term)
Stop::start(matches)
}
Some(("config", matches)) => {
Config::start(matches, &config, &mut term)
Config::start(matches)
}
_ => { error_not_found() }
};
Expand All @@ -96,13 +85,11 @@ fn error_not_found() -> Result<Success, Message> {
}));
}

fn show_update_alert(last_version: &String, current_version: &String) -> Result<Success, Message> {
fn show_update_alert(current_version: String) {
let last_version = get_last_cvm_version().unwrap_or("".to_string());
let last_version = last_version.replace("v", "");
if &last_version > &current_version {
return Err(Message::CommandNotFound(MessageData {
message: format!("{} {} => {}", "New update available", &current_version, &last_version),
kind: MessageKind::Info,
..Default::default()
}));
print!("{}\n {}\n", format!("{} {} => {}", "New update available".yellow(), &current_version.blue(),
&last_version.yellow()), "To actualize run [cvm update]".green());
};
Ok(Success{})
}
2 changes: 1 addition & 1 deletion src/subcommands/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
pub mod commands_config;
pub mod subcommand;
pub mod subcommand_strategy;
pub mod subcommands_impl;
9 changes: 0 additions & 9 deletions src/subcommands/subcommand.rs

This file was deleted.

8 changes: 8 additions & 0 deletions src/subcommands/subcommand_strategy.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#![allow(dead_code, unused_variables)]

use clap::ArgMatches;
use crate::{Message, Success};

pub trait CommandStrategy {
fn start(command: &ArgMatches) -> Result<Success, Message>;
}
13 changes: 8 additions & 5 deletions src/subcommands/subcommands_impl/clean.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
#![allow(dead_code, unused_variables)]

use std::io::stdout;
use clap::{ArgMatches};
use crate::{Command, Message, Success, Term};
use crate::config::remote_config::RemoteConfig;
use crate::{CommandStrategy, config, Message, Success, Term};
use crate::task::task_impl::commons::folder_manager_task::{FolderManagerAction, FolderManagerTask};
use crate::task::task_impl::commons::run_command_task::{Cmd, RunCommandInputData, RunCommandTask};
use crate::task_manager::task_manager::TaskManager;
Expand All @@ -11,8 +11,11 @@ use crate::utils::folders::Folder;

pub struct Clean{}

impl Command for Clean{
fn start(command: &ArgMatches, config: &RemoteConfig, term: &mut Term) -> Result<Success, Message> {
impl CommandStrategy for Clean{
fn start(command: &ArgMatches) -> Result<Success, Message> {

let config = config::remote_config::get_remote_config()?;
let mut term = Term { stdout: stdout() };

let home_dir = Folder::get_home_dir()?;
let mut ghcup_dir = String::from(home_dir);
Expand All @@ -23,7 +26,7 @@ impl Command for Clean{
TaskManager::default().start(vec![
Box::new(RunCommandTask { input_data: build_cabal_clean_command(ghcup_dir), command_description: "Cleaning cabal cache, package and build temporal files".to_string() }),
Box::new(FolderManagerTask { input_data: FolderManagerAction::Clean(vec![git_folder]) }),
], config, term, L1)
], &config, &mut term, L1)
}
}

Expand Down
15 changes: 10 additions & 5 deletions src/subcommands/subcommands_impl/config.rs
Original file line number Diff line number Diff line change
@@ -1,27 +1,32 @@
#![allow(dead_code, unused_variables)]

use std::io::stdout;
use clap::ArgMatches;
use crate::subcommands::subcommand::Command;
use crate::subcommands::subcommand_strategy::CommandStrategy;
use crate::subcommands::commands_config::Args;
use crate::config::remote_config::RemoteConfig;
use crate::message::message::Message;
use crate::task::task::Success;
use crate::task_manager::task_manager::TaskManager;
use crate::Term;
use crate::{config, Term};
use crate::task::task_impl::config::update_config_files_task::UpdateConfigFilesTask;
use crate::term::log_level::LogLevel::L1;


pub struct Config {}

impl Command for Config {
fn start<'a>(command: &'a ArgMatches, config: &RemoteConfig, term: &mut Term) -> Result<Success, Message> {
impl CommandStrategy for Config {
fn start(command: &ArgMatches) -> Result<Success, Message> {

let config = config::remote_config::get_remote_config()?;
let mut term = Term { stdout: stdout() };

let default_value = "".to_string();

match command.subcommand() {
Some(("update", matches)) => {
let force_arg = matches.contains_id(Args::FORCE._to_string());
update_config(force_arg, config, term)
update_config(force_arg, &config, &mut term)
}
_ => { Ok(Success {}) }
}
Expand Down
15 changes: 9 additions & 6 deletions src/subcommands/subcommands_impl/init.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
#![allow(dead_code, unused_variables)]

use std::io::stdout;
use clap::ArgMatches;
use crate::subcommands::subcommand::Command;
use crate::subcommands::subcommand_strategy::CommandStrategy;
use crate::subcommands::commands_config::Args;
use crate::config::remote_config::RemoteConfig;
use crate::config::state_config::{reset_init, set_init_network, set_init_success};
use crate::message::message::Message;
use crate::task::task::Success;
Expand All @@ -14,7 +14,7 @@ use crate::task::task_impl::init::install_dependences_task::InstallDependenciesT
use crate::task::task_impl::init::install_ghcup_task::InstallHanskellGhcTask;
use crate::task::task_impl::init::install_libsecp256k1_task::Installlibsecp256k1Task;
use crate::task_manager::task_manager::TaskManager;
use crate::Term;
use crate::{config, Term};
use crate::term::log_level::LogLevel::L1;
use crate::utils::folders::Folder;

Expand All @@ -23,8 +23,11 @@ const TESTNET: &str = "testnet";

pub struct Init{}

impl Command for Init {
fn start<'a>(command: &'a ArgMatches, config: &RemoteConfig, term: &mut Term) -> Result<Success, Message> {
impl CommandStrategy for Init {
fn start(command: &ArgMatches) -> Result<Success, Message> {

let config = config::remote_config::get_remote_config()?;
let mut term = Term { stdout: stdout() };

let mut network = MAINNET;

Expand All @@ -45,7 +48,7 @@ impl Command for Init {
Box::new(CreateFolderStructure::default()),
Box::new(Installlibsecp256k1Task::default()),
Box::new(DownloadConfigFilesTask { network: network.to_string() }),
], config, term, L1)?;
], &config, &mut term, L1)?;

set_init_network(network.to_string())?;
set_init_success(true)
Expand Down
14 changes: 9 additions & 5 deletions src/subcommands/subcommands_impl/install.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
#![allow(dead_code, unused_variables)]

use std::io::stdout;
use std::path::Path;
use clap::ArgMatches;
use crate::subcommands::commands_config::{Args};
use crate::task::task::Success;
use crate::utils::version_utils::{get_last_tag, LATEST, verify_version};
use crate::config::remote_config::RemoteConfig;
use crate::{Message, Command, Term, MessageData, url_build};
use crate::{Message, CommandStrategy, Term, MessageData, url_build, config};
use crate::config::state_config::get_state;
use crate::message::message::MessageKind;
use crate::task::task_impl::commons::folder_manager_task::{FolderManagerAction, FolderManagerTask};
Expand All @@ -18,8 +18,12 @@ use crate::utils::folders::Folder;

pub struct Install {}

impl Command for Install {
fn start(command: &ArgMatches, config: &RemoteConfig, term: &mut Term) -> Result<Success, Message> {
impl CommandStrategy for Install {
fn start(command: &ArgMatches) -> Result<Success, Message> {

let config = config::remote_config::get_remote_config()?;
let mut term = Term { stdout: stdout() };

let version_arg = command.get_one::<String>(Args::VERSION._to_string()).unwrap();
let mut version = verify_version(version_arg.as_str())?.to_string();

Expand Down Expand Up @@ -61,6 +65,6 @@ impl Command for Install {
Box::new(FolderManagerTask { input_data: FolderManagerAction::Create(vec![(bin_folder.clone(), version.clone())]) }),
Box::new(CopyBinTask { input_data: CopyBinInputData { files_names: config.binaries.required_files.clone(),
origin_path: cardano_folder.clone(), version: version.clone(), bin_folder: bin_folder.clone(), version_folder: version_folder.clone() } }),
], config, term, L1)
], &config, &mut term, L1)
}
}
Loading

0 comments on commit 675928b

Please sign in to comment.