From 07c7cc1ce54d9e36ebff697496c5ee3672125b7d Mon Sep 17 00:00:00 2001 From: skrrb Date: Fri, 11 Mar 2022 16:46:52 +0100 Subject: [PATCH] cli: add anchor clean (#1479) --- CHANGELOG.md | 1 + cli/src/lib.rs | 31 +++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 775f374d..62c71568 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ incremented for features. ### Features +* cli: Add `anchor clean` command that's the same as `cargo clean` but preserves keypairs inside `target/deploy` ([#1470](https://github.com/project-serum/anchor/issues/1470)). * lang: Add new `AccountSysvarMismatch` error code and test cases for sysvars ([#1535](https://github.com/project-serum/anchor/pull/1535)). * spl: Add support for revoke instruction ([#1493](https://github.com/project-serum/anchor/pull/1493)). * ts: Add provider parameter to `Spl.token` factory method ([#1597](https://github.com/project-serum/anchor/pull/1597)). diff --git a/cli/src/lib.rs b/cli/src/lib.rs index a4d3d3a0..f8c486e1 100644 --- a/cli/src/lib.rs +++ b/cli/src/lib.rs @@ -189,6 +189,8 @@ pub enum Command { #[clap(subcommand)] subcmd: IdlCommand, }, + /// Remove all artifacts from the target directory except program keypairs. + Clean, /// Deploys each program in the workspace. Deploy { #[clap(short, long)] @@ -403,6 +405,7 @@ pub fn entry(opts: Opts) -> Result<()> { bootstrap, cargo_args, ), + Command::Clean => clean(&opts.cfg_override), Command::Deploy { program_name } => deploy(&opts.cfg_override, program_name), Command::Expand { program_name, @@ -2139,6 +2142,34 @@ fn cluster_url(cfg: &Config) -> String { } } +fn clean(cfg_override: &ConfigOverride) -> Result<()> { + let cfg = Config::discover(cfg_override)?.expect("Not in workspace."); + let cfg_parent = cfg.path().parent().expect("Invalid Anchor.toml"); + let target_dir = cfg_parent.join("target"); + let deploy_dir = target_dir.join("deploy"); + + for entry in fs::read_dir(target_dir)? { + let path = entry?.path(); + if path.is_dir() && path != deploy_dir { + fs::remove_dir_all(&path) + .map_err(|e| anyhow!("Could not remove directory {}: {}", path.display(), e))?; + } else if path.is_file() { + fs::remove_file(&path) + .map_err(|e| anyhow!("Could not remove file {}: {}", path.display(), e))?; + } + } + + for file in fs::read_dir(deploy_dir)? { + let path = file?.path(); + if path.extension() != Some(&OsString::from("json")) { + fs::remove_file(&path) + .map_err(|e| anyhow!("Could not remove file {}: {}", path.display(), e))?; + } + } + + Ok(()) +} + fn deploy(cfg_override: &ConfigOverride, program_str: Option) -> Result<()> { with_workspace(cfg_override, |cfg| { let url = cluster_url(cfg);