1
use std::str::FromStr;
2
use std::{env, process};
3

            
4
pub mod cd;
5
pub mod hint;
6
pub mod matcher;
7
pub mod shell;
8

            
9
use matcher::Matcher;
10

            
11
/// Number or String input
12
#[derive(Clone, Debug)]
13
pub enum NumberOrString {
14
    Number(u8),
15
    Str(String),
16
}
17

            
18
/// Create instance from string argument
19
impl FromStr for NumberOrString {
20
    type Err = &'static str;
21

            
22
    fn from_str(s: &str) -> Result<Self, Self::Err> {
23
        Ok(s.parse::<u8>()
24
            .map(NumberOrString::Number)
25
            .unwrap_or_else(|_| NumberOrString::Str(s.to_string())))
26
    }
27
}
28

            
29
/// Run cd command
30
pub fn run_cd(target: &NumberOrString) {
31
    let matcher = Matcher::default();
32
    let cwd = env::current_dir().expect("Could not get current working directory");
33
    let new_path = match target {
34
        NumberOrString::Number(level) => cd::up_by_count(&cwd, *level as usize),
35
        NumberOrString::Str(component) => cd::up_to_target(&matcher, &cwd, component),
36
    };
37

            
38
    match new_path {
39
        Ok(new_path) => {
40
            println!("{}", new_path.display());
41
        }
42
        Err(e) => {
43
            eprintln!("{}", e);
44
            println!("{}", cwd.display());
45
            process::exit(1);
46
        }
47
    }
48
}
49

            
50
/// Run hint command
51
pub fn run_hint(term: Option<&str>) {
52
    let matcher = Matcher::default();
53
    let cwd = env::current_dir().expect("Could not get current working directory");
54
    let hint = hint::completion_for(&matcher, &cwd, term);
55

            
56
    println!("{}", hint);
57
}
58

            
59
/// Run init command
60
pub fn run_init(alias: &String, hint: &Option<String>) {
61
    match shell::initialize(alias.to_string(), hint) {
62
        Ok(shell) => println!("{}", shell.compile_script()),
63
        Err(e) => {
64
            println!("{e}");
65
            process::exit(1);
66
        }
67
    }
68
}