wash_cli/
drain.rs

1use std::collections::HashMap;
2
3use anyhow::Result;
4use serde_json::json;
5use wash_lib::cli::CommandOutput;
6use wash_lib::config::{host_pid_file, wadm_pid_file};
7use wash_lib::drain::Drain;
8
9pub fn handle_command(cmd: Drain) -> Result<CommandOutput, anyhow::Error> {
10    if matches!(cmd, Drain::All | Drain::Downloads) {
11        let wasmcloud_pid_path = host_pid_file().unwrap();
12        let wadm_pid_path = wadm_pid_file().unwrap();
13
14        if wasmcloud_pid_path.exists() || wadm_pid_path.exists() {
15            anyhow::bail!("Cannot clear the caches : wasmcloud and wadm PID files are still present on disk, processes might still be active or were not properly terminated.")
16        }
17    }
18    let paths = cmd.drain()?;
19    let mut map = HashMap::new();
20    map.insert("drained".to_string(), json!(paths));
21    Ok(CommandOutput::new(
22        format!("Successfully cleared caches at: {paths:?}"),
23        map,
24    ))
25}
26
27#[cfg(test)]
28mod test {
29    use super::*;
30    use clap::Parser;
31
32    #[derive(Parser)]
33    struct Cmd {
34        #[clap(subcommand)]
35        drain: Drain,
36    }
37
38    #[test]
39    // Enumerates all options of drain subcommands to ensure
40    // changes are not made to the drain API
41    fn test_drain_comprehensive() {
42        let all: Cmd = Parser::try_parse_from(["drain", "all"]).unwrap();
43        match all.drain {
44            Drain::All => {}
45            _ => panic!("drain constructed incorrect command"),
46        }
47        let lib: Cmd = Parser::try_parse_from(["drain", "lib"]).unwrap();
48        match lib.drain {
49            Drain::Lib => {}
50            _ => panic!("drain constructed incorrect command"),
51        }
52        let oci: Cmd = Parser::try_parse_from(["drain", "oci"]).unwrap();
53        match oci.drain {
54            Drain::Oci => {}
55            _ => panic!("drain constructed incorrect command"),
56        }
57    }
58}