Skip to content

Commit

Permalink
refactor: hide cliclack behind a feature flag
Browse files Browse the repository at this point in the history
  • Loading branch information
beeb committed Sep 5, 2024
1 parent 9a17879 commit 236c285
Show file tree
Hide file tree
Showing 6 changed files with 105 additions and 26 deletions.
5 changes: 3 additions & 2 deletions crates/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ chrono = { version = "0.4.38", default-features = false, features = [
"serde",
"std",
] }
cliclack.workspace = true
cliclack = { workspace = true, optional = true }
const-hex = "1.12.0"
derive_more = { version = "1.0.0", features = ["from", "display", "from_str"] }
dunce = "1.0.5"
Expand Down Expand Up @@ -60,6 +60,7 @@ temp-env = { version = "0.3.6", features = ["async_closure"] }
testdir = "0.9.1"

[features]
default = ["rustls"]
default = ["rustls", "cli"]
rustls = ["reqwest/rustls-tls"]
cli = ["cliclack"]
serde = []
33 changes: 27 additions & 6 deletions crates/core/src/auth.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,22 @@
use crate::{errors::AuthError, registry::api_url, utils::login_file_path};
use cliclack::log::{info, remark, success};
use crate::{errors::AuthError, utils::login_file_path};
use serde::{Deserialize, Serialize};
use std::fs;

#[cfg(feature = "cli")]
use crate::registry::api_url;
#[cfg(feature = "cli")]
use cliclack::{
input,
log::{info, remark, success},
};
#[cfg(feature = "cli")]
use email_address_parser::{EmailAddress, ParsingOptions};
#[cfg(feature = "cli")]
use path_slash::PathBufExt as _;
#[cfg(feature = "cli")]
use reqwest::{Client, StatusCode};
use serde::{Deserialize, Serialize};
use std::{fs, path::PathBuf};
#[cfg(feature = "cli")]
use std::path::PathBuf;

pub type Result<T> = std::result::Result<T, AuthError>;

Expand All @@ -20,9 +32,12 @@ pub struct LoginResponse {
pub token: String,
}

