use crate::config::StarshipConfig;
use crate::module::Module;
use clap::ArgMatches;
use git2::{Repository, RepositoryState};
use once_cell::sync::OnceCell;
use std::collections::HashMap;
use std::env;
use std::ffi::OsStr;
use std::fs;
use std::path::{Path, PathBuf};
use std::string::String;
use std::time::{Duration, SystemTime};
pub struct Context<'a> {
pub config: StarshipConfig,
pub current_dir: PathBuf,
dir_files: OnceCell<Vec<PathBuf>>,
pub properties: HashMap<&'a str, String>,
repo: OnceCell<Repo>,
}
impl<'a> Context<'a> {
pub fn new(arguments: ArgMatches) -> Context {
let path = arguments
.value_of("path")
.map(From::from)
.unwrap_or_else(|| {
env::var("PWD").map(PathBuf::from).unwrap_or_else(|err| {
log::debug!("Unable to get path from $PWD: {}", err);
env::current_dir().expect("Unable to identify current directory.")
})
});
Context::new_with_dir(arguments, path)
}
pub fn new_with_dir<T>(arguments: ArgMatches, dir: T) -> Context
where
T: Into<PathBuf>,
{
let config = StarshipConfig::initialize();
let properties: HashMap<&str, std::string::String> = arguments
.args
.iter()
.filter(|(_, v)| !v.vals.is_empty())
.map(|(a, b)| (*a, b.vals.first().cloned().unwrap().into_string().unwrap()))
.collect();
let current_dir = Context::expand_tilde(dir.into());
Context {
config,
properties,
current_dir,
dir_files: OnceCell::new(),
repo: OnceCell::new(),
}
}
fn expand_tilde(dir: PathBuf) -> PathBuf {
if dir.starts_with("~") {
let without_home = dir.strip_prefix("~").unwrap();
return dirs::home_dir().unwrap().join(without_home);
}
dir
}
pub fn new_module(&self, name: &str) -> Module {
let config = self.config.get_module_config(name);
Module::new(name, config)
}
pub fn is_module_disabled_in_config(&self, name: &str) -> bool {
let config = self.config.get_module_config(name);
let disabled = config.and_then(|table| table.as_table()?.get("disabled")?.as_bool());
disabled == Some(true)
}
pub fn try_begin_scan(&'a self) -> Option<ScanDir<'a>> {
Some(ScanDir {
dir_files: self.get_dir_files().ok()?,
files: &[],
folders: &[],
extensions: &[],
})
}
pub fn get_repo(&self) -> Result<&Repo, std::io::Error> {
self.repo
.get_or_try_init(|| -> Result<Repo, std::io::Error> {
let repository = Repository::discover(&self.current_dir).ok();
let branch = repository
.as_ref()
.and_then(|repo| get_current_branch(repo));
let root = repository
.as_ref()
.and_then(|repo| repo.workdir().map(Path::to_path_buf));
let state = repository.as_ref().map(|repo| repo.state());
Ok(Repo {
branch,
root,
state,
})
})
}
pub fn get_dir_files(&self) -> Result<&Vec<PathBuf>, std::io::Error> {
let start_time = SystemTime::now();
let scan_timeout = Duration::from_millis(self.config.get_root_config().scan_timeout);
self.dir_files
.get_or_try_init(|| -> Result<Vec<PathBuf>, std::io::Error> {
let dir_files = fs::read_dir(&self.current_dir)?
.take_while(|_item| {
SystemTime::now().duration_since(start_time).unwrap() < scan_timeout
})
.filter_map(Result::ok)
.map(|entry| entry.path())
.collect::<Vec<PathBuf>>();
log::trace!(
"Building a vector of directory files took {:?}",
SystemTime::now().duration_since(start_time).unwrap()
);
Ok(dir_files)
})
}
}
pub struct Repo {
pub branch: Option<String>,
pub root: Option<PathBuf>,
pub state: Option<RepositoryState>,
}
pub struct ScanDir<'a> {
dir_files: &'a Vec<PathBuf>,
files: &'a [&'a str],
folders: &'a [&'a str],
extensions: &'a [&'a str],
}
impl<'a> ScanDir<'a> {
pub const fn set_files(mut self, files: &'a [&'a str]) -> Self {
self.files = files;
self
}
pub const fn set_extensions(mut self, extensions: &'a [&'a str]) -> Self {
self.extensions = extensions;
self
}
pub const fn set_folders(mut self, folders: &'a [&'a str]) -> Self {
self.folders = folders;
self
}
pub fn is_match(&self) -> bool {
self.dir_files.iter().any(|path| {
if path.is_dir() {
path_has_name(path, self.folders)
} else {
path_has_name(path, self.files) || has_extension(path, self.extensions)
}
})
}
}
pub fn path_has_name<'a>(dir_entry: &PathBuf, names: &'a [&'a str]) -> bool {
let found_file_or_folder_name = names.iter().find(|file_or_folder_name| {
dir_entry
.file_name()
.and_then(OsStr::to_str)
.unwrap_or_default()
== **file_or_folder_name
});
match found_file_or_folder_name {
Some(name) => !name.is_empty(),
None => false,
}
}
pub fn has_extension<'a>(dir_entry: &PathBuf, extensions: &'a [&'a str]) -> bool {
if let Some(file_name) = dir_entry.file_name() {
if file_name.to_string_lossy().starts_with('.') {
return false;
}
return extensions.iter().any(|ext| {
dir_entry
.extension()
.and_then(OsStr::to_str)
.map_or(false, |e| e == *ext)
});
}
false
}
fn get_current_branch(repository: &Repository) -> Option<String> {
let head = repository.head().ok()?;
let shorthand = head.shorthand();
shorthand.map(std::string::ToString::to_string)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_path_has_name() {
let mut buf = PathBuf::from("/");
let files = vec!["package.json"];
assert_eq!(path_has_name(&buf, &files), false);
buf.set_file_name("some-file.js");
assert_eq!(path_has_name(&buf, &files), false);
buf.set_file_name("package.json");
assert_eq!(path_has_name(&buf, &files), true);
}
#[test]
fn test_has_extension() {
let mut buf = PathBuf::from("/");
let extensions = vec!["js"];
assert_eq!(has_extension(&buf, &extensions), false);
buf.set_file_name("some-file.rs");
assert_eq!(has_extension(&buf, &extensions), false);
buf.set_file_name(".some-file.js");
assert_eq!(has_extension(&buf, &extensions), false);
buf.set_file_name("some-file.js");
assert_eq!(has_extension(&buf, &extensions), true)
}
#[test]
fn test_criteria_scan_fails() {
let failing_criteria = ScanDir {
dir_files: &vec![PathBuf::new()],
files: &["package.json"],
extensions: &["js"],
folders: &["node_modules"],
};
assert_eq!(failing_criteria.is_match(), false);
let failing_dir_criteria = ScanDir {
dir_files: &vec![PathBuf::from("/package.js/dog.go")],
files: &["package.json"],
extensions: &["js"],
folders: &["node_modules"],
};
assert_eq!(failing_dir_criteria.is_match(), false);
}
#[test]
fn test_criteria_scan_passes() {
let passing_criteria = ScanDir {
dir_files: &vec![PathBuf::from("package.json")],
files: &["package.json"],
extensions: &["js"],
folders: &["node_modules"],
};
assert_eq!(passing_criteria.is_match(), true);
}
}