use std::env;
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
pub fn pop_newline<T>(string: T) -> String
where
T: std::string::ToString,
{
let mut string = string.to_string();
if string.ends_with('\n') {
string.pop();
}
string
}
pub fn is_int(s: String) -> Result<(), String> {
if s.chars().all(char::is_numeric) {
return Ok(());
}
Err(String::from("this argument only accepts integers."))
}
pub fn ucfirst<S: AsRef<str>>(s: S) -> String {
let mut c = s.as_ref().chars();
match c.next() {
None => String::new(),
Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
}
}
pub fn which<P>(program_name: P) -> bool
where
P: AsRef<Path>,
{
let exists = env::var_os("PATH").and_then(|paths| {
env::split_paths(&paths).find_map(|dir| {
let full_path = dir.join(&program_name);
if full_path.exists() {
Some(full_path)
} else {
None
}
})
});
exists.is_some()
}
pub fn count_lines<T>(buffer: T) -> Option<usize>
where
T: std::string::ToString,
{
let buf = buffer.to_string().trim().to_owned();
if !buf.is_empty() {
return Some(buf.as_bytes().iter().filter(|&&c| c == b'\n').count() + 1);
}
None
}
pub fn list_dir_entries(path: &Path) -> Vec<PathBuf> {
let mut directory_entries: Vec<PathBuf> = Vec::new();
let directory = std::fs::read_dir(path);
if let Ok(dir) = directory {
for entry in dir.flatten() {
directory_entries.push(entry.path())
}
}
directory_entries
}
pub fn path_extension(path: &Path) -> Option<&str> {
path.extension().and_then(OsStr::to_str)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_ucfirst() {
assert_eq!(ucfirst("testString"), "TestString");
}
#[test]
fn test_is_int() {
assert_eq!(is_int(String::from("1")).is_ok(), true);
}
#[test]
fn test_pop_newline() {
assert_eq!(pop_newline(String::from("Haha\n")), "Haha");
}
#[test]
fn test_path_extension() {
assert_eq!(path_extension(Path::new("test.rs")).unwrap(), "rs");
}
}