From c3d7edb10703596031c4ade82448734f305c1b72 Mon Sep 17 00:00:00 2001 From: sslivkoff Date: Thu, 25 Jan 2024 11:12:04 -0800 Subject: [PATCH 1/4] add new input types and error types for file parsing --- rust/crates/mesc/src/load.rs | 14 ++++++++++---- rust/crates/mesc/src/types/errors.rs | 8 ++++++++ rust/crates/mesc/src/write.rs | 12 +++++++----- 3 files changed, 25 insertions(+), 9 deletions(-) diff --git a/rust/crates/mesc/src/load.rs b/rust/crates/mesc/src/load.rs index c8e0d91..fa4f0f4 100644 --- a/rust/crates/mesc/src/load.rs +++ b/rust/crates/mesc/src/load.rs @@ -4,7 +4,7 @@ use std::{env, fs}; /// check whether mesc is enabled pub fn is_mesc_enabled() -> bool { if let Ok("DISABLED") = std::env::var("MESC_MODE").as_deref() { - return false + return false; }; let env_vars = [ "MESC_MODE", @@ -79,6 +79,9 @@ pub fn load_file_config(path: Option) -> Result { Some(path) => path, None => get_config_path()?, }; + if !std::path::Path::new(path.as_str()).exists() { + return Err(MescError::MissingConfigFile(path)); + }; let config_str = fs::read_to_string(path).map_err(MescError::IOError)?; serde_json::from_str(&config_str).map_err(|_| MescError::InvalidJson) } @@ -91,10 +94,13 @@ pub fn get_config_path() -> Result { } /// expand tilde's in path -pub fn expand_path(path: String) -> Result { - if let Some(subpath) = path.strip_prefix("~/") { +pub fn expand_path>(path: P) -> Result { + let path_str = + path.as_ref().to_str().ok_or(MescError::InvalidPath("Invalid path".to_string()))?; + + if let Some(subpath) = path_str.strip_prefix("~/") { Ok(format!("{}/{}", env::var("HOME")?, subpath)) } else { - Ok(path) + Ok(path_str.to_string()) } } diff --git a/rust/crates/mesc/src/types/errors.rs b/rust/crates/mesc/src/types/errors.rs index 4ed9312..a5f2f3c 100644 --- a/rust/crates/mesc/src/types/errors.rs +++ b/rust/crates/mesc/src/types/errors.rs @@ -23,6 +23,14 @@ pub enum MescError { #[error("Missing endpoint: {0}")] MissingEndpoint(String), + /// Error for missing invalid path + #[error("Invalid path: {0}")] + InvalidPath(String), + + /// Error for missing config file + #[error("Missing config file: {0}")] + MissingConfigFile(String), + /// Error wrapper for standard IO errors. #[error(transparent)] IOError(#[from] std::io::Error), diff --git a/rust/crates/mesc/src/write.rs b/rust/crates/mesc/src/write.rs index 867c875..8ecc328 100644 --- a/rust/crates/mesc/src/write.rs +++ b/rust/crates/mesc/src/write.rs @@ -1,15 +1,17 @@ use crate::{MescError, RpcConfig, TryIntoChainId}; -use std::fs::File; +use std::{fs::File, path::Path}; /// write config to file -pub fn write_config(config: RpcConfig, path: String) -> Result<(), MescError> { - if let Some(parent) = std::path::Path::new(&path).parent() { +pub fn write_config>(config: RpcConfig, path: P) -> Result<(), MescError> { + let path_ref = path.as_ref(); + + if let Some(parent) = path_ref.parent() { if !parent.exists() { - std::fs::create_dir_all(&path)? + std::fs::create_dir_all(parent)? }; } - let file = File::create(path)?; + let file = File::create(path_ref)?; Ok(serde_json::to_writer_pretty(file, &config)?) } From 02ebac8b4dfe8db52fb34671f0f08b4f42106731 Mon Sep 17 00:00:00 2001 From: sslivkoff Date: Thu, 25 Jan 2024 11:13:37 -0800 Subject: [PATCH 2/4] refactor setup subcommand --- rust/crates/mesc/src/overrides.rs | 14 + .../mesc_cli/src/cli/subcommands/setup.rs | 1088 ----------------- .../src/cli/subcommands/setup/command.rs | 229 ++++ .../subcommands/setup/config_modification.rs | 74 ++ .../src/cli/subcommands/setup/defaults.rs | 156 +++ .../src/cli/subcommands/setup/endpoints.rs | 207 ++++ .../cli/subcommands/setup/inquire_utils.rs | 25 + .../src/cli/subcommands/setup/metadata.rs | 139 +++ .../mesc_cli/src/cli/subcommands/setup/mod.rs | 12 + .../cli/subcommands/setup/network_names.rs | 96 ++ .../src/cli/subcommands/setup/selectors.rs | 238 ++++ .../src/cli/subcommands/setup/shell_config.rs | 258 ++++ .../src/cli/subcommands/setup/writing.rs | 77 ++ .../mesc_cli/src/cli/subcommands/status.rs | 56 +- rust/crates/mesc_cli/src/network.rs | 13 + 15 files changed, 1574 insertions(+), 1108 deletions(-) delete mode 100644 rust/crates/mesc_cli/src/cli/subcommands/setup.rs create mode 100644 rust/crates/mesc_cli/src/cli/subcommands/setup/command.rs create mode 100644 rust/crates/mesc_cli/src/cli/subcommands/setup/config_modification.rs create mode 100644 rust/crates/mesc_cli/src/cli/subcommands/setup/defaults.rs create mode 100644 rust/crates/mesc_cli/src/cli/subcommands/setup/endpoints.rs create mode 100644 rust/crates/mesc_cli/src/cli/subcommands/setup/inquire_utils.rs create mode 100644 rust/crates/mesc_cli/src/cli/subcommands/setup/metadata.rs create mode 100644 rust/crates/mesc_cli/src/cli/subcommands/setup/mod.rs create mode 100644 rust/crates/mesc_cli/src/cli/subcommands/setup/network_names.rs create mode 100644 rust/crates/mesc_cli/src/cli/subcommands/setup/selectors.rs create mode 100644 rust/crates/mesc_cli/src/cli/subcommands/setup/shell_config.rs create mode 100644 rust/crates/mesc_cli/src/cli/subcommands/setup/writing.rs diff --git a/rust/crates/mesc/src/overrides.rs b/rust/crates/mesc/src/overrides.rs index a79b740..835c271 100644 --- a/rust/crates/mesc/src/overrides.rs +++ b/rust/crates/mesc/src/overrides.rs @@ -1,6 +1,20 @@ use crate::{ChainId, Endpoint, MescError, Profile, RpcConfig, TryIntoChainId}; use std::collections::HashMap; +/// get active overrides +pub fn get_active_overrides() -> Vec { + let overrides = [ + "MESC_NETWORK_NAMES", + "MESC_NETWORK_DEFAULTS", + "MESC_ENDPOINTS", + "MESC_DEFAULT_ENDPOINT", + "MESC_GLOBAL_METADATA", + "MESC_ENDPOINT_METADATA", + "MESC_PROFILES", + ]; + overrides.iter().filter_map(|v| std::env::var(v).ok()).collect() +} + /// apply overrides to config pub fn apply_overrides(config: &mut RpcConfig) -> Result<(), MescError> { if let Some(default_endpoint) = get_default_endpoint_override() { diff --git a/rust/crates/mesc_cli/src/cli/subcommands/setup.rs b/rust/crates/mesc_cli/src/cli/subcommands/setup.rs deleted file mode 100644 index 60bcba0..0000000 --- a/rust/crates/mesc_cli/src/cli/subcommands/setup.rs +++ /dev/null @@ -1,1088 +0,0 @@ -use crate::{print_defaults, MescCliError, SetupArgs}; -use inquire::{ - ui::{Attributes, Color, IndexPrefix, RenderConfig, StyleSheet, Styled}, - InquireError, -}; -use mesc::{ChainId, Endpoint, RpcConfig, TryIntoChainId}; -use std::collections::{HashMap, HashSet}; -use toolstr::Colorize; - -pub(crate) async fn setup_command(args: SetupArgs) -> Result<(), MescCliError> { - inquire::set_global_render_config(get_render_config()); - - if args.editor { - return edit_config_in_editor(args); - } - - let config_mode = mesc::load::get_config_mode()?; - match config_mode { - mesc::ConfigMode::Path => { - println!("MESC is enabled"); - println!(); - println!("config stored at: {}", mesc::load::get_config_path()?.bold()); - } - mesc::ConfigMode::Env => { - println!("MESC is enabled"); - println!(); - println!("config stored in MESC_ENV environment variable"); - } - mesc::ConfigMode::Disabled => { - println!("MESC is not enabled"); - } - }; - println!(); - - loop { - if mesc::is_mesc_enabled() { - match mesc::load::load_config_data() { - Ok(config) => return modify_existing_config(config, None).await, - Err(_) => { - println!("The current MESC config contains improper data"); - println!(); - let options = vec!["Fix the data manually", "Create a new config from scratch"]; - match inquire::Select::new("How to proceed?", options).prompt() { - Ok("Fix the data manually") => match config_mode { - mesc::ConfigMode::Path => { - let path = mesc::load::get_config_path()?; - edit::edit_file(path)? - } - _ => { - println!("Config data stored in MESC_ENV environment variable"); - println!(); - println!("Edit MESC_ENV in your terminal config files and then restart your terminal"); - } - }, - Ok("Create a new config from scratch") => return setup_new_config().await, - Err(InquireError::OperationCanceled) => { - println!("exiting"); - std::process::exit(1); - } - _ => println!("Improper selection"), - }; - return Ok(()); - } - } - } else if let Ok(path) = mesc::load::get_config_path() { - println!("a MESC config path has still been specified: {}", path.bold()); - - if std::path::Path::new(&path).exists() { - println!(); - match mesc::load::load_file_config(None) { - Ok(config) => { - println!("To enable MESC, select \"Setup environment\" below"); - println!(); - return modify_existing_config(config, None).await; - } - Err(_) => { - println!("This MESC config file contains improper data"); - let options = - vec!["Fix the data manually", "Create a new config from scratch"]; - match inquire::Select::new("How to proceed?", options).prompt() { - Ok("Fix the data manually") => edit::edit_file(path)?, - Ok("Create a new config from scratch") => { - return setup_new_config().await - } - Err(InquireError::OperationCanceled) => { - println!("exiting"); - std::process::exit(1); - } - _ => {} - }; - } - } - } else { - println!(); - return setup_new_config().await; - } - } else { - return setup_new_config().await; - } - } -} - -fn edit_config_in_editor(args: SetupArgs) -> Result<(), MescCliError> { - if let Some(path) = args.path { - edit::edit_file(path)? - } else if let Ok(mesc::ConfigMode::Path) = mesc::load::get_config_mode() { - let path = mesc::load::get_config_path()?; - edit::edit_file(path)? - } else { - return Err(MescCliError::Error("no file to edit".to_string())); - }; - Ok(()) -} - -async fn setup_new_config() -> Result<(), MescCliError> { - println!(" {}", "Creating new config...".bold()); - let mut write_mode = None; - let mut config = RpcConfig::default(); - setup_environment(&mut config, &mut write_mode)?; - if let Some(ConfigWriteMode::Path(path)) = write_mode.clone() { - if std::path::Path::new(&path).exists() { - println!(" Config file already exists, loading"); - config = mesc::load::load_file_config(Some(path))?; - } else { - mesc::write::write_config(config.clone(), path)?; - println!(" {}", "Empty configuration created".bold()); - } - } - - modify_existing_config(config, write_mode).await?; - - Ok(()) -} - -async fn modify_existing_config( - config: RpcConfig, - mut config_write_mode: Option, -) -> Result<(), MescCliError> { - let options = [ - "Setup environment", - "Add new endpoint", - "Modify endpoint", - "Modify defaults", - "Modify global metadata", - "Print config as JSON", - "Exit and save changes", - "Exit without saving", - ] - .to_vec(); - let original_config = config.clone(); - let mut valid_config = config.clone(); - let mut config = config.clone(); - // let mut config_write_mode: Option = None; - loop { - // modify config - let input = match inquire::Select::new("What do you want to do?", options.clone()) - .with_page_size(10) - .prompt() - { - Ok(input) => input, - Err(InquireError::OperationCanceled) => { - println!(" Exiting without saving"); - std::process::exit(0) - } - Err(e) => return Err(e.into()), - }; - match input { - "Setup environment" => setup_environment(&mut config, &mut config_write_mode)?, - "Add new endpoint" => add_endpoint(&mut config).await?, - "Modify endpoint" => modify_endpoint(&mut config).await?, - "Modify defaults" => modify_defaults(&mut config)?, - "Modify global metadata" => modify_global_metadata(&mut config).await?, - "Print config as JSON" => { - println!(); - println!("{}", colored_json::to_colored_json_auto(&config)?); - println!(); - } - "Exit and save changes" => break, - "Exit without saving" => return Ok(()), - _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), - }; - - // validation - match config.validate() { - Ok(()) => {} - Err(e) => { - println!("Invalid data: {:?}", e); - println!("Reverting to previous config state"); - config = valid_config.clone(); - continue; - } - }; - - valid_config = config.clone(); - } - - // write file - if config != original_config { - if config_write_mode.is_none() { - config_write_mode = get_config_write_mode()?; - }; - if config_write_mode.is_none() { - println!(" No write mode selected"); - println!(" Not writing changes to disk"); - } else { - match &config_write_mode { - Some(write_mode) => match write_mode { - ConfigWriteMode::Path(path) => { - mesc::write::write_config(config, path.clone())?; - println!(" {} {}", "config written to".bold(), path.green()); - } - ConfigWriteMode::Env(_) => { - todo!("writing environment variables not supported yet") - } - }, - None => return Err(MescCliError::Error("could not obtain write mode".to_string())), - }; - } - } else { - println!(" {}", "No updates to save".bold()) - } - Ok(()) -} - -fn setup_environment( - _config: &mut RpcConfig, - config_write_mode: &mut Option, -) -> Result<(), MescCliError> { - if mesc::is_mesc_enabled() { - println!(); - println!(" MESC is already enabled"); - println!(" Using path {}", mesc::load::get_config_path()?.green().bold()); - println!(); - } else if let Some(config_write_mode) = config_write_mode { - match config_write_mode { - ConfigWriteMode::Path(path) => { - println!(" MESC not yet enabled, but will write config to {}", path.green().bold()) - } - ConfigWriteMode::Env(_) => { - println!(" ENV mode not yet available in the interactive cli") - } - }; - } else { - let options = - vec!["Store MESC config in a file", "Store MESC config in an environment variable"]; - let prompt = "How do you want to store your MESC config?"; - match inquire::Select::new(prompt, options).prompt() { - Ok("Store MESC config in a file") => { - let prompt = "Where should mesc.json file be saved? (enter a directory path)"; - let parent = match inquire::Text::new(prompt).prompt() { - Ok(parent) => { - let parent = if parent.trim().is_empty() { - ".".to_string() - } else { - mesc::load::expand_path(parent)? - }; - std::path::PathBuf::from(parent) - } - Err(InquireError::OperationCanceled) => return Ok(()), - Err(_) => return Err(MescCliError::InvalidInput("invalid input".to_string())), - }; - let path: String = parent.join("mesc.json").to_string_lossy().to_string(); - *config_write_mode = Some(ConfigWriteMode::Path(path.to_string())); - println!( - " Insert this line into your {} and {} files:", - "~/.bashrc".green().bold(), - "~/.profile".green().bold() - ); - println!(" {}{}", "MESC_PATH=".green().bold(), path.green().bold()); - println!(" Then restart your terminal shell"); - } - Ok("Store MESC config in an environment variable") => { - println!(" This is not available in the interactive MESC cli yet"); - } - Err(InquireError::OperationCanceled) => {} - _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), - } - } - - Ok(()) -} - -#[derive(Clone)] -enum ConfigWriteMode { - /// file path of JSON config file - Path(String), - /// list of config files to write to - Env(Vec), -} - -fn get_config_write_mode() -> Result, MescCliError> { - if let Ok(path) = mesc::load::get_config_path() { - return Ok(Some(ConfigWriteMode::Path(path))); - }; - - let prompt = "How do you want to save the config?"; - let options = ["Save as path file", "Save as an environment variable"].to_vec(); - loop { - let write_mode = match inquire::Select::new(prompt, options.clone()).prompt() { - Ok("Save as path file") => { - let prompt = "Where should mesc.json file be saved? (enter a directory path)"; - let parent = match inquire::Text::new(prompt).prompt() { - Ok(parent) => { - let parent = if parent.trim().is_empty() { - ".".to_string() - } else { - mesc::load::expand_path(parent)? - }; - std::path::PathBuf::from(parent) - } - Err(InquireError::OperationCanceled) => return Ok(None), - Err(_) => return Err(MescCliError::InvalidInput("invalid input".to_string())), - }; - let path: String = parent.join("mesc.json").to_string_lossy().to_string(); - Some(ConfigWriteMode::Path(path.to_string())) - } - Ok("Save an environment variable") => { - println!("not supported yet"); - continue; - } - Err(InquireError::OperationCanceled) => return Ok(None), - _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), - }; - return Ok(write_mode); - } -} - -fn is_ip(url: &str) -> bool { - use std::net::{Ipv4Addr, Ipv6Addr}; - if url.is_empty() { - return false; - } - let domain = match url.split_once('/') { - Some((domain, _)) => domain, - None => url, - }; - let domain = domain.split(':').next().unwrap_or(""); - domain.parse::().is_ok() || domain.parse::().is_ok() -} - -async fn add_endpoint(config: &mut RpcConfig) -> Result<(), MescCliError> { - let url = match inquire::Text::new("New endpoint URL?").prompt() { - Ok(input) => input, - Err(InquireError::OperationCanceled) => return Ok(()), - Err(_) => return Err(MescCliError::InvalidInput("invalid input".to_string())), - }; - - // add transport protocol - let url = if !url.starts_with("http") & !url.starts_with("ws") & !url.ends_with(".ipc") { - if url.starts_with("localhost") | is_ip(&url) { - let url = format!("http://{}", url); - println!( - " Transport protocol not included. Defaulting to http: {}", - url.green().bold() - ); - url - } else { - let url = format!("https://{}", url); - println!( - " Transport protocol not included. Defaulting to https: {}", - url.green().bold() - ); - url - } - } else { - url - }; - - // get chain_id - println!(" Querying chain id..."); - let client = reqwest::Client::builder().timeout(std::time::Duration::from_secs(4)).build()?; - let chain_id = crate::rpc::request_chain_id(client, url.clone()).await; - let chain_id = match chain_id { - Ok(chain_id) => { - println!(" {} {}", "Using chain_id".bold(), chain_id.as_str().green()); - Some(chain_id) - } - _ => { - println!(" {}", "Could not detect chain id".red()); - select_chain_id("How to proceed?".to_string()).await? - } - }; - - // get name - let default_name = mesc::overrides::get_default_endpoint_name(&url, chain_id.clone()); - let mut input = inquire::Text::new("New endpoint name?"); - if let Some(default_name) = default_name.as_ref() { - input = input.with_default(default_name); - } - let name = match input.prompt() { - Ok(choice) => choice, - Err(InquireError::OperationCanceled) => return Ok(()), - Err(_) => return Err(MescCliError::InvalidInput("invalid input".to_string())), - }; - - // create endpoint - let endpoint = - Endpoint { url, name, chain_id, endpoint_metadata: std::collections::HashMap::new() }; - config.endpoints.insert(endpoint.name.clone(), endpoint); - println!(" {}", "New endpoint added".bold()); - Ok(()) -} - -async fn select_chain_id(prompt: String) -> Result, MescCliError> { - let options = vec![ - "Search known network names", - "Enter endpoint chain id manually", - "Do not use a chain id for this endpoint", - ]; - loop { - match inquire::Select::new(prompt.as_str(), options.clone()).prompt() { - Ok("Do not use a chain id for this endpoint") => return Ok(None), - Ok("Enter endpoint chain id manually") => { - match inquire::Text::new("Chain id?").prompt() { - Ok(text) => { - match text.try_into_chain_id() { - Ok(chain_id) => return Ok(Some(chain_id)), - _ => continue, - }; - } - Err(InquireError::OperationCanceled) => return Ok(None), - _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), - } - } - Ok("Search known network names") => { - println!( - " Fetching network names from {}...", - "https://chainid.network".green().bold() - ); - match select_chain_id_by_name().await { - Ok(Some(chain_id)) => return Ok(Some(chain_id)), - Ok(None) => return Ok(None), - _ => { - println!(" Exiting without saving"); - std::process::exit(0); - } - } - } - Err(InquireError::OperationCanceled) => return Ok(None), - _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), - } - } -} - -async fn modify_endpoint(config: &mut RpcConfig) -> Result<(), MescCliError> { - // select endpoint - let mut options: Vec = config.endpoints.clone().into_keys().collect(); - options.sort(); - let endpoint_name = match inquire::Select::new("Which endpoint to modify?", options).prompt() { - Ok(name) => name, - Err(InquireError::OperationCanceled) => return Ok(()), - _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), - }; - let endpoint = match config.endpoints.get(&endpoint_name) { - Some(endpoint) => endpoint.clone(), - None => return Err(MescCliError::InvalidInput("endpoint does not exist".to_string())), - }; - println!(" {}", "Current endpoint data:".bold(),); - println!(); - let colored = colored_json::to_colored_json_auto(&serde_json::to_value(&endpoint)?)?; - for line in colored.split('\n') { - println!(" {}", line); - } - println!(); - - // gather modifications - let halt_options: HashSet<&str> = vec!["Delete endpoint", "Done"].into_iter().collect(); - let mut option = query_modify_endpoint(endpoint_name.clone(), config, true).await?; - loop { - if halt_options.contains(option.as_str()) { - break; - } - option = query_modify_endpoint(endpoint_name.clone(), config, false).await?; - } - - // commit modifications - if option != "Delete endpoint" { - let new_endpoint = match config.endpoints.get(&endpoint_name) { - Some(endpoint) => endpoint.clone(), - None => return Err(MescCliError::InvalidInput("endpoint does not exist".to_string())), - }; - if new_endpoint == endpoint { - println!(" Endpoint unmodified"); - } else { - println!(" {}", "New endpoint data:".bold(),); - println!(); - let colored = colored_json::to_colored_json_auto(&serde_json::to_value(endpoint)?)?; - for line in colored.split('\n') { - println!(" {}", line); - } - println!(); - } - } - - Ok(()) -} - -async fn query_modify_endpoint( - endpoint_name: String, - config: &mut RpcConfig, - first_change: bool, -) -> Result { - let options = [ - "Modify endpoint name", - "Modify endpoint url", - "Modify endpoint chain_id", - "Modify endpoint metadata", - "Delete endpoint", - "Print endpoint as JSON", - "Done", - ] - .to_vec(); - - let message = if first_change { "How to modify endpoint?" } else { "Any other modifications?" }; - - let option = match inquire::Select::new(message, options.clone()).prompt() { - Ok(answer) => answer, - Err(InquireError::OperationCanceled) => return Ok("Done".to_string()), - _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), - }; - - match option { - "Modify endpoint name" => { - let new_name = match inquire::Text::new("New name?").prompt() { - Ok(answer) => answer, - Err(InquireError::OperationCanceled) => return Ok("Done".to_string()), - _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), - }; - mesc::write::update_endpoint_name(config, endpoint_name.as_str(), new_name.as_str())?; - } - "Modify endpoint url" => { - let new_url = match inquire::Text::new("New url?").prompt() { - Ok(answer) => answer, - Err(InquireError::OperationCanceled) => return Ok("Done".to_string()), - _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), - }; - if let Some(endpoint) = config.endpoints.get_mut(&endpoint_name) { - endpoint.url = new_url; - } - } - "Modify endpoint chain_id" => { - match select_chain_id("New chain_id?".to_string()).await { - Ok(Some(chain_id)) => mesc::write::update_endpoint_chain_id( - config, - endpoint_name.as_str(), - chain_id.clone(), - )?, - Ok(None) => return Ok("Done".to_string()), - _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), - }; - } - "Modify endpoint metadata" => modify_endpoint_metadata(endpoint_name.as_str(), config)?, - "Delete endpoint" => { - mesc::write::delete_endpoint(config, endpoint_name.as_str())?; - println!("{} {}", "Deleted endpoint:".red(), endpoint_name.green()); - } - "Print endpoint as JSON" => { - let endpoint = match config.endpoints.get(&endpoint_name) { - Some(endpoint) => endpoint.clone(), - None => { - return Err(MescCliError::InvalidInput("endpoint does not exist".to_string())) - } - }; - println!(" {}", "Current endpoint data:".bold(),); - println!(); - let colored = colored_json::to_colored_json_auto(&serde_json::to_value(endpoint)?)?; - for line in colored.split('\n') { - println!(" {}", line); - } - println!(); - } - "Done" => {} - _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), - }; - - Ok(option.to_string()) -} - -fn modify_endpoint_metadata( - endpoint_name: &str, - config: &mut RpcConfig, -) -> Result<(), MescCliError> { - let endpoint = match config.endpoints.get_mut(endpoint_name) { - Some(endpoint) => endpoint, - None => { - return Err(MescCliError::InvalidInput(format!("missing endpoint: {}", endpoint_name))) - } - }; - let options = vec![ - "Add label", - "Remove label", - "Set ratelimit", - "Set api key", - "Edit raw JSON", - "Done editing metadata", - ]; - match inquire::Select::new("How to modify metadata?", options).prompt() { - Ok("Add label") => { - let new_label = match inquire::Text::new("What is the new label?").prompt() { - Ok(new_label) => new_label, - Err(InquireError::OperationCanceled) => return Ok(()), - _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), - }; - if endpoint.endpoint_metadata.get_mut("labels").is_none() { - endpoint - .endpoint_metadata - .insert("labels".to_string(), serde_json::json!(Vec::::new())); - }; - let labels = endpoint.endpoint_metadata.get_mut("labels").unwrap(); - if let Some(array) = labels.as_array_mut() { - array.push(serde_json::Value::String(new_label)); - println!(" Added label") - } else { - println!("Incorrectly formatted data, labels is not a list"); - }; - } - Ok("Remove label") => { - match endpoint.endpoint_metadata.get_mut("labels") { - Some(serde_json::Value::Array(labels)) => { - let label_strings: Vec<&str> = - labels.iter().filter_map(|val| val.as_str()).collect(); - if label_strings.is_empty() { - println!("No labels for endpoint"); - return Ok(()); - }; - match inquire::Select::new("Which label to remove?", label_strings.clone()) - .prompt() - { - Ok(label) => { - if let Some(index) = - label_strings.iter().position(|test_label| test_label == &label) - { - labels.remove(index); - } else { - println!("Label not found."); - } - } - Err(InquireError::OperationCanceled) => return Ok(()), - _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), - } - } - Some(_) => { - println!("Incorrectly formatted data, labels is not a list"); - } - None => { - println!(" Endpoint does not have any labels") - } - }; - } - Ok("Set ratelimit") => { - let message = "What is the rate limit, in requests per second?"; - let value = match inquire::CustomType::::new(message) - .with_formatter(&|i| format!("{:.2}", i)) - .with_error_message("Please type a valid number") - .with_help_message(" Enter the number of requests per seconds") - .prompt() - { - Ok(value) => value, - Err(InquireError::OperationCanceled) => return Ok(()), - _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), - }; - endpoint - .endpoint_metadata - .insert("rate_limit_rps".to_string(), serde_json::json!(value)); - } - Ok("Set api key") => { - let api_key = match inquire::Text::new("What is the api key?").prompt() { - Ok(api_key) => api_key, - Err(InquireError::OperationCanceled) => return Ok(()), - _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), - }; - endpoint.endpoint_metadata.insert("api_key".to_string(), serde_json::json!(api_key)); - } - Ok("Edit raw JSON") => { - let edited = edit::edit(serde_json::to_string(&endpoint.endpoint_metadata)?)?; - let value: Result, serde_json::Error> = - serde_json::from_str(&edited); - endpoint.endpoint_metadata = value?; - } - Ok("Done editing metadata") => return Ok(()), - Err(InquireError::OperationCanceled) => return Ok(()), - _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), - } - Ok(()) -} - -async fn modify_global_metadata(config: &mut RpcConfig) -> Result<(), MescCliError> { - let options = - vec!["Modify raw global metadata JSON", "Edit custom network names", "Back to main menu"]; - match inquire::Select::new("What do you want to do?", options).prompt() { - Ok("Modify raw global metadata JSON") => { - let old_metadata = serde_json::to_string(&config.global_metadata)?; - let new_metadata = edit::edit(&old_metadata)?; - if old_metadata == new_metadata { - println!(" {}", "Global metadata unchanged".bold()); - } else { - let value: Result, serde_json::Error> = - serde_json::from_str(&new_metadata); - config.global_metadata = value?; - println!(" {}", "Global metadata updated".bold()); - } - Ok(()) - } - Ok("Edit custom network names") => modify_custom_network_names(config).await, - Ok("Back to main menu") => Ok(()), - Err(InquireError::OperationCanceled) => Ok(()), - _ => Err(MescCliError::InvalidInput("invalid input".to_string())), - } -} - -async fn modify_custom_network_names(config: &mut RpcConfig) -> Result<(), MescCliError> { - print_custom_network_names(config); - - loop { - let options = if config.network_names.is_empty() { - vec![ - "Add custom network name", - "Print custom network names", - "Done editing custom names", - ] - } else { - vec![ - "Add custom network name", - "Edit custom network name", - "Remove custom network name", - "Print custom network names", - "Done editing custom names", - ] - }; - match inquire::Select::new("What do you want to do?", options).prompt() { - Ok("Add custom network name") => { - let name = match inquire::Text::new("Custom network name?").prompt() { - Ok(name) => name, - Err(InquireError::OperationCanceled) => continue, - _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), - }; - loop { - match inquire::Text::new("What is the chain id?").prompt() { - Ok(chain_id) => match chain_id.try_into_chain_id() { - Ok(chain_id) => { - config.network_names.insert(name.clone(), chain_id); - println!(" Custom network name added"); - break; - } - _ => { - println!(" not a valid chain id"); - continue; - } - }, - Err(InquireError::OperationCanceled) => break, - _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), - } - } - } - Ok("Edit custom network name") => match select_custom_network_name(config) { - Ok(Some(old_name)) => match inquire::Text::new("New name?").prompt() { - Ok(new_name) => match config.network_names.remove(&old_name) { - Some(chain_id) => { - config.network_names.insert(new_name, chain_id); - } - None => continue, - }, - Err(InquireError::OperationCanceled) => return Ok(()), - _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), - }, - Ok(None) => return Ok(()), - _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), - }, - Ok("Remove custom network name") => match select_custom_network_name(config) { - Ok(Some(name)) => { - config.network_names.remove(&name); - println!(" Name removed"); - } - Ok(None) => return Ok(()), - _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), - }, - Ok("Print custom network names") => print_custom_network_names(config), - Ok("Done editing custom names") => return Ok(()), - Err(InquireError::OperationCanceled) => return Ok(()), - _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), - } - } -} - -fn print_custom_network_names(config: &RpcConfig) { - if config.network_names.is_empty() { - println!(" No custom network names currently being used"); - } else { - println!( - " {} custom network names currently being used:", - config.network_names.len().to_string().green().bold() - ); - for (network_name, chain_id) in config.network_names.iter() { - println!(" - {} = {}", network_name.bold(), chain_id.as_str().green().bold()); - } - }; -} - -fn select_custom_network_name(config: &RpcConfig) -> Result, MescCliError> { - let names: Vec<_> = config.network_names.keys().collect(); - if names.is_empty() { - return Ok(None); - } - match inquire::Select::new("Which custom name?", names).prompt() { - Ok(name) => Ok(Some(name.clone())), - Err(InquireError::OperationCanceled) => Ok(None), - _ => Err(MescCliError::InvalidInput("invalid input".to_string())), - } -} - -fn modify_defaults(config: &mut RpcConfig) -> Result<(), MescCliError> { - println!(" Current defaults:"); - println!(); - print_defaults(config)?; - println!(); - - let options = [ - "Set the default endpoint", - "Set the default endpoint for network", - "Add new profile", - "Modify existing profile", - "Print current defaults", - "Done modifying defaults", - ] - .to_vec(); - - loop { - match inquire::Select::new("Which defaults do you want to modify?", options.clone()) - .prompt() - { - Ok("Set the default endpoint") => { - let prompt = "Which endpoint should be the default?"; - let endpoint_name = match select_endpoint(config, prompt)? { - Some(value) => value, - _ => return Ok(()), - }; - config.default_endpoint = Some(endpoint_name.clone()); - if let Some(endpoint) = - mesc::query::get_endpoint_by_name(config, endpoint_name.as_str())? - { - if let Some(chain_id) = endpoint.chain_id { - config.network_defaults.insert(chain_id, endpoint_name); - }; - } - } - Ok("Set the default endpoint for network") => { - let prompt = "Set the default endpoint for which network?"; - let chain_id = match select_config_chain_id(config, prompt)? { - Some(value) => value, - _ => return Ok(()), - }; - let prompt = "What should be the default endpoint for this network?"; - let endpoint_name = match select_endpoint_of_network(config, &chain_id, prompt)? { - Some(value) => value, - _ => return Ok(()), - }; - config.network_defaults.insert(chain_id, endpoint_name); - } - Ok("Add new profile") => { - let name = match inquire::Text::new("Name?").prompt() { - Ok(answer) => answer, - Err(InquireError::OperationCanceled) => return Ok(()), - _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), - }; - if config.profiles.contains_key(&name) { - println!(); - } else { - config.profiles.insert(name.clone(), mesc::Profile::new(name)); - println!(" profile added"); - } - } - Ok("Modify existing profile") => { - if config.profiles.is_empty() { - println!(" no profiles are currently configured"); - continue; - } - - let profile_name = match select_profile(config, "Which profile to modify?")? { - Some(value) => value, - _ => return Ok(()), - }; - let options = vec![ - "Set the profile's name", - "Set the profile's default endpoint", - "Set the profile's default endpoint for a network", - ]; - match inquire::Select::new("What to modify?", options).prompt() { - Ok("Set the profile's name") => { - let new_name = match inquire::Text::new("New name?").prompt() { - Ok(answer) => answer, - Err(InquireError::OperationCanceled) => return Ok(()), - _ => { - return Err(MescCliError::InvalidInput("invalid input".to_string())) - } - }; - if config.profiles.contains_key(&new_name) { - println!("profile with this name already exists"); - continue; - }; - if let Some(mut profile) = config.profiles.remove(&profile_name) { - profile.name = new_name.clone(); - config.profiles.insert(new_name, profile); - } else { - println!("profile not present"); - } - } - Ok("Set the profile's default endpoint") => { - let prompt = "Which endpoint to use as profile default?"; - let default_endpoint = match select_endpoint(config, prompt)? { - Some(value) => value, - _ => return Ok(()), - }; - if let Some(endpoint) = - mesc::query::get_endpoint_by_name(config, &default_endpoint)? - { - if let Some(profile) = config.profiles.get_mut(&profile_name) { - profile.default_endpoint = Some(default_endpoint.clone()); - if let Some(chain_id) = endpoint.chain_id.clone() { - profile.network_defaults.insert(chain_id, default_endpoint); - } - } else { - println!("profile not present"); - } - } - } - Ok("Set the profile's default endpoint for a network") => { - let prompt = "Set the profile's default endpoint for which network?"; - let chain_id = match select_config_chain_id(config, prompt)? { - Some(value) => value, - _ => return Ok(()), - }; - let prompt = "What should be the default endpoint for this network?"; - let endpoint_name = - match select_endpoint_of_network(config, &chain_id, prompt)? { - Some(value) => value, - _ => return Ok(()), - }; - if let Some(profile) = config.profiles.get_mut(&profile_name) { - profile.network_defaults.insert(chain_id, endpoint_name); - } else { - println!("profile not present"); - } - } - Err(InquireError::OperationCanceled) => return Ok(()), - _ => { - println!("invalid input"); - } - } - } - Ok("Print current defaults") => { - println!("Current defaults:"); - println!(); - print_defaults(config)?; - println!(); - } - Ok("Done modifying defaults") => return Ok(()), - Err(InquireError::OperationCanceled) => return Ok(()), - _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), - } - } -} - -fn select_endpoint(config: &RpcConfig, prompt: &str) -> Result, MescCliError> { - let mut options: Vec = config.endpoints.clone().into_keys().collect(); - options.sort(); - match inquire::Select::new(prompt, options).prompt() { - Ok(answer) => Ok(Some(answer)), - Err(InquireError::OperationCanceled) => Ok(None), - _ => Err(MescCliError::InvalidInput("invalid input".to_string())), - } -} - -fn select_endpoint_of_network( - config: &RpcConfig, - chain_id: &ChainId, - prompt: &str, -) -> Result, MescCliError> { - let mut options: Vec = config - .endpoints - .clone() - .values() - .filter(|endpoint| endpoint.chain_id.as_ref() == Some(chain_id)) - .map(|endpoint| endpoint.name.clone()) - .collect(); - options.sort(); - match inquire::Select::new(prompt, options).prompt() { - Ok(answer) => Ok(Some(answer)), - Err(InquireError::OperationCanceled) => Ok(None), - _ => Err(MescCliError::InvalidInput("invalid input".to_string())), - } -} - -fn select_profile(config: &RpcConfig, prompt: &str) -> Result, MescCliError> { - let mut options: Vec<_> = config.profiles.keys().collect(); - options.sort(); - match inquire::Select::new(prompt, options).prompt() { - Ok(answer) => Ok(Some(answer.to_string())), - Err(InquireError::OperationCanceled) => Ok(None), - _ => Err(MescCliError::InvalidInput("invalid input".to_string())), - } -} - -fn select_config_chain_id( - config: &RpcConfig, - prompt: &str, -) -> Result, MescCliError> { - let mut chain_ids: HashSet = HashSet::new(); - for endpoint in config.endpoints.values() { - if let Some(chain_id) = endpoint.chain_id.as_ref() { - chain_ids.insert(chain_id.clone()); - } - } - let mut sorted_chain_ids: Vec = chain_ids.into_iter().collect(); - sorted_chain_ids.sort_by_key(|chain_id| chain_id.to_hex_256().unwrap_or("".to_string())); - let options: Vec = sorted_chain_ids - .iter() - .map(|chain_id| match mesc::directory::get_network_name(chain_id) { - Some(name) => format!("{}) {}", chain_id.as_str(), name), - None => chain_id.to_string(), - }) - .collect(); - let input = match inquire::Select::new(prompt, options.clone()).prompt() { - Ok(answer) => answer, - Err(InquireError::OperationCanceled) => return Ok(None), - _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), - }; - match options.iter().position(|x| x == &input) { - Some(index) => Ok(Some(sorted_chain_ids.remove(index))), - None => Err(MescCliError::Error("invalid input".to_string())), - } -} - -async fn select_chain_id_by_name() -> Result, MescCliError> { - let network_list = match crate::network::fetch_network_list().await { - Ok(mapping) => mapping, - Err(_) => { - println!(" could not retrieve network list"); - return Ok(None); - } - }; - let mut pairs: Vec<(ChainId, String)> = network_list.into_iter().collect(); - pairs.sort_by_key(|(chain_id, _)| { - chain_id.to_hex_256().unwrap_or(chain_id.as_str().to_string()) - }); - - let options: Vec<_> = - pairs.iter().map(|(chain_id, name)| format!("{}) {}", chain_id, name)).collect(); - let mut render_config = get_render_config(); - render_config.option_index_prefix = IndexPrefix::None; - match inquire::Select::new("Which network?", options.clone()) - .with_render_config(render_config) - .prompt() - { - Ok(answer) => match options.iter().position(|option| option == &answer) { - Some(index) => match pairs.get(index) { - Some((chain_id, _)) => Ok(Some(chain_id.clone())), - None => Ok(None), - }, - None => Err(MescCliError::InvalidInput("bad input".to_string())), - }, - Err(InquireError::OperationCanceled) => Ok(None), - _ => Err(MescCliError::Error("invalid input".to_string())), - } -} - -fn get_render_config() -> RenderConfig { - let highlight_color = Color::DarkGreen; - - let mut render_config = RenderConfig::default(); - render_config.prompt = StyleSheet::new().with_attr(Attributes::BOLD); - render_config.prompt_prefix = Styled::new("").with_fg(Color::LightRed); - render_config.answered_prompt_prefix = Styled::new("").with_fg(Color::LightRed); - render_config.placeholder = StyleSheet::new().with_fg(Color::LightRed); - render_config.selected_option = Some(StyleSheet::new().with_fg(highlight_color)); - render_config.highlighted_option_prefix = Styled::new("→").with_fg(highlight_color); - render_config.selected_checkbox = Styled::new("☑").with_fg(highlight_color); - render_config.scroll_up_prefix = Styled::new("⇞"); - render_config.scroll_down_prefix = Styled::new("⇟"); - render_config.unselected_checkbox = Styled::new("☐"); - render_config.option_index_prefix = IndexPrefix::Simple; - render_config.error_message = - render_config.error_message.with_prefix(Styled::new("❌").with_fg(Color::LightRed)); - render_config.answer = StyleSheet::new().with_attr(Attributes::BOLD).with_fg(highlight_color); - let grey = Color::Rgb { r: 100, g: 100, b: 100 }; - render_config.help_message = StyleSheet::new().with_fg(grey).with_attr(Attributes::ITALIC); - - render_config -} diff --git a/rust/crates/mesc_cli/src/cli/subcommands/setup/command.rs b/rust/crates/mesc_cli/src/cli/subcommands/setup/command.rs new file mode 100644 index 0000000..087e104 --- /dev/null +++ b/rust/crates/mesc_cli/src/cli/subcommands/setup/command.rs @@ -0,0 +1,229 @@ +use crate::{MescCliError, SetupArgs}; +use mesc::{MescError, RpcConfig}; +use toolstr::Colorize; + +use super::{config_modification::*, inquire_utils::*, selectors::*, shell_config::*, writing::*}; + +pub(crate) async fn setup_command(args: SetupArgs) -> Result<(), MescCliError> { + inquire::set_global_render_config(get_render_config()); + if args.editor { + edit_config_in_editor(args) + } else { + let mode = get_write_mode()?; + let config = load_config_data(&mode)?; + println!( + " Current config has {} endpoints and {} profiles", + config.endpoints.len().to_string().green(), + config.profiles.len().to_string().green() + ); + println!(); + modify_existing_config(config, Some(mode)).await + } +} + +/// edit MESC config in editor instead of interactive menus +fn edit_config_in_editor(args: SetupArgs) -> Result<(), MescCliError> { + if let Some(path) = args.path { + edit::edit_file(path)? + } else if let Ok(mesc::ConfigMode::Path) = mesc::load::get_config_mode() { + let path = mesc::load::get_config_path()?; + edit::edit_file(path)? + } else { + return Err(MescCliError::Error("no file to edit".to_string())); + }; + Ok(()) +} + +/// get write mode for config +fn get_write_mode() -> Result { + match ( + std::env::var("MESC_MODE").as_deref(), + std::env::var("MESC_PATH").as_deref(), + std::env::var("MESC_ENV").as_deref(), + !mesc::overrides::get_active_overrides().is_empty(), + ) { + (Ok("DISABLED"), _, _, _) => { + println!(" MESC is disabled because {}", "MESC_MODE=DISABLED".green().bold()); + println!( + " To enable MESC, set {} to {} or {} or unset it", + "MESC_MODE".green().bold(), + "PATH".green().bold(), + "ENV".green().bold() + ); + let config_mode = select_config_mode()?; + setup_mesc_mode_env_var(&config_mode)?; + setup_mesc_env_vars(&config_mode)?; + Ok(config_mode) + } + (Ok("PATH"), Ok(path), _, _) | (Err(_), Ok(path), _, _) => { + let path = mesc::load::expand_path(path)?; + println!(" MESC is {}", "enabled".green().bold()); + let print_path = + if let Ok(raw_path) = std::env::var("MESC_PATH") { raw_path } else { path.clone() }; + println!(" Using {}{}", "MESC_PATH=".green().bold(), print_path.green().bold()); + + Ok(ConfigWriteMode::Path(path.into())) + } + (Ok("PATH"), Err(_), _, _) => { + println!(" MESC is enabled"); + println!( + " Using {}, but {} is not set", + "MESC_MODE=PATH".green().bold(), + "MESC_PATH".green().bold() + ); + let path = select_config_path()?; + println!(" Using config path: {}", path.to_string_lossy().green().bold()); + setup_mesc_path_env_var(&path)?; + Ok(ConfigWriteMode::Path(path)) + } + (Ok("ENV"), _, Ok(_env), _) | (Err(_), Err(_), Ok(_env), _) => { + println!(" MESC is enabled"); + println!(" Using {}", "MESC_MODE=ENV".green().bold()); + Ok(ConfigWriteMode::Env(vec![])) + } + (Ok("ENV"), _, Err(_), _) => { + println!(" MESC is enabled"); + println!( + " Using {}, but {} is not set", + "MESC_MODE=ENV".green().bold(), + "MESC_ENV".green().bold() + ); + Ok(ConfigWriteMode::Env(vec![])) + } + (Ok(other), _, _, _) => { + eprintln!("Invaild value for {}: {}", "MESC_MODE".green().bold(), other.green().bold()); + eprintln!( + "Either 1) unset this variable, or 2) set it to one of {{PATH, ENV, DISABLED}}" + ); + Err(MescCliError::Error("invalid MESC_MODE".to_string())) + } + (Err(_), Err(_), Err(_), true) => { + println!(" MESC is only enabled because overrides are set:"); + for var_name in mesc::overrides::get_active_overrides().iter() { + println!("- {}", var_name.bold().green()) + } + println!( + " To enable MESC more permanently, set either {} or {}", + "MESC_PATH".green().bold(), + "MESC_ENV".green().bold() + ); + let mode = select_config_mode()?; + setup_mesc_env_vars(&mode)?; + Ok(mode) + } + (Err(_), Err(_), Err(_), false) => { + println!(" MESC is disabled because no MESC env vars are set"); + println!(" To enabled MESC, set one of the MESC env vars"); + let mode = select_config_mode()?; + setup_mesc_env_vars(&mode)?; + Ok(mode) + } + } +} + +/// load config data based on write mode +fn load_config_data(mode: &ConfigWriteMode) -> Result { + // attempt to load config data + let config = match mode { + ConfigWriteMode::Path(path) => { + // if path DNE that is ok, just start from scratch + // if invalid json, or other io error, ask to start from scratch break + let option_path = Some(path.to_string_lossy().into()); + match mesc::load::load_file_config(option_path) { + Ok(config) => Ok(config), + Err(MescError::MissingConfigFile(_)) => { + let config = RpcConfig::default(); + let prompt = "Config file does not exist, do you want to create one?"; + match inquire::Confirm::new(prompt).with_default(true).prompt() { + Ok(true) => { + mesc::write::write_config(config.clone(), path)?; + println!( + " Created blank config at {}", + path.to_string_lossy().bold().green() + ); + } + Ok(false) => { + println!(" Starting from blank config. Use \"Exit and save changes\" below to save"); + } + Err(_) => std::process::exit(1), + } + Ok(config) + } + Err(e) => Err(e), + } + } + ConfigWriteMode::Env(_) => { + // if env unset that is ok, just start from scratch + // if invalid json, ask to start from scratch, or break + match std::env::var("MESC_ENV") { + Ok(val) if !val.is_empty() => mesc::load::load_env_config(), + _ => { + println!(" {} var is empty, using blank config", "MESC_ENV".green().bold()); + Ok(RpcConfig::default()) + } + } + } + }; + + // create new config upon loading error + let config = match config { + Ok(config) => config, + Err(e) => { + eprintln!("Could not load config data: {}", format!("{}", e).red()); + let prompt = "How do you want to procede?"; + let options = vec!["Start a new config from scratch", "Exit setup"]; + match inquire::Select::new(prompt, options).prompt() { + Ok("Start a new config from scratch") => RpcConfig::default(), + _ => std::process::exit(1), + } + } + }; + + // ensure that config data is valid + let mut config = config.clone(); + loop { + match config.validate() { + Ok(()) => break, + Err(e) => { + eprintln!("Config data is not valid: {}", format!("{}", e).red()); + let prompt = "What do you want to do?"; + let options = + vec!["Create new config from scratch", "Edit the data manually", "Exit setup"]; + match inquire::Select::new(prompt, options).prompt() { + Ok("Create new config from scratch") => config = RpcConfig::default(), + Ok("Edit the data manually") => { + let new_config = edit::edit(serde_json::to_string(&config)?)?; + if let Ok(new_config) = serde_json::from_str(new_config.as_str()) { + config = new_config + } + } + Ok("Exit setup") | Ok(_) | Err(_) => std::process::exit(1), + } + } + }; + } + + Ok(config) +} + +fn setup_mesc_mode_env_var(mode: &ConfigWriteMode) -> Result<(), MescCliError> { + let value = match mode { + ConfigWriteMode::Path(_) => "PATH", + ConfigWriteMode::Env(_) => "ENV", + }; + modify_shell_config_var("MESC_MODE", value.to_string(), None)?; + Ok(()) +} + +fn setup_mesc_env_vars(mode: &ConfigWriteMode) -> Result<(), MescCliError> { + match mode { + ConfigWriteMode::Path(path) => setup_mesc_path_env_var(path), + ConfigWriteMode::Env(_) => Ok(()), + } +} + +fn setup_mesc_path_env_var(path: &std::path::Path) -> Result<(), MescCliError> { + let value = path.to_string_lossy().to_string(); + modify_shell_config_var("MESC_PATH", value, None)?; + Ok(()) +} diff --git a/rust/crates/mesc_cli/src/cli/subcommands/setup/config_modification.rs b/rust/crates/mesc_cli/src/cli/subcommands/setup/config_modification.rs new file mode 100644 index 0000000..7d564f5 --- /dev/null +++ b/rust/crates/mesc_cli/src/cli/subcommands/setup/config_modification.rs @@ -0,0 +1,74 @@ +use crate::MescCliError; +use inquire::InquireError; +use mesc::RpcConfig; + +use super::{defaults::*, endpoints::*, metadata::*, writing::*}; +use toolstr::Colorize; + +pub(crate) async fn modify_existing_config( + config: RpcConfig, + config_write_mode: Option, +) -> Result<(), MescCliError> { + let options = [ + "Add new endpoint", + "Modify endpoint", + "Modify defaults", + "Modify global metadata", + "Print config as JSON", + "Exit and save changes", + "Exit without saving", + ] + .to_vec(); + let original_config = config.clone(); + let mut valid_config = config.clone(); + let mut config = config.clone(); + loop { + // modify config + match inquire::Select::new("What do you want to do?", options.clone()) + .with_page_size(10) + .prompt() + { + Ok("Add new endpoint") => add_endpoint(&mut config).await?, + Ok("Modify endpoint") => modify_endpoint(&mut config).await?, + Ok("Modify defaults") => modify_defaults(&mut config)?, + Ok("Modify global metadata") => modify_global_metadata(&mut config).await?, + Ok("Print config as JSON") => { + println!(); + println!("{}", colored_json::to_colored_json_auto(&config)?); + println!(); + } + Ok("Exit and save changes") => break, + Ok("Exit without saving") => return Ok(()), + Err(InquireError::OperationCanceled) => { + if config != original_config { + println!(" Exiting without saving"); + } else { + println!(" Exiting"); + } + std::process::exit(0) + } + Ok(_) | Err(_) => return Err(MescCliError::InvalidInput("invalid input".to_string())), + }; + + // validation + match config.validate() { + Ok(()) => {} + Err(e) => { + println!("Invalid data: {:?}", e); + println!("Reverting to previous config state"); + config = valid_config.clone(); + continue; + } + }; + + valid_config = config.clone(); + } + + // write file + if config != original_config { + write_config(config, config_write_mode)?; + } else { + println!(" {}", "No updates to save".bold()) + } + Ok(()) +} diff --git a/rust/crates/mesc_cli/src/cli/subcommands/setup/defaults.rs b/rust/crates/mesc_cli/src/cli/subcommands/setup/defaults.rs new file mode 100644 index 0000000..dfd2420 --- /dev/null +++ b/rust/crates/mesc_cli/src/cli/subcommands/setup/defaults.rs @@ -0,0 +1,156 @@ +use super::selectors::*; +use crate::{print_defaults, MescCliError}; +use inquire::InquireError; +use mesc::RpcConfig; + +pub(crate) fn modify_defaults(config: &mut RpcConfig) -> Result<(), MescCliError> { + println!(" Current defaults:"); + println!(); + print_defaults(config)?; + println!(); + + let options = [ + "Set the default endpoint", + "Set the default endpoint for network", + "Add new profile", + "Modify existing profile", + "Print current defaults", + "Done modifying defaults", + ] + .to_vec(); + + loop { + match inquire::Select::new("Which defaults do you want to modify?", options.clone()) + .prompt() + { + Ok("Set the default endpoint") => { + let prompt = "Which endpoint should be the default?"; + let endpoint_name = match select_endpoint(config, prompt)? { + Some(value) => value, + _ => return Ok(()), + }; + config.default_endpoint = Some(endpoint_name.clone()); + if let Some(endpoint) = + mesc::query::get_endpoint_by_name(config, endpoint_name.as_str())? + { + if let Some(chain_id) = endpoint.chain_id { + config.network_defaults.insert(chain_id, endpoint_name); + }; + } + } + Ok("Set the default endpoint for network") => { + let prompt = "Set the default endpoint for which network?"; + let chain_id = match select_config_chain_id(config, prompt)? { + Some(value) => value, + _ => return Ok(()), + }; + let prompt = "What should be the default endpoint for this network?"; + let endpoint_name = match select_endpoint_of_network(config, &chain_id, prompt)? { + Some(value) => value, + _ => return Ok(()), + }; + config.network_defaults.insert(chain_id, endpoint_name); + } + Ok("Add new profile") => { + let name = match inquire::Text::new("Name?").prompt() { + Ok(answer) => answer, + Err(InquireError::OperationCanceled) => return Ok(()), + _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), + }; + if config.profiles.contains_key(&name) { + println!(); + } else { + config.profiles.insert(name.clone(), mesc::Profile::new(name)); + println!(" profile added"); + } + } + Ok("Modify existing profile") => { + if config.profiles.is_empty() { + println!(" no profiles are currently configured"); + continue; + } + + let profile_name = match select_profile(config, "Which profile to modify?")? { + Some(value) => value, + _ => return Ok(()), + }; + let options = vec![ + "Set the profile's name", + "Set the profile's default endpoint", + "Set the profile's default endpoint for a network", + ]; + match inquire::Select::new("What to modify?", options).prompt() { + Ok("Set the profile's name") => { + let new_name = match inquire::Text::new("New name?").prompt() { + Ok(answer) => answer, + Err(InquireError::OperationCanceled) => return Ok(()), + _ => { + return Err(MescCliError::InvalidInput("invalid input".to_string())) + } + }; + if config.profiles.contains_key(&new_name) { + println!("profile with this name already exists"); + continue; + }; + if let Some(mut profile) = config.profiles.remove(&profile_name) { + profile.name = new_name.clone(); + config.profiles.insert(new_name, profile); + } else { + println!("profile not present"); + } + } + Ok("Set the profile's default endpoint") => { + let prompt = "Which endpoint to use as profile default?"; + let default_endpoint = match select_endpoint(config, prompt)? { + Some(value) => value, + _ => return Ok(()), + }; + if let Some(endpoint) = + mesc::query::get_endpoint_by_name(config, &default_endpoint)? + { + if let Some(profile) = config.profiles.get_mut(&profile_name) { + profile.default_endpoint = Some(default_endpoint.clone()); + if let Some(chain_id) = endpoint.chain_id.clone() { + profile.network_defaults.insert(chain_id, default_endpoint); + } + } else { + println!("profile not present"); + } + } + } + Ok("Set the profile's default endpoint for a network") => { + let prompt = "Set the profile's default endpoint for which network?"; + let chain_id = match select_config_chain_id(config, prompt)? { + Some(value) => value, + _ => return Ok(()), + }; + let prompt = "What should be the default endpoint for this network?"; + let endpoint_name = + match select_endpoint_of_network(config, &chain_id, prompt)? { + Some(value) => value, + _ => return Ok(()), + }; + if let Some(profile) = config.profiles.get_mut(&profile_name) { + profile.network_defaults.insert(chain_id, endpoint_name); + } else { + println!("profile not present"); + } + } + Err(InquireError::OperationCanceled) => return Ok(()), + _ => { + println!("invalid input"); + } + } + } + Ok("Print current defaults") => { + println!("Current defaults:"); + println!(); + print_defaults(config)?; + println!(); + } + Ok("Done modifying defaults") => return Ok(()), + Err(InquireError::OperationCanceled) => return Ok(()), + _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), + } + } +} diff --git a/rust/crates/mesc_cli/src/cli/subcommands/setup/endpoints.rs b/rust/crates/mesc_cli/src/cli/subcommands/setup/endpoints.rs new file mode 100644 index 0000000..30958fe --- /dev/null +++ b/rust/crates/mesc_cli/src/cli/subcommands/setup/endpoints.rs @@ -0,0 +1,207 @@ +use crate::{network::is_ip, MescCliError}; +use inquire::InquireError; +use mesc::{Endpoint, RpcConfig}; +use std::collections::{HashMap, HashSet}; +use toolstr::Colorize; + +use super::{metadata::*, selectors::*}; + +pub(crate) async fn add_endpoint(config: &mut RpcConfig) -> Result<(), MescCliError> { + let url = match inquire::Text::new("New endpoint URL?").prompt() { + Ok(input) => input, + Err(InquireError::OperationCanceled) => return Ok(()), + Err(_) => return Err(MescCliError::InvalidInput("invalid input".to_string())), + }; + + // add transport protocol + let url = if !url.starts_with("http") & !url.starts_with("ws") & !url.ends_with(".ipc") { + if url.starts_with("localhost") | is_ip(&url) { + let url = format!("http://{}", url); + println!( + " Transport protocol not included. Defaulting to http: {}", + url.green().bold() + ); + url + } else { + let url = format!("https://{}", url); + println!( + " Transport protocol not included. Defaulting to https: {}", + url.green().bold() + ); + url + } + } else { + url + }; + + // get chain_id + println!(" Querying chain id..."); + let client = reqwest::Client::builder().timeout(std::time::Duration::from_secs(4)).build()?; + let chain_id = crate::rpc::request_chain_id(client, url.clone()).await; + let chain_id = match chain_id { + Ok(chain_id) => { + println!(" {} {}", "Using chain_id".bold(), chain_id.as_str().green()); + Some(chain_id) + } + _ => { + println!(" {}", "Could not detect chain id".red()); + select_chain_id("How to proceed?".to_string()).await? + } + }; + + // get name + let default_name = mesc::overrides::get_default_endpoint_name(&url, chain_id.clone()); + let mut input = inquire::Text::new("New endpoint name?"); + if let Some(default_name) = default_name.as_ref() { + input = input.with_default(default_name); + } + let name = match input.prompt() { + Ok(choice) => choice, + Err(InquireError::OperationCanceled) => return Ok(()), + Err(_) => return Err(MescCliError::InvalidInput("invalid input".to_string())), + }; + + // create endpoint + let endpoint = Endpoint { url, name, chain_id, endpoint_metadata: HashMap::new() }; + config.endpoints.insert(endpoint.name.clone(), endpoint); + println!(" {}", "New endpoint added".bold()); + Ok(()) +} + +pub(crate) async fn modify_endpoint(config: &mut RpcConfig) -> Result<(), MescCliError> { + // select endpoint + let mut options: Vec = config.endpoints.clone().into_keys().collect(); + if options.is_empty() { + println!(" No endpoints to modify"); + return Ok(()) + } + options.sort(); + let endpoint_name = match inquire::Select::new("Which endpoint to modify?", options).prompt() { + Ok(name) => name, + Err(InquireError::OperationCanceled) => return Ok(()), + _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), + }; + let endpoint = match config.endpoints.get(&endpoint_name) { + Some(endpoint) => endpoint.clone(), + None => return Err(MescCliError::InvalidInput("endpoint does not exist".to_string())), + }; + println!(" {}", "Current endpoint data:".bold(),); + println!(); + let colored = colored_json::to_colored_json_auto(&serde_json::to_value(&endpoint)?)?; + for line in colored.split('\n') { + println!(" {}", line); + } + println!(); + + // gather modifications + let halt_options: HashSet<&str> = vec!["Delete endpoint", "Done"].into_iter().collect(); + let mut option = query_modify_endpoint(endpoint_name.clone(), config, true).await?; + loop { + if halt_options.contains(option.as_str()) { + break; + } + option = query_modify_endpoint(endpoint_name.clone(), config, false).await?; + } + + // commit modifications + if option != "Delete endpoint" { + let new_endpoint = match config.endpoints.get(&endpoint_name) { + Some(endpoint) => endpoint.clone(), + None => return Err(MescCliError::InvalidInput("endpoint does not exist".to_string())), + }; + if new_endpoint == endpoint { + println!(" Endpoint unmodified"); + } else { + println!(" {}", "New endpoint data:".bold(),); + println!(); + let colored = colored_json::to_colored_json_auto(&serde_json::to_value(endpoint)?)?; + for line in colored.split('\n') { + println!(" {}", line); + } + println!(); + } + } + + Ok(()) +} + +pub(crate) async fn query_modify_endpoint( + endpoint_name: String, + config: &mut RpcConfig, + first_change: bool, +) -> Result { + let options = [ + "Modify endpoint name", + "Modify endpoint url", + "Modify endpoint chain_id", + "Modify endpoint metadata", + "Delete endpoint", + "Print endpoint as JSON", + "Done", + ] + .to_vec(); + + let message = if first_change { "How to modify endpoint?" } else { "Any other modifications?" }; + + let option = match inquire::Select::new(message, options.clone()).prompt() { + Ok(answer) => answer, + Err(InquireError::OperationCanceled) => return Ok("Done".to_string()), + _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), + }; + + match option { + "Modify endpoint name" => { + let new_name = match inquire::Text::new("New name?").prompt() { + Ok(answer) => answer, + Err(InquireError::OperationCanceled) => return Ok("Done".to_string()), + _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), + }; + mesc::write::update_endpoint_name(config, endpoint_name.as_str(), new_name.as_str())?; + } + "Modify endpoint url" => { + let new_url = match inquire::Text::new("New url?").prompt() { + Ok(answer) => answer, + Err(InquireError::OperationCanceled) => return Ok("Done".to_string()), + _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), + }; + if let Some(endpoint) = config.endpoints.get_mut(&endpoint_name) { + endpoint.url = new_url; + } + } + "Modify endpoint chain_id" => { + match select_chain_id("New chain_id?".to_string()).await { + Ok(Some(chain_id)) => mesc::write::update_endpoint_chain_id( + config, + endpoint_name.as_str(), + chain_id.clone(), + )?, + Ok(None) => return Ok("Done".to_string()), + _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), + }; + } + "Modify endpoint metadata" => modify_endpoint_metadata(endpoint_name.as_str(), config)?, + "Delete endpoint" => { + mesc::write::delete_endpoint(config, endpoint_name.as_str())?; + println!("{} {}", "Deleted endpoint:".red(), endpoint_name.green()); + } + "Print endpoint as JSON" => { + let endpoint = match config.endpoints.get(&endpoint_name) { + Some(endpoint) => endpoint.clone(), + None => { + return Err(MescCliError::InvalidInput("endpoint does not exist".to_string())) + } + }; + println!(" {}", "Current endpoint data:".bold(),); + println!(); + let colored = colored_json::to_colored_json_auto(&serde_json::to_value(endpoint)?)?; + for line in colored.split('\n') { + println!(" {}", line); + } + println!(); + } + "Done" => {} + _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), + }; + + Ok(option.to_string()) +} diff --git a/rust/crates/mesc_cli/src/cli/subcommands/setup/inquire_utils.rs b/rust/crates/mesc_cli/src/cli/subcommands/setup/inquire_utils.rs new file mode 100644 index 0000000..789dfed --- /dev/null +++ b/rust/crates/mesc_cli/src/cli/subcommands/setup/inquire_utils.rs @@ -0,0 +1,25 @@ +use inquire::ui::{Attributes, Color, IndexPrefix, RenderConfig, StyleSheet, Styled}; + +pub(crate) fn get_render_config() -> RenderConfig { + let highlight_color = Color::DarkGreen; + + let mut render_config = RenderConfig::default(); + render_config.prompt = StyleSheet::new().with_attr(Attributes::BOLD); + render_config.prompt_prefix = Styled::new("").with_fg(Color::LightRed); + render_config.answered_prompt_prefix = Styled::new("").with_fg(Color::LightRed); + render_config.placeholder = StyleSheet::new().with_fg(Color::LightRed); + render_config.selected_option = Some(StyleSheet::new().with_fg(highlight_color)); + render_config.highlighted_option_prefix = Styled::new("→").with_fg(highlight_color); + render_config.selected_checkbox = Styled::new("☑").with_fg(highlight_color); + render_config.scroll_up_prefix = Styled::new("⇞"); + render_config.scroll_down_prefix = Styled::new("⇟"); + render_config.unselected_checkbox = Styled::new("☐"); + render_config.option_index_prefix = IndexPrefix::Simple; + render_config.error_message = + render_config.error_message.with_prefix(Styled::new("❌").with_fg(Color::LightRed)); + render_config.answer = StyleSheet::new().with_attr(Attributes::BOLD).with_fg(highlight_color); + let grey = Color::Rgb { r: 100, g: 100, b: 100 }; + render_config.help_message = StyleSheet::new().with_fg(grey).with_attr(Attributes::ITALIC); + + render_config +} diff --git a/rust/crates/mesc_cli/src/cli/subcommands/setup/metadata.rs b/rust/crates/mesc_cli/src/cli/subcommands/setup/metadata.rs new file mode 100644 index 0000000..d6fa6d4 --- /dev/null +++ b/rust/crates/mesc_cli/src/cli/subcommands/setup/metadata.rs @@ -0,0 +1,139 @@ +use crate::MescCliError; +use inquire::InquireError; +use mesc::RpcConfig; +use std::collections::HashMap; +use toolstr::Colorize; + +use super::network_names::*; + +pub(crate) fn modify_endpoint_metadata( + endpoint_name: &str, + config: &mut RpcConfig, +) -> Result<(), MescCliError> { + let endpoint = match config.endpoints.get_mut(endpoint_name) { + Some(endpoint) => endpoint, + None => { + return Err(MescCliError::InvalidInput(format!("missing endpoint: {}", endpoint_name))) + } + }; + let options = vec![ + "Add label", + "Remove label", + "Set ratelimit", + "Set api key", + "Edit raw JSON", + "Done editing metadata", + ]; + match inquire::Select::new("How to modify metadata?", options).prompt() { + Ok("Add label") => { + let new_label = match inquire::Text::new("What is the new label?").prompt() { + Ok(new_label) => new_label, + Err(InquireError::OperationCanceled) => return Ok(()), + _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), + }; + if endpoint.endpoint_metadata.get_mut("labels").is_none() { + endpoint + .endpoint_metadata + .insert("labels".to_string(), serde_json::json!(Vec::::new())); + }; + let labels = endpoint.endpoint_metadata.get_mut("labels").unwrap(); + if let Some(array) = labels.as_array_mut() { + array.push(serde_json::Value::String(new_label)); + println!(" Added label") + } else { + println!("Incorrectly formatted data, labels is not a list"); + }; + } + Ok("Remove label") => { + match endpoint.endpoint_metadata.get_mut("labels") { + Some(serde_json::Value::Array(labels)) => { + let label_strings: Vec<&str> = + labels.iter().filter_map(|val| val.as_str()).collect(); + if label_strings.is_empty() { + println!("No labels for endpoint"); + return Ok(()); + }; + match inquire::Select::new("Which label to remove?", label_strings.clone()) + .prompt() + { + Ok(label) => { + if let Some(index) = + label_strings.iter().position(|test_label| test_label == &label) + { + labels.remove(index); + } else { + println!("Label not found."); + } + } + Err(InquireError::OperationCanceled) => return Ok(()), + _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), + } + } + Some(_) => { + println!("Incorrectly formatted data, labels is not a list"); + } + None => { + println!(" Endpoint does not have any labels") + } + }; + } + Ok("Set ratelimit") => { + let message = "What is the rate limit, in requests per second?"; + let value = match inquire::CustomType::::new(message) + .with_formatter(&|i| format!("{:.2}", i)) + .with_error_message("Please type a valid number") + .with_help_message(" Enter the number of requests per seconds") + .prompt() + { + Ok(value) => value, + Err(InquireError::OperationCanceled) => return Ok(()), + _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), + }; + endpoint + .endpoint_metadata + .insert("rate_limit_rps".to_string(), serde_json::json!(value)); + } + Ok("Set api key") => { + let api_key = match inquire::Text::new("What is the api key?").prompt() { + Ok(api_key) => api_key, + Err(InquireError::OperationCanceled) => return Ok(()), + _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), + }; + endpoint.endpoint_metadata.insert("api_key".to_string(), serde_json::json!(api_key)); + } + Ok("Edit raw JSON") => { + let edited = edit::edit(serde_json::to_string(&endpoint.endpoint_metadata)?)?; + let value: Result, serde_json::Error> = + serde_json::from_str(&edited); + endpoint.endpoint_metadata = value?; + } + Ok("Done editing metadata") => return Ok(()), + Err(InquireError::OperationCanceled) => return Ok(()), + _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), + } + Ok(()) +} + +pub(crate) async fn modify_global_metadata(config: &mut RpcConfig) -> Result<(), MescCliError> { + let options = + vec!["Modify raw global metadata JSON", "Edit custom network names", "Back to main menu"]; + match inquire::Select::new("What do you want to do?", options).prompt() { + Ok("Modify raw global metadata JSON") => { + let old_metadata = serde_json::to_string(&config.global_metadata)?; + let new_metadata = edit::edit(&old_metadata)?; + if old_metadata == new_metadata { + println!(" {}", "Global metadata unchanged".bold()); + } else { + let value: Result, serde_json::Error> = + serde_json::from_str(&new_metadata); + config.global_metadata = value?; + println!(" {}", "Global metadata updated".bold()); + } + Ok(()) + } + Ok("Edit custom network names") => modify_custom_network_names(config).await, + Ok("Back to main menu") => Ok(()), + Err(InquireError::OperationCanceled) => Ok(()), + _ => Err(MescCliError::InvalidInput("invalid input".to_string())), + } +} diff --git a/rust/crates/mesc_cli/src/cli/subcommands/setup/mod.rs b/rust/crates/mesc_cli/src/cli/subcommands/setup/mod.rs new file mode 100644 index 0000000..80b49f4 --- /dev/null +++ b/rust/crates/mesc_cli/src/cli/subcommands/setup/mod.rs @@ -0,0 +1,12 @@ +mod command; +mod config_modification; +mod defaults; +mod endpoints; +mod inquire_utils; +mod metadata; +mod network_names; +mod selectors; +mod shell_config; +mod writing; + +pub(crate) use command::setup_command; diff --git a/rust/crates/mesc_cli/src/cli/subcommands/setup/network_names.rs b/rust/crates/mesc_cli/src/cli/subcommands/setup/network_names.rs new file mode 100644 index 0000000..f8c1375 --- /dev/null +++ b/rust/crates/mesc_cli/src/cli/subcommands/setup/network_names.rs @@ -0,0 +1,96 @@ +use crate::MescCliError; +use inquire::InquireError; +use mesc::{RpcConfig, TryIntoChainId}; +use toolstr::Colorize; + +use super::selectors::*; + +pub(crate) async fn modify_custom_network_names( + config: &mut RpcConfig, +) -> Result<(), MescCliError> { + print_custom_network_names(config); + + loop { + let options = if config.network_names.is_empty() { + vec![ + "Add custom network name", + "Print custom network names", + "Done editing custom names", + ] + } else { + vec![ + "Add custom network name", + "Edit custom network name", + "Remove custom network name", + "Print custom network names", + "Done editing custom names", + ] + }; + match inquire::Select::new("What do you want to do?", options).prompt() { + Ok("Add custom network name") => { + let name = match inquire::Text::new("Custom network name?").prompt() { + Ok(name) => name, + Err(InquireError::OperationCanceled) => continue, + _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), + }; + loop { + match inquire::Text::new("What is the chain id?").prompt() { + Ok(chain_id) => match chain_id.try_into_chain_id() { + Ok(chain_id) => { + config.network_names.insert(name.clone(), chain_id); + println!(" Custom network name added"); + break; + } + _ => { + println!(" not a valid chain id"); + continue; + } + }, + Err(InquireError::OperationCanceled) => break, + _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), + } + } + } + Ok("Edit custom network name") => match select_custom_network_name(config) { + Ok(Some(old_name)) => match inquire::Text::new("New name?").prompt() { + Ok(new_name) => match config.network_names.remove(&old_name) { + Some(chain_id) => { + config.network_names.insert(new_name, chain_id); + } + None => continue, + }, + Err(InquireError::OperationCanceled) => return Ok(()), + _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), + }, + Ok(None) => return Ok(()), + _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), + }, + Ok("Remove custom network name") => match select_custom_network_name(config) { + Ok(Some(name)) => { + config.network_names.remove(&name); + println!(" Name removed"); + } + Ok(None) => return Ok(()), + _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), + }, + Ok("Print custom network names") => print_custom_network_names(config), + Ok("Done editing custom names") => return Ok(()), + Err(InquireError::OperationCanceled) => return Ok(()), + _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), + } + } +} + +fn print_custom_network_names(config: &RpcConfig) { + if config.network_names.is_empty() { + println!(" No custom network names currently being used"); + } else { + println!( + " {} custom network names currently being used:", + config.network_names.len().to_string().green().bold() + ); + for (network_name, chain_id) in config.network_names.iter() { + println!(" - {} = {}", network_name.bold(), chain_id.as_str().green().bold()); + } + }; +} diff --git a/rust/crates/mesc_cli/src/cli/subcommands/setup/selectors.rs b/rust/crates/mesc_cli/src/cli/subcommands/setup/selectors.rs new file mode 100644 index 0000000..4996b2e --- /dev/null +++ b/rust/crates/mesc_cli/src/cli/subcommands/setup/selectors.rs @@ -0,0 +1,238 @@ +use crate::MescCliError; +use inquire::{ui::IndexPrefix, InquireError}; +use mesc::{ChainId, RpcConfig, TryIntoChainId}; +use std::collections::HashSet; +use toolstr::Colorize; + +use super::{inquire_utils::*, writing::*}; + +pub(crate) async fn select_chain_id(prompt: String) -> Result, MescCliError> { + let options = vec![ + "Search known network names", + "Enter endpoint chain id manually", + "Do not use a chain id for this endpoint", + ]; + loop { + match inquire::Select::new(prompt.as_str(), options.clone()).prompt() { + Ok("Do not use a chain id for this endpoint") => return Ok(None), + Ok("Enter endpoint chain id manually") => { + match inquire::Text::new("Chain id?").prompt() { + Ok(text) => { + match text.try_into_chain_id() { + Ok(chain_id) => return Ok(Some(chain_id)), + _ => continue, + }; + } + Err(InquireError::OperationCanceled) => return Ok(None), + _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), + } + } + Ok("Search known network names") => { + println!( + " Fetching network names from {}...", + "https://chainid.network".green().bold() + ); + match select_chain_id_by_name().await { + Ok(Some(chain_id)) => return Ok(Some(chain_id)), + Ok(None) => return Ok(None), + _ => { + println!(" Exiting without saving"); + std::process::exit(0); + } + } + } + Err(InquireError::OperationCanceled) => return Ok(None), + _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), + } + } +} + +pub(crate) async fn select_chain_id_by_name() -> Result, MescCliError> { + let network_list = match crate::network::fetch_network_list().await { + Ok(mapping) => mapping, + Err(_) => { + println!(" could not retrieve network list"); + return Ok(None); + } + }; + let mut pairs: Vec<(ChainId, String)> = network_list.into_iter().collect(); + pairs.sort_by_key(|(chain_id, _)| { + chain_id.to_hex_256().unwrap_or(chain_id.as_str().to_string()) + }); + + let options: Vec<_> = + pairs.iter().map(|(chain_id, name)| format!("{}) {}", chain_id, name)).collect(); + let mut render_config = get_render_config(); + render_config.option_index_prefix = IndexPrefix::None; + match inquire::Select::new("Which network?", options.clone()) + .with_render_config(render_config) + .prompt() + { + Ok(answer) => match options.iter().position(|option| option == &answer) { + Some(index) => match pairs.get(index) { + Some((chain_id, _)) => Ok(Some(chain_id.clone())), + None => Ok(None), + }, + None => Err(MescCliError::InvalidInput("bad input".to_string())), + }, + Err(InquireError::OperationCanceled) => Ok(None), + _ => Err(MescCliError::Error("invalid input".to_string())), + } +} + +pub(crate) fn select_custom_network_name( + config: &RpcConfig, +) -> Result, MescCliError> { + let names: Vec<_> = config.network_names.keys().collect(); + if names.is_empty() { + return Ok(None); + } + match inquire::Select::new("Which custom name?", names).prompt() { + Ok(name) => Ok(Some(name.clone())), + Err(InquireError::OperationCanceled) => Ok(None), + _ => Err(MescCliError::InvalidInput("invalid input".to_string())), + } +} + +pub(crate) fn select_endpoint( + config: &RpcConfig, + prompt: &str, +) -> Result, MescCliError> { + let mut options: Vec = config.endpoints.clone().into_keys().collect(); + options.sort(); + match inquire::Select::new(prompt, options).prompt() { + Ok(answer) => Ok(Some(answer)), + Err(InquireError::OperationCanceled) => Ok(None), + _ => Err(MescCliError::InvalidInput("invalid input".to_string())), + } +} + +pub(crate) fn select_endpoint_of_network( + config: &RpcConfig, + chain_id: &ChainId, + prompt: &str, +) -> Result, MescCliError> { + let mut options: Vec = config + .endpoints + .clone() + .values() + .filter(|endpoint| endpoint.chain_id.as_ref() == Some(chain_id)) + .map(|endpoint| endpoint.name.clone()) + .collect(); + options.sort(); + match inquire::Select::new(prompt, options).prompt() { + Ok(answer) => Ok(Some(answer)), + Err(InquireError::OperationCanceled) => Ok(None), + _ => Err(MescCliError::InvalidInput("invalid input".to_string())), + } +} + +pub(crate) fn select_profile( + config: &RpcConfig, + prompt: &str, +) -> Result, MescCliError> { + let mut options: Vec<_> = config.profiles.keys().collect(); + options.sort(); + match inquire::Select::new(prompt, options).prompt() { + Ok(answer) => Ok(Some(answer.to_string())), + Err(InquireError::OperationCanceled) => Ok(None), + _ => Err(MescCliError::InvalidInput("invalid input".to_string())), + } +} + +pub(crate) fn select_config_chain_id( + config: &RpcConfig, + prompt: &str, +) -> Result, MescCliError> { + let mut chain_ids: HashSet = HashSet::new(); + for endpoint in config.endpoints.values() { + if let Some(chain_id) = endpoint.chain_id.as_ref() { + chain_ids.insert(chain_id.clone()); + } + } + let mut sorted_chain_ids: Vec = chain_ids.into_iter().collect(); + sorted_chain_ids.sort_by_key(|chain_id| chain_id.to_hex_256().unwrap_or("".to_string())); + let options: Vec = sorted_chain_ids + .iter() + .map(|chain_id| match mesc::directory::get_network_name(chain_id) { + Some(name) => format!("{}) {}", chain_id.as_str(), name), + None => chain_id.to_string(), + }) + .collect(); + let input = match inquire::Select::new(prompt, options.clone()).prompt() { + Ok(answer) => answer, + Err(InquireError::OperationCanceled) => return Ok(None), + _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), + }; + match options.iter().position(|x| x == &input) { + Some(index) => Ok(Some(sorted_chain_ids.remove(index))), + None => Err(MescCliError::Error("invalid input".to_string())), + } +} + +pub(crate) fn select_config_mode() -> Result { + let prompt = "Do you want to store your MESC config in a file or in an env var?"; + let options = vec!["File (recommended)", "Environment Variable"]; + match inquire::Select::new(prompt, options).prompt() { + Ok("File (recommended)") => Ok(ConfigWriteMode::Path(select_config_path()?)), + Ok("Environment Variable") => Ok(ConfigWriteMode::Env(vec![])), + Ok(_) | Err(_) => { + eprintln!("Aborting setup"); + std::process::exit(1); + } + } +} + +pub(crate) fn select_config_path() -> Result { + loop { + let prompt = "Where to save MESC config file?"; + match inquire::Text::new(prompt).with_default("~/mesc.json").prompt() { + Ok(path) => { + let path = mesc::load::expand_path(path)?; + let path = std::path::Path::new(path.as_str()); + if path.exists() { + if path.is_file() { + match path.extension().map(|ext| ext.to_string_lossy()) { + Some(ext) if ext == "json" => return Ok(path.to_path_buf()), + _ => { + let prompt = "Use file even without a .json file extension?"; + if let Ok(true) = + inquire::Confirm::new(prompt).with_default(false).prompt() + { + return Ok(path.to_path_buf()); + } + } + } + } else if path.is_dir() { + let path = path.join("mesc.json"); + println!("Treating as a directory, will save to {}", path.display()); + return Ok(path); + } else { + println!("Not a valid file path"); + } + } else { + match path.extension() { + Some(ext) if ext == "json" => return Ok(path.to_path_buf()), + Some(_) => { + let prompt = "Use file even without a .json file extension?"; + if let Ok(true) = + inquire::Confirm::new(prompt).with_default(false).prompt() + { + return Ok(path.to_path_buf()); + } + } + None => { + let path = path.join("mesc.json"); + println!("Treating as a directory, will save to {}", path.display()); + return Ok(path); + } + } + } + } + Err(_) => { + eprintln!("Aborting setup"); + std::process::exit(1); + } + } + } +} diff --git a/rust/crates/mesc_cli/src/cli/subcommands/setup/shell_config.rs b/rust/crates/mesc_cli/src/cli/subcommands/setup/shell_config.rs new file mode 100644 index 0000000..7c73ffa --- /dev/null +++ b/rust/crates/mesc_cli/src/cli/subcommands/setup/shell_config.rs @@ -0,0 +1,258 @@ +use crate::MescCliError; + +use std::{ + fs::{File, OpenOptions}, + io::{BufRead, BufReader, Write}, + path::{Path, PathBuf}, +}; +use toolstr::Colorize; + +#[derive(Hash, PartialEq, Eq)] +pub(crate) struct Mention { + pub(crate) path: PathBuf, + pub(crate) env_var: String, + pub(crate) simple_value: Option, + pub(crate) line: String, +} + +pub(crate) fn get_shell_config_paths() -> Result, MescCliError> { + let home_dir = + std::env::var("HOME").map_err(|_| MescCliError::Error("home dir not found".to_string()))?; + let home_path = PathBuf::from(home_dir); + let candidates = vec![ + home_path.join(".bashrc"), + home_path.join(".profile"), + home_path.join(".bash_profile"), + ]; + Ok(candidates) +} + +/// return list of modified files +pub(crate) fn modify_shell_config_var( + var_name: &str, + value: String, + paths: Option>, +) -> Result, MescCliError> { + // decide where to look + let shell_configs = match paths { + Some(paths) => paths, + None => get_shell_config_paths()?, + }; + + // detect where env var is currently defined + let mut not_set: Vec = Vec::new(); + let mut complex_mentions: Vec = Vec::new(); + let mut set_already: Vec = Vec::new(); + let mut set_wrong: Vec = Vec::new(); + for path in shell_configs.into_iter() { + let mentions = find_env_var_mentions(var_name, &path)?; + if mentions.is_empty() { + not_set.push(path) + } else if mentions.iter().all(|m| m.simple_value.is_none()) { + complex_mentions.push(path) + } else if mentions.iter().all(|m| m.simple_value == Some(value.clone())) { + set_already.push(path) + } else { + set_wrong.push(path) + } + } + + println!("NOT_SET {:?}", not_set); + println!("COMPLEX_MENTIONS {:?}", complex_mentions); + println!("SET_ALREADY {:?}", set_already); + println!("SET_WRONG {:?}", set_wrong); + + // modify shell configs accordingly + match (not_set.len(), complex_mentions.len(), set_wrong.len(), set_already.len()) { + (0, 0, 0, 0) => { + println!(" No shell config files specified"); + Ok(vec![]) + } + (n_not_set, n_set_complex, n_set_wrong, n_set_already) => { + println!(" Need to set {} in order to use this file", "MESC_PATH".green().bold()); + if n_set_already > 0 { + println!( + " {} is already set to the desired value in {} shell config files", + var_name.bold().green(), + n_set_already.to_string().green().bold() + ); + for (i, path) in set_already.iter().enumerate() { + println!(" {}. {}", i + 1, path.to_string_lossy().green().bold()); + } + } + if n_set_complex > 0 { + println!(" {} is already set in a complex, non-standard way for {} shell config files. You must edit these files manually: {:?}", var_name.green().bold(), n_set_complex.to_string().green().bold(), get_file_names(&complex_mentions)); + for (i, path) in complex_mentions.iter().enumerate() { + println!(" {}. {}", i + 1, path.to_string_lossy().green().bold()); + } + } + if n_not_set + n_set_wrong > 0 { + let to_change: Vec<_> = not_set.into_iter().chain(set_wrong).collect(); + edit_shell_config_files_to_value(var_name, value, to_change) + } else { + Ok(vec![]) + } + } + } +} + +fn edit_shell_config_files_to_value( + var_name: &str, + value: String, + to_edit: Vec, +) -> Result, MescCliError> { + println!( + " {} can be automatically updated for {} shell config files:", + var_name.bold().green(), + format!("{}", to_edit.len()).green().bold(), + ); + for (i, path) in to_edit.iter().enumerate() { + println!(" {}. {}", i + 1, path.to_string_lossy().green().bold()); + } + let mut to_edit: std::collections::HashSet = to_edit.into_iter().collect(); + + let prompt = "What do you want to do?"; + let options = vec![ + "Edit these files automatically (recommended)", + "Edit these files manually in editor", + "Choose a subset of these files", + "Ignore this for now", + "Exit setup", + ]; + let original_to_edit = to_edit.clone(); + let edited = loop { + match inquire::Select::new(prompt, options.clone()).prompt() { + Ok("Edit these files automatically (recommended)") => { + for path in to_edit.iter() { + replace_mentions(path, var_name, &value)? + } + break to_edit.into_iter().collect(); + } + Ok("Edit these files manually in editor") => { + for path in to_edit.iter() { + edit::edit_file(path)?; + } + break to_edit.into_iter().collect(); + } + Ok("Choose a subset of these files") => { + to_edit = match inquire::MultiSelect::new( + "Select which files to edit", + original_to_edit + .clone() + .into_iter() + .map(|x| x.to_string_lossy().to_string()) + .collect(), + ) + .prompt() + { + Ok(paths) => { + println!(" Selected {} files", paths.len().to_string().bold().green()); + paths.iter().map(|p| PathBuf::from(p.to_string())).collect() + } + Err(_) => continue, + } + } + Ok("Ignore this for now") => break vec![], + Ok("Exit setup") | Ok(_) | Err(_) => std::process::exit(0), + }; + }; + + match edited.len() { + 0 => println!(" {} not updated in any shell config files", var_name.green().bold()), + 1 => println!(" {} updated in 1 config file", var_name.green().bold()), + n => println!(" Edited {} config files", n.to_string().green().bold()), + }; + + Ok(edited) +} + +/// Find mentions of environment variable in path +pub(crate) fn find_env_var_mentions( + env_var: &str, + path: &PathBuf, +) -> Result, MescCliError> { + let mut mentions: Vec = Vec::new(); + if path.exists() { + let file = File::open(path)?; + let reader = BufReader::new(file); + for line in reader.lines() { + let line = line?; + if line.trim_start().starts_with('#') { + continue; + } + if let Some(value) = extract_simple_value(&line, env_var) { + mentions.push(Mention { + path: path.clone(), + env_var: env_var.to_string(), + simple_value: Some(value), + line: line.clone(), + }); + } else if line.contains(env_var) { + mentions.push(Mention { + path: path.clone(), + env_var: env_var.to_string(), + simple_value: None, + line, + }); + } + } + } + Ok(mentions) +} + +/// Helper function to extract the simple value from a line, if present +fn extract_simple_value(line: &str, env_var: &str) -> Option { + if line.starts_with(&format!("export {}=", env_var)) { + line.split_once('=').map(|(_, value)| value.to_string()) + } else { + None + } +} + +/// Helper function to get a list of file names from a list of paths +fn get_file_names(paths: &[PathBuf]) -> Vec { + paths + .iter() + .filter_map(|path| path.file_name()) + .filter_map(|os_str| os_str.to_str()) + .map(|str_slice| str_slice.to_owned()) + .collect() +} + +/// Replace mentions of an environment variable in a file with a new value +pub(crate) fn replace_mentions>( + path: P, + env_var: &str, + new_value: &str, +) -> Result<(), MescCliError> { + let path = path.as_ref(); + let file = File::open(path)?; + let reader = BufReader::new(file); + + let mut lines: Vec = Vec::new(); + let mut modified = false; + + for line in reader.lines() { + let line = line?; + if line.starts_with(&format!("export {}=", env_var)) { + lines.push(format!("export {}={}", env_var, new_value)); + modified = true; + } else { + lines.push(line); + } + } + if !modified { + lines.push("".to_string()); + lines.push(format!("export {}={}", env_var, new_value)); + modified = true; + } + + if modified { + let mut file = OpenOptions::new().write(true).truncate(true).open(path)?; + for line in lines { + writeln!(file, "{}", line)?; + } + } + + Ok(()) +} diff --git a/rust/crates/mesc_cli/src/cli/subcommands/setup/writing.rs b/rust/crates/mesc_cli/src/cli/subcommands/setup/writing.rs new file mode 100644 index 0000000..e85cfd0 --- /dev/null +++ b/rust/crates/mesc_cli/src/cli/subcommands/setup/writing.rs @@ -0,0 +1,77 @@ +use crate::MescCliError; +use inquire::InquireError; +use mesc::RpcConfig; +use toolstr::Colorize; + +#[derive(Clone)] +pub(crate) enum ConfigWriteMode { + /// file path of JSON config file + Path(std::path::PathBuf), + /// list of config files to write to + Env(Vec), +} + +pub(crate) fn write_config( + config: RpcConfig, + config_write_mode: Option, +) -> Result<(), MescCliError> { + let config_write_mode = match config_write_mode { + Some(config_write_mode) => Some(config_write_mode), + None => get_config_write_mode()?, + }; + if config_write_mode.is_none() { + println!(" No write mode selected"); + println!(" Not writing changes to disk"); + } else { + match &config_write_mode { + Some(write_mode) => match write_mode { + ConfigWriteMode::Path(path) => { + mesc::write::write_config(config, path.clone())?; + println!(" {} {}", "config written to".bold(), path.to_string_lossy().green()); + } + ConfigWriteMode::Env(_) => { + todo!("writing environment variables not supported yet") + } + }, + None => return Err(MescCliError::Error("could not obtain write mode".to_string())), + }; + }; + Ok(()) +} + +pub(crate) fn get_config_write_mode() -> Result, MescCliError> { + if let Ok(path) = mesc::load::get_config_path() { + return Ok(Some(ConfigWriteMode::Path(path.into()))); + }; + + let prompt = "How do you want to save the config?"; + let options = ["Save as path file", "Save as an environment variable"].to_vec(); + loop { + let write_mode = match inquire::Select::new(prompt, options.clone()).prompt() { + Ok("Save as path file") => { + let prompt = "Where should mesc.json file be saved? (enter a directory path)"; + let parent = match inquire::Text::new(prompt).prompt() { + Ok(parent) => { + let parent = if parent.trim().is_empty() { + ".".to_string() + } else { + mesc::load::expand_path(parent)? + }; + std::path::PathBuf::from(parent) + } + Err(InquireError::OperationCanceled) => return Ok(None), + Err(_) => return Err(MescCliError::InvalidInput("invalid input".to_string())), + }; + let path: String = parent.join("mesc.json").to_string_lossy().to_string(); + Some(ConfigWriteMode::Path(path.into())) + } + Ok("Save an environment variable") => { + println!("not supported yet"); + continue; + } + Err(InquireError::OperationCanceled) => return Ok(None), + _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), + }; + return Ok(write_mode); + } +} diff --git a/rust/crates/mesc_cli/src/cli/subcommands/status.rs b/rust/crates/mesc_cli/src/cli/subcommands/status.rs index 3dfae8c..03815af 100644 --- a/rust/crates/mesc_cli/src/cli/subcommands/status.rs +++ b/rust/crates/mesc_cli/src/cli/subcommands/status.rs @@ -46,33 +46,41 @@ pub(crate) fn status_command(args: StatusArgs) -> Result<(), MescCliError> { values.push("false".to_string()); if let MescError::IOError(ref e) = e { if let std::io::ErrorKind::NotFound = e.kind() { - println!("config file not found"); + println!("{}", "config file not found".red()); + println!(); } else { - println!("could not load config: {:?}", e); + println!("{}", format!("could not load config: {:?}", e).red()); + println!(); + keys.push("config found"); + values.push(format!("{}", "false".to_string().red())); } } else { - println!("could not load config: {:?}", e); + println!("{}", format!("could not load config: {:?}", e).red()); + println!(); }; - return Err(e.into()); + None } Ok(config) => { - keys.push("config found"); - values.push("true".to_string()); - config + values.push(format!("{}", "true".to_string().green())); + Some(config) } }; // validate config keys.push("config valid"); - match config.validate() { - Ok(()) => { - values.push("true".to_string()); - } - Err(e) => { - values.push("false".to_string()); - println!("{:?}", e); - } - }; + if let Some(config) = config.clone() { + match config.validate() { + Ok(()) => { + values.push(format!("{}", "true".to_string().green())); + } + Err(e) => { + values.push(format!("{}", "false".to_string().red())); + println!("{:?}", e); + } + }; + } else { + values.push("[no config]".to_string()); + } let format = toolstr::TableFormat::default(); let column_formats = vec![ @@ -80,7 +88,7 @@ pub(crate) fn status_command(args: StatusArgs) -> Result<(), MescCliError> { toolstr::ColumnFormatShorthand::new() .name("v") .left_justify() - .font_style("".green().bold()), + .font_style("".bold().green()), ]; let format = toolstr::TableFormat { include_header_row: false, @@ -103,8 +111,12 @@ pub(crate) fn status_command(args: StatusArgs) -> Result<(), MescCliError> { println!(); toolstr::print_header("Configured Endpoints", &theme); println!(); - let endpoints: Vec<_> = config.endpoints.clone().into_values().collect(); - print_endpoints(&endpoints, args.reveal)?; + if let Some(ref config) = config.clone() { + let endpoints: Vec<_> = config.endpoints.clone().into_values().collect(); + print_endpoints(&endpoints, args.reveal)?; + } else { + println!("[no config]"); + } }; // print defaults @@ -113,7 +125,11 @@ pub(crate) fn status_command(args: StatusArgs) -> Result<(), MescCliError> { println!(); toolstr::print_header("Default Endpoints", &theme); println!(); - print_defaults(&config)?; + if let Some(config) = config.clone() { + print_defaults(&config)?; + } else { + println!("[no config]"); + } }; Ok(()) diff --git a/rust/crates/mesc_cli/src/network.rs b/rust/crates/mesc_cli/src/network.rs index a61eef3..2118e67 100644 --- a/rust/crates/mesc_cli/src/network.rs +++ b/rust/crates/mesc_cli/src/network.rs @@ -73,6 +73,19 @@ pub(crate) async fn get_node_network_info( }) } +pub(crate) fn is_ip(url: &str) -> bool { + use std::net::{Ipv4Addr, Ipv6Addr}; + if url.is_empty() { + return false; + } + let domain = match url.split_once('/') { + Some((domain, _)) => domain, + None => url, + }; + let domain = domain.split(':').next().unwrap_or(""); + domain.parse::().is_ok() || domain.parse::().is_ok() +} + fn get_ip_address(url: &str) -> Result { let parsed_url = url::Url::parse(url) .map_err(|_| MescCliError::UrlError("could not parse url".to_string()))?; From 4edbb587111e1c5c07c614bbeb67fbc2c6d2af5d Mon Sep 17 00:00:00 2001 From: sslivkoff Date: Thu, 25 Jan 2024 12:46:46 -0800 Subject: [PATCH 3/4] build out metadata setup modifiers --- .../src/cli/subcommands/setup/command.rs | 16 ++- .../subcommands/setup/config_modification.rs | 7 +- .../src/cli/subcommands/setup/metadata.rs | 110 ++++++++++++++---- .../src/cli/subcommands/setup/selectors.rs | 9 ++ 4 files changed, 116 insertions(+), 26 deletions(-) diff --git a/rust/crates/mesc_cli/src/cli/subcommands/setup/command.rs b/rust/crates/mesc_cli/src/cli/subcommands/setup/command.rs index 087e104..b933d87 100644 --- a/rust/crates/mesc_cli/src/cli/subcommands/setup/command.rs +++ b/rust/crates/mesc_cli/src/cli/subcommands/setup/command.rs @@ -11,10 +11,22 @@ pub(crate) async fn setup_command(args: SetupArgs) -> Result<(), MescCliError> { } else { let mode = get_write_mode()?; let config = load_config_data(&mode)?; + let endpoint_word = if config.endpoints.len() == 1 { + "endpoint" + } else { + "endpoints" + }; + let profile_word = if config.profiles.len() == 1 { + "profile" + } else { + "profiles" + }; println!( - " Current config has {} endpoints and {} profiles", + " Current config has {} {} and {} {}", config.endpoints.len().to_string().green(), - config.profiles.len().to_string().green() + endpoint_word, + config.profiles.len().to_string().green(), + profile_word, ); println!(); modify_existing_config(config, Some(mode)).await diff --git a/rust/crates/mesc_cli/src/cli/subcommands/setup/config_modification.rs b/rust/crates/mesc_cli/src/cli/subcommands/setup/config_modification.rs index 7d564f5..d259e1f 100644 --- a/rust/crates/mesc_cli/src/cli/subcommands/setup/config_modification.rs +++ b/rust/crates/mesc_cli/src/cli/subcommands/setup/config_modification.rs @@ -4,6 +4,7 @@ use mesc::RpcConfig; use super::{defaults::*, endpoints::*, metadata::*, writing::*}; use toolstr::Colorize; +use super::network_names::*; pub(crate) async fn modify_existing_config( config: RpcConfig, @@ -13,7 +14,8 @@ pub(crate) async fn modify_existing_config( "Add new endpoint", "Modify endpoint", "Modify defaults", - "Modify global metadata", + "Modify metadata", + "Modify network names", "Print config as JSON", "Exit and save changes", "Exit without saving", @@ -31,7 +33,8 @@ pub(crate) async fn modify_existing_config( Ok("Add new endpoint") => add_endpoint(&mut config).await?, Ok("Modify endpoint") => modify_endpoint(&mut config).await?, Ok("Modify defaults") => modify_defaults(&mut config)?, - Ok("Modify global metadata") => modify_global_metadata(&mut config).await?, + Ok("Modify metadata") => modify_global_metadata(&mut config).await?, + Ok("Modify network names") => modify_custom_network_names(&mut config).await?, Ok("Print config as JSON") => { println!(); println!("{}", colored_json::to_colored_json_auto(&config)?); diff --git a/rust/crates/mesc_cli/src/cli/subcommands/setup/metadata.rs b/rust/crates/mesc_cli/src/cli/subcommands/setup/metadata.rs index d6fa6d4..dc41392 100644 --- a/rust/crates/mesc_cli/src/cli/subcommands/setup/metadata.rs +++ b/rust/crates/mesc_cli/src/cli/subcommands/setup/metadata.rs @@ -4,7 +4,7 @@ use mesc::RpcConfig; use std::collections::HashMap; use toolstr::Colorize; -use super::network_names::*; +use super::selectors::*; pub(crate) fn modify_endpoint_metadata( endpoint_name: &str, @@ -20,7 +20,7 @@ pub(crate) fn modify_endpoint_metadata( "Add label", "Remove label", "Set ratelimit", - "Set api key", + "Set API key", "Edit raw JSON", "Done editing metadata", ]; @@ -93,8 +93,8 @@ pub(crate) fn modify_endpoint_metadata( .endpoint_metadata .insert("rate_limit_rps".to_string(), serde_json::json!(value)); } - Ok("Set api key") => { - let api_key = match inquire::Text::new("What is the api key?").prompt() { + Ok("Set API key") => { + let api_key = match inquire::Text::new("What is the API key?").prompt() { Ok(api_key) => api_key, Err(InquireError::OperationCanceled) => return Ok(()), _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), @@ -115,25 +115,91 @@ pub(crate) fn modify_endpoint_metadata( } pub(crate) async fn modify_global_metadata(config: &mut RpcConfig) -> Result<(), MescCliError> { - let options = - vec!["Modify raw global metadata JSON", "Edit custom network names", "Back to main menu"]; - match inquire::Select::new("What do you want to do?", options).prompt() { - Ok("Modify raw global metadata JSON") => { - let old_metadata = serde_json::to_string(&config.global_metadata)?; - let new_metadata = edit::edit(&old_metadata)?; - if old_metadata == new_metadata { - println!(" {}", "Global metadata unchanged".bold()); - } else { - let value: Result, serde_json::Error> = - serde_json::from_str(&new_metadata); - config.global_metadata = value?; - println!(" {}", "Global metadata updated".bold()); + loop { + let options = vec![ + "Modify global metadata as JSON", + "Modify profile metadata as JSON", + "Modify endpoint metadata", + "Print global metadata", + "Print profiles metadata", + "Back to main menu", + ]; + match inquire::Select::new("What do you want to do?", options).prompt() { + Ok("Modify global metadata as JSON") => { + let old_metadata = serde_json::to_string(&config.global_metadata)?; + let new_metadata = edit::edit(&old_metadata)?; + if old_metadata == new_metadata { + println!(" {}", "Global metadata unchanged".bold()); + } else { + let value: Result, serde_json::Error> = + serde_json::from_str(&new_metadata); + match value { + Ok(value) => { + config.global_metadata = value; + println!(" {}", "Global metadata updated".bold()); + }, + Err(_) => { + println!(" {}", "Invalid JSON, ignoring".red().bold()) + } + } + } } - Ok(()) + Ok("Modify profile metadata as JSON") => { + if config.profiles.is_empty() { + println!(" No profiles in config"); + } else if let Some(profile_name) = select_profile(config, "Which profile?")? { + if let Some(profile) = config.profiles.get(&profile_name) { + let old_metadata = serde_json::to_string(&profile.profile_metadata)?; + let new_metadata = edit::edit(&old_metadata)?; + if old_metadata == new_metadata { + println!(" {}", "Profile metadata unchanged".bold()); + } else { + let value: Result, serde_json::Error> = + serde_json::from_str(&new_metadata); + match value { + Ok(value) => { + config.global_metadata = value; + println!(" {}", "Profile metadata updated".bold()); + }, + Err(_) => { + println!(" {}", "Invalid JSON, ignoring".red().bold()) + } + } + } + } + } else { + return Ok(()) + } + }, + Ok("Modify endpoint metadata") => { + if config.endpoints.is_empty() { + println!(" No endpoints in config"); + } else if let Some(endpoint) = select_endpoint(config, "Which endpoint?")? { + modify_endpoint_metadata(endpoint.as_str(), config)?; + } else { + return Ok(()) + } + }, + Ok("Print global metadata") => { + println!(); + println!("{}", colored_json::to_colored_json_auto(&config.global_metadata)?); + println!(); + }, + Ok("Print profiles metadata") => { + if config.profiles.is_empty() { + println!(" No profiles in config"); + } else { + println!(); + for (profile_name, profile) in config.profiles.iter() { + println!("profile: {}:", profile_name.bold().white()); + println!("{}", colored_json::to_colored_json_auto(&profile.profile_metadata)?); + println!(); + } + } + }, + Ok("Back to main menu") => return Ok(()), + Err(InquireError::OperationCanceled) => return Ok(()), + _ => return Err(MescCliError::InvalidInput("invalid input".to_string())), } - Ok("Edit custom network names") => modify_custom_network_names(config).await, - Ok("Back to main menu") => Ok(()), - Err(InquireError::OperationCanceled) => Ok(()), - _ => Err(MescCliError::InvalidInput("invalid input".to_string())), } } diff --git a/rust/crates/mesc_cli/src/cli/subcommands/setup/selectors.rs b/rust/crates/mesc_cli/src/cli/subcommands/setup/selectors.rs index 4996b2e..4cf1dfe 100644 --- a/rust/crates/mesc_cli/src/cli/subcommands/setup/selectors.rs +++ b/rust/crates/mesc_cli/src/cli/subcommands/setup/selectors.rs @@ -99,6 +99,9 @@ pub(crate) fn select_endpoint( prompt: &str, ) -> Result, MescCliError> { let mut options: Vec = config.endpoints.clone().into_keys().collect(); + if options.is_empty() { + return Ok(None) + } options.sort(); match inquire::Select::new(prompt, options).prompt() { Ok(answer) => Ok(Some(answer)), @@ -119,6 +122,9 @@ pub(crate) fn select_endpoint_of_network( .filter(|endpoint| endpoint.chain_id.as_ref() == Some(chain_id)) .map(|endpoint| endpoint.name.clone()) .collect(); + if options.is_empty() { + return Ok(None) + } options.sort(); match inquire::Select::new(prompt, options).prompt() { Ok(answer) => Ok(Some(answer)), @@ -132,6 +138,9 @@ pub(crate) fn select_profile( prompt: &str, ) -> Result, MescCliError> { let mut options: Vec<_> = config.profiles.keys().collect(); + if options.is_empty() { + return Ok(None) + } options.sort(); match inquire::Select::new(prompt, options).prompt() { Ok(answer) => Ok(Some(answer.to_string())), From fb8fe5c6f9ed03ef60b1fc7044123477a574864e Mon Sep 17 00:00:00 2001 From: sslivkoff Date: Thu, 25 Jan 2024 12:51:24 -0800 Subject: [PATCH 4/4] rust format --- .../src/cli/subcommands/setup/command.rs | 12 ++-------- .../subcommands/setup/config_modification.rs | 3 +-- .../src/cli/subcommands/setup/metadata.rs | 23 +++++++++++-------- 3 files changed, 17 insertions(+), 21 deletions(-) diff --git a/rust/crates/mesc_cli/src/cli/subcommands/setup/command.rs b/rust/crates/mesc_cli/src/cli/subcommands/setup/command.rs index b933d87..74727b5 100644 --- a/rust/crates/mesc_cli/src/cli/subcommands/setup/command.rs +++ b/rust/crates/mesc_cli/src/cli/subcommands/setup/command.rs @@ -11,16 +11,8 @@ pub(crate) async fn setup_command(args: SetupArgs) -> Result<(), MescCliError> { } else { let mode = get_write_mode()?; let config = load_config_data(&mode)?; - let endpoint_word = if config.endpoints.len() == 1 { - "endpoint" - } else { - "endpoints" - }; - let profile_word = if config.profiles.len() == 1 { - "profile" - } else { - "profiles" - }; + let endpoint_word = if config.endpoints.len() == 1 { "endpoint" } else { "endpoints" }; + let profile_word = if config.profiles.len() == 1 { "profile" } else { "profiles" }; println!( " Current config has {} {} and {} {}", config.endpoints.len().to_string().green(), diff --git a/rust/crates/mesc_cli/src/cli/subcommands/setup/config_modification.rs b/rust/crates/mesc_cli/src/cli/subcommands/setup/config_modification.rs index d259e1f..eb31ac6 100644 --- a/rust/crates/mesc_cli/src/cli/subcommands/setup/config_modification.rs +++ b/rust/crates/mesc_cli/src/cli/subcommands/setup/config_modification.rs @@ -2,9 +2,8 @@ use crate::MescCliError; use inquire::InquireError; use mesc::RpcConfig; -use super::{defaults::*, endpoints::*, metadata::*, writing::*}; +use super::{defaults::*, endpoints::*, metadata::*, network_names::*, writing::*}; use toolstr::Colorize; -use super::network_names::*; pub(crate) async fn modify_existing_config( config: RpcConfig, diff --git a/rust/crates/mesc_cli/src/cli/subcommands/setup/metadata.rs b/rust/crates/mesc_cli/src/cli/subcommands/setup/metadata.rs index dc41392..bd2e4f4 100644 --- a/rust/crates/mesc_cli/src/cli/subcommands/setup/metadata.rs +++ b/rust/crates/mesc_cli/src/cli/subcommands/setup/metadata.rs @@ -137,7 +137,7 @@ pub(crate) async fn modify_global_metadata(config: &mut RpcConfig) -> Result<(), Ok(value) => { config.global_metadata = value; println!(" {}", "Global metadata updated".bold()); - }, + } Err(_) => { println!(" {}", "Invalid JSON, ignoring".red().bold()) } @@ -154,13 +154,15 @@ pub(crate) async fn modify_global_metadata(config: &mut RpcConfig) -> Result<(), if old_metadata == new_metadata { println!(" {}", "Profile metadata unchanged".bold()); } else { - let value: Result, serde_json::Error> = - serde_json::from_str(&new_metadata); + let value: Result< + HashMap, + serde_json::Error, + > = serde_json::from_str(&new_metadata); match value { Ok(value) => { config.global_metadata = value; println!(" {}", "Profile metadata updated".bold()); - }, + } Err(_) => { println!(" {}", "Invalid JSON, ignoring".red().bold()) } @@ -170,7 +172,7 @@ pub(crate) async fn modify_global_metadata(config: &mut RpcConfig) -> Result<(), } else { return Ok(()) } - }, + } Ok("Modify endpoint metadata") => { if config.endpoints.is_empty() { println!(" No endpoints in config"); @@ -179,12 +181,12 @@ pub(crate) async fn modify_global_metadata(config: &mut RpcConfig) -> Result<(), } else { return Ok(()) } - }, + } Ok("Print global metadata") => { println!(); println!("{}", colored_json::to_colored_json_auto(&config.global_metadata)?); println!(); - }, + } Ok("Print profiles metadata") => { if config.profiles.is_empty() { println!(" No profiles in config"); @@ -192,11 +194,14 @@ pub(crate) async fn modify_global_metadata(config: &mut RpcConfig) -> Result<(), println!(); for (profile_name, profile) in config.profiles.iter() { println!("profile: {}:", profile_name.bold().white()); - println!("{}", colored_json::to_colored_json_auto(&profile.profile_metadata)?); + println!( + "{}", + colored_json::to_colored_json_auto(&profile.profile_metadata)? + ); println!(); } } - }, + } Ok("Back to main menu") => return Ok(()), Err(InquireError::OperationCanceled) => return Ok(()), _ => return Err(MescCliError::InvalidInput("invalid input".to_string())),