Browse Source

cli: add anchor clean (#1479)

skrrb 3 years ago
parent
commit
07c7cc1ce5
2 changed files with 32 additions and 0 deletions
  1. 1 0
      CHANGELOG.md
  2. 31 0
      cli/src/lib.rs

+ 1 - 0
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)).

+ 31 - 0
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<String>) -> Result<()> {
     with_workspace(cfg_override, |cfg| {
         let url = cluster_url(cfg);