From 95d399674d8d5c610aa4dd4a2cc30be9267f1b7f Mon Sep 17 00:00:00 2001 From: abhi3700 Date: Tue, 30 Jan 2024 01:23:26 +0530 Subject: [PATCH 01/20] added boilerplate for 'config' command --- src/commands.rs | 1 + src/commands/config.rs | 53 ++++++++++++++++++++++++++++++++++++++++++ src/main.rs | 33 ++++++++++++++++++++++++++ 3 files changed, 87 insertions(+) create mode 100644 src/commands/config.rs diff --git a/src/commands.rs b/src/commands.rs index 42411cf4..5a57d902 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -1,3 +1,4 @@ +pub(crate) mod config; pub(crate) mod farm; pub(crate) mod info; pub(crate) mod init; diff --git a/src/commands/config.rs b/src/commands/config.rs new file mode 100644 index 00000000..d580cdb5 --- /dev/null +++ b/src/commands/config.rs @@ -0,0 +1,53 @@ +//! Config CLI command of pulsar is about setting the parameters: +//! - chain +//! - farm size +//! - reward address +//! - node directory +//! - farm directory + +use std::path::PathBuf; + +use color_eyre::eyre; +use sp_core::sr25519::Public; +use subspace_sdk::ByteSize; + +use crate::config::{ChainConfig, MIN_FARM_SIZE}; + +// TODO: implement this +pub(crate) async fn config( + chain: ChainConfig, + show: bool, + farm_size: ByteSize, + reward_address: Option, + node_dir: PathBuf, + farm_dir: PathBuf, +) -> eyre::Result<()> { + // ensure `settings.toml`file from the dir (as per OS) & then fetch + // let mut config = toml + + // Handle the `show` subcommand + // match show { + // true => { + + // // Logic to display the current configuration + // } + // // false => { + // // Handle the `farm_size` subcommand + // if farm_size < MIN_FARM_SIZE { + // eyre + // } else { + // // Additional logic for `farm_size` + // // config.farm_size = farm_size + // } + + // // Handle the `reward_address` subcommand + // if let Some(address) = reward_address { + // // Logic for handling the reward address + // } + + // // Handle `node_dir` and `farm_dir` similarly... + // } + // }; + + Ok(()) +} diff --git a/src/main.rs b/src/main.rs index 564c3f5c..83f144ab 100644 --- a/src/main.rs +++ b/src/main.rs @@ -13,18 +13,23 @@ mod utils; mod tests; use std::io::{self, Write}; +use std::path::PathBuf; use clap::{Parser, Subcommand}; use color_eyre::eyre::{Context, Report}; use color_eyre::Help; +use config::ChainConfig; use crossterm::event::{Event, KeyCode}; use crossterm::terminal::{disable_raw_mode, enable_raw_mode}; use crossterm::{cursor, execute}; use owo_colors::OwoColorize; +use sp_core::sr25519::Public; use strum::IntoEnumIterator; use strum_macros::EnumIter; +use subspace_sdk::{node, ByteSize}; use tracing::instrument; +use crate::commands::config::config; use crate::commands::farm::farm; use crate::commands::info::info; use crate::commands::init::init; @@ -75,6 +80,21 @@ enum Commands { and status of initial plotting)")] Info, OpenLogs, + #[command(about = "set the config params: farm-size, reward-address, node-dir, farm-dir")] + Config { + #[arg(short, long, action)] + show: bool, + #[arg(short, long, action)] + chain: ChainConfig, + #[arg(short, long, action)] + farm_size: ByteSize, + #[arg(short, long, action)] + reward_address: Option, + #[arg(short, long, action)] + node_dir: PathBuf, + #[arg(short = 'd', long, action)] + farm_dir: PathBuf, + }, } #[tokio::main] @@ -97,6 +117,11 @@ async fn main() -> Result<(), Report> { Some(Commands::OpenLogs) => { open_log_dir().suggestion(support_message())?; } + Some(Commands::Config { chain, show, farm_size, reward_address, node_dir, farm_dir }) => { + config(chain, show, farm_size, reward_address, node_dir, farm_dir) + .await + .suggestion(support_message())?; + } None => arrow_key_mode().await.suggestion(support_message())?, } @@ -229,6 +254,14 @@ impl std::fmt::Display for Commands { Commands::Info => write!(f, "info"), Commands::Init => write!(f, "init"), Commands::OpenLogs => write!(f, "open logs directory"), + Commands::Config { + chain: _, + show: _, + farm_size: _, + reward_address: _, + node_dir: _, + farm_dir: _, + } => write!(f, "config"), } } } From 4f08f9c2fef5f5afa314758ef059e3d0df80aeeb Mon Sep 17 00:00:00 2001 From: abhi3700 Date: Tue, 30 Jan 2024 20:04:44 +0530 Subject: [PATCH 02/20] Added logic for config function --- src/commands/config.rs | 73 +++++++++++++++++++++++++----------------- src/config.rs | 12 +++++-- src/main.rs | 5 ++- 3 files changed, 54 insertions(+), 36 deletions(-) diff --git a/src/commands/config.rs b/src/commands/config.rs index d580cdb5..a10a5876 100644 --- a/src/commands/config.rs +++ b/src/commands/config.rs @@ -5,49 +5,62 @@ //! - node directory //! - farm directory +use std::fs; use std::path::PathBuf; -use color_eyre::eyre; -use sp_core::sr25519::Public; +use color_eyre::eyre::{self, eyre}; use subspace_sdk::ByteSize; -use crate::config::{ChainConfig, MIN_FARM_SIZE}; +use crate::config::{parse_config, parse_config_path, ChainConfig, Config, MIN_FARM_SIZE}; +use crate::utils::reward_address_parser; // TODO: implement this pub(crate) async fn config( chain: ChainConfig, show: bool, farm_size: ByteSize, - reward_address: Option, + reward_address: String, node_dir: PathBuf, farm_dir: PathBuf, ) -> eyre::Result<()> { - // ensure `settings.toml`file from the dir (as per OS) & then fetch - // let mut config = toml - - // Handle the `show` subcommand - // match show { - // true => { - - // // Logic to display the current configuration - // } - // // false => { - // // Handle the `farm_size` subcommand - // if farm_size < MIN_FARM_SIZE { - // eyre - // } else { - // // Additional logic for `farm_size` - // // config.farm_size = farm_size - // } - - // // Handle the `reward_address` subcommand - // if let Some(address) = reward_address { - // // Logic for handling the reward address - // } - - // // Handle `node_dir` and `farm_dir` similarly... - // } - // }; + // Define the path to your settings.toml file + let config_path = parse_config_path()?; + + // if config file doesn't exist, then throw error + if !config_path.exists() { + return Err(eyre!( + "Config file: \"settings.toml\" not found.\nPlease use `pulsar init` command first." + )); + } + + // Load the current configuration + let mut config: Config = parse_config()?; + + if show { + // Display the current configuration + println!("Current Configuration: \n{:?}", config); + } else { + // Update the configuration based on the provided arguments + if farm_size >= MIN_FARM_SIZE { + config.farmer.farm_size = farm_size; + } else { + return Err(eyre!("Farm size must be ≥ 2 GB")); + } + + let reward_address = reward_address_parser(&reward_address)?; + config.farmer.reward_address = reward_address; + + if node_dir.exists() { + config.node.directory = node_dir; + } + + if farm_dir.exists() { + config.farmer.farm_directory = farm_dir; + } + + // Save the updated configuration back to the file + fs::write(config_path, toml::to_string(&config)?)?; + } Ok(()) } diff --git a/src/config.rs b/src/config.rs index 173399ef..096d0ea4 100644 --- a/src/config.rs +++ b/src/config.rs @@ -189,13 +189,19 @@ pub(crate) fn create_config() -> Result<(File, PathBuf)> { Ok((file, config_path)) } -/// parses the config, and returns [`Config`] +/// parses the config path, and returns [`ConfigPath`] #[instrument] -pub(crate) fn parse_config() -> Result { +pub(crate) fn parse_config_path() -> Result { let config_path = dirs::config_dir().expect("couldn't get the default config directory!"); let config_path = config_path.join("pulsar").join("settings.toml"); - let config: Config = toml::from_str(&std::fs::read_to_string(config_path)?)?; + Ok(config_path) +} + +/// parses the config, and returns [`Config`] +#[instrument] +pub(crate) fn parse_config() -> Result { + let config: Config = toml::from_str(&std::fs::read_to_string(parse_config_path()?)?)?; Ok(config) } diff --git a/src/main.rs b/src/main.rs index 83f144ab..a028a836 100644 --- a/src/main.rs +++ b/src/main.rs @@ -23,10 +23,9 @@ use crossterm::event::{Event, KeyCode}; use crossterm::terminal::{disable_raw_mode, enable_raw_mode}; use crossterm::{cursor, execute}; use owo_colors::OwoColorize; -use sp_core::sr25519::Public; use strum::IntoEnumIterator; use strum_macros::EnumIter; -use subspace_sdk::{node, ByteSize}; +use subspace_sdk::ByteSize; use tracing::instrument; use crate::commands::config::config; @@ -89,7 +88,7 @@ enum Commands { #[arg(short, long, action)] farm_size: ByteSize, #[arg(short, long, action)] - reward_address: Option, + reward_address: String, #[arg(short, long, action)] node_dir: PathBuf, #[arg(short = 'd', long, action)] From 93fed0b41ccd27a8b67a56b1aee4fb61477688b1 Mon Sep 17 00:00:00 2001 From: abhi3700 Date: Wed, 31 Jan 2024 01:18:33 +0530 Subject: [PATCH 03/20] added individual options possibility in config command - wrapped config options with 'Option' type - show config is working fine! - added fn in utils - prettify the config details --- Cargo.lock | 109 +++++++++++++++++++++-------------------- Cargo.toml | 1 + src/commands/config.rs | 95 +++++++++++++++++++++++------------ src/config.rs | 4 +- src/main.rs | 14 +++--- src/utils.rs | 30 +++++++++++- 6 files changed, 158 insertions(+), 95 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index fb99703e..35bf46bd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -75,7 +75,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e01ed3140b2f8d422c68afa1ed2e85d996ea619c988ac834d255db32138655cb" dependencies = [ "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -188,7 +188,7 @@ dependencies = [ "actix-router", "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -847,7 +847,7 @@ checksum = "16e62a023e7c117e27523144c5d2459f4397fcc3cab0085af8e2224f643a0193" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -858,7 +858,7 @@ checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -1606,7 +1606,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -2238,7 +2238,7 @@ checksum = "83fdaf97f4804dcebfa5862639bc9ce4121e82140bec2a987ac5140294865b5b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -2265,7 +2265,7 @@ dependencies = [ "proc-macro2", "quote", "scratch", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -2282,7 +2282,7 @@ checksum = "2fa16a70dd58129e4dfffdff535fb1bce66673f7bbeec4a5a1765a504e1ccd84" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -2592,7 +2592,7 @@ checksum = "487585f4d0c6655fe74905e2504d8ad6908e4db67f744eb140876906c2f3175d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -2633,7 +2633,7 @@ dependencies = [ "proc-macro2", "quote", "regex", - "syn 2.0.39", + "syn 2.0.48", "termcolor", "toml 0.7.8", "walkdir", @@ -3112,7 +3112,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -3371,7 +3371,7 @@ dependencies = [ "fs-err", "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -3926,7 +3926,7 @@ dependencies = [ "proc-macro-warning", "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -3938,7 +3938,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -3948,7 +3948,7 @@ source = "git+https://github.com/subspace/polkadot-sdk?rev=c63a8b28a9fd26d42116b dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -4124,7 +4124,7 @@ checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -6119,7 +6119,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -6513,7 +6513,7 @@ dependencies = [ "macro_magic_core", "macro_magic_macros", "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -6527,7 +6527,7 @@ dependencies = [ "macro_magic_core_macros", "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -6538,7 +6538,7 @@ checksum = "c12469fc165526520dff2807c2975310ab47cf7190a45b99b49a7dc8befab17b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -6549,7 +6549,7 @@ checksum = "b8fb85ec1620619edf2984a7693497d4ec88a9665d8b87e942856884c92dbf2a" dependencies = [ "macro_magic_core", "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -7206,7 +7206,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -7217,7 +7217,7 @@ checksum = "681030a937600a36906c185595136d26abfebb4aa9c65701cefcaf8578bb982b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -7941,7 +7941,7 @@ checksum = "4359fd9c9171ec6e8c62926d6faaf553a8dc3f64e1507e76da7911b4f6a04405" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -8157,14 +8157,14 @@ checksum = "3d1eaa7fa0aa1929ffdf7eeb6eac234dde6268914a14ad44d23521ab6a9b258e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] name = "proc-macro2" -version = "1.0.69" +version = "1.0.78" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "134c189feb4956b20f6f547d2cf727d4c0fe06722b20a0eec87ed445a97f92da" +checksum = "e2422ad645d89c99f8f3e6b88a9fdeca7fabeac836b1002371c4367c8f984aae" dependencies = [ "unicode-ident", ] @@ -8215,7 +8215,7 @@ checksum = "440f724eba9f6996b75d63681b0a92b06947f1457076d503a4d2e2c8f56442b8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -8308,6 +8308,7 @@ dependencies = [ "rand 0.8.5", "serde", "serde_derive", + "serde_json", "single-instance", "sp-core", "strum", @@ -8444,9 +8445,9 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.33" +version = "1.0.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae" +checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef" dependencies = [ "proc-macro2", ] @@ -8646,7 +8647,7 @@ checksum = "7f7473c2cfcf90008193dd0e3e16599455cb601a9fce322b5bb55de799664925" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -9198,7 +9199,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -10021,7 +10022,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -10509,9 +10510,9 @@ checksum = "a3f0bf26fd526d2a95683cd0f87bf103b8539e2ca1ef48ce002d67aad59aa0b4" [[package]] name = "serde" -version = "1.0.188" +version = "1.0.196" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf9e0fcba69a370eed61bcf2b728575f726b50b55cba78064753d708ddc7549e" +checksum = "870026e60fa08c69f064aa766c10f10b1d62db9ccd4d0abb206472bee0ce3b32" dependencies = [ "serde_derive", ] @@ -10527,20 +10528,20 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.188" +version = "1.0.196" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4eca7ac642d82aa35b60049a6eccb4be6be75e599bd2e9adb5f875a737654af2" +checksum = "33c85360c95e7d137454dc81d9a4ed2b8efd8fbe19cee57357b32b9771fccb67" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] name = "serde_json" -version = "1.0.106" +version = "1.0.113" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2cc66a619ed80bf7a0f6b17dd063a84b88f6dea1813737cf469aef1d081142c2" +checksum = "69801b70b1c3dac963ecb03a364ba0ceda9cf60c71cfe475e99864759c8b8a79" dependencies = [ "itoa", "ryu", @@ -10842,7 +10843,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -11056,7 +11057,7 @@ source = "git+https://github.com/subspace/polkadot-sdk?rev=c63a8b28a9fd26d42116b dependencies = [ "quote", "sp-core-hashing", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -11075,7 +11076,7 @@ source = "git+https://github.com/subspace/polkadot-sdk?rev=c63a8b28a9fd26d42116b dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -11362,7 +11363,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -11554,7 +11555,7 @@ dependencies = [ "parity-scale-codec", "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -11713,7 +11714,7 @@ dependencies = [ "proc-macro2", "quote", "rustversion", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -12223,9 +12224,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.39" +version = "2.0.48" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23e78b90f2fcf45d3e842032ce32e3f2d1545ba6636271dcbf24fa306d87be7a" +checksum = "0f3531638e407dfc0814761abb7c00a5b54992b849452a0646b7f65c9f770f3f" dependencies = [ "proc-macro2", "quote", @@ -12339,7 +12340,7 @@ checksum = "266b2e40bc00e5a6c09c3584011e08b06f123c00362c92b975ba9843aaaa14b8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -12480,7 +12481,7 @@ checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -12670,7 +12671,7 @@ source = "git+https://github.com/tokio-rs/tracing?branch=v0.1.x#c6bedbe2725830c1 dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] @@ -13143,7 +13144,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.48", "wasm-bindgen-shared", ] @@ -13177,7 +13178,7 @@ checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.48", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -14204,7 +14205,7 @@ checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.48", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index ca9edf9f..defb043a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -25,6 +25,7 @@ owo-colors = "3.5.0" rand = "0.8.5" serde = "1" serde_derive = "1" +serde_json = "1.0.113" single-instance = "0.3.3" sp-core = { version = "21.0.0", git = "https://github.com/subspace/polkadot-sdk", rev = "c63a8b28a9fd26d42116b0dcef1f2a5cefb9cd1c", features = ["full_crypto"] } strum = "0.24.1" diff --git a/src/commands/config.rs b/src/commands/config.rs index a10a5876..854beabd 100644 --- a/src/commands/config.rs +++ b/src/commands/config.rs @@ -6,56 +6,91 @@ //! - farm directory use std::fs; -use std::path::PathBuf; -use color_eyre::eyre::{self, eyre}; -use subspace_sdk::ByteSize; +use color_eyre::eyre::{self, bail}; use crate::config::{parse_config, parse_config_path, ChainConfig, Config, MIN_FARM_SIZE}; -use crate::utils::reward_address_parser; +use crate::utils::{create_and_move_data, dir_parser, reward_address_parser, size_parser}; // TODO: implement this pub(crate) async fn config( - chain: ChainConfig, show: bool, - farm_size: ByteSize, - reward_address: String, - node_dir: PathBuf, - farm_dir: PathBuf, + chain: Option, + farm_size: Option, + reward_address: Option, + node_dir: Option, + farm_dir: Option, ) -> eyre::Result<()> { // Define the path to your settings.toml file let config_path = parse_config_path()?; // if config file doesn't exist, then throw error if !config_path.exists() { - return Err(eyre!( - "Config file: \"settings.toml\" not found.\nPlease use `pulsar init` command first." - )); + bail!("Config file: \"settings.toml\" not found.\nPlease use `pulsar init` command first."); } // Load the current configuration let mut config: Config = parse_config()?; if show { - // Display the current configuration - println!("Current Configuration: \n{:?}", config); + // Display the current configuration as JSON + // Serialize `config` to a pretty-printed JSON string + let serialized = serde_json::to_string_pretty(&config)?; + println!( + "Current Config set as: \n{}\n in file: {:?}", + serialized, + config_path.to_str().expect("Expected stringified config path") + ); } else { - // Update the configuration based on the provided arguments - if farm_size >= MIN_FARM_SIZE { - config.farmer.farm_size = farm_size; - } else { - return Err(eyre!("Farm size must be ≥ 2 GB")); - } - - let reward_address = reward_address_parser(&reward_address)?; - config.farmer.reward_address = reward_address; - - if node_dir.exists() { - config.node.directory = node_dir; - } - - if farm_dir.exists() { - config.farmer.farm_directory = farm_dir; + match chain { + Some(c) => { + // TODO: update (optional) the chain + } + None => match farm_size { + Some(f) => { + // update (optional) the farm size + let farm_size = size_parser(&f)?; + // if let Ok(farm_size) = size_parser(&farm_size.unwrap()) {} + if farm_size >= MIN_FARM_SIZE { + config.farmer.farm_size = farm_size; + } else { + bail!("Farm size must be ≥ 2 GB"); + } + } + None => match reward_address { + Some(r) => { + // update (optional) the reward address + let reward_address = reward_address_parser(&r)?; + config.farmer.reward_address = reward_address; + } + None => match node_dir { + Some(n) => { + // update (optional) the node directory + let node_dir = dir_parser(&n).expect("Invalid node directory"); + create_and_move_data(config.node.directory.clone(), node_dir.clone()) + .expect("Error in setting new node directory."); + config.node.directory = node_dir; + } + None => match farm_dir { + Some(fd) => { + // update (optional) the farm directory + let farm_dir = dir_parser(&fd).expect("Invalid farm directory"); + create_and_move_data( + config.farmer.farm_directory.clone(), + farm_dir.clone(), + ) + .expect("Error in setting new farm directory."); + if farm_dir.exists() { + config.farmer.farm_directory = farm_dir; + } + } + None => bail!( + "At least one option has to be provided.\nTry `pulsar config -h`" + ), + }, + }, + }, + }, } // Save the updated configuration back to the file diff --git a/src/config.rs b/src/config.rs index 096d0ea4..b103e35e 100644 --- a/src/config.rs +++ b/src/config.rs @@ -2,7 +2,7 @@ use std::fs::{create_dir_all, remove_file, File}; use std::num::NonZeroU8; use std::path::PathBuf; -use color_eyre::eyre::{eyre, Report, Result, WrapErr}; +use color_eyre::eyre::{bail, eyre, Report, Result, WrapErr}; use derivative::Derivative; use serde::{Deserialize, Serialize}; use strum_macros::EnumIter; @@ -212,7 +212,7 @@ pub(crate) fn validate_config() -> Result { // validity checks if config.farmer.farm_size < MIN_FARM_SIZE { - return Err(eyre!("farm size should be bigger than {MIN_FARM_SIZE}!")); + bail!("farm size should be bigger than {MIN_FARM_SIZE}!"); } Ok(config) diff --git a/src/main.rs b/src/main.rs index a028a836..797f1d58 100644 --- a/src/main.rs +++ b/src/main.rs @@ -13,7 +13,6 @@ mod utils; mod tests; use std::io::{self, Write}; -use std::path::PathBuf; use clap::{Parser, Subcommand}; use color_eyre::eyre::{Context, Report}; @@ -25,7 +24,6 @@ use crossterm::{cursor, execute}; use owo_colors::OwoColorize; use strum::IntoEnumIterator; use strum_macros::EnumIter; -use subspace_sdk::ByteSize; use tracing::instrument; use crate::commands::config::config; @@ -84,15 +82,15 @@ enum Commands { #[arg(short, long, action)] show: bool, #[arg(short, long, action)] - chain: ChainConfig, + chain: Option, #[arg(short, long, action)] - farm_size: ByteSize, + farm_size: Option, #[arg(short, long, action)] - reward_address: String, + reward_address: Option, #[arg(short, long, action)] - node_dir: PathBuf, + node_dir: Option, #[arg(short = 'd', long, action)] - farm_dir: PathBuf, + farm_dir: Option, }, } @@ -117,7 +115,7 @@ async fn main() -> Result<(), Report> { open_log_dir().suggestion(support_message())?; } Some(Commands::Config { chain, show, farm_size, reward_address, node_dir, farm_dir }) => { - config(chain, show, farm_size, reward_address, node_dir, farm_dir) + config(show, chain, farm_size, reward_address, node_dir, farm_dir) .await .suggestion(support_message())?; } diff --git a/src/utils.rs b/src/utils.rs index 6cef31bc..74b0d7c6 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -1,5 +1,5 @@ use std::env; -use std::fs::create_dir_all; +use std::fs::{self, create_dir_all, rename}; use std::path::{Path, PathBuf}; use std::str::FromStr; @@ -388,3 +388,31 @@ impl<'de> Deserialize<'de> for Rewards { Ok(Rewards(value)) } } + +// move data from old directory to new directory +pub(crate) fn create_and_move_data(old_dir: PathBuf, new_dir: PathBuf) -> Result<()> { + // create the directory if doesn't exist + if !new_dir.exists() { + fs::create_dir_all(&new_dir)?; + } + + // get the folder content + let mut entries = fs::read_dir(&old_dir)?; + + // move if there is any content + if entries.next().is_some() { + for entry in entries { + let entry = entry?; + let file_name = entry.file_name(); + rename(entry.path(), new_dir.join(file_name))?; + } + } + + Ok(()) +} + +pub(crate) fn dir_parser(path: &str) -> Result { + let dir = PathBuf::from(path); + + Ok(dir) +} From 15c4f9e9b7f97dacf310b7be916f8bf8e839e63c Mon Sep 17 00:00:00 2001 From: abhi3700 Date: Wed, 31 Jan 2024 01:21:28 +0530 Subject: [PATCH 04/20] replaced bail w println because of better CLI interface that doesn not show debug info --- src/commands/config.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/commands/config.rs b/src/commands/config.rs index 854beabd..e5282914 100644 --- a/src/commands/config.rs +++ b/src/commands/config.rs @@ -84,9 +84,13 @@ pub(crate) async fn config( config.farmer.farm_directory = farm_dir; } } - None => bail!( - "At least one option has to be provided.\nTry `pulsar config -h`" - ), + None => { + println!( + "At least one option has to be provided.\nTry `pulsar config \ + -h`" + ); + return Ok(()); + } }, }, }, From 313b7bfa6a6ed55f1f0152b166c1d479e664d848 Mon Sep 17 00:00:00 2001 From: abhi3700 Date: Wed, 31 Jan 2024 01:34:09 +0530 Subject: [PATCH 05/20] changed the logic from 'set one param only' to 'either or all params' --- src/commands/config.rs | 104 ++++++++++++++++++++--------------------- 1 file changed, 51 insertions(+), 53 deletions(-) diff --git a/src/commands/config.rs b/src/commands/config.rs index e5282914..69d46e8f 100644 --- a/src/commands/config.rs +++ b/src/commands/config.rs @@ -1,9 +1,12 @@ -//! Config CLI command of pulsar is about setting the parameters: +//! Config CLI command of pulsar is about setting either or all of the +//! parameters: //! - chain //! - farm size //! - reward address //! - node directory //! - farm directory +//! +//! and showing the set config details. use std::fs; @@ -42,59 +45,54 @@ pub(crate) async fn config( config_path.to_str().expect("Expected stringified config path") ); } else { - match chain { - Some(c) => { - // TODO: update (optional) the chain + // no options provided + if chain.is_none() + && farm_size.is_none() + && reward_address.is_none() + && node_dir.is_none() + && farm_dir.is_none() + { + println!("At least one option has to be provided.\nTry `pulsar config -h`"); + return Ok(()); + } + + if let Some(_c) = chain { + // TODO: update (optional) the chain + } + + if let Some(ref f) = farm_size { + // update (optional) the farm size + let farm_size = size_parser(&f)?; + // if let Ok(farm_size) = size_parser(&farm_size.unwrap()) {} + if farm_size >= MIN_FARM_SIZE { + config.farmer.farm_size = farm_size; + } else { + bail!("Farm size must be ≥ 2 GB"); + } + } + + if let Some(ref r) = reward_address { + // update (optional) the reward address + let reward_address = reward_address_parser(&r)?; + config.farmer.reward_address = reward_address; + } + + if let Some(ref n) = node_dir { + // update (optional) the node directory + let node_dir = dir_parser(&n).expect("Invalid node directory"); + create_and_move_data(config.node.directory.clone(), node_dir.clone()) + .expect("Error in setting new node directory."); + config.node.directory = node_dir; + } + + if let Some(ref fd) = farm_dir { + // update (optional) the farm directory + let farm_dir = dir_parser(&fd).expect("Invalid farm directory"); + create_and_move_data(config.farmer.farm_directory.clone(), farm_dir.clone()) + .expect("Error in setting new farm directory."); + if farm_dir.exists() { + config.farmer.farm_directory = farm_dir; } - None => match farm_size { - Some(f) => { - // update (optional) the farm size - let farm_size = size_parser(&f)?; - // if let Ok(farm_size) = size_parser(&farm_size.unwrap()) {} - if farm_size >= MIN_FARM_SIZE { - config.farmer.farm_size = farm_size; - } else { - bail!("Farm size must be ≥ 2 GB"); - } - } - None => match reward_address { - Some(r) => { - // update (optional) the reward address - let reward_address = reward_address_parser(&r)?; - config.farmer.reward_address = reward_address; - } - None => match node_dir { - Some(n) => { - // update (optional) the node directory - let node_dir = dir_parser(&n).expect("Invalid node directory"); - create_and_move_data(config.node.directory.clone(), node_dir.clone()) - .expect("Error in setting new node directory."); - config.node.directory = node_dir; - } - None => match farm_dir { - Some(fd) => { - // update (optional) the farm directory - let farm_dir = dir_parser(&fd).expect("Invalid farm directory"); - create_and_move_data( - config.farmer.farm_directory.clone(), - farm_dir.clone(), - ) - .expect("Error in setting new farm directory."); - if farm_dir.exists() { - config.farmer.farm_directory = farm_dir; - } - } - None => { - println!( - "At least one option has to be provided.\nTry `pulsar config \ - -h`" - ); - return Ok(()); - } - }, - }, - }, - }, } // Save the updated configuration back to the file From 7f558ef5062a45562a0abe29ebcb57d43f8d9c01 Mon Sep 17 00:00:00 2001 From: abhi3700 Date: Wed, 31 Jan 2024 18:40:59 +0530 Subject: [PATCH 06/20] config command modified - removed redundant check for MIN_FARM_SIZE - added config command in arrow_key_mode - added usages except node, farm directory --- src/commands/config.rs | 81 +++++++++++++++++++++++++++++++++--------- src/commands/wipe.rs | 2 +- src/main.rs | 8 +++-- src/utils.rs | 9 ++++- 4 files changed, 78 insertions(+), 22 deletions(-) diff --git a/src/commands/config.rs b/src/commands/config.rs index 69d46e8f..e93a44a4 100644 --- a/src/commands/config.rs +++ b/src/commands/config.rs @@ -7,18 +7,64 @@ //! - farm directory //! //! and showing the set config details. +//! +//! ## Usage +//! +//! ### Show +//! ``` +//! $ pulsar config -s +//! Current Config set as: +//! { +//! "chain": "Gemini3g", +//! "farmer": { +//! "reward_address": "06fef8efdd808a95500e5baee2bcde4cf8d5e1191b2b3f93065f10f0e4648c09", +//! "farm_directory": "/Users/abhi3700/Library/Application Support/pulsar/farms", +//! "farm_size": "3.0 GB" +//! }, +//! "node": { +//! "directory": "/Users/abhi3700/Library/Application Support/pulsar/node", +//! "name": "abhi3700" +//! } +//! } +//! in file: "/Users/abhi3700/Library/Application Support/pulsar/settings.toml" +//! ``` +//! +//! ### Chain +//! ``` +//! $ pulsar config -c devnet +//! ``` +//! +//! ### Farm size +//! ``` +//! $ pulsar config -f 3GB +//! ``` +//! +//! ### Reward address +//! +//! ``` +//! $ pulsar config -r 5CDstQSbxPrPAaRTuVR2n9PHuhGYnnQvXdbJSQmodD5i16x2 +//! ``` +//! +//! ### Node directory +//! TODO: add usage +//! +//! ### Farm directory +//! TODO: add usage use std::fs; use color_eyre::eyre::{self, bail}; -use crate::config::{parse_config, parse_config_path, ChainConfig, Config, MIN_FARM_SIZE}; -use crate::utils::{create_and_move_data, dir_parser, reward_address_parser, size_parser}; +use crate::commands::wipe::wipe; +use crate::config::{parse_config, parse_config_path, Config}; +use crate::utils::{ + chain_parser, create_and_move_data, dir_parser, reward_address_parser, size_parser, +}; -// TODO: implement this +// function for config cli command pub(crate) async fn config( show: bool, - chain: Option, + chain: Option, farm_size: Option, reward_address: Option, node_dir: Option, @@ -40,7 +86,7 @@ pub(crate) async fn config( // Serialize `config` to a pretty-printed JSON string let serialized = serde_json::to_string_pretty(&config)?; println!( - "Current Config set as: \n{}\n in file: {:?}", + "Current Config set as: \n{}\nin file: {:?}", serialized, config_path.to_str().expect("Expected stringified config path") ); @@ -56,37 +102,37 @@ pub(crate) async fn config( return Ok(()); } - if let Some(_c) = chain { - // TODO: update (optional) the chain + // update (optional) the chain + if let Some(c) = chain { + config.chain = chain_parser(&c)?; + println!("Chain updated as {:?}", c); + + // wipe everything (farmer, node, summary) except config file + wipe(true, true, true, false).await.expect("Error while wiping."); } + // update (optional) the farm size if let Some(ref f) = farm_size { - // update (optional) the farm size let farm_size = size_parser(&f)?; - // if let Ok(farm_size) = size_parser(&farm_size.unwrap()) {} - if farm_size >= MIN_FARM_SIZE { - config.farmer.farm_size = farm_size; - } else { - bail!("Farm size must be ≥ 2 GB"); - } + config.farmer.farm_size = farm_size; } + // update (optional) the reward address if let Some(ref r) = reward_address { - // update (optional) the reward address let reward_address = reward_address_parser(&r)?; config.farmer.reward_address = reward_address; } + // update (optional) the node directory if let Some(ref n) = node_dir { - // update (optional) the node directory let node_dir = dir_parser(&n).expect("Invalid node directory"); create_and_move_data(config.node.directory.clone(), node_dir.clone()) .expect("Error in setting new node directory."); config.node.directory = node_dir; } + // update (optional) the farm directory if let Some(ref fd) = farm_dir { - // update (optional) the farm directory let farm_dir = dir_parser(&fd).expect("Invalid farm directory"); create_and_move_data(config.farmer.farm_directory.clone(), farm_dir.clone()) .expect("Error in setting new farm directory."); @@ -96,6 +142,7 @@ pub(crate) async fn config( } // Save the updated configuration back to the file + // FIXME: might be needed to use `to_string_pretty` fs::write(config_path, toml::to_string(&config)?)?; } diff --git a/src/commands/wipe.rs b/src/commands/wipe.rs index 2282a751..2908b5c5 100644 --- a/src/commands/wipe.rs +++ b/src/commands/wipe.rs @@ -42,7 +42,7 @@ pub(crate) async fn wipe_config(farmer: bool, node: bool) -> Result<()> { /// implementation of the `wipe` command /// /// can wipe farmer, node, summary and farm -async fn wipe( +pub(crate) async fn wipe( wipe_farmer: bool, wipe_node: bool, wipe_summary: bool, diff --git a/src/main.rs b/src/main.rs index 797f1d58..8f051072 100644 --- a/src/main.rs +++ b/src/main.rs @@ -17,7 +17,6 @@ use std::io::{self, Write}; use clap::{Parser, Subcommand}; use color_eyre::eyre::{Context, Report}; use color_eyre::Help; -use config::ChainConfig; use crossterm::event::{Event, KeyCode}; use crossterm::terminal::{disable_raw_mode, enable_raw_mode}; use crossterm::{cursor, execute}; @@ -82,7 +81,7 @@ enum Commands { #[arg(short, long, action)] show: bool, #[arg(short, long, action)] - chain: Option, + chain: Option, #[arg(short, long, action)] farm_size: Option, #[arg(short, long, action)] @@ -205,6 +204,9 @@ async fn arrow_key_mode() -> Result<(), Report> { info().await.suggestion(support_message())?; } 4 => { + config(true, None, None, None, None, None).await.suggestion(support_message())?; + } + 5 => { open_log_dir().suggestion(support_message())?; } _ => { @@ -252,8 +254,8 @@ impl std::fmt::Display for Commands { Commands::Init => write!(f, "init"), Commands::OpenLogs => write!(f, "open logs directory"), Commands::Config { - chain: _, show: _, + chain: _, farm_size: _, reward_address: _, node_dir: _, diff --git a/src/utils.rs b/src/utils.rs index 74b0d7c6..0d7448d9 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -7,6 +7,7 @@ use color_eyre::eyre::{eyre, Context, Result}; use futures::prelude::*; use owo_colors::OwoColorize; use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use strum::IntoEnumIterator; use subspace_sdk::{ByteSize, PublicKey}; use tracing::level_filters::LevelFilter; use tracing_appender::rolling::{RollingFileAppender, Rotation}; @@ -16,7 +17,7 @@ use tracing_subscriber::fmt::format::FmtSpan; use tracing_subscriber::prelude::*; use tracing_subscriber::{fmt, EnvFilter, Layer}; -use crate::config::MIN_FARM_SIZE; +use crate::config::{ChainConfig, MIN_FARM_SIZE}; use crate::summary::Rewards; /// for how long a log file should be valid @@ -416,3 +417,9 @@ pub(crate) fn dir_parser(path: &str) -> Result { Ok(dir) } + +pub(crate) fn chain_parser(c: &str) -> Result { + let valid_chain = ChainConfig::from_str(c)?; + + Ok(valid_chain) +} From b56e71a0dbbd431dcd13c0c4e697cc02de7bf100 Mon Sep 17 00:00:00 2001 From: abhi3700 Date: Wed, 31 Jan 2024 19:13:44 +0530 Subject: [PATCH 07/20] Refactor utils and correct command order in interactive mode - removed small fn from utils & used the code directly into placeholders - corrected the order of commands in interactive mode --- src/commands/config.rs | 15 +++++++-------- src/main.rs | 12 ++++++------ src/utils.rs | 15 +-------------- 3 files changed, 14 insertions(+), 28 deletions(-) diff --git a/src/commands/config.rs b/src/commands/config.rs index e93a44a4..80f481d9 100644 --- a/src/commands/config.rs +++ b/src/commands/config.rs @@ -52,14 +52,14 @@ //! TODO: add usage use std::fs; +use std::path::PathBuf; +use std::str::FromStr; use color_eyre::eyre::{self, bail}; use crate::commands::wipe::wipe; -use crate::config::{parse_config, parse_config_path, Config}; -use crate::utils::{ - chain_parser, create_and_move_data, dir_parser, reward_address_parser, size_parser, -}; +use crate::config::{parse_config, parse_config_path, ChainConfig, Config}; +use crate::utils::{create_and_move_data, reward_address_parser, size_parser}; // function for config cli command pub(crate) async fn config( @@ -104,7 +104,7 @@ pub(crate) async fn config( // update (optional) the chain if let Some(c) = chain { - config.chain = chain_parser(&c)?; + config.chain = ChainConfig::from_str(&c)?; println!("Chain updated as {:?}", c); // wipe everything (farmer, node, summary) except config file @@ -125,7 +125,7 @@ pub(crate) async fn config( // update (optional) the node directory if let Some(ref n) = node_dir { - let node_dir = dir_parser(&n).expect("Invalid node directory"); + let node_dir = PathBuf::from_str(&n).expect("Invalid node directory"); create_and_move_data(config.node.directory.clone(), node_dir.clone()) .expect("Error in setting new node directory."); config.node.directory = node_dir; @@ -133,7 +133,7 @@ pub(crate) async fn config( // update (optional) the farm directory if let Some(ref fd) = farm_dir { - let farm_dir = dir_parser(&fd).expect("Invalid farm directory"); + let farm_dir = PathBuf::from_str(&fd).expect("Invalid farm directory"); create_and_move_data(config.farmer.farm_directory.clone(), farm_dir.clone()) .expect("Error in setting new farm directory."); if farm_dir.exists() { @@ -142,7 +142,6 @@ pub(crate) async fn config( } // Save the updated configuration back to the file - // FIXME: might be needed to use `to_string_pretty` fs::write(config_path, toml::to_string(&config)?)?; } diff --git a/src/main.rs b/src/main.rs index 8f051072..485136d9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -75,7 +75,6 @@ enum Commands { #[command(about = "displays info about the farmer instance (i.e. total amount of rewards, \ and status of initial plotting)")] Info, - OpenLogs, #[command(about = "set the config params: farm-size, reward-address, node-dir, farm-dir")] Config { #[arg(short, long, action)] @@ -91,6 +90,7 @@ enum Commands { #[arg(short = 'd', long, action)] farm_dir: Option, }, + OpenLogs, } #[tokio::main] @@ -110,14 +110,14 @@ async fn main() -> Result<(), Report> { Some(Commands::Wipe { farmer, node }) => { wipe_config(farmer, node).await.suggestion(support_message())?; } - Some(Commands::OpenLogs) => { - open_log_dir().suggestion(support_message())?; - } Some(Commands::Config { chain, show, farm_size, reward_address, node_dir, farm_dir }) => { config(show, chain, farm_size, reward_address, node_dir, farm_dir) .await .suggestion(support_message())?; } + Some(Commands::OpenLogs) => { + open_log_dir().suggestion(support_message())?; + } None => arrow_key_mode().await.suggestion(support_message())?, } @@ -210,7 +210,7 @@ async fn arrow_key_mode() -> Result<(), Report> { open_log_dir().suggestion(support_message())?; } _ => { - unreachable!("this number must stay in [0-4]") + unreachable!("this number must stay in [0-5]") } } @@ -252,7 +252,6 @@ impl std::fmt::Display for Commands { Commands::Wipe { farmer: _, node: _ } => write!(f, "wipe"), Commands::Info => write!(f, "info"), Commands::Init => write!(f, "init"), - Commands::OpenLogs => write!(f, "open logs directory"), Commands::Config { show: _, chain: _, @@ -261,6 +260,7 @@ impl std::fmt::Display for Commands { node_dir: _, farm_dir: _, } => write!(f, "config"), + Commands::OpenLogs => write!(f, "open logs directory"), } } } diff --git a/src/utils.rs b/src/utils.rs index 0d7448d9..c94b83d7 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -7,7 +7,6 @@ use color_eyre::eyre::{eyre, Context, Result}; use futures::prelude::*; use owo_colors::OwoColorize; use serde::{Deserialize, Deserializer, Serialize, Serializer}; -use strum::IntoEnumIterator; use subspace_sdk::{ByteSize, PublicKey}; use tracing::level_filters::LevelFilter; use tracing_appender::rolling::{RollingFileAppender, Rotation}; @@ -17,7 +16,7 @@ use tracing_subscriber::fmt::format::FmtSpan; use tracing_subscriber::prelude::*; use tracing_subscriber::{fmt, EnvFilter, Layer}; -use crate::config::{ChainConfig, MIN_FARM_SIZE}; +use crate::config::MIN_FARM_SIZE; use crate::summary::Rewards; /// for how long a log file should be valid @@ -411,15 +410,3 @@ pub(crate) fn create_and_move_data(old_dir: PathBuf, new_dir: PathBuf) -> Result Ok(()) } - -pub(crate) fn dir_parser(path: &str) -> Result { - let dir = PathBuf::from(path); - - Ok(dir) -} - -pub(crate) fn chain_parser(c: &str) -> Result { - let valid_chain = ChainConfig::from_str(c)?; - - Ok(valid_chain) -} From b9f9bcb5a8e6552f3d8cfe356772f7c52ab2fc34 Mon Sep 17 00:00:00 2001 From: abhi3700 Date: Wed, 31 Jan 2024 23:33:10 +0530 Subject: [PATCH 08/20] Manual testing of create_or_move_data fn, doc update for parameters - thorough manual testing of `create_or_move_data` fn was done - added usage for `node-dir` & `farm-dir` params & all params at a time. --- src/commands/config.rs | 26 +++++++++++++++++++------- src/main.rs | 4 +++- src/utils.rs | 34 +++++++++++++++++++++++----------- 3 files changed, 45 insertions(+), 19 deletions(-) diff --git a/src/commands/config.rs b/src/commands/config.rs index 80f481d9..979513d3 100644 --- a/src/commands/config.rs +++ b/src/commands/config.rs @@ -46,10 +46,24 @@ //! ``` //! //! ### Node directory -//! TODO: add usage +//! ``` +//! $ pulsar config -n "/Users/abhi3700/test/pulsar1/node" +//! ``` //! //! ### Farm directory -//! TODO: add usage +//! ``` +//! $ pulsar config -d "/Users/abhi3700/test/pulsar1/farms" +//! ``` +//! +//! ### All params +//! ``` +//! $ pulsar config \ +//! --chain devnet \ +//! --farm-size 5GB \ +//! --reward-address 5DXRtoHJePQBEk44onMy5yG4T8CjpPaK4qKNmrwpxqxZALGY \ +//! --node-directory "/Users/abhi3700/test/pulsar1/node" \ +//! --farm-directory "/Users/abhi3700/test/pulsar1/farms" +//! ``` use std::fs; use std::path::PathBuf; @@ -59,7 +73,7 @@ use color_eyre::eyre::{self, bail}; use crate::commands::wipe::wipe; use crate::config::{parse_config, parse_config_path, ChainConfig, Config}; -use crate::utils::{create_and_move_data, reward_address_parser, size_parser}; +use crate::utils::{create_or_move_data, reward_address_parser, size_parser}; // function for config cli command pub(crate) async fn config( @@ -126,16 +140,14 @@ pub(crate) async fn config( // update (optional) the node directory if let Some(ref n) = node_dir { let node_dir = PathBuf::from_str(&n).expect("Invalid node directory"); - create_and_move_data(config.node.directory.clone(), node_dir.clone()) - .expect("Error in setting new node directory."); + create_or_move_data(config.node.directory.clone(), node_dir.clone())?; config.node.directory = node_dir; } // update (optional) the farm directory if let Some(ref fd) = farm_dir { let farm_dir = PathBuf::from_str(&fd).expect("Invalid farm directory"); - create_and_move_data(config.farmer.farm_directory.clone(), farm_dir.clone()) - .expect("Error in setting new farm directory."); + create_or_move_data(config.farmer.farm_directory.clone(), farm_dir.clone())?; if farm_dir.exists() { config.farmer.farm_directory = farm_dir; } diff --git a/src/main.rs b/src/main.rs index 485136d9..2266af53 100644 --- a/src/main.rs +++ b/src/main.rs @@ -75,7 +75,9 @@ enum Commands { #[command(about = "displays info about the farmer instance (i.e. total amount of rewards, \ and status of initial plotting)")] Info, - #[command(about = "set the config params: farm-size, reward-address, node-dir, farm-dir")] + #[command( + about = "set the config params: chain, farm-size, reward-address, node-dir, farm-dir" + )] Config { #[arg(short, long, action)] show: bool, diff --git a/src/utils.rs b/src/utils.rs index c94b83d7..94e38148 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -1,9 +1,9 @@ use std::env; -use std::fs::{self, create_dir_all, rename}; +use std::fs::{self, create_dir_all}; use std::path::{Path, PathBuf}; use std::str::FromStr; -use color_eyre::eyre::{eyre, Context, Result}; +use color_eyre::eyre::{bail, eyre, Context, Result}; use futures::prelude::*; use owo_colors::OwoColorize; use serde::{Deserialize, Deserializer, Serialize, Serializer}; @@ -389,22 +389,34 @@ impl<'de> Deserialize<'de> for Rewards { } } -// move data from old directory to new directory -pub(crate) fn create_and_move_data(old_dir: PathBuf, new_dir: PathBuf) -> Result<()> { - // create the directory if doesn't exist +/// move data from old directory (if any) to new directory, or else just create +/// the new directory. +pub(crate) fn create_or_move_data(old_dir: PathBuf, new_dir: PathBuf) -> Result<()> { + if old_dir == new_dir { + bail!("This directory is already set"); + } + + if !new_dir.starts_with("/") { + bail!("New directory path must start with /"); + } + + // Create the new directory if it doesn't exist if !new_dir.exists() { fs::create_dir_all(&new_dir)?; } - // get the folder content - let mut entries = fs::read_dir(&old_dir)?; - - // move if there is any content - if entries.next().is_some() { + // Move contents if the old directory exists + if old_dir.exists() { + let entries = fs::read_dir(&old_dir)?; for entry in entries { let entry = entry?; let file_name = entry.file_name(); - rename(entry.path(), new_dir.join(file_name))?; + fs::rename(entry.path(), new_dir.join(file_name))?; + } + + // Check if the old directory is empty now and remove it + if fs::read_dir(&old_dir)?.next().is_none() { + fs::remove_dir(&old_dir)?; } } From a9826fa7cfb6a09cc85599794594071c5ea4dbe6 Mon Sep 17 00:00:00 2001 From: abhi3700 Date: Thu, 1 Feb 2024 00:59:39 +0530 Subject: [PATCH 09/20] added missing pkg: serde_json --- pulsar/Cargo.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/pulsar/Cargo.toml b/pulsar/Cargo.toml index 57f8f70e..fe53f167 100644 --- a/pulsar/Cargo.toml +++ b/pulsar/Cargo.toml @@ -26,6 +26,7 @@ owo-colors = "3.5.0" rand = "0.8.5" serde = "1" serde_derive = "1" +serde_json = "1.0.113" single-instance = "0.3.3" sp-core = { version = "21.0.0", git = "https://github.com/subspace/polkadot-sdk", rev = "c63a8b28a9fd26d42116b0dcef1f2a5cefb9cd1c", features = ["full_crypto"] } strum = "0.24.1" From ef9072f468a1496d026ba1705289f26ca1533497 Mon Sep 17 00:00:00 2001 From: abhi3700 Date: Thu, 1 Feb 2024 02:07:19 +0530 Subject: [PATCH 10/20] ensured check for already set chain, wipe after new chain set confirmation --- pulsar/src/commands/config.rs | 15 +++++++++++---- pulsar/src/config.rs | 2 +- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/pulsar/src/commands/config.rs b/pulsar/src/commands/config.rs index 979513d3..6791845a 100644 --- a/pulsar/src/commands/config.rs +++ b/pulsar/src/commands/config.rs @@ -118,11 +118,18 @@ pub(crate) async fn config( // update (optional) the chain if let Some(c) = chain { - config.chain = ChainConfig::from_str(&c)?; - println!("Chain updated as {:?}", c); + let new_chain = ChainConfig::from_str(&c)?; + if config.chain == new_chain.clone() { + bail!("Chain already set"); + } + + config.chain = new_chain.clone(); - // wipe everything (farmer, node, summary) except config file - wipe(true, true, true, false).await.expect("Error while wiping."); + // if chain is changed, then wipe everything (farmer, node, summary) except + // config file + if parse_config()?.chain == new_chain { + wipe(true, true, true, false).await.expect("Error while wiping."); + } } // update (optional) the farm size diff --git a/pulsar/src/config.rs b/pulsar/src/config.rs index b103e35e..8e47932a 100644 --- a/pulsar/src/config.rs +++ b/pulsar/src/config.rs @@ -150,7 +150,7 @@ impl FarmerConfig { } /// Enum for Chain -#[derive(Deserialize, Serialize, Default, Clone, Debug, EnumIter)] +#[derive(Deserialize, Serialize, Default, Clone, Debug, EnumIter, PartialEq)] pub(crate) enum ChainConfig { #[default] Gemini3g, From 8ea0009cc9379ed2c4ded3dfb9fde990eced4e7c Mon Sep 17 00:00:00 2001 From: abhi3700 Date: Thu, 1 Feb 2024 12:43:51 +0530 Subject: [PATCH 11/20] fixed clippy errors --- pulsar/src/commands/config.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pulsar/src/commands/config.rs b/pulsar/src/commands/config.rs index 6791845a..51ff1829 100644 --- a/pulsar/src/commands/config.rs +++ b/pulsar/src/commands/config.rs @@ -133,26 +133,26 @@ pub(crate) async fn config( } // update (optional) the farm size - if let Some(ref f) = farm_size { + if let Some(f) = farm_size { let farm_size = size_parser(&f)?; config.farmer.farm_size = farm_size; } // update (optional) the reward address - if let Some(ref r) = reward_address { + if let Some(r) = reward_address { let reward_address = reward_address_parser(&r)?; config.farmer.reward_address = reward_address; } // update (optional) the node directory - if let Some(ref n) = node_dir { + if let Some(n) = node_dir { let node_dir = PathBuf::from_str(&n).expect("Invalid node directory"); create_or_move_data(config.node.directory.clone(), node_dir.clone())?; config.node.directory = node_dir; } // update (optional) the farm directory - if let Some(ref fd) = farm_dir { + if let Some(fd) = farm_dir { let farm_dir = PathBuf::from_str(&fd).expect("Invalid farm directory"); create_or_move_data(config.farmer.farm_directory.clone(), farm_dir.clone())?; if farm_dir.exists() { From bb4a85f09d3d1b23dfe9dcd23d79febc86022e4b Mon Sep 17 00:00:00 2001 From: abhi3700 Date: Thu, 1 Feb 2024 13:09:46 +0530 Subject: [PATCH 12/20] fixed 'cargo doc' issues --- pulsar/src/commands/config.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/pulsar/src/commands/config.rs b/pulsar/src/commands/config.rs index 51ff1829..1cb9b518 100644 --- a/pulsar/src/commands/config.rs +++ b/pulsar/src/commands/config.rs @@ -11,7 +11,7 @@ //! ## Usage //! //! ### Show -//! ``` +//! ```bash //! $ pulsar config -s //! Current Config set as: //! { @@ -30,33 +30,33 @@ //! ``` //! //! ### Chain -//! ``` +//! ```bash //! $ pulsar config -c devnet //! ``` //! //! ### Farm size -//! ``` +//! ```bash //! $ pulsar config -f 3GB //! ``` //! //! ### Reward address //! -//! ``` +//! ```bash //! $ pulsar config -r 5CDstQSbxPrPAaRTuVR2n9PHuhGYnnQvXdbJSQmodD5i16x2 //! ``` //! //! ### Node directory -//! ``` +//! ```bash //! $ pulsar config -n "/Users/abhi3700/test/pulsar1/node" //! ``` //! //! ### Farm directory -//! ``` +//! ```bash //! $ pulsar config -d "/Users/abhi3700/test/pulsar1/farms" //! ``` //! //! ### All params -//! ``` +//! ```bash //! $ pulsar config \ //! --chain devnet \ //! --farm-size 5GB \ From a82110fc1f03e3ce494f8301b24988692117c0b9 Mon Sep 17 00:00:00 2001 From: abhi3700 Date: Fri, 2 Feb 2024 01:31:37 +0530 Subject: [PATCH 13/20] fixed build doc error --- pulsar/src/config.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pulsar/src/config.rs b/pulsar/src/config.rs index 8e47932a..abbf5025 100644 --- a/pulsar/src/config.rs +++ b/pulsar/src/config.rs @@ -189,7 +189,7 @@ pub(crate) fn create_config() -> Result<(File, PathBuf)> { Ok((file, config_path)) } -/// parses the config path, and returns [`ConfigPath`] +/// parses the config path, and returns `ConfigPath` #[instrument] pub(crate) fn parse_config_path() -> Result { let config_path = dirs::config_dir().expect("couldn't get the default config directory!"); From fd985c53c2f78bb79e3bef4a426bd17ebf427655 Mon Sep 17 00:00:00 2001 From: abhi3700 Date: Mon, 5 Feb 2024 21:35:19 +0530 Subject: [PATCH 14/20] Remove show flag from config command `$ pulsar config -s` has been replaced with `$ pulsar config` to show the already set config params/fields details. --- pulsar/src/commands/config.rs | 28 ++++++++++++++++------------ pulsar/src/main.rs | 9 +++------ 2 files changed, 19 insertions(+), 18 deletions(-) diff --git a/pulsar/src/commands/config.rs b/pulsar/src/commands/config.rs index 1cb9b518..49f517f9 100644 --- a/pulsar/src/commands/config.rs +++ b/pulsar/src/commands/config.rs @@ -12,7 +12,7 @@ //! //! ### Show //! ```bash -//! $ pulsar config -s +//! $ pulsar config //! Current Config set as: //! { //! "chain": "Gemini3g", @@ -77,7 +77,6 @@ use crate::utils::{create_or_move_data, reward_address_parser, size_parser}; // function for config cli command pub(crate) async fn config( - show: bool, chain: Option, farm_size: Option, reward_address: Option, @@ -95,16 +94,12 @@ pub(crate) async fn config( // Load the current configuration let mut config: Config = parse_config()?; - if show { - // Display the current configuration as JSON - // Serialize `config` to a pretty-printed JSON string - let serialized = serde_json::to_string_pretty(&config)?; - println!( - "Current Config set as: \n{}\nin file: {:?}", - serialized, - config_path.to_str().expect("Expected stringified config path") - ); - } else { + if chain.is_some() + || farm_size.is_some() + || reward_address.is_some() + || node_dir.is_some() + || farm_dir.is_some() + { // no options provided if chain.is_none() && farm_size.is_none() @@ -162,6 +157,15 @@ pub(crate) async fn config( // Save the updated configuration back to the file fs::write(config_path, toml::to_string(&config)?)?; + } else { + // Display the current configuration as JSON + // Serialize `config` to a pretty-printed JSON string + let serialized = serde_json::to_string_pretty(&config)?; + println!( + "Current Config already set as: \n{}\nin file: {:?}", + serialized, + config_path.to_str().expect("Expected stringified config path") + ); } Ok(()) diff --git a/pulsar/src/main.rs b/pulsar/src/main.rs index 63a4ec85..7ee9a211 100644 --- a/pulsar/src/main.rs +++ b/pulsar/src/main.rs @@ -73,8 +73,6 @@ enum Commands { about = "set the config params: chain, farm-size, reward-address, node-dir, farm-dir" )] Config { - #[arg(short, long, action)] - show: bool, #[arg(short, long, action)] chain: Option, #[arg(short, long, action)] @@ -106,8 +104,8 @@ async fn main() -> Result<(), Report> { Some(Commands::Wipe { farmer, node }) => { wipe_config(farmer, node).await.suggestion(support_message())?; } - Some(Commands::Config { chain, show, farm_size, reward_address, node_dir, farm_dir }) => { - config(show, chain, farm_size, reward_address, node_dir, farm_dir) + Some(Commands::Config { chain, farm_size, reward_address, node_dir, farm_dir }) => { + config(chain, farm_size, reward_address, node_dir, farm_dir) .await .suggestion(support_message())?; } @@ -200,7 +198,7 @@ async fn arrow_key_mode() -> Result<(), Report> { info().await.suggestion(support_message())?; } 4 => { - config(true, None, None, None, None, None).await.suggestion(support_message())?; + config(None, None, None, None, None).await.suggestion(support_message())?; } 5 => { open_log_dir().suggestion(support_message())?; @@ -249,7 +247,6 @@ impl std::fmt::Display for Commands { Commands::Info => write!(f, "info"), Commands::Init => write!(f, "init"), Commands::Config { - show: _, chain: _, farm_size: _, reward_address: _, From 689b06116e56fe0b2552fdabef3779fb923de2d9 Mon Sep 17 00:00:00 2001 From: abhi3700 Date: Mon, 5 Feb 2024 21:44:06 +0530 Subject: [PATCH 15/20] Correct rust doc for config --- pulsar/src/commands/config.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pulsar/src/commands/config.rs b/pulsar/src/commands/config.rs index 49f517f9..381d57e2 100644 --- a/pulsar/src/commands/config.rs +++ b/pulsar/src/commands/config.rs @@ -61,8 +61,8 @@ //! --chain devnet \ //! --farm-size 5GB \ //! --reward-address 5DXRtoHJePQBEk44onMy5yG4T8CjpPaK4qKNmrwpxqxZALGY \ -//! --node-directory "/Users/abhi3700/test/pulsar1/node" \ -//! --farm-directory "/Users/abhi3700/test/pulsar1/farms" +//! --node-dir "/Users/abhi3700/test/pulsar1/node" \ +//! --farm-dir "/Users/abhi3700/test/pulsar1/farms" //! ``` use std::fs; From fb6c7728d4cc4b05bf5e8ec5c7bcf0a1c8387a5d Mon Sep 17 00:00:00 2001 From: abhi3700 Date: Tue, 6 Feb 2024 01:46:33 +0530 Subject: [PATCH 16/20] Add tests for fn used in config fn --- pulsar/src/tests.rs | 68 +++++++++++++++++++++++++++++++++++++++++++-- pulsar/src/utils.rs | 1 + 2 files changed, 67 insertions(+), 2 deletions(-) diff --git a/pulsar/src/tests.rs b/pulsar/src/tests.rs index b18e34c2..9512c436 100644 --- a/pulsar/src/tests.rs +++ b/pulsar/src/tests.rs @@ -1,3 +1,4 @@ +use std::path::PathBuf; use std::str::FromStr; use rand::rngs::SmallRng; @@ -7,8 +8,9 @@ use subspace_sdk::ByteSize; use crate::config::ChainConfig; use crate::summary::*; use crate::utils::{ - apply_extra_options, custom_log_dir, directory_parser, farm_directory_getter, - node_directory_getter, node_name_parser, reward_address_parser, size_parser, yes_or_no_parser, + apply_extra_options, create_or_move_data, custom_log_dir, directory_parser, + farm_directory_getter, node_directory_getter, node_name_parser, reward_address_parser, + size_parser, yes_or_no_parser, }; async fn update_summary_file_randomly(summary_file: SummaryFile) { @@ -175,3 +177,65 @@ fn custom_log_dir_test() { #[cfg(target_os = "windows")] assert!(log_path.ends_with("AppData/Local/pulsar/logs")); } + +#[cfg(test)] +mod create_or_move_data_tests { + + use std::fs::{self}; + use std::path::Path; + + use super::*; + + /// Set up a temporary directory for testing. + /// Returns a `PathBuf` representing the path to the temporary directory. + fn setup_temp_directory() -> PathBuf { + let temp_dir = Path::new("/tmp").join(format!("test_pulsar")); + fs::create_dir_all(&temp_dir).expect("Failed to create temp directory for test"); + temp_dir + } + + /// Tear down the temporary directory used in testing. + fn teardown_temp_directory(temp_dir: PathBuf) { + fs::remove_dir_all(temp_dir).expect("Failed to remove temp directory after test"); + } + + /// Ensuring the function correctly handles the case where the old and new + /// directories are the same. + #[test] + fn test_fails_when_old_new_dirs_same() { + let temp_dir = setup_temp_directory(); + let old_dir = temp_dir.join("node"); + let new_dir = temp_dir.join("node"); + + assert!(create_or_move_data(PathBuf::from(old_dir), PathBuf::from(new_dir)).is_err()); + + teardown_temp_directory(temp_dir); + } + + /// Verifying the function fails when the new directory path does not start + /// with "/". + #[test] + #[cfg(any(target_os = "macos", target_os = "linux"))] + fn test_fails_when_new_dir_no_slash() { + let temp_dir = setup_temp_directory(); + let old_dir = temp_dir.join("old_node"); + let new_dir = "pulsar/node"; + + assert!(create_or_move_data(PathBuf::from(old_dir), PathBuf::from(new_dir)).is_err()); + + teardown_temp_directory(temp_dir); + } + + /// test if old dir doesn't exist + #[test] + fn test_if_old_dir_doesnt_exist() { + // TODO: Add test logic + } + + /// test if empty old dir is removed after the data is moved from there to + /// new dir. + #[test] + fn test_remove_dir_if_old_dir_empty() { + // TODO: Add test logic + } +} diff --git a/pulsar/src/utils.rs b/pulsar/src/utils.rs index 94e38148..179a3ae4 100644 --- a/pulsar/src/utils.rs +++ b/pulsar/src/utils.rs @@ -396,6 +396,7 @@ pub(crate) fn create_or_move_data(old_dir: PathBuf, new_dir: PathBuf) -> Result< bail!("This directory is already set"); } + #[cfg(any(target_os = "macos", target_os = "linux"))] if !new_dir.starts_with("/") { bail!("New directory path must start with /"); } From 208e2971fa1f75b27883f3dd7d265b3a63eb4d94 Mon Sep 17 00:00:00 2001 From: abhi3700 Date: Tue, 6 Feb 2024 02:21:20 +0530 Subject: [PATCH 17/20] Add tests --- pulsar/src/commands/config.rs | 4 ++-- pulsar/src/tests.rs | 13 ++++++++++--- pulsar/src/utils.rs | 10 +++++----- 3 files changed, 17 insertions(+), 10 deletions(-) diff --git a/pulsar/src/commands/config.rs b/pulsar/src/commands/config.rs index 381d57e2..e32ff3e6 100644 --- a/pulsar/src/commands/config.rs +++ b/pulsar/src/commands/config.rs @@ -142,14 +142,14 @@ pub(crate) async fn config( // update (optional) the node directory if let Some(n) = node_dir { let node_dir = PathBuf::from_str(&n).expect("Invalid node directory"); - create_or_move_data(config.node.directory.clone(), node_dir.clone())?; + create_or_move_data(&config.node.directory, &node_dir)?; config.node.directory = node_dir; } // update (optional) the farm directory if let Some(fd) = farm_dir { let farm_dir = PathBuf::from_str(&fd).expect("Invalid farm directory"); - create_or_move_data(config.farmer.farm_directory.clone(), farm_dir.clone())?; + create_or_move_data(&config.farmer.farm_directory, &farm_dir)?; if farm_dir.exists() { config.farmer.farm_directory = farm_dir; } diff --git a/pulsar/src/tests.rs b/pulsar/src/tests.rs index 9512c436..0d4e0b03 100644 --- a/pulsar/src/tests.rs +++ b/pulsar/src/tests.rs @@ -207,7 +207,7 @@ mod create_or_move_data_tests { let old_dir = temp_dir.join("node"); let new_dir = temp_dir.join("node"); - assert!(create_or_move_data(PathBuf::from(old_dir), PathBuf::from(new_dir)).is_err()); + assert!(create_or_move_data(&old_dir, &new_dir).is_err()); teardown_temp_directory(temp_dir); } @@ -221,15 +221,22 @@ mod create_or_move_data_tests { let old_dir = temp_dir.join("old_node"); let new_dir = "pulsar/node"; - assert!(create_or_move_data(PathBuf::from(old_dir), PathBuf::from(new_dir)).is_err()); + assert!(create_or_move_data(&old_dir, &PathBuf::from(new_dir)).is_err()); teardown_temp_directory(temp_dir); } /// test if old dir doesn't exist #[test] - fn test_if_old_dir_doesnt_exist() { + fn test_pass_even_if_old_dir_doesnt_exist() { + let old_dir = "/path/that/does/not/exist"; + let temp_dir = setup_temp_directory(); + let new_dir = temp_dir.join("node"); // TODO: Add test logic + assert!(create_or_move_data(&PathBuf::from(old_dir), &new_dir).is_ok()); + assert!(new_dir.exists()); + + teardown_temp_directory(temp_dir); } /// test if empty old dir is removed after the data is moved from there to diff --git a/pulsar/src/utils.rs b/pulsar/src/utils.rs index 179a3ae4..3c4773e0 100644 --- a/pulsar/src/utils.rs +++ b/pulsar/src/utils.rs @@ -391,7 +391,7 @@ impl<'de> Deserialize<'de> for Rewards { /// move data from old directory (if any) to new directory, or else just create /// the new directory. -pub(crate) fn create_or_move_data(old_dir: PathBuf, new_dir: PathBuf) -> Result<()> { +pub(crate) fn create_or_move_data(old_dir: &PathBuf, new_dir: &PathBuf) -> Result<()> { if old_dir == new_dir { bail!("This directory is already set"); } @@ -403,12 +403,12 @@ pub(crate) fn create_or_move_data(old_dir: PathBuf, new_dir: PathBuf) -> Result< // Create the new directory if it doesn't exist if !new_dir.exists() { - fs::create_dir_all(&new_dir)?; + fs::create_dir_all(new_dir)?; } // Move contents if the old directory exists if old_dir.exists() { - let entries = fs::read_dir(&old_dir)?; + let entries = fs::read_dir(old_dir)?; for entry in entries { let entry = entry?; let file_name = entry.file_name(); @@ -416,8 +416,8 @@ pub(crate) fn create_or_move_data(old_dir: PathBuf, new_dir: PathBuf) -> Result< } // Check if the old directory is empty now and remove it - if fs::read_dir(&old_dir)?.next().is_none() { - fs::remove_dir(&old_dir)?; + if fs::read_dir(old_dir)?.next().is_none() { + fs::remove_dir(old_dir)?; } } From 9b2539e06ed38b12251ef7de1c25564b0090af32 Mon Sep 17 00:00:00 2001 From: abhi3700 Date: Tue, 6 Feb 2024 17:39:39 +0530 Subject: [PATCH 18/20] Updated tests for 'create_or_move_data' fn --- pulsar/src/tests.rs | 62 ++++++++++++++------------------------------- pulsar/src/utils.rs | 2 +- 2 files changed, 20 insertions(+), 44 deletions(-) diff --git a/pulsar/src/tests.rs b/pulsar/src/tests.rs index 0d4e0b03..4cbbaf5d 100644 --- a/pulsar/src/tests.rs +++ b/pulsar/src/tests.rs @@ -181,68 +181,44 @@ fn custom_log_dir_test() { #[cfg(test)] mod create_or_move_data_tests { - use std::fs::{self}; - use std::path::Path; + use std::fs; use super::*; - - /// Set up a temporary directory for testing. - /// Returns a `PathBuf` representing the path to the temporary directory. - fn setup_temp_directory() -> PathBuf { - let temp_dir = Path::new("/tmp").join(format!("test_pulsar")); - fs::create_dir_all(&temp_dir).expect("Failed to create temp directory for test"); - temp_dir - } - - /// Tear down the temporary directory used in testing. - fn teardown_temp_directory(temp_dir: PathBuf) { - fs::remove_dir_all(temp_dir).expect("Failed to remove temp directory after test"); - } + use crate::utils::data_dir_getter; /// Ensuring the function correctly handles the case where the old and new /// directories are the same. #[test] fn test_fails_when_old_new_dirs_same() { - let temp_dir = setup_temp_directory(); - let old_dir = temp_dir.join("node"); - let new_dir = temp_dir.join("node"); + let old_dir = node_directory_getter(); + let new_dir = node_directory_getter(); assert!(create_or_move_data(&old_dir, &new_dir).is_err()); - - teardown_temp_directory(temp_dir); } /// Verifying the function fails when the new directory path does not start /// with "/". #[test] #[cfg(any(target_os = "macos", target_os = "linux"))] - fn test_fails_when_new_dir_no_slash() { - let temp_dir = setup_temp_directory(); - let old_dir = temp_dir.join("old_node"); - let new_dir = "pulsar/node"; - - assert!(create_or_move_data(&old_dir, &PathBuf::from(new_dir)).is_err()); + fn test_fails_new_dir_wo_slash() { + let old_dir = node_directory_getter(); + let new_dir = PathBuf::from("pulsar/node"); - teardown_temp_directory(temp_dir); + assert!(create_or_move_data(&old_dir, &new_dir).is_err()); } - /// test if old dir doesn't exist + /// test as expected by parsing valid old & new dirs #[test] - fn test_pass_even_if_old_dir_doesnt_exist() { - let old_dir = "/path/that/does/not/exist"; - let temp_dir = setup_temp_directory(); - let new_dir = temp_dir.join("node"); - // TODO: Add test logic - assert!(create_or_move_data(&PathBuf::from(old_dir), &new_dir).is_ok()); - assert!(new_dir.exists()); - - teardown_temp_directory(temp_dir); - } + fn test_create_or_move_data_success() { + let old_dir = node_directory_getter(); + let new_dir = data_dir_getter().join("node2"); - /// test if empty old dir is removed after the data is moved from there to - /// new dir. - #[test] - fn test_remove_dir_if_old_dir_empty() { - // TODO: Add test logic + assert!(create_or_move_data(&old_dir, &new_dir).is_ok()); + + // old dir shouldn't exist + assert!(!old_dir.exists()); + + // delete the newly created dir to reset + fs::remove_dir_all(new_dir).unwrap(); } } diff --git a/pulsar/src/utils.rs b/pulsar/src/utils.rs index 3c4773e0..1bdb4b0b 100644 --- a/pulsar/src/utils.rs +++ b/pulsar/src/utils.rs @@ -153,7 +153,7 @@ pub(crate) fn provider_storage_dir_getter() -> PathBuf { node_directory_getter().join("provider-storage") } -fn data_dir_getter() -> PathBuf { +pub(crate) fn data_dir_getter() -> PathBuf { dirs::data_dir().expect("data folder must be present in every major OS").join("pulsar") } From 96e408b430aa1b3316aa06762e2d88ced2f776fa Mon Sep 17 00:00:00 2001 From: abhi3700 Date: Tue, 6 Feb 2024 18:35:27 +0530 Subject: [PATCH 19/20] removed redundant check --- pulsar/src/commands/config.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/pulsar/src/commands/config.rs b/pulsar/src/commands/config.rs index e32ff3e6..2bce00c8 100644 --- a/pulsar/src/commands/config.rs +++ b/pulsar/src/commands/config.rs @@ -150,9 +150,7 @@ pub(crate) async fn config( if let Some(fd) = farm_dir { let farm_dir = PathBuf::from_str(&fd).expect("Invalid farm directory"); create_or_move_data(&config.farmer.farm_directory, &farm_dir)?; - if farm_dir.exists() { - config.farmer.farm_directory = farm_dir; - } + config.farmer.farm_directory = farm_dir; } // Save the updated configuration back to the file From 3caa3c7473e433891b16f0a4695e27ba095d32bb Mon Sep 17 00:00:00 2001 From: abhi3700 Date: Thu, 8 Feb 2024 18:35:34 +0530 Subject: [PATCH 20/20] Refactor code with 'bail!' --- pulsar/src/commands/farm.rs | 6 ++---- pulsar/src/commands/init.rs | 4 ++-- pulsar/src/utils.rs | 4 +--- 3 files changed, 5 insertions(+), 9 deletions(-) diff --git a/pulsar/src/commands/farm.rs b/pulsar/src/commands/farm.rs index 16e77d79..bb6354e3 100644 --- a/pulsar/src/commands/farm.rs +++ b/pulsar/src/commands/farm.rs @@ -2,7 +2,7 @@ use std::io::Write; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; -use color_eyre::eyre::{eyre, Context, Error, Result}; +use color_eyre::eyre::{bail, eyre, Context, Error, Result}; use color_eyre::Report; use futures::prelude::*; use indicatif::{ProgressBar, ProgressStyle}; @@ -42,9 +42,7 @@ pub(crate) async fn farm(is_verbose: bool, enable_domains: bool, no_rotation: bo let instance = SingleInstance::new(SINGLE_INSTANCE) .context("Cannot take the instance lock from the OS! Aborting...")?; if !instance.is_single() { - return Err(eyre!( - "It seems like there is already a farming instance running. Aborting...", - )); + bail!("It seems like there is already a farming instance running. Aborting...",) } // raise file limit raise_fd_limit(); diff --git a/pulsar/src/commands/init.rs b/pulsar/src/commands/init.rs index 3004a226..704835c9 100644 --- a/pulsar/src/commands/init.rs +++ b/pulsar/src/commands/init.rs @@ -1,7 +1,7 @@ use std::io::{BufRead, Write}; use std::str::FromStr; -use color_eyre::eyre::{eyre, Context, Error, Result}; +use color_eyre::eyre::{bail, Context, Error, Result}; use crossterm::terminal::{Clear, ClearType}; use crossterm::{cursor, execute}; use rand::prelude::IteratorRandom; @@ -137,7 +137,7 @@ fn generate_or_get_reward_address(reward_address_exist: bool) -> Result Result { /// utilize `ByteSize` crate for the validation pub(crate) fn size_parser(size: &str) -> Result { - let Ok(size) = size.parse::() else { - return Err(eyre!("could not parse the value!")); - }; + let Ok(size) = size.parse::() else { bail!("could not parse the value!") }; if size < MIN_FARM_SIZE { Err(eyre!(format!("farm size cannot be smaller than {}", MIN_FARM_SIZE))) } else {