2019-05-24 01:25:55 -07:00
|
|
|
use crate::common::*;
|
|
|
|
|
|
|
|
pub(crate) struct Environment {
|
|
|
|
args: Vec<String>,
|
|
|
|
dir: Box<dyn AsRef<Path>>,
|
2020-01-04 18:58:42 -08:00
|
|
|
pub(crate) err: Box<dyn Write>,
|
2019-05-24 01:25:55 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Environment {
|
2020-01-04 18:58:42 -08:00
|
|
|
pub(crate) fn main() -> Self {
|
2019-05-24 01:25:55 -07:00
|
|
|
let dir = match env::current_dir() {
|
|
|
|
Ok(dir) => dir,
|
|
|
|
Err(error) => panic!("Failed to get current directory: {}", error),
|
|
|
|
};
|
|
|
|
|
2020-01-04 18:58:42 -08:00
|
|
|
Self::new(dir, io::stderr(), env::args())
|
2019-05-24 01:25:55 -07:00
|
|
|
}
|
|
|
|
|
2020-01-04 18:58:42 -08:00
|
|
|
pub(crate) fn run(&mut self) -> Result<(), Error> {
|
2019-05-24 01:25:55 -07:00
|
|
|
Opt::from_iter_safe(&self.args)?.run(self)
|
|
|
|
}
|
|
|
|
|
2020-01-04 18:58:42 -08:00
|
|
|
pub(crate) fn new<D, E, S, I>(dir: D, err: E, args: I) -> Self
|
2019-05-24 01:25:55 -07:00
|
|
|
where
|
|
|
|
D: AsRef<Path> + 'static,
|
|
|
|
E: Write + 'static,
|
|
|
|
S: Into<String>,
|
|
|
|
I: IntoIterator<Item = S>,
|
|
|
|
{
|
2020-01-04 18:58:42 -08:00
|
|
|
Self {
|
|
|
|
args: args.into_iter().map(Into::into).collect(),
|
2019-05-24 01:25:55 -07:00
|
|
|
dir: Box::new(dir),
|
|
|
|
err: Box::new(err),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub(crate) fn status(&mut self) -> Result<(), i32> {
|
|
|
|
if let Err(error) = self.run() {
|
|
|
|
write!(&mut self.err, "error: {}", error).ok();
|
|
|
|
Err(EXIT_FAILURE)
|
|
|
|
} else {
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub(crate) fn resolve(&self, path: impl AsRef<Path>) -> PathBuf {
|
|
|
|
self.dir.as_ref().as_ref().join(path).clean()
|
|
|
|
}
|
|
|
|
}
|