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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
//! Miscellaneous convenience functions
//! 
//! These functions make some menial tasks a little easier to do,
//! like getting the executable's name, or running a command
use std::{env, fmt};
use std::path::Path;
use std::ffi::OsStr;
use std::fs;
use std::fs::DirBuilder;
use std::process::Command;

/// Data returned by utils::run_command()
///
/// This has the command's ouput, status code, and whether it was successful or not
pub struct CommandOutput {
    pub output: String,
    pub success: bool,
    pub code: u32
}

/// Run a command and return the output, statsus code, and whether the command succeeded or not
pub fn run_command<A: IntoIterator<Item = S> + Clone, S: AsRef<OsStr>>(prog: &str, superuser: bool, args: A) -> CommandOutput {
    let mut cmd = if superuser {
        let mut cmd_t = Command::new("sudo");
        cmd_t.arg(prog);
        cmd_t
    }
    else {
        Command::new(prog)
    };

    cmd.args(args);
    let output = cmd.output().expect("Failed to launch process!");
    let success = output.status.success();
    let mut o_fmt = if success { String::from_utf8(output.stdout).unwrap() } else { String::from_utf8(output.stderr).unwrap() };
    o_fmt.pop();

    CommandOutput {
        output: o_fmt,
        success,
        code: output.status.code().unwrap_or(1) as u32
    }
}

/// Alphabetizes a vector of strings
pub fn alphabetize<L: fmt::Display>(list: &[L]) -> Vec<String> {
    // extract the strings from the generic value
    let mut string_list: Vec<String> = Vec::new();
    for item in list {
        string_list.push(item.to_string());
    }

    string_list.sort_unstable_by_key(|a| a.to_lowercase());
    string_list
}

/// Get the name of the file/directory from a file path
pub fn get_filename<D: Into<String>>(dir: D) -> String {
    let dir_t = dir.into();
    let dir_vec = dir_t.split('/');
    dir_vec.last().unwrap().to_string()
}

/// Gets the parent directory from a file path
pub fn get_parent<D: Into<String>>(dir: D) -> String {
    let dir_t = dir.into();
    let mut dir_vec: Vec<&str> = dir_t.split('/').collect();
    dir_vec.pop();
    dir_vec.pop();
    let mut new_dir= String::from("");

    for (_, folder) in dir_vec.iter().enumerate(){
        for c in folder.chars(){
            new_dir.push(c);
        }
        new_dir.push('/');
    }
    new_dir
}

/// Capitalize the first letter in a string
pub fn capitalize<W: fmt::Display>(word: W) -> String {
    let s1 = word.to_string();
    let mut v: Vec<char> = s1.chars().collect();

    for item in &mut v {
        if !item.is_ascii_digit() {
            *item = item.to_uppercase().next().unwrap();
            break;
        }
    }

    let s2: String = v.into_iter().collect();
    s2
}

/// Get the name of the executable
pub fn get_execname() -> String {
    env::args().next()
        .as_ref()
        .map(Path::new)
        .and_then(Path::file_name)
        .and_then(OsStr::to_str)
        .map(String::from).unwrap()
}

// deprecated items

/// Returns the location (starting from 0) of the first instance of a character in a string
///
/// Skips any leading digits
///
/// Useful for parsing arguments
///
/// Returns the string's length if the char is not found
#[deprecated(since = "0.6.0", note = "str::find() does the exact same thing. Will be removed in 0.7.0")]
pub fn find_char<T: Into<String>>(text: T, sym: char) -> usize {
    let mut counter = 0;

    for c in text.into().chars(){
        if c == sym{
            break;
        }
        counter += 1;
    }

    counter
}

/// Creates directory (and any parents) and handles any errors that may occur
///
/// Returns the following codes:
///
/// OK: Successfully created the directory and its parents
///
/// ERR: Unable to create the directory
#[deprecated(since = "0.6.0", note = "fs::create_dir_all() does the exact same thing as this. Will be removed in 0.7.0")]
pub fn make_dir<P: fmt::Display>(path: P) -> String {
    let mut dir_build = DirBuilder::new();
    dir_build.recursive(true);

    match dir_build.create(path.to_string()) {
        Ok(_) => "OK".to_string(),
        Err(_) => "ERR".to_string()
    }
}

/// Abstraction around fs::read_to_string() that includes error handling
///
/// Returns the file content as a `String` or returns "ERR" if something went wrong
#[deprecated(since = "0.6.0", note = "fs::read_to_string() does the exact same thing as this. Will be removed in 0.7.0")]
pub fn read_file<P: fmt::Display>(path: P) -> String {
    match fs::read_to_string(path.to_string()) {
        Ok(file) => file,
        Err(_) => "ERR".to_string()
    }
}

/// Abstraction around fs::write() that includes error handling
///
/// Returns the following codes:
///
/// OK: Save operation successful
///
/// ERR: There was a problem writing the file
#[deprecated(since = "0.6.0", note = "fs::write() does the exact same thing as this. Will be removed in 0.7.0")]
pub fn save_file<P: fmt::Display>(path: P, contents: &[u8]) -> String {
    match fs::write(path.to_string(), contents) {
        Ok(_) => "OK".to_string(),
        Err(_) => "ERR".to_string()
    }
}

/// Saves a string to a shared value (temp file in /tmp or ~/.cache)
///
/// Value must be a string value
#[allow(deprecated)]
#[deprecated(since = "0.6.0", note = "Use Mutex or RwLock instead. They have better APIs than this. Will be removed in 0.7.0")]
pub fn set_shared_val(name: &str, val: &str) {
    //get the .cache folder path
    let cache_dir = format!("{}/.cache/",env::var("HOME").unwrap());

    let code = save_file(format!("/tmp/{name}"), val.as_bytes());
    if code == "ERR" {
        save_file(format!("{cache_dir}/{name}"), val.as_bytes());
    }
}

/// Gets a shared value (temp file in /tmp or .cache)
///
/// Value must be a string value
#[allow(deprecated)]
#[deprecated(since = "0.6.0", note = "Use Mutex or RwLock instead. They have better APIs than this. Will be removed in 0.7.0")]
pub fn get_shared_val(name: &str) -> String {
    //get the .cache folder path
    let cache_dir = format!("{}/.cache/",env::var("HOME").unwrap());
    let mut val = read_file(format!("/tmp/{name}"));
    if val == "ERR" {
        val = read_file(format!("{cache_dir}/{name}"));
    }
    val
}

/// Returns a list of files/directories using path string
#[deprecated(since = "0.6.0", note = "Use fs::read_dir() instead. Will be removed in 0.7.0")]
pub fn get_dir<D: fmt::Display>(dir: D, show_hidden: bool) -> Vec<String> {
    let dir_str = dir.to_string();
    let mut dir_name = dir_str.clone();
    if !dir_str.ends_with('/') {
        dir_name = format!("{dir_str}/");
    }

    let dir = fs::read_dir(&dir_name).unwrap();
    let mut output: Vec<String> = Vec::new();
    for file in dir {
        let name = file.unwrap();
        let sep = "/".to_string();
        let filename = get_filename(name.path().display().to_string());
        let attrs = name.metadata().unwrap();
        if show_hidden || !filename.starts_with('.') {
            if attrs.is_dir() {
                let path_t = format!("{}{}", name.path().display(), sep);
                let path: Vec<&str> = path_t.split('/').collect();
                output.push(format!("{}/", path[path.len() - 2]));
            }
            else {
                output.push(get_filename(name.path().display().to_string()));
            }
        }
    }
    alphabetize(&output)
}