Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 5 additions & 4 deletions crates/cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
23 changes: 14 additions & 9 deletions crates/cli/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")]
Expand All @@ -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 => {
Expand Down Expand Up @@ -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)?)
}
}
}
}
4 changes: 2 additions & 2 deletions crates/cli/src/commands/build.rs
Original file line number Diff line number Diff line change
@@ -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)?;
Expand Down
93 changes: 93 additions & 0 deletions crates/cli/src/commands/clean.rs
Original file line number Diff line number Diff line change
@@ -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;
Comment thread
ikripaka marked this conversation as resolved.
Outdated

pub struct Clean;

pub struct DeletedItems(Vec<PathBuf>);

#[derive(Error, Debug)]
pub enum CleanError {
Comment thread
ikripaka marked this conversation as resolved.
Outdated
#[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<T> = Result<T, CleanError>;

impl Clean {
pub fn run(config: BuildConfig, additional_flags: CleanFlags, config_path: impl AsRef<Path>) -> 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<Path>,
) -> CleanResult<DeletedItems> {
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<Option<PathBuf>> {
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<Path>) -> CleanResult<Option<PathBuf>> {
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)
}
}
26 changes: 24 additions & 2 deletions crates/cli/src/commands/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)]
Expand Down Expand Up @@ -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,
}
8 changes: 8 additions & 0 deletions crates/cli/src/commands/error.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
pub type CommandResult<T> = Result<T, CommandError>;

#[derive(thiserror::Error, Debug)]
pub enum CommandError {
#[error(transparent)]
Expand All @@ -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),
}
Loading