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 14 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
168 changes: 168 additions & 0 deletions pulsar/src/commands/config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
//! 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 -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
//! ```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-directory "/Users/abhi3700/test/pulsar1/node" \
//! --farm-directory "/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(
show: bool,
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 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 {
// 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.clone(), node_dir.clone())?;
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())?;
if farm_dir.exists() {
ParthDesai marked this conversation as resolved.
Show resolved Hide resolved
config.farmer.farm_directory = farm_dir;
}
}

// Save the updated configuration back to the file
fs::write(config_path, toml::to_string(&config)?)?;
}

Ok(())
}
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
36 changes: 35 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,23 @@ 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
show: bool,
#[arg(short, long, action)]
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 +106,11 @@ 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)
.await
.suggestion(support_message())?;
}
Some(Commands::OpenLogs) => {
open_log_dir().suggestion(support_message())?;
}
Expand Down Expand Up @@ -177,10 +200,13 @@ 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())?;
}
_ => {
unreachable!("this number must stay in [0-4]")
unreachable!("this number must stay in [0-5]")
}
}

Expand Down Expand Up @@ -222,6 +248,14 @@ 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 {
show: _,
chain: _,
farm_size: _,
reward_address: _,
node_dir: _,
farm_dir: _,
} => write!(f, "config"),
Commands::OpenLogs => write!(f, "open logs directory"),
}
}
Expand Down
38 changes: 36 additions & 2 deletions pulsar/src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use std::env;
use std::fs::create_dir_all;
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};
Expand Down Expand Up @@ -388,3 +388,37 @@ impl<'de> Deserialize<'de> for Rewards {
Ok(Rewards(value))
}
}

/// 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<()> {
ParthDesai marked this conversation as resolved.
Show resolved Hide resolved
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)?;
}

// 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();
fs::rename(entry.path(), new_dir.join(file_name))?;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What would happen if this fails? We are left with some data in old directory and some data in new one. Which means after this happen, user won't be able to use pulsar and have to fix the situation by hand.

I would like to have atomic move implemented here. Either we move everything or we move nothing.

}

// Check if the old directory is empty now and remove it
if fs::read_dir(&old_dir)?.next().is_none() {
ParthDesai marked this conversation as resolved.
Show resolved Hide resolved
fs::remove_dir(&old_dir)?;
}
}

Ok(())
}
Loading