From e8f15c68acd149c7323473d3397aa50065e1ce27 Mon Sep 17 00:00:00 2001 From: Illia Kripaka Date: Fri, 20 Mar 2026 16:30:21 +0200 Subject: [PATCH 1/5] Extend init and clean commands chore: * introduce *Result types for simplification * move Simplex.default.toml to crates/cli/assets folder --- Cargo.lock | 21 ++- crates/cli/Cargo.toml | 9 +- crates/cli/{ => assets}/Simplex.default.toml | 0 crates/cli/src/cli.rs | 23 ++- crates/cli/src/commands/build.rs | 4 +- crates/cli/src/commands/clean.rs | 93 ++++++++++ crates/cli/src/commands/core.rs | 26 ++- crates/cli/src/commands/error.rs | 8 + crates/cli/src/commands/init.rs | 169 +++++++++++++++++++ crates/cli/src/commands/mod.rs | 2 + crates/cli/src/commands/regtest.rs | 4 +- crates/cli/src/commands/test.rs | 6 +- crates/cli/src/config/core.rs | 21 ++- crates/cli/src/config/error.rs | 2 + crates/cli/src/error.rs | 2 + 15 files changed, 359 insertions(+), 31 deletions(-) rename crates/cli/{ => assets}/Simplex.default.toml (100%) create mode 100644 crates/cli/src/commands/clean.rs create mode 100644 crates/cli/src/commands/init.rs diff --git a/Cargo.lock b/Cargo.lock index 3af41ae..6f459ed 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1313,9 +1313,9 @@ dependencies = [ "clap", "ctrlc", "dotenvy", - "electrsd", + "minreq", "serde", - "simplicityhl", + "serde_json", "smplx-build", "smplx-regtest", "smplx-sdk", @@ -1323,6 +1323,7 @@ dependencies = [ "thiserror", "tokio", "toml 0.9.12+spec-1.1.0", + "toml_edit", ] [[package]] @@ -1554,6 +1555,19 @@ dependencies = [ "serde_core", ] +[[package]] +name = "toml_edit" +version = "0.23.10+spec-1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84c8b9f757e028cee9fa244aea147aab2a9ec09d5325a9b01e0a49730c2b5269" +dependencies = [ + "indexmap", + "toml_datetime 0.7.5+spec-1.1.0", + "toml_parser", + "toml_writer", + "winnow", +] + [[package]] name = "toml_parser" version = "1.0.9+spec-1.1.0" @@ -1877,6 +1891,9 @@ name = "winnow" version = "0.7.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] [[package]] name = "wit-bindgen" diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index 5bb32b1..351d980 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -15,17 +15,18 @@ workspace = true [dependencies] smplx-regtest = { workspace = true } smplx-test = { workspace = true } -smplx-build = { workspace = true} +smplx-build = { workspace = true } smplx-sdk = { workspace = true } -simplicityhl = { workspace = true } -electrsd = { workspace = true } thiserror = { workspace = true } serde = { workspace = true } toml = { workspace = true } +minreq = { workspace = true } anyhow = "1" dotenvy = "0.15" clap = { version = "4", features = ["derive", "env"] } tokio = { version = "1", features = ["rt-multi-thread", "macros"] } -ctrlc = { version = "3.5.2", features = ["termination"] } +toml_edit = { version = "0.23.9" } +ctrlc = { version = "3.5.2", features = ["termination"] } +serde_json = { version = "1.0.149" } \ No newline at end of file diff --git a/crates/cli/Simplex.default.toml b/crates/cli/assets/Simplex.default.toml similarity index 100% rename from crates/cli/Simplex.default.toml rename to crates/cli/assets/Simplex.default.toml diff --git a/crates/cli/src/cli.rs b/crates/cli/src/cli.rs index 09a98a5..22d56be 100644 --- a/crates/cli/src/cli.rs +++ b/crates/cli/src/cli.rs @@ -4,10 +4,12 @@ use clap::Parser; use crate::commands::Command; use crate::commands::build::Build; +use crate::commands::clean::Clean; +use crate::commands::init::Init; use crate::commands::regtest::Regtest; use crate::commands::test::Test; -use crate::config::{Config, INIT_CONFIG}; -use crate::error::CliError; +use crate::config::Config; +use crate::error::CliResult; #[derive(Debug, Parser)] #[command(name = "Simplex")] @@ -20,14 +22,11 @@ pub struct Cli { } impl Cli { - pub async fn run(&self) -> Result<(), CliError> { + pub async fn run(&self) -> CliResult<()> { match &self.command { - Command::Init => { - let config_path = Config::get_default_path()?; - std::fs::write(&config_path, INIT_CONFIG)?; - - println!("Config written to: '{}'", config_path.display()); - + Command::Init { additional_flags } => { + let smplx_conf_path = Config::get_default_path()?; + Init::init_smplx(*additional_flags, smplx_conf_path)?; Ok(()) } Command::Config => { @@ -56,6 +55,12 @@ impl Cli { Ok(Build::run(loaded_config.build)?) } + Command::Clean { additional_flags } => { + let config_path = Config::get_default_path()?; + let loaded_config = Config::load(&config_path)?; + + Ok(Clean::run(loaded_config.build, *additional_flags, config_path)?) + } } } } diff --git a/crates/cli/src/commands/build.rs b/crates/cli/src/commands/build.rs index 337e7f2..251f7e8 100644 --- a/crates/cli/src/commands/build.rs +++ b/crates/cli/src/commands/build.rs @@ -1,11 +1,11 @@ use smplx_build::{ArtifactsGenerator, ArtifactsResolver, BuildConfig}; -use super::error::CommandError; +use super::error::CommandResult; pub struct Build {} impl Build { - pub fn run(config: BuildConfig) -> Result<(), CommandError> { + pub fn run(config: BuildConfig) -> CommandResult<()> { let output_dir = ArtifactsResolver::resolve_local_dir(&config.out_dir)?; let src_dir = ArtifactsResolver::resolve_local_dir(&config.src_dir)?; let files_to_build = ArtifactsResolver::resolve_files_to_build(&config.src_dir, &config.simf_files)?; diff --git a/crates/cli/src/commands/clean.rs b/crates/cli/src/commands/clean.rs new file mode 100644 index 0000000..0efe92f --- /dev/null +++ b/crates/cli/src/commands/clean.rs @@ -0,0 +1,93 @@ +use crate::commands::CleanFlags; +use crate::commands::error::CommandResult; +use smplx_build::{ArtifactsResolver, BuildConfig}; +use std::fmt::Display; +use std::fs; +use std::path::{Path, PathBuf}; +use thiserror::Error; + +pub struct Clean; + +pub struct DeletedItems(Vec); + +#[derive(Error, Debug)] +pub enum CleanError { + #[error("Failed to resolve out_dir from config, err: '{0}'")] + ResolveOutDir(String), + + #[error("Failed to remove output directory '{1}': {0}")] + RemoveOutDir(std::io::Error, PathBuf), + + #[error("Failed to remove file '{1}': {0}")] + RemoveFile(std::io::Error, PathBuf), +} + +type CleanResult = Result; + +impl Clean { + pub fn run(config: BuildConfig, additional_flags: CleanFlags, config_path: impl AsRef) -> CommandResult<()> { + let deleted_files = Self::delete_files(config, additional_flags, config_path)?; + println!("Deleted files: {deleted_files}"); + Ok(()) + } +} + +impl Clean { + fn delete_files( + config: BuildConfig, + additional_flags: CleanFlags, + smplx_toml_path: impl AsRef, + ) -> CleanResult { + let mut deleted_items = Vec::with_capacity(2); + + let generated_artifacts = Self::remove_artifacts(config)?; + if let Some(artifacts_dir) = generated_artifacts { + deleted_items.push(artifacts_dir); + } + if additional_flags.all { + let simplex_toml_path = Self::remove_file(smplx_toml_path)?; + if let Some(simplex_toml) = simplex_toml_path { + deleted_items.push(simplex_toml); + } + } + Ok(DeletedItems(deleted_items)) + } + + fn remove_artifacts(config: BuildConfig) -> CleanResult> { + let output_dir = ArtifactsResolver::resolve_local_dir(&config.out_dir) + .map_err(|e| CleanError::ResolveOutDir(e.to_string()))?; + let res = if output_dir.exists() { + fs::remove_dir_all(&output_dir).map_err(|e| CleanError::RemoveOutDir(e, output_dir.to_path_buf()))?; + Some(output_dir) + } else { + None + }; + Ok(res) + } + + fn remove_file(config_path: impl AsRef) -> CleanResult> { + let config_path = config_path.as_ref().to_path_buf(); + if config_path.exists() && config_path.is_file() { + fs::remove_file(&config_path).map_err(|e| CleanError::RemoveFile(e, config_path.to_path_buf()))?; + Ok(Some(config_path)) + } else { + Ok(None) + } + } +} + +impl Display for DeletedItems { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let paths_len = self.0.len(); + let mut result = String::from("["); + for (index, path) in self.0.iter().enumerate() { + result.push_str(&format!("\n\t{}", path.display())); + if index < paths_len - 1 { + result.push(','); + } + result.push('\n'); + } + result.push(']'); + write!(f, "{}", result) + } +} diff --git a/crates/cli/src/commands/core.rs b/crates/cli/src/commands/core.rs index 1e59c70..98df42b 100644 --- a/crates/cli/src/commands/core.rs +++ b/crates/cli/src/commands/core.rs @@ -2,8 +2,11 @@ use clap::{Args, Subcommand}; #[derive(Debug, Subcommand)] pub enum Command { - /// Initializes the Simplex project (TODO) - Init, + /// Initializes the Simplex project + Init { + #[command(flatten)] + additional_flags: InitFlags, + }, /// Prints the current Simplex config in use Config, /// Spins up the local Electrs + Elements regtest @@ -15,6 +18,11 @@ pub enum Command { }, /// Generates the simplicity contracts artifacts Build, + /// Clean directory after file generation inside + Clean { + #[command(flatten)] + additional_flags: CleanFlags, + }, } #[derive(Debug, Subcommand)] @@ -46,3 +54,17 @@ pub struct TestFlags { #[arg(long)] pub ignored: bool, } + +#[derive(Debug, Args, Copy, Clone)] +pub struct InitFlags { + /// Generate a draft library instead of just `Simplex.toml` + #[arg(long)] + pub lib: bool, +} + +#[derive(Debug, Args, Copy, Clone)] +pub struct CleanFlags { + /// Remove `Simplex.toml` as well + #[arg(long)] + pub all: bool, +} diff --git a/crates/cli/src/commands/error.rs b/crates/cli/src/commands/error.rs index 6cadf5f..e3ece1b 100644 --- a/crates/cli/src/commands/error.rs +++ b/crates/cli/src/commands/error.rs @@ -1,3 +1,5 @@ +pub type CommandResult = Result; + #[derive(thiserror::Error, Debug)] pub enum CommandError { #[error(transparent)] @@ -12,6 +14,12 @@ pub enum CommandError { #[error(transparent)] Build(#[from] smplx_build::error::BuildError), + #[error(transparent)] + Clean(#[from] crate::commands::clean::CleanError), + + #[error(transparent)] + Init(#[from] crate::commands::init::InitError), + #[error("IO error: {0}")] Io(#[from] std::io::Error), } diff --git a/crates/cli/src/commands/init.rs b/crates/cli/src/commands/init.rs new file mode 100644 index 0000000..acd1598 --- /dev/null +++ b/crates/cli/src/commands/init.rs @@ -0,0 +1,169 @@ +use crate::commands::InitFlags; +use crate::commands::error::CommandResult; +use crate::config::INIT_CONFIG; +use std::fs; +use std::fs::OpenOptions; +use std::io::Write; +use std::path::{Path, PathBuf}; +use thiserror::Error; + +pub struct Init; + +#[derive(Error, Debug)] +pub enum InitError { + #[error("Failed to open file '{1}': {0}")] + OpenFile(std::io::Error, PathBuf), + + #[error("Failed to write to file '{1}': {0}")] + WriteToFile(std::io::Error, PathBuf), + + #[error("Failed to format file with rustfmt: {0}")] + FmtError(std::io::Error), + + #[error("Failed to resolve parent directory for: {0}")] + ResolveParent(PathBuf), + + #[error("Failed to create directories at '{1}': {0}")] + CreateDirs(std::io::Error, PathBuf), + + #[error("Failed to fetch crate info from crates.io: {0}")] + CratesIoFetch(String), + + #[error("Cannot auto-detect package name from path: {0}")] + PackageName(PathBuf), + + #[error("Cannot create package with a non-unicode name: '{0}'")] + NonUnicodeName(String), +} + +type InitResult = Result; + +impl Init { + pub fn init_smplx(conf: InitFlags, smplx_conf_path: impl AsRef) -> CommandResult<()> { + if conf.lib { + Self::generate_lib_inplace(&smplx_conf_path)? + } + Self::fill_smplx_toml(smplx_conf_path)?; + Ok(()) + } +} + +impl Init { + fn fill_smplx_toml(config_path: impl AsRef) -> InitResult<()> { + let path_to_write = config_path.as_ref(); + Self::write_to_file(path_to_write, INIT_CONFIG)?; + println!("Config written to: '{}'", path_to_write.display()); + Ok(()) + } + + fn get_name(path: &Path) -> InitResult<&str> { + let file_name = path + .file_name() + .ok_or_else(|| InitError::PackageName(path.to_path_buf()))?; + + file_name + .to_str() + .ok_or_else(|| InitError::NonUnicodeName(format!("{file_name:?}"))) + } + + fn generate_lib_inplace(config_path: impl AsRef) -> InitResult<()> { + let pwd = config_path.as_ref().parent().unwrap(); + let name = Self::get_name(pwd)?; + + // Create `Cargo.toml` file + let manifest = { + let mut manifest = toml_edit::DocumentMut::new(); + manifest["package"] = toml_edit::Item::Table(toml_edit::Table::new()); + manifest["package"]["name"] = toml_edit::value(name); + manifest["package"]["version"] = toml_edit::value("0.1.0"); + manifest["package"]["edition"] = toml_edit::value("2024"); + let mut dep_table = toml_edit::Table::default(); + dep_table.insert( + "smplx-std", + toml_edit::Item::Value(toml_edit::Value::String(toml_edit::Formatted::new( + Self::get_smplx_max_version()?, + ))), + ); + manifest["dependencies"] = toml_edit::Item::Table(dep_table); + manifest + }; + + let default_lib_rs_file_content: &[u8] = { + b"\ +pub fn add(left: u64, right: u64) -> u64 { + left + right +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn it_works() { + let result = add(2, 2); + assert_eq!(result, 4); + } +} + " + }; + + let manifest_path = pwd.join("Cargo.toml"); + let lib_rs_path = pwd.join("src/lib.rs"); + + Self::write_to_file(manifest_path, manifest.to_string())?; + Self::write_to_file(&lib_rs_path, default_lib_rs_file_content)?; + Self::execute_cargo_fmt(lib_rs_path)?; + + Ok(()) + } + + fn get_smplx_max_version() -> InitResult { + let crate_name = "smplx-std"; + let url = format!("https://crates.io/api/v1/crates/{}", crate_name); + + let response = minreq::get(&url) + .with_header("User-Agent", "simplex_generator") + .send() + .map_err(|e| InitError::CratesIoFetch(format!("Failed to fetch crate info: {}", e)))?; + + let body = response + .as_str() + .map_err(|e| InitError::CratesIoFetch(format!("Invalid response body: {}", e)))?; + + let json: serde_json::Value = + serde_json::from_str(body).map_err(|e| InitError::CratesIoFetch(format!("Failed to parse JSON: {}", e)))?; + + let latest_version = json["crate"]["max_stable_version"] + .as_str() + .ok_or_else(|| InitError::CratesIoFetch("Could not find max_version in response".to_string()))?; + + Ok(latest_version.to_string()) + } + + fn write_to_file(path: impl AsRef, content: impl AsRef<[u8]>) -> InitResult<()> { + let path = path.as_ref(); + fs::create_dir_all( + path.parent() + .ok_or_else(|| InitError::ResolveParent(path.to_path_buf()))?, + ) + .map_err(|e| InitError::CreateDirs(e, path.to_path_buf()))?; + let mut file = OpenOptions::new() + .create(true) + .write(true) + .truncate(true) + .open(path) + .map_err(|e| InitError::OpenFile(e, path.to_path_buf()))?; + file.write_all(content.as_ref()) + .map_err(|e| InitError::WriteToFile(e, path.to_path_buf()))?; + file.flush() + .map_err(|e| InitError::WriteToFile(e, path.to_path_buf()))?; + Ok(()) + } + + fn execute_cargo_fmt(file: impl AsRef) -> InitResult<()> { + let mut cargo_test_command = std::process::Command::new("sh"); + cargo_test_command.args(["-c".to_string(), format!("rustfmt {}", file.as_ref().display())]); + let _output = cargo_test_command.output().map_err(InitError::FmtError); + Ok(()) + } +} diff --git a/crates/cli/src/commands/mod.rs b/crates/cli/src/commands/mod.rs index 81faac2..50cb5fb 100644 --- a/crates/cli/src/commands/mod.rs +++ b/crates/cli/src/commands/mod.rs @@ -1,6 +1,8 @@ pub mod build; +pub mod clean; pub mod core; pub mod error; +pub mod init; pub mod regtest; pub mod test; diff --git a/crates/cli/src/commands/regtest.rs b/crates/cli/src/commands/regtest.rs index 4c44eea..cbc3e46 100644 --- a/crates/cli/src/commands/regtest.rs +++ b/crates/cli/src/commands/regtest.rs @@ -4,12 +4,12 @@ use std::sync::atomic::{AtomicBool, Ordering}; use smplx_regtest::Regtest as RegtestRunner; use smplx_regtest::RegtestConfig; -use crate::commands::error::CommandError; +use crate::commands::error::CommandResult; pub struct Regtest {} impl Regtest { - pub fn run(config: RegtestConfig) -> Result<(), CommandError> { + pub fn run(config: RegtestConfig) -> CommandResult<()> { let (mut client, signer) = RegtestRunner::from_config(config)?; let running = Arc::new(AtomicBool::new(true)); diff --git a/crates/cli/src/commands/test.rs b/crates/cli/src/commands/test.rs index 05adaf5..f655ff5 100644 --- a/crates/cli/src/commands/test.rs +++ b/crates/cli/src/commands/test.rs @@ -4,12 +4,12 @@ use std::process::Stdio; use smplx_test::TestConfig; use super::core::{TestCommand, TestFlags}; -use super::error::CommandError; +use super::error::CommandResult; pub struct Test {} impl Test { - pub fn run(config: TestConfig, command: &TestCommand) -> Result<(), CommandError> { + pub fn run(config: TestConfig, command: &TestCommand) -> CommandResult<()> { let cache_path = Self::get_test_config_cache_name()?; config.to_file(&cache_path)?; @@ -103,7 +103,7 @@ impl Test { opt_params } - fn get_test_config_cache_name() -> Result { + fn get_test_config_cache_name() -> CommandResult { const TARGET_DIR_NAME: &str = "target"; const SIMPLEX_CACHE_DIR_NAME: &str = "simplex"; const SIMPLEX_TEST_CONFIG_NAME: &str = "simplex_test_config.toml"; diff --git a/crates/cli/src/config/core.rs b/crates/cli/src/config/core.rs index e03b6a3..ca286e1 100644 --- a/crates/cli/src/config/core.rs +++ b/crates/cli/src/config/core.rs @@ -5,9 +5,9 @@ use smplx_build::BuildConfig; use smplx_regtest::RegtestConfig; use smplx_test::TestConfig; -use super::error::ConfigError; +use super::error::{ConfigError, ConfigResult}; -pub const INIT_CONFIG: &str = include_str!("../../Simplex.default.toml"); +pub const INIT_CONFIG: &str = include_str!("../../assets/Simplex.default.toml"); pub const CONFIG_FILENAME: &str = "Simplex.toml"; #[derive(Debug, Default, Clone, Deserialize)] @@ -19,13 +19,20 @@ pub struct Config { } impl Config { - pub fn get_default_path() -> Result { + pub fn get_default_path() -> ConfigResult { let cwd = std::env::current_dir()?; + Self::get_derived_default_path(cwd) + } + + pub fn pwd() -> ConfigResult { + Ok(std::env::current_dir()?) + } - Ok(cwd.join(CONFIG_FILENAME)) + pub fn get_derived_default_path(path: impl AsRef) -> ConfigResult { + Ok(path.as_ref().join(CONFIG_FILENAME)) } - pub fn load(path_buf: impl AsRef) -> Result { + pub fn load(path_buf: impl AsRef) -> ConfigResult { let path = path_buf.as_ref().to_path_buf(); if !path.is_file() { @@ -44,7 +51,7 @@ impl Config { Ok(config) } - fn validate(config: &Config) -> Result<(), ConfigError> { + fn validate(config: &Config) -> ConfigResult<()> { match config.test.esplora.clone() { Some(esplora_config) => { Self::validate_network(&esplora_config.network)?; @@ -59,7 +66,7 @@ impl Config { } } - fn validate_network(network: &String) -> Result<(), ConfigError> { + fn validate_network(network: &String) -> ConfigResult<()> { if network != "Liquid" && network != "LiquidTestnet" && network != "ElementsRegtest" { return Err(ConfigError::BadNetworkName(network.clone())); } diff --git a/crates/cli/src/config/error.rs b/crates/cli/src/config/error.rs index d76ca7b..e4570ee 100644 --- a/crates/cli/src/config/error.rs +++ b/crates/cli/src/config/error.rs @@ -26,3 +26,5 @@ pub enum ConfigError { #[error("Path doesn't exist: '{0}'")] PathNotExists(PathBuf), } + +pub type ConfigResult = Result; diff --git a/crates/cli/src/error.rs b/crates/cli/src/error.rs index 885a3e1..798a77e 100644 --- a/crates/cli/src/error.rs +++ b/crates/cli/src/error.rs @@ -11,3 +11,5 @@ pub enum CliError { #[error("IO error: '{0}'")] Io(#[from] std::io::Error), } + +pub type CliResult = Result; From ef7361e1c4bf757d656f19fa948764d67615f5ef Mon Sep 17 00:00:00 2001 From: Illia Kripaka Date: Fri, 20 Mar 2026 16:53:49 +0200 Subject: [PATCH 2/5] Move errors to src/commands/error --- crates/cli/src/commands/clean.rs | 17 +---------- crates/cli/src/commands/error.rs | 52 ++++++++++++++++++++++++++++++-- crates/cli/src/commands/init.rs | 34 ++------------------- 3 files changed, 52 insertions(+), 51 deletions(-) diff --git a/crates/cli/src/commands/clean.rs b/crates/cli/src/commands/clean.rs index 0efe92f..2526bdf 100644 --- a/crates/cli/src/commands/clean.rs +++ b/crates/cli/src/commands/clean.rs @@ -1,29 +1,14 @@ use crate::commands::CleanFlags; -use crate::commands::error::CommandResult; +use crate::commands::error::{CleanError, CleanResult, CommandResult}; use smplx_build::{ArtifactsResolver, BuildConfig}; use std::fmt::Display; use std::fs; use std::path::{Path, PathBuf}; -use thiserror::Error; pub struct Clean; pub struct DeletedItems(Vec); -#[derive(Error, Debug)] -pub enum CleanError { - #[error("Failed to resolve out_dir from config, err: '{0}'")] - ResolveOutDir(String), - - #[error("Failed to remove output directory '{1}': {0}")] - RemoveOutDir(std::io::Error, PathBuf), - - #[error("Failed to remove file '{1}': {0}")] - RemoveFile(std::io::Error, PathBuf), -} - -type CleanResult = Result; - impl Clean { pub fn run(config: BuildConfig, additional_flags: CleanFlags, config_path: impl AsRef) -> CommandResult<()> { let deleted_files = Self::delete_files(config, additional_flags, config_path)?; diff --git a/crates/cli/src/commands/error.rs b/crates/cli/src/commands/error.rs index e3ece1b..47c72bf 100644 --- a/crates/cli/src/commands/error.rs +++ b/crates/cli/src/commands/error.rs @@ -1,4 +1,5 @@ -pub type CommandResult = Result; +use std::path::PathBuf; +use thiserror::Error; #[derive(thiserror::Error, Debug)] pub enum CommandError { @@ -15,11 +16,56 @@ pub enum CommandError { Build(#[from] smplx_build::error::BuildError), #[error(transparent)] - Clean(#[from] crate::commands::clean::CleanError), + Init(#[from] InitError), #[error(transparent)] - Init(#[from] crate::commands::init::InitError), + Clean(#[from] CleanError), #[error("IO error: {0}")] Io(#[from] std::io::Error), } + +pub type CommandResult = Result; + +#[derive(Error, Debug)] +pub enum InitError { + #[error("Failed to open file '{1}': {0}")] + OpenFile(std::io::Error, PathBuf), + + #[error("Failed to write to file '{1}': {0}")] + WriteToFile(std::io::Error, PathBuf), + + #[error("Failed to format file with rustfmt: {0}")] + FmtError(std::io::Error), + + #[error("Failed to resolve parent directory for: {0}")] + ResolveParent(PathBuf), + + #[error("Failed to create directories at '{1}': {0}")] + CreateDirs(std::io::Error, PathBuf), + + #[error("Failed to fetch crate info from crates.io: {0}")] + CratesIoFetch(String), + + #[error("Cannot auto-detect package name from path: {0}")] + PackageName(PathBuf), + + #[error("Cannot create package with a non-unicode name: '{0}'")] + NonUnicodeName(String), +} + +pub type InitResult = Result; + +#[derive(Error, Debug)] +pub enum CleanError { + #[error("Failed to resolve out_dir from config, err: '{0}'")] + ResolveOutDir(String), + + #[error("Failed to remove output directory '{1}': {0}")] + RemoveOutDir(std::io::Error, PathBuf), + + #[error("Failed to remove file '{1}': {0}")] + RemoveFile(std::io::Error, PathBuf), +} + +pub type CleanResult = Result; diff --git a/crates/cli/src/commands/init.rs b/crates/cli/src/commands/init.rs index acd1598..fe8b668 100644 --- a/crates/cli/src/commands/init.rs +++ b/crates/cli/src/commands/init.rs @@ -1,43 +1,13 @@ use crate::commands::InitFlags; -use crate::commands::error::CommandResult; +use crate::commands::error::{CommandResult, InitError, InitResult}; use crate::config::INIT_CONFIG; use std::fs; use std::fs::OpenOptions; use std::io::Write; -use std::path::{Path, PathBuf}; -use thiserror::Error; +use std::path::Path; pub struct Init; -#[derive(Error, Debug)] -pub enum InitError { - #[error("Failed to open file '{1}': {0}")] - OpenFile(std::io::Error, PathBuf), - - #[error("Failed to write to file '{1}': {0}")] - WriteToFile(std::io::Error, PathBuf), - - #[error("Failed to format file with rustfmt: {0}")] - FmtError(std::io::Error), - - #[error("Failed to resolve parent directory for: {0}")] - ResolveParent(PathBuf), - - #[error("Failed to create directories at '{1}': {0}")] - CreateDirs(std::io::Error, PathBuf), - - #[error("Failed to fetch crate info from crates.io: {0}")] - CratesIoFetch(String), - - #[error("Cannot auto-detect package name from path: {0}")] - PackageName(PathBuf), - - #[error("Cannot create package with a non-unicode name: '{0}'")] - NonUnicodeName(String), -} - -type InitResult = Result; - impl Init { pub fn init_smplx(conf: InitFlags, smplx_conf_path: impl AsRef) -> CommandResult<()> { if conf.lib { From 74ea9b7ca3888cea05814e91233723cbecc3010c Mon Sep 17 00:00:00 2001 From: Illia Kripaka Date: Fri, 20 Mar 2026 17:15:21 +0200 Subject: [PATCH 3/5] Add additional files to generate in `init --lib` command --- crates/cli/src/commands/init.rs | 35 ++++++++++++++++++--------------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/crates/cli/src/commands/init.rs b/crates/cli/src/commands/init.rs index fe8b668..79cb143 100644 --- a/crates/cli/src/commands/init.rs +++ b/crates/cli/src/commands/init.rs @@ -58,30 +58,33 @@ impl Init { manifest }; - let default_lib_rs_file_content: &[u8] = { + let default_lib_rs_file_content: &[u8] = { b"mod artifacts;" }; + let default_test_file_content: &[u8] = { b"\ -pub fn add(left: u64, right: u64) -> u64 { - left + right -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn it_works() { - let result = add(2, 2); - assert_eq!(result, 4); - } -} - " +#[simplex::test] +fn dummy_test(context: simplex::TestContext) { + todo!() +}" + }; + let default_p2pk_simf_file_content: &[u8] = { + b"\ +fn main() { + jet::bip_0340_verify((param::PUBLIC_KEY, jet::sig_all_hash()), witness::SIGNATURE) +}" }; + let default_gitignore_file_content: &[u8] = { b"src/artifacts" }; let manifest_path = pwd.join("Cargo.toml"); let lib_rs_path = pwd.join("src/lib.rs"); + let p2pk_simf_content = pwd.join("simf/p2pk.simf"); + let test_rs_path = pwd.join("tests/p2pk_test.rs"); + let gitignore_path = pwd.join(".gitignore"); Self::write_to_file(manifest_path, manifest.to_string())?; Self::write_to_file(&lib_rs_path, default_lib_rs_file_content)?; + Self::write_to_file(&test_rs_path, default_test_file_content)?; + Self::write_to_file(&p2pk_simf_content, default_p2pk_simf_file_content)?; + Self::write_to_file(&gitignore_path, default_gitignore_file_content)?; Self::execute_cargo_fmt(lib_rs_path)?; Ok(()) From bbb1ef666e9efebd13cf1271203aea5480f2bdcc Mon Sep 17 00:00:00 2001 From: Illia Kripaka Date: Fri, 20 Mar 2026 17:23:01 +0200 Subject: [PATCH 4/5] Mix imports --- crates/cli/src/commands/clean.rs | 16 +++++++++++----- crates/cli/src/commands/error.rs | 3 ++- crates/cli/src/commands/init.rs | 12 ++++++------ 3 files changed, 19 insertions(+), 12 deletions(-) diff --git a/crates/cli/src/commands/clean.rs b/crates/cli/src/commands/clean.rs index 2526bdf..1b2483a 100644 --- a/crates/cli/src/commands/clean.rs +++ b/crates/cli/src/commands/clean.rs @@ -1,9 +1,15 @@ -use crate::commands::CleanFlags; -use crate::commands::error::{CleanError, CleanResult, CommandResult}; +use crate::commands::{ + CleanFlags, + error::{CleanError, CleanResult, CommandResult}, +}; + use smplx_build::{ArtifactsResolver, BuildConfig}; -use std::fmt::Display; -use std::fs; -use std::path::{Path, PathBuf}; + +use std::{ + fmt::Display, + fs, + path::{Path, PathBuf}, +}; pub struct Clean; diff --git a/crates/cli/src/commands/error.rs b/crates/cli/src/commands/error.rs index 47c72bf..fad1221 100644 --- a/crates/cli/src/commands/error.rs +++ b/crates/cli/src/commands/error.rs @@ -1,6 +1,7 @@ -use std::path::PathBuf; use thiserror::Error; +use std::path::PathBuf; + #[derive(thiserror::Error, Debug)] pub enum CommandError { #[error(transparent)] diff --git a/crates/cli/src/commands/init.rs b/crates/cli/src/commands/init.rs index 79cb143..2d99d9f 100644 --- a/crates/cli/src/commands/init.rs +++ b/crates/cli/src/commands/init.rs @@ -1,10 +1,10 @@ -use crate::commands::InitFlags; -use crate::commands::error::{CommandResult, InitError, InitResult}; +use crate::commands::{ + InitFlags, + error::{CommandResult, InitError, InitResult}, +}; use crate::config::INIT_CONFIG; -use std::fs; -use std::fs::OpenOptions; -use std::io::Write; -use std::path::Path; + +use std::{fs, fs::OpenOptions, io::Write, path::Path}; pub struct Init; From 3d22888b91eda399a262ef901df80799c228a8a9 Mon Sep 17 00:00:00 2001 From: Artem Chystiakov Date: Mon, 23 Mar 2026 16:51:55 +0200 Subject: [PATCH 5/5] clean up --- README.md | 5 ++- crates/cli/Cargo.toml | 2 +- crates/cli/src/cli.rs | 10 ++--- crates/cli/src/commands/build.rs | 4 +- crates/cli/src/commands/clean.rs | 43 ++++++++++++------- crates/cli/src/commands/core.rs | 10 ++--- crates/cli/src/commands/error.rs | 12 +----- crates/cli/src/commands/init.rs | 67 +++++++++++++++++------------- crates/cli/src/commands/regtest.rs | 4 +- crates/cli/src/commands/test.rs | 6 +-- crates/cli/src/config/core.rs | 19 ++++----- crates/cli/src/config/error.rs | 2 - crates/cli/src/error.rs | 2 - 13 files changed, 97 insertions(+), 89 deletions(-) diff --git a/README.md b/README.md index ef111d3..5ef0d6d 100644 --- a/README.md +++ b/README.md @@ -97,11 +97,12 @@ Where: Simplex CLI provides the following commands: -- `simplex init` - Initializes a Simplex project. +- `simplex init` - Initializes a new Simplex project. - `simplex config` - Prints the current config. - `simplex build` - Generates simplicity artifacts. - `simplex regtest` - Spins up local Electrs + Elements nodes. - `simplex test` - Runs Simplex tests. +- `simplex clean` - Cleans up generated artifacts. To view the available options, run the help command: @@ -119,7 +120,7 @@ We are open to any mind-blowing ideas! Please take a look at our [contributing g ## Future work -- [ ] Complete `simplex init` and `simplex clean` tasks. +- [x] Complete `simplex init` and `simplex clean` tasks. - [ ] SDK support for confidential assets, taproot signer, and custom witness signatures. - [ ] Local regtest 10x speedup. - [ ] Regtest cheat codes. diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index 8d3491e..a96e5f8 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -31,4 +31,4 @@ clap = { version = "4", features = ["derive", "env"] } tokio = { version = "1", features = ["rt-multi-thread", "macros"] } toml_edit = { version = "0.23.9" } ctrlc = { version = "3.5.2", features = ["termination"] } -serde_json = { version = "1.0.149" } \ No newline at end of file +serde_json = { version = "1.0.149" } diff --git a/crates/cli/src/cli.rs b/crates/cli/src/cli.rs index 22d56be..ad0d15d 100644 --- a/crates/cli/src/cli.rs +++ b/crates/cli/src/cli.rs @@ -9,7 +9,7 @@ use crate::commands::init::Init; use crate::commands::regtest::Regtest; use crate::commands::test::Test; use crate::config::Config; -use crate::error::CliResult; +use crate::error::CliError; #[derive(Debug, Parser)] #[command(name = "Simplex")] @@ -22,12 +22,12 @@ pub struct Cli { } impl Cli { - pub async fn run(&self) -> CliResult<()> { + pub async fn run(&self) -> Result<(), CliError> { match &self.command { Command::Init { additional_flags } => { - let smplx_conf_path = Config::get_default_path()?; - Init::init_smplx(*additional_flags, smplx_conf_path)?; - Ok(()) + let simplex_conf_path = Config::get_default_path()?; + + Ok(Init::run(*additional_flags, simplex_conf_path)?) } Command::Config => { let config_path = Config::get_default_path()?; diff --git a/crates/cli/src/commands/build.rs b/crates/cli/src/commands/build.rs index 251f7e8..337e7f2 100644 --- a/crates/cli/src/commands/build.rs +++ b/crates/cli/src/commands/build.rs @@ -1,11 +1,11 @@ use smplx_build::{ArtifactsGenerator, ArtifactsResolver, BuildConfig}; -use super::error::CommandResult; +use super::error::CommandError; pub struct Build {} impl Build { - pub fn run(config: BuildConfig) -> CommandResult<()> { + pub fn run(config: BuildConfig) -> Result<(), CommandError> { let output_dir = ArtifactsResolver::resolve_local_dir(&config.out_dir)?; let src_dir = ArtifactsResolver::resolve_local_dir(&config.src_dir)?; let files_to_build = ArtifactsResolver::resolve_files_to_build(&config.src_dir, &config.simf_files)?; diff --git a/crates/cli/src/commands/clean.rs b/crates/cli/src/commands/clean.rs index 1b2483a..220b246 100644 --- a/crates/cli/src/commands/clean.rs +++ b/crates/cli/src/commands/clean.rs @@ -1,65 +1,74 @@ -use crate::commands::{ - CleanFlags, - error::{CleanError, CleanResult, CommandResult}, -}; - -use smplx_build::{ArtifactsResolver, BuildConfig}; - use std::{ fmt::Display, fs, path::{Path, PathBuf}, }; +use smplx_build::{ArtifactsResolver, BuildConfig}; + +use crate::commands::error::CommandError; +use crate::commands::{CleanFlags, error::CleanError}; + pub struct Clean; pub struct DeletedItems(Vec); impl Clean { - pub fn run(config: BuildConfig, additional_flags: CleanFlags, config_path: impl AsRef) -> CommandResult<()> { + pub fn run( + config: BuildConfig, + additional_flags: CleanFlags, + config_path: impl AsRef, + ) -> Result<(), CommandError> { let deleted_files = Self::delete_files(config, additional_flags, config_path)?; + println!("Deleted files: {deleted_files}"); + Ok(()) } -} -impl Clean { fn delete_files( config: BuildConfig, additional_flags: CleanFlags, smplx_toml_path: impl AsRef, - ) -> CleanResult { + ) -> Result { let mut deleted_items = Vec::with_capacity(2); - let generated_artifacts = Self::remove_artifacts(config)?; + if let Some(artifacts_dir) = generated_artifacts { deleted_items.push(artifacts_dir); } + if additional_flags.all { - let simplex_toml_path = Self::remove_file(smplx_toml_path)?; + let simplex_toml_path = Self::remove_config(smplx_toml_path)?; + if let Some(simplex_toml) = simplex_toml_path { deleted_items.push(simplex_toml); } } + Ok(DeletedItems(deleted_items)) } - fn remove_artifacts(config: BuildConfig) -> CleanResult> { + fn remove_artifacts(config: BuildConfig) -> Result, CleanError> { let output_dir = ArtifactsResolver::resolve_local_dir(&config.out_dir) .map_err(|e| CleanError::ResolveOutDir(e.to_string()))?; + let res = if output_dir.exists() { fs::remove_dir_all(&output_dir).map_err(|e| CleanError::RemoveOutDir(e, output_dir.to_path_buf()))?; Some(output_dir) } else { None }; + Ok(res) } - fn remove_file(config_path: impl AsRef) -> CleanResult> { + fn remove_config(config_path: impl AsRef) -> Result, CleanError> { let config_path = config_path.as_ref().to_path_buf(); + if config_path.exists() && config_path.is_file() { fs::remove_file(&config_path).map_err(|e| CleanError::RemoveFile(e, config_path.to_path_buf()))?; + Ok(Some(config_path)) } else { Ok(None) @@ -71,14 +80,18 @@ impl Display for DeletedItems { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let paths_len = self.0.len(); let mut result = String::from("["); + for (index, path) in self.0.iter().enumerate() { result.push_str(&format!("\n\t{}", path.display())); + if index < paths_len - 1 { result.push(','); } result.push('\n'); } + result.push(']'); + write!(f, "{}", result) } } diff --git a/crates/cli/src/commands/core.rs b/crates/cli/src/commands/core.rs index 98df42b..2ff8f51 100644 --- a/crates/cli/src/commands/core.rs +++ b/crates/cli/src/commands/core.rs @@ -2,23 +2,23 @@ use clap::{Args, Subcommand}; #[derive(Debug, Subcommand)] pub enum Command { - /// Initializes the Simplex project + /// Initializes Simplex project Init { #[command(flatten)] additional_flags: InitFlags, }, - /// Prints the current Simplex config in use + /// Prints current Simplex config in use Config, /// Spins up the local Electrs + Elements regtest Regtest, - /// Runs the Simplex tests + /// Runs Simplex tests Test { #[command(subcommand)] command: TestCommand, }, /// Generates the simplicity contracts artifacts Build, - /// Clean directory after file generation inside + /// Clean Simplex artifacts in the current directory Clean { #[command(flatten)] additional_flags: CleanFlags, @@ -57,7 +57,7 @@ pub struct TestFlags { #[derive(Debug, Args, Copy, Clone)] pub struct InitFlags { - /// Generate a draft library instead of just `Simplex.toml` + /// Generate a draft Rust library instead of just `Simplex.toml` #[arg(long)] pub lib: bool, } diff --git a/crates/cli/src/commands/error.rs b/crates/cli/src/commands/error.rs index fad1221..38e27c1 100644 --- a/crates/cli/src/commands/error.rs +++ b/crates/cli/src/commands/error.rs @@ -1,5 +1,3 @@ -use thiserror::Error; - use std::path::PathBuf; #[derive(thiserror::Error, Debug)] @@ -26,9 +24,7 @@ pub enum CommandError { Io(#[from] std::io::Error), } -pub type CommandResult = Result; - -#[derive(Error, Debug)] +#[derive(thiserror::Error, Debug)] pub enum InitError { #[error("Failed to open file '{1}': {0}")] OpenFile(std::io::Error, PathBuf), @@ -55,9 +51,7 @@ pub enum InitError { NonUnicodeName(String), } -pub type InitResult = Result; - -#[derive(Error, Debug)] +#[derive(thiserror::Error, Debug)] pub enum CleanError { #[error("Failed to resolve out_dir from config, err: '{0}'")] ResolveOutDir(String), @@ -68,5 +62,3 @@ pub enum CleanError { #[error("Failed to remove file '{1}': {0}")] RemoveFile(std::io::Error, PathBuf), } - -pub type CleanResult = Result; diff --git a/crates/cli/src/commands/init.rs b/crates/cli/src/commands/init.rs index 2d99d9f..97865e2 100644 --- a/crates/cli/src/commands/init.rs +++ b/crates/cli/src/commands/init.rs @@ -1,44 +1,36 @@ -use crate::commands::{ - InitFlags, - error::{CommandResult, InitError, InitResult}, -}; +use std::{fs, fs::OpenOptions, io::Write, path::Path}; + +use crate::commands::error::CommandError; +use crate::commands::{InitFlags, error::InitError}; use crate::config::INIT_CONFIG; -use std::{fs, fs::OpenOptions, io::Write, path::Path}; +pub const SIMPLEX_CRATE_NAME: &str = "smplx-std"; pub struct Init; impl Init { - pub fn init_smplx(conf: InitFlags, smplx_conf_path: impl AsRef) -> CommandResult<()> { + pub fn run(conf: InitFlags, smplx_conf_path: impl AsRef) -> Result<(), CommandError> { if conf.lib { Self::generate_lib_inplace(&smplx_conf_path)? } - Self::fill_smplx_toml(smplx_conf_path)?; + + Self::fill_simplex_toml(smplx_conf_path)?; + Ok(()) } -} -impl Init { - fn fill_smplx_toml(config_path: impl AsRef) -> InitResult<()> { + fn fill_simplex_toml(config_path: impl AsRef) -> Result<(), InitError> { let path_to_write = config_path.as_ref(); Self::write_to_file(path_to_write, INIT_CONFIG)?; - println!("Config written to: '{}'", path_to_write.display()); - Ok(()) - } - fn get_name(path: &Path) -> InitResult<&str> { - let file_name = path - .file_name() - .ok_or_else(|| InitError::PackageName(path.to_path_buf()))?; + println!("Config written to: '{}'", path_to_write.display()); - file_name - .to_str() - .ok_or_else(|| InitError::NonUnicodeName(format!("{file_name:?}"))) + Ok(()) } - fn generate_lib_inplace(config_path: impl AsRef) -> InitResult<()> { + fn generate_lib_inplace(config_path: impl AsRef) -> Result<(), InitError> { let pwd = config_path.as_ref().parent().unwrap(); - let name = Self::get_name(pwd)?; + let name = Self::get_project_name(pwd)?; // Create `Cargo.toml` file let manifest = { @@ -47,13 +39,15 @@ impl Init { manifest["package"]["name"] = toml_edit::value(name); manifest["package"]["version"] = toml_edit::value("0.1.0"); manifest["package"]["edition"] = toml_edit::value("2024"); + let mut dep_table = toml_edit::Table::default(); dep_table.insert( - "smplx-std", + SIMPLEX_CRATE_NAME, toml_edit::Item::Value(toml_edit::Value::String(toml_edit::Formatted::new( Self::get_smplx_max_version()?, ))), ); + manifest["dependencies"] = toml_edit::Item::Table(dep_table); manifest }; @@ -63,6 +57,7 @@ impl Init { b"\ #[simplex::test] fn dummy_test(context: simplex::TestContext) { + // your test code here todo!() }" }; @@ -85,14 +80,24 @@ fn main() { Self::write_to_file(&test_rs_path, default_test_file_content)?; Self::write_to_file(&p2pk_simf_content, default_p2pk_simf_file_content)?; Self::write_to_file(&gitignore_path, default_gitignore_file_content)?; + Self::execute_cargo_fmt(lib_rs_path)?; Ok(()) } - fn get_smplx_max_version() -> InitResult { - let crate_name = "smplx-std"; - let url = format!("https://crates.io/api/v1/crates/{}", crate_name); + fn get_project_name(path: &Path) -> Result<&str, InitError> { + let file_name = path + .file_name() + .ok_or_else(|| InitError::PackageName(path.to_path_buf()))?; + + file_name + .to_str() + .ok_or_else(|| InitError::NonUnicodeName(format!("{file_name:?}"))) + } + + fn get_smplx_max_version() -> Result { + let url = format!("https://crates.io/api/v1/crates/{}", SIMPLEX_CRATE_NAME); let response = minreq::get(&url) .with_header("User-Agent", "simplex_generator") @@ -113,13 +118,15 @@ fn main() { Ok(latest_version.to_string()) } - fn write_to_file(path: impl AsRef, content: impl AsRef<[u8]>) -> InitResult<()> { + fn write_to_file(path: impl AsRef, content: impl AsRef<[u8]>) -> Result<(), InitError> { let path = path.as_ref(); + fs::create_dir_all( path.parent() .ok_or_else(|| InitError::ResolveParent(path.to_path_buf()))?, ) .map_err(|e| InitError::CreateDirs(e, path.to_path_buf()))?; + let mut file = OpenOptions::new() .create(true) .write(true) @@ -130,13 +137,17 @@ fn main() { .map_err(|e| InitError::WriteToFile(e, path.to_path_buf()))?; file.flush() .map_err(|e| InitError::WriteToFile(e, path.to_path_buf()))?; + Ok(()) } - fn execute_cargo_fmt(file: impl AsRef) -> InitResult<()> { + fn execute_cargo_fmt(file: impl AsRef) -> Result<(), InitError> { let mut cargo_test_command = std::process::Command::new("sh"); + cargo_test_command.args(["-c".to_string(), format!("rustfmt {}", file.as_ref().display())]); + let _output = cargo_test_command.output().map_err(InitError::FmtError); + Ok(()) } } diff --git a/crates/cli/src/commands/regtest.rs b/crates/cli/src/commands/regtest.rs index cbc3e46..4c44eea 100644 --- a/crates/cli/src/commands/regtest.rs +++ b/crates/cli/src/commands/regtest.rs @@ -4,12 +4,12 @@ use std::sync::atomic::{AtomicBool, Ordering}; use smplx_regtest::Regtest as RegtestRunner; use smplx_regtest::RegtestConfig; -use crate::commands::error::CommandResult; +use crate::commands::error::CommandError; pub struct Regtest {} impl Regtest { - pub fn run(config: RegtestConfig) -> CommandResult<()> { + pub fn run(config: RegtestConfig) -> Result<(), CommandError> { let (mut client, signer) = RegtestRunner::from_config(config)?; let running = Arc::new(AtomicBool::new(true)); diff --git a/crates/cli/src/commands/test.rs b/crates/cli/src/commands/test.rs index f655ff5..05adaf5 100644 --- a/crates/cli/src/commands/test.rs +++ b/crates/cli/src/commands/test.rs @@ -4,12 +4,12 @@ use std::process::Stdio; use smplx_test::TestConfig; use super::core::{TestCommand, TestFlags}; -use super::error::CommandResult; +use super::error::CommandError; pub struct Test {} impl Test { - pub fn run(config: TestConfig, command: &TestCommand) -> CommandResult<()> { + pub fn run(config: TestConfig, command: &TestCommand) -> Result<(), CommandError> { let cache_path = Self::get_test_config_cache_name()?; config.to_file(&cache_path)?; @@ -103,7 +103,7 @@ impl Test { opt_params } - fn get_test_config_cache_name() -> CommandResult { + fn get_test_config_cache_name() -> Result { const TARGET_DIR_NAME: &str = "target"; const SIMPLEX_CACHE_DIR_NAME: &str = "simplex"; const SIMPLEX_TEST_CONFIG_NAME: &str = "simplex_test_config.toml"; diff --git a/crates/cli/src/config/core.rs b/crates/cli/src/config/core.rs index ca286e1..14caf75 100644 --- a/crates/cli/src/config/core.rs +++ b/crates/cli/src/config/core.rs @@ -5,7 +5,7 @@ use smplx_build::BuildConfig; use smplx_regtest::RegtestConfig; use smplx_test::TestConfig; -use super::error::{ConfigError, ConfigResult}; +use super::error::ConfigError; pub const INIT_CONFIG: &str = include_str!("../../assets/Simplex.default.toml"); pub const CONFIG_FILENAME: &str = "Simplex.toml"; @@ -19,20 +19,15 @@ pub struct Config { } impl Config { - pub fn get_default_path() -> ConfigResult { - let cwd = std::env::current_dir()?; - Self::get_derived_default_path(cwd) + pub fn get_default_path() -> Result { + Self::get_path(std::env::current_dir()?) } - pub fn pwd() -> ConfigResult { - Ok(std::env::current_dir()?) - } - - pub fn get_derived_default_path(path: impl AsRef) -> ConfigResult { + pub fn get_path(path: impl AsRef) -> Result { Ok(path.as_ref().join(CONFIG_FILENAME)) } - pub fn load(path_buf: impl AsRef) -> ConfigResult { + pub fn load(path_buf: impl AsRef) -> Result { let path = path_buf.as_ref().to_path_buf(); if !path.is_file() { @@ -51,7 +46,7 @@ impl Config { Ok(config) } - fn validate(config: &Config) -> ConfigResult<()> { + fn validate(config: &Config) -> Result<(), ConfigError> { match config.test.esplora.clone() { Some(esplora_config) => { Self::validate_network(&esplora_config.network)?; @@ -66,7 +61,7 @@ impl Config { } } - fn validate_network(network: &String) -> ConfigResult<()> { + fn validate_network(network: &String) -> Result<(), ConfigError> { if network != "Liquid" && network != "LiquidTestnet" && network != "ElementsRegtest" { return Err(ConfigError::BadNetworkName(network.clone())); } diff --git a/crates/cli/src/config/error.rs b/crates/cli/src/config/error.rs index e4570ee..d76ca7b 100644 --- a/crates/cli/src/config/error.rs +++ b/crates/cli/src/config/error.rs @@ -26,5 +26,3 @@ pub enum ConfigError { #[error("Path doesn't exist: '{0}'")] PathNotExists(PathBuf), } - -pub type ConfigResult = Result; diff --git a/crates/cli/src/error.rs b/crates/cli/src/error.rs index 798a77e..885a3e1 100644 --- a/crates/cli/src/error.rs +++ b/crates/cli/src/error.rs @@ -11,5 +11,3 @@ pub enum CliError { #[error("IO error: '{0}'")] Io(#[from] std::io::Error), } - -pub type CliResult = Result;