use aleo_std;
use leo_errors::Result;
use leo_package::{Manifest, Workspace};
use aleo_std::aleo_dir;
use std::{env::current_dir, path::PathBuf};
#[derive(Clone)]
pub struct Context {
pub path: Option<PathBuf>,
pub home: Option<PathBuf>,
pub recursive: bool,
pub package_filter: Option<String>,
}
impl Context {
pub fn new(
path: Option<PathBuf>,
home: Option<PathBuf>,
recursive: bool,
package_filter: Option<String>,
) -> Result<Context> {
Ok(Context { path, home, recursive, package_filter })
}
pub fn parent_dir(&self) -> Result<PathBuf> {
match &self.path {
Some(path) => {
let mut path = path.clone();
path.pop();
Ok(path)
}
None => Ok(current_dir().map_err(crate::errors::cli_io_error)?),
}
}
pub fn dir(&self) -> Result<PathBuf> {
match &self.path {
Some(path) => Ok(path.clone()),
None => Ok(current_dir().map_err(crate::errors::cli_io_error)?),
}
}
pub fn home(&self) -> Result<PathBuf> {
match &self.home {
Some(path) => Ok(path.clone()),
None => Ok(aleo_dir()),
}
}
pub fn open_manifest(&self) -> Result<Manifest> {
let path = self.dir()?;
let manifest_path = path.join(leo_package::MANIFEST_FILENAME);
let manifest = Manifest::read_from_file(manifest_path)?;
Ok(manifest)
}
pub fn resolve_targets(&self) -> Result<Option<(PathBuf, Vec<PathBuf>)>> {
let dir = self.dir()?;
let workspace = match Workspace::discover(&dir)? {
Some(ws) => ws,
None => {
if self.package_filter.is_some() {
return Err(crate::errors::workspace_no_workspace().into());
}
return Ok(None);
}
};
let root = workspace.root_directory.clone();
if let Some(ref filter) = self.package_filter {
match workspace.find_member(filter) {
Some(path) => Ok(Some((root, vec![path.clone()]))),
None => Err(crate::errors::workspace_package_not_found(filter, root.display()).into()),
}
} else {
let canonical = dir.canonicalize().unwrap_or_else(|_| dir.clone());
if canonical == workspace.root_directory {
Ok(Some((root, workspace.member_paths)))
} else if workspace.is_member(&canonical) {
Ok(Some((root, vec![canonical])))
} else {
Ok(None)
}
}
}
pub fn with_path(&self, path: PathBuf) -> Self {
Context { path: Some(path), home: self.home.clone(), recursive: self.recursive, package_filter: None }
}
}