Skip to content
This repository has been archived by the owner on Mar 1, 2024. It is now read-only.

Add config command #294

Open
wants to merge 21 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 55 additions & 54 deletions Cargo.lock

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions pulsar/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
1 change: 1 addition & 0 deletions pulsar/src/commands.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub(crate) mod config;
pub(crate) mod farm;
pub(crate) mod info;
pub(crate) mod init;
Expand Down
170 changes: 170 additions & 0 deletions pulsar/src/commands/config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
//! 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.
//!
//! ## Usage
//!
//! ### Show
//! ```bash
//! $ pulsar config
//! 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
//! ```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 \
//! --reward-address 5DXRtoHJePQBEk44onMy5yG4T8CjpPaK4qKNmrwpxqxZALGY \
//! --node-dir "/Users/abhi3700/test/pulsar1/node" \
//! --farm-dir "/Users/abhi3700/test/pulsar1/farms"
//! ```

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, ChainConfig, Config};
use crate::utils::{create_or_move_data, reward_address_parser, size_parser};

// function for config cli command
pub(crate) async fn config(
chain: Option<String>,
farm_size: Option<String>,
reward_address: Option<String>,
node_dir: Option<String>,
farm_dir: Option<String>,
) -> 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() {
bail!("Config file: \"settings.toml\" not found.\nPlease use `pulsar init` command first.");
}

// Load the current configuration
let mut config: Config = parse_config()?;

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()
&& 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(());
}

// update (optional) the chain
if let Some(c) = chain {
let new_chain = ChainConfig::from_str(&c)?;
if config.chain == new_chain.clone() {
bail!("Chain already set");
}

config.chain = new_chain.clone();

// 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
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(r) = reward_address {
let reward_address = reward_address_parser(&r)?;
config.farmer.reward_address = reward_address;
}

// 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, &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, &farm_dir)?;
config.farmer.farm_directory = farm_dir;
}

// 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(())
}
6 changes: 2 additions & 4 deletions pulsar/src/commands/farm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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();
Expand Down
4 changes: 2 additions & 2 deletions pulsar/src/commands/init.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -137,7 +137,7 @@ fn generate_or_get_reward_address(reward_address_exist: bool) -> Result<PublicKe
)?;

if !wants_new_key {
return Err(eyre!("New key creation was not confirmed"));
bail!("New key creation was not confirmed")
}

// generate new mnemonic and key pair
Expand Down
2 changes: 1 addition & 1 deletion pulsar/src/commands/wipe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
18 changes: 12 additions & 6 deletions pulsar/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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<Config> {
pub(crate) fn parse_config_path() -> Result<PathBuf> {
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<Config> {
let config: Config = toml::from_str(&std::fs::read_to_string(parse_config_path()?)?)?;
Ok(config)
}

Expand All @@ -206,7 +212,7 @@ pub(crate) fn validate_config() -> Result<Config> {

// 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)
Expand Down
33 changes: 32 additions & 1 deletion pulsar/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ use strum::IntoEnumIterator;
use strum_macros::EnumIter;
use tracing::instrument;

use crate::commands::config::config;
use crate::commands::farm::farm;
use crate::commands::info::info;
use crate::commands::init::init;
Expand Down Expand Up @@ -68,6 +69,21 @@ 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: chain, farm-size, reward-address, node-dir, farm-dir"
)]
Config {
#[arg(short, long, action)]
ParthDesai marked this conversation as resolved.
Show resolved Hide resolved
chain: Option<String>,
#[arg(short, long, action)]
farm_size: Option<String>,
#[arg(short, long, action)]
reward_address: Option<String>,
#[arg(short, long, action)]
node_dir: Option<String>,
#[arg(short = 'd', long, action)]
farm_dir: Option<String>,
},
OpenLogs,
}

Expand All @@ -88,6 +104,11 @@ async fn main() -> Result<(), Report> {
Some(Commands::Wipe { farmer, node }) => {
wipe_config(farmer, node).await.suggestion(support_message())?;
}
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())?;
}
Some(Commands::OpenLogs) => {
open_log_dir().suggestion(support_message())?;
}
Expand Down Expand Up @@ -177,10 +198,13 @@ async fn arrow_key_mode() -> Result<(), Report> {
info().await.suggestion(support_message())?;
}
4 => {
config(None, None, None, None, None).await.suggestion(support_message())?;
}
5 => {
open_log_dir().suggestion(support_message())?;
}
_ => {
unreachable!("this number must stay in [0-4]")
unreachable!("this number must stay in [0-5]")
}
}

Expand Down Expand Up @@ -222,6 +246,13 @@ impl std::fmt::Display for Commands {
Commands::Wipe { farmer: _, node: _ } => write!(f, "wipe"),
Commands::Info => write!(f, "info"),
Commands::Init => write!(f, "init"),
Commands::Config {
chain: _,
farm_size: _,
reward_address: _,
node_dir: _,
farm_dir: _,
} => write!(f, "config"),
Commands::OpenLogs => write!(f, "open logs directory"),
}
}
Expand Down
Loading
Loading