summaryrefslogtreecommitdiff
path: root/src/utils.rs
blob: 9c08fd3317f2e5b49c4103196f055d4ec3c46326 (plain)
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
86
87
88
89
90
use colored::Colorize;
use std::fmt::Debug;
use std::io::Write;
use std::process::exit;

pub fn log_warning(msg: &str) {
    let msg = format!("⚠️ {}", msg).yellow();
    println!("{}", msg);
}

pub fn log_error(msg: &str) {
    let msg = format!("❌ {}", msg).red();
    println!("{}", msg);
}

pub fn log_info(msg: &str) {
    let msg = format!("ℹ️  {}", msg).bright_blue();
    println!("{}", msg);
}

pub fn log_check(msg: &str) {
    let msg = format!("✅ {}", msg).bright_green();
    println!("{}", msg);
}

pub fn assert_result<E>(res: &Result<String, E>, error_msg: &str) where E: Debug {
    if res.is_err() {
        log_error(error_msg);
        log_error(&format!("{:?}", res));
        exit(1);
    }
}

pub fn get_repo_name(repo: &str) -> String {
    let mut chars = repo.chars().rev();
    let length = repo.chars().count();
    let mut last_i = 0;
    let mut first_i = 0;

    let mut i = length;

    while i > 0 {
        match chars.next() {
            Some('.') => {
                last_i = i - 1;
            }
            Some('/') => {
                first_i = i;
                break;
            }
            _ => {}
        }
        i -= 1;
    }

    if last_i == 0 {
        last_i = length;
    }

    let name = &repo[first_i..last_i];
    // TODO: Return a Result (may be error)
    return name.to_string();
}

pub fn run_shell_command(command: &str, folder: &str, verbose: bool) -> Result<String, String> {
    let output = std::process::Command::new("sh")
        .current_dir(folder)
        .stdin(std::process::Stdio::inherit())
        .arg("-c")
        .arg(command)
        .output()
        .expect("Error running command.");

    if verbose {
        std::io::stdout().write_all(&output.stdout).unwrap();
        std::io::stderr().write_all(&output.stderr).unwrap();
    }

    match output.status.success() {
        true => {
            let stdout_str = String::from_utf8(output.stdout).unwrap();
            return Ok(stdout_str);
        }

        false => {
            let stderr_str = String::from_utf8(output.stderr).unwrap();
            return Err(stderr_str);
        }
    }
}