leetcode_cli/cmds/
data.rs

1//! Cache managger
2use super::Command;
3use crate::{cache::Cache, helper::Digit, Error};
4use async_trait::async_trait;
5use clap::{Arg, ArgAction, ArgMatches, Command as ClapCommand};
6use colored::Colorize;
7
8/// Abstract `data` command
9///
10/// ```sh
11/// leetcode-data
12/// Manage Cache
13///
14/// USAGE:
15///     leetcode data [FLAGS]
16///
17/// FLAGS:
18///     -d, --delete     Delete cache
19///     -u, --update     Update cache
20///     -h, --help       Prints help information
21///     -V, --version    Prints version information
22/// ```
23pub struct DataCommand;
24
25#[async_trait]
26impl Command for DataCommand {
27    /// `data` command usage
28    fn usage() -> ClapCommand {
29        ClapCommand::new("data")
30            .about("Manage Cache")
31            .visible_alias("d")
32            .arg(
33                Arg::new("delete")
34                    .display_order(1)
35                    .short('d')
36                    .long("delete")
37                    .help("Delete cache")
38                    .action(ArgAction::SetTrue),
39            )
40            .arg(
41                Arg::new("update")
42                    .display_order(2)
43                    .short('u')
44                    .long("update")
45                    .help("Update cache")
46                    .action(ArgAction::SetTrue),
47            )
48    }
49
50    /// `data` handler
51    async fn handler(m: &ArgMatches) -> Result<(), Error> {
52        use std::fs::File;
53        use std::path::Path;
54
55        let cache = Cache::new()?;
56        let path = cache.0.conf.storage.cache()?;
57        let f = File::open(&path)?;
58        let len = format!("{}K", f.metadata()?.len() / 1000);
59
60        let out = format!(
61            "  {}{}",
62            Path::new(&path)
63                .file_name()
64                .ok_or(Error::NoneError)?
65                .to_string_lossy()
66                .to_string()
67                .digit(65 - (len.len() as i32))
68                .bright_green(),
69            len
70        );
71
72        let mut title = "\n  Cache".digit(63);
73        title.push_str("Size");
74        title.push_str("\n  ");
75        title.push_str(&"-".repeat(65));
76
77        let mut flags = 0;
78        if m.get_flag("delete") {
79            flags += 1;
80            cache.clean()?;
81            println!("{}", "ok!".bright_green());
82        }
83
84        if m.get_flag("update") {
85            flags += 1;
86            cache.update().await?;
87            println!("{}", "ok!".bright_green());
88        }
89
90        if flags == 0 {
91            println!("{}", title.bright_black());
92            println!("{}\n", out);
93        }
94
95        Ok(())
96    }
97}