1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
//! cache managger
use super::Command;
use crate::{cache::Cache, helper::Digit};
use colored::Colorize;
use clap::{SubCommand, App, Arg, ArgMatches};

/// Abstract `data` command in `leetcode-cli`.
///
/// ## Handler
/// + update cache
/// + delete cache
/// + show the location of cache.
///
/// ## Storage Config
/// + cache -> Problems db
/// + code -> code storage dir
/// + root -> root path of `leetcode-cli`
pub struct DataCommand;

impl Command for DataCommand {
    /// `data` command usage
    fn usage<'a, 'cache>() -> App<'a, 'cache> {
        SubCommand::with_name("data")
            .about("Manage Cache")
            .visible_alias("d")
            .arg(Arg::with_name("delete")
                 .display_order(1)
                 .short("d")
                 .long("delete")
                 .help("Delete cache")
            )
            .arg(Arg::with_name("update")
                 .display_order(2)
                 .short("u")
                 .long("update")
                 .help("Update cache")
            )
    }

    /// `data` handler
    fn handler(m: &ArgMatches) -> Result<(), crate::err::Error>{
        use std::fs::File;
        use std::path::Path;
        
        let cache = Cache::new().unwrap();
        let path = cache.0.conf.storage.cache();
        let f = File::open(&path).unwrap();
        let len = format!("{}K", f.metadata().unwrap().len() / 1000);

        let out = format!(
            "  {}{}",
            Path::new(&path)
                .file_name().unwrap()
                .to_string_lossy()
                .to_string().digit(65 - (len.len() as i32))
                .bright_green(),
            len
        );

        let mut title = "\n  Cache".digit(63);
        title.push_str("Size");
        title.push_str("\n  ");
        title.push_str(&"-".repeat(65).to_string());

        let mut flags = 0;
        if m.is_present("delete") {
            flags += 1;
            cache.clean().unwrap();
            println!("{}", "ok!".bright_green());
        }

        if m.is_present("update") {
            flags += 1;
            cache.update().unwrap();
            println!("{}", "ok!".bright_green());
        }

        if flags == 0 {
            println!("{}", title.bright_black());
            println!("{}\n", out);
        }

        Ok(())
    }
}