mod git;
mod local;
mod registry;
use crate::Workspace;
use log::info;
use std::path::Path;
pub use registry::AlternativeRegistry;
trait CrateTrait: std::fmt::Display {
fn fetch(&self, workspace: &Workspace) -> anyhow::Result<()>;
fn purge_from_cache(&self, workspace: &Workspace) -> anyhow::Result<()>;
fn copy_source_to(&self, workspace: &Workspace, dest: &Path) -> anyhow::Result<()>;
}
enum CrateType {
Registry(registry::RegistryCrate),
Git(git::GitRepo),
Local(local::Local),
}
pub struct Crate(CrateType);
impl Crate {
pub fn registry(registry: AlternativeRegistry, name: &str, version: &str) -> Self {
Crate(CrateType::Registry(registry::RegistryCrate::new(
registry::Registry::Alternative(registry),
name,
version,
)))
}
pub fn crates_io(name: &str, version: &str) -> Self {
Crate(CrateType::Registry(registry::RegistryCrate::new(
registry::Registry::CratesIo,
name,
version,
)))
}
pub fn git(url: &str) -> Self {
Crate(CrateType::Git(git::GitRepo::new(url)))
}
pub fn local(path: &Path) -> Self {
Crate(CrateType::Local(local::Local::new(path)))
}
pub fn fetch(&self, workspace: &Workspace) -> anyhow::Result<()> {
self.as_trait().fetch(workspace)
}
pub fn purge_from_cache(&self, workspace: &Workspace) -> anyhow::Result<()> {
self.as_trait().purge_from_cache(workspace)
}
pub fn git_commit(&self, workspace: &Workspace) -> Option<String> {
if let CrateType::Git(repo) = &self.0 {
repo.git_commit(workspace)
} else {
None
}
}
pub fn copy_source_to(&self, workspace: &Workspace, dest: &Path) -> anyhow::Result<()> {
if dest.exists() {
info!(
"crate source directory {} already exists, cleaning it up",
dest.display()
);
crate::utils::remove_dir_all(dest)?;
}
self.as_trait().copy_source_to(workspace, dest)
}
fn as_trait(&self) -> &dyn CrateTrait {
match &self.0 {
CrateType::Registry(krate) => krate,
CrateType::Git(repo) => repo,
CrateType::Local(local) => local,
}
}
}
impl std::fmt::Display for Crate {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", self.as_trait())
}
}