2019-04-19 20:57:14 +00:00
|
|
|
use clap::ArgMatches;
|
2019-04-27 02:07:07 +00:00
|
|
|
use git2::Repository;
|
2019-04-19 20:57:14 +00:00
|
|
|
use std::env;
|
2019-04-23 18:51:08 +00:00
|
|
|
use std::fs;
|
2019-04-19 20:57:14 +00:00
|
|
|
use std::path::PathBuf;
|
|
|
|
|
|
|
|
pub struct Context<'a> {
|
|
|
|
pub current_dir: PathBuf,
|
2019-04-23 18:51:08 +00:00
|
|
|
pub dir_files: Vec<PathBuf>,
|
2019-04-19 20:57:14 +00:00
|
|
|
pub arguments: ArgMatches<'a>,
|
2019-04-27 02:07:07 +00:00
|
|
|
pub repository: Option<Repository>,
|
2019-04-19 20:57:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> Context<'a> {
|
|
|
|
pub fn new(arguments: ArgMatches) -> Context {
|
|
|
|
let current_dir = env::current_dir().expect("Unable to identify current directory.");
|
2019-04-23 18:51:08 +00:00
|
|
|
Context::new_with_dir(arguments, current_dir)
|
2019-04-19 20:57:14 +00:00
|
|
|
}
|
|
|
|
|
2019-04-23 18:51:08 +00:00
|
|
|
#[allow(dead_code)]
|
2019-04-19 20:57:14 +00:00
|
|
|
pub fn new_with_dir<T>(arguments: ArgMatches, dir: T) -> Context
|
|
|
|
where
|
|
|
|
T: Into<PathBuf>,
|
|
|
|
{
|
2019-04-23 18:51:08 +00:00
|
|
|
// TODO: Currently gets the physical directory. Get the logical directory.
|
|
|
|
let current_dir = Context::expand_tilde(dir.into());
|
|
|
|
|
|
|
|
let dir_files = fs::read_dir(¤t_dir)
|
|
|
|
.unwrap_or_else(|_| {
|
|
|
|
panic!(
|
|
|
|
"Unable to read current directory: {}",
|
|
|
|
current_dir.to_string_lossy()
|
|
|
|
)
|
|
|
|
})
|
|
|
|
.filter_map(Result::ok)
|
|
|
|
.map(|entry| entry.path())
|
|
|
|
.collect::<Vec<PathBuf>>();
|
|
|
|
|
2019-04-27 02:07:07 +00:00
|
|
|
let repository: Option<Repository> = Repository::discover(¤t_dir).ok();
|
|
|
|
|
2019-04-19 20:57:14 +00:00
|
|
|
Context {
|
|
|
|
arguments,
|
2019-04-27 02:07:07 +00:00
|
|
|
current_dir,
|
2019-04-23 18:51:08 +00:00
|
|
|
dir_files,
|
2019-04-27 02:07:07 +00:00
|
|
|
repository,
|
2019-04-23 18:51:08 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Convert a `~` in a path to the home directory
|
|
|
|
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);
|
2019-04-19 20:57:14 +00:00
|
|
|
}
|
2019-04-23 18:51:08 +00:00
|
|
|
dir
|
2019-04-19 20:57:14 +00:00
|
|
|
}
|
|
|
|
}
|