#[cfg(feature = "cli")]
pub async fn login() -> Result<()> {
#[cfg(feature = "cli")]
remark("If you do not have an account, please visit soldeer.xyz to create one.")?;
let email: String = cliclack::input("Email address")

let email: String = input("Email address")
.validate(|input: &String| {
if input.is_empty() {
Err("Email is required")
Expand Down Expand Up @@ -51,20 +66,26 @@ pub fn get_token() -> Result<String> {
Ok(jwt)
}

#[cfg(feature = "cli")]
async fn execute_login(login: &Login) -> Result<()> {
let security_file = login_file_path()?;
let url = api_url("auth/login", &[]);
let client = Client::new();
let res = client.post(url).json(login).send().await?;
match res.status() {
s if s.is_success() => {
#[cfg(feature = "cli")]
success("Login successful")?;

let response: LoginResponse = res.json().await?;
fs::write(&security_file, response.token)?;

#[cfg(feature = "cli")]
info(format!(
"Login details saved in: {}",
PathBuf::from_slash_lossy(&security_file).to_string_lossy() // normalize separators
PathBuf::from_slash_lossy(&security_file).to_string_lossy() /* normalize separators */
))?;

Ok(())
}
StatusCode::UNAUTHORIZED => Err(AuthError::InvalidCredentials),
Expand Down
9 changes: 8 additions & 1 deletion crates/core/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use crate::{
remappings::RemappingsLocation,
utils::{get_url_type, UrlType},
};
use cliclack::{log::warning, select};
use derive_more::derive::{Display, From, FromStr};
use serde::Deserialize;
use std::{
Expand All @@ -13,6 +12,9 @@ use std::{
};
use toml_edit::{value, DocumentMut, InlineTable, Item, Table};

#[cfg(feature = "cli")]
use cliclack::{log::warning, select};

pub type Result<T> = std::result::Result<T, ConfigError>;

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
Expand Down Expand Up @@ -88,7 +90,9 @@ impl Paths {
return Ok(soldeer_path);
}

#[cfg(feature = "cli")]
warning("No soldeer config found")?;
#[cfg(feature = "cli")]
let config_option: ConfigLocation = select("Select how you want to configure Soldeer")
.initial_value("foundry")
.item("foundry", "Using foundry.toml", "recommended")
Expand All @@ -97,6 +101,9 @@ impl Paths {
.parse()
.map_err(|_| ConfigError::InvalidPromptOption)?;

#[cfg(not(feature = "cli"))]
let config_option = ConfigLocation::Foundry;

create_example_config(config_option, &foundry_path, &soldeer_path)
}
}
Expand Down
52 changes: 42 additions & 10 deletions crates/core/src/install.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,16 @@ use crate::{
registry::{get_dependency_url_remote, get_latest_supported_version},
utils::{canonicalize, hash_file, hash_folder, run_forge_command, run_git_command},
};
use cliclack::{progress_bar, MultiProgress, ProgressBar};
use path_slash::PathBufExt as _;
use std::{
fmt,
path::{Path, PathBuf},
};
use std::path::{Path, PathBuf};
use tokio::{fs, task::JoinSet};
use toml_edit::DocumentMut;

#[cfg(feature = "cli")]
use cliclack::{progress_bar, MultiProgress, ProgressBar};
#[cfg(feature = "cli")]
use std::fmt;

pub const PROGRESS_TEMPLATE: &str = "[{elapsed_precise}] {bar:30.magenta} ({pos}/{len}) {msg}";

pub type Result<T> = std::result::Result<T, InstallError>;
Expand All @@ -27,6 +28,7 @@ pub enum DependencyStatus {
Installed,
}

#[cfg(feature = "cli")]
#[derive(Clone)]
pub struct Progress {
pub multi: MultiProgress,
Expand All @@ -37,6 +39,7 @@ pub struct Progress {
pub integrity: ProgressBar,
}

#[cfg(feature = "cli")]
impl Progress {
pub fn new(multi: &MultiProgress, deps: u64) -> Self {
let versions = multi.add(progress_bar(deps).with_template(PROGRESS_TEMPLATE));
Expand Down Expand Up @@ -76,6 +79,10 @@ impl Progress {
}
}

#[cfg(not(feature = "cli"))]
#[derive(Clone)]
pub struct Progress;

#[bon::builder(on(String, into))]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct HttpInstallInfo {
Expand Down Expand Up @@ -138,7 +145,7 @@ pub async fn install_dependencies(
locks: &[LockEntry],
deps: impl AsRef<Path>,
recursive_deps: bool,
progress: Progress,
#[allow(unused_variables)] progress: Progress,
) -> Result<Vec<LockEntry>> {
let mut set = JoinSet::new();
for dep in dependencies {
Expand Down Expand Up @@ -175,32 +182,41 @@ pub async fn install_dependency(
DependencyStatus::Installed => {
// no action needed, dependency is already installed and matches the lockfile
// entry
#[cfg(feature = "cli")]
progress.increment_all();

return Ok(lock.clone());
}
DependencyStatus::FailedIntegrity => match dependency {
Dependency::Http(_) => {
// we know the folder exists because otherwise we would have gotten
// `Missing`
#[cfg(feature = "cli")]
progress.log(format!(
"Dependency {dependency} failed integrity check, reinstalling"
));

delete_dependency_files(dependency, &deps).await?;
// we won't need to retrieve the version number so we mark it as done
#[cfg(feature = "cli")]
progress.versions.inc(1);
}
Dependency::Git(_) => {
#[cfg(feature = "cli")]
progress.log(format!(
"Dependency {dependency} failed integrity check, resetting to commit {}",
lock.as_git().expect("lock entry should be of type git").rev
));

reset_git_dependency(
lock.as_git().expect("lock entry should be of type git"),
&deps,
)
.await?;
// dependency should now be at the correct commit, we can exit
#[cfg(feature = "cli")]
progress.increment_all();

return Ok(lock.clone());
}
},
Expand All @@ -212,6 +228,7 @@ pub async fn install_dependency(
.map_err(|e| InstallError::IOError { path, source: e })?;
}
// we won't need to retrieve the version number so we mark it as done
#[cfg(feature = "cli")]
progress.versions.inc(1);
}
}
Expand Down Expand Up @@ -245,7 +262,9 @@ pub async fn install_dependency(
}
};
// indicate that we have retrieved the version number
#[cfg(feature = "cli")]
progress.versions.inc(1);

let info = match &dependency {
Dependency::Http(dep) => {
HttpInstallInfo::builder().name(&dep.name).version(&version).url(url).build().into()
Expand Down Expand Up @@ -291,12 +310,14 @@ async fn install_dependency_inner(
dep: &InstallInfo,
path: impl AsRef<Path>,
subdependencies: bool,
progress: Progress,
#[allow(unused_variables)] progress: Progress,
) -> Result<LockEntry> {
match dep {
InstallInfo::Http(dep) => {
let zip_path = download_file(&dep.url, &path).await?;
#[cfg(feature = "cli")]
progress.downloads.inc(1);

let zip_integrity = tokio::task::spawn_blocking({
let zip_path = zip_path.clone();
move || hash_file(zip_path)
Expand All @@ -313,16 +334,22 @@ async fn install_dependency_inner(
}
}
unzip_file(&zip_path, &path).await?;
#[cfg(feature = "cli")]
progress.unzip.inc(1);

if subdependencies {
install_subdependencies(&path).await?;
}
#[cfg(feature = "cli")]
progress.subdependencies.inc(1);

let integrity = hash_folder(&path).map_err(|e| InstallError::IOError {
path: path.as_ref().to_path_buf(),
source: e,
})?;
#[cfg(feature = "cli")]
progress.integrity.inc(1);

Ok(HttpLockEntry::builder()
.name(&dep.name)
.version(&dep.version)
Expand All @@ -336,13 +363,18 @@ async fn install_dependency_inner(
// if the dependency was specified without a commit hash and we didn't have a lockfile,
// clone the default branch
let commit = clone_repo(&dep.git, dep.identifier.as_ref(), &path).await?;
#[cfg(feature = "cli")]
progress.downloads.inc(1);

if subdependencies {
install_subdependencies(&path).await?;
}
progress.unzip.inc(1);
progress.subdependencies.inc(1);
progress.integrity.inc(1);
#[cfg(feature = "cli")]
{
progress.unzip.inc(1);
progress.subdependencies.inc(1);
progress.integrity.inc(1);
}
Ok(GitLockEntry::builder()
.name(&dep.name)
.version(&dep.version)
Expand Down
28 changes: 21 additions & 7 deletions crates/core/src/push.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@ use crate::{
registry::{api_url, get_project_id},
utils::read_file,
};
use cliclack::log::{info, remark, success};
use ignore::{WalkBuilder, WalkState};
use path_slash::{PathBufExt as _, PathExt as _};
use path_slash::PathExt as _;
use regex::Regex;
use reqwest::{
header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE},
Expand All @@ -21,6 +20,11 @@ use std::{
};
use zip::{write::SimpleFileOptions, CompressionMethod, ZipWriter};

#[cfg(feature = "cli")]
use cliclack::log::{info, remark, success};
#[cfg(feature = "cli")]
use path_slash::PathBufExt as _;

pub type Result<T> = std::result::Result<T, PublishError>;

pub async fn push_version(
Expand All @@ -41,11 +45,13 @@ pub async fn push_version(
};

if dry_run {
#[cfg(feature = "cli")]
info(format!(
"Zip file created at {}",
PathBuf::from_slash_lossy(&zip_archive).to_string_lossy()
))
.ok();

return Ok(());
}

Expand Down Expand Up @@ -196,7 +202,9 @@ async fn push_to_repo(
let response = client.post(url).headers(headers.clone()).multipart(form).send().await?;
match response.status() {
StatusCode::OK => {
#[cfg(feature = "cli")]
success("Pushed to repository!").ok();

Ok(())
}
StatusCode::NO_CONTENT => Err(PublishError::ProjectNotFound),
Expand All @@ -212,12 +220,18 @@ async fn push_to_repo(

// Function to prompt the user for confirmation
pub fn prompt_user_for_confirmation() -> Result<bool> {
remark("You are about to include some sensitive files in this version").ok();
info("If you are not sure which files will be included, you can run the command with `--dry-run`and inspect the generated zip file.").ok();
#[cfg(feature = "cli")]
{
remark("You are about to include some sensitive files in this version").ok();
info("If you are not sure which files will be included, you can run the command with `--dry-run`and inspect the generated zip file.").ok();

cliclack::confirm("Do you want to continue?")
.interact()
.map_err(|e| PublishError::IOError { path: PathBuf::new(), source: e })
}

cliclack::confirm("Do you want to continue?")
.interact()
.map_err(|e| PublishError::IOError { path: PathBuf::new(), source: e })
#[cfg(not(feature = "cli"))]
Ok(true)
}

#[cfg(test)]
Expand Down
Loading

0 comments on commit 236c285

Please sign in to comment.