Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: clean cache #216

Merged
merged 8 commits into from
Jun 25, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
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
5 changes: 3 additions & 2 deletions Cargo.lock

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

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ git2_credentials = "0.13.0"

# pop-cli
clap = { version = "4.5", features = ["derive"] }
cliclack = "0.2"
cliclack = "0.3.1"
console = "0.15"
strum = "0.26"
strum_macros = "0.26"
Expand Down
126 changes: 126 additions & 0 deletions crates/pop-cli/src/commands/clean.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
// SPDX-License-Identifier: GPL-3.0
evilrobot-01 marked this conversation as resolved.
Show resolved Hide resolved

use crate::{cache, style::Theme};
use anyhow::Result;
use clap::{Args, Subcommand};
use cliclack::{clear_screen, confirm, intro, log, multiselect, outro, outro_cancel, set_theme};
use console::style;
use std::{
fs::{read_dir, remove_file},
path::PathBuf,
};

#[derive(Args)]
#[command(args_conflicts_with_subcommands = true)]
pub(crate) struct CleanArgs {
#[command(subcommand)]
pub(crate) command: Command,
}

/// Remove generated/cached artifacts.
#[derive(Subcommand)]
pub(crate) enum Command {
#[cfg(feature = "parachain")]
/// Remove cached artifacts.
#[clap(alias = "c")]
Cache(CleanCacheCommand),
}

#[derive(Args)]
pub(crate) struct CleanCacheCommand;

impl CleanCacheCommand {
/// Executes the command.
pub(crate) fn execute(self) -> Result<()> {
clear_screen()?;
set_theme(Theme);
intro(format!("{}: Remove cached artifacts", style(" Pop CLI ").black().on_magenta()))?;

// Get the cache contents
let cache = cache()?;
if !cache.exists() {
outro_cancel("🚫 The cache does not exist.")?;
return Ok(());
};
let contents = contents(&cache)?;
if contents.is_empty() {
outro(format!(
"ℹ️ The cache at {} is empty.",
cache.to_str().expect("expected local cache is invalid")
))?;
return Ok(());
}
log::info(format!(
"ℹ️ The cache is located at {}",
cache.to_str().expect("expected local cache is invalid")
))?;

// Prompt for selection of artifacts to be removed
let mut prompt = multiselect("Select the artifacts you wish to remove:").required(false);
for (name, path, size) in &contents {
prompt = prompt.item(path, name, format!("{}MiB", size / 1_048_576))
}
let selected = prompt.interact()?;
if selected.is_empty() {
outro("ℹ️ No artifacts removed")?;
return Ok(());
}

// Confirm removal
let prompt = match selected.len() {
1 => "Are you sure you want to remove the selected artifact?".into(),
_ => format!(
"Are you sure you want to remove the {} selected artifacts?",
selected.len()
),
};
if !confirm(prompt).interact()? {
outro("ℹ️ No artifacts removed")?;
return Ok(());
}

// Finally remove selected artifacts
for file in &selected {
remove_file(file)?
AlexD10S marked this conversation as resolved.
Show resolved Hide resolved
}
outro(format!("ℹ️ {} artifacts removed", selected.len()))?;
Ok(())
}
}

/// Returns the contents of the specified path.
fn contents(path: &PathBuf) -> Result<Vec<(String, PathBuf, u64)>> {
let mut contents: Vec<_> = read_dir(&path)?
.filter_map(|e| {
e.ok().and_then(|e| {
e.file_name()
.to_str()
.map(|f| (f.to_string(), e.path()))
.zip(e.metadata().ok())
.map(|f| (f.0 .0, f.0 .1, f.1.len()))
})
})
.filter(|(name, _, _)| !name.starts_with("."))
.collect();
contents.sort_by(|(a, _, _), (b, _, _)| a.cmp(b));
Ok(contents)
}

#[test]
fn contents_works() -> Result<()> {
use std::fs::File;
let temp = tempfile::tempdir()?;
let cache = temp.path().to_path_buf();
let mut files = vec!["a", "z", "1"];
for file in &files {
File::create(cache.join(file))?;
}
files.sort();

let contents = contents(&cache)?;
assert_eq!(
contents,
files.iter().map(|f| (f.to_string(), cache.join(f), 0)).collect::<Vec<_>>()
);
Ok(())
}
19 changes: 14 additions & 5 deletions crates/pop-cli/src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use serde_json::{json, Value};

pub(crate) mod build;
pub(crate) mod call;
pub(crate) mod clean;
pub(crate) mod install;
pub(crate) mod new;
pub(crate) mod test;
Expand All @@ -13,6 +14,9 @@ pub(crate) mod up;
#[derive(Subcommand)]
#[command(subcommand_required = true)]
pub(crate) enum Command {
/// Set up the environment for development by installing required packages.
#[clap(alias = "i")]
Install(install::InstallArgs),
/// Generate a new parachain, pallet or smart contract.
#[clap(alias = "n")]
#[cfg(any(feature = "parachain", feature = "contract"))]
Expand All @@ -33,15 +37,18 @@ pub(crate) enum Command {
#[clap(alias = "t")]
#[cfg(feature = "contract")]
Test(test::TestArgs),
/// Set up the environment for development by installing required packages.
#[clap(alias = "i")]
Install(install::InstallArgs),
/// Remove generated/cached artifacts.
#[clap(alias = "C")]
#[cfg(feature = "parachain")]
evilrobot-01 marked this conversation as resolved.
Show resolved Hide resolved
Clean(clean::CleanArgs),
}

impl Command {
/// Executes the command.
pub(crate) async fn execute(self) -> anyhow::Result<Value> {
match self {
#[cfg(any(feature = "parachain", feature = "contract"))]
Self::Install(args) => install::Command.execute(args).await.map(|_| Value::Null),
#[cfg(any(feature = "parachain", feature = "contract"))]
Self::New(args) => match args.command {
#[cfg(feature = "parachain")]
Expand Down Expand Up @@ -90,8 +97,10 @@ impl Command {
Err(e) => Err(e),
},
},
#[cfg(any(feature = "parachain", feature = "contract"))]
Self::Install(args) => install::Command.execute(args).await.map(|_| Value::Null),
#[cfg(feature = "parachain")]
evilrobot-01 marked this conversation as resolved.
Show resolved Hide resolved
Self::Clean(args) => match args.command {
clean::Command::Cache(cmd) => cmd.execute().map(|_| Value::Null),
},
}
}
}
Loading