use alloc::{
format,
string::String,
vec::Vec,
};
use core::fmt;
#[cfg(feature = "cache")]
use crate::data::resources::ResourceCache;
use crate::{
data::catalog::ResolvedBuild,
errors::BunsenResult,
};
pub const CATALOG: &str = "catalog";
pub trait BuildProvider: Send + Sync + fmt::Debug {
fn name(&self) -> &str;
fn description(&self) -> &str;
fn license(&self) -> Option<&str> {
None
}
fn origin(&self) -> Option<&str> {
None
}
fn list(&self) -> Vec<ResolvedBuild>;
fn lookup(
&self,
name: &str,
) -> BunsenResult<Option<ResolvedBuild>> {
Ok(self.list().into_iter().find(|b| b.answers_to(name)))
}
#[cfg(feature = "cache")]
fn resolve(
&self,
name: &str,
cache: &ResourceCache,
) -> BunsenResult<Option<ResolvedBuild>> {
let _ = cache;
self.lookup(name)
}
fn answers_bare_names(&self) -> bool {
true
}
fn id(
&self,
build: &ResolvedBuild,
) -> String {
build.qualified_id(self.name())
}
fn ids(&self) -> Vec<String> {
self.list().iter().map(|b| self.id(b)).collect()
}
}
impl ResolvedBuild {
pub fn qualified_id(
&self,
provider: &str,
) -> String {
let name = self.name.to_string();
let reference = name
.strip_prefix(provider)
.and_then(|rest| rest.strip_prefix('/'))
.unwrap_or(&name);
format!("{provider}:{reference}")
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::data::catalog::CatalogName;
fn build(
name: &str,
aliases: &[&str],
) -> ResolvedBuild {
let mut build = ResolvedBuild::new(CatalogName::parse(name).unwrap(), "a build");
build.aliases = aliases
.iter()
.map(|a| CatalogName::parse(a).unwrap())
.collect();
build
}
#[test]
fn test_the_provided_lookup_scans_the_listing() {
#[derive(Debug)]
struct Flat;
impl BuildProvider for Flat {
fn name(&self) -> &str {
"flat"
}
fn description(&self) -> &str {
"two builds"
}
fn origin(&self) -> Option<&str> {
Some("https://flat.example")
}
fn list(&self) -> Vec<ResolvedBuild> {
alloc::vec![build("a/small", &["a/s"]), build("b/tiny", &[])]
}
}
let flat = Flat;
assert_eq!(flat.origin(), Some("https://flat.example"));
assert_eq!(flat.ids(), ["flat:a/small", "flat:b/tiny"]);
let found = |name: &str| flat.lookup(name).unwrap().map(|b| b.name.to_string());
assert_eq!(found("A/Small").as_deref(), Some("a/small"));
assert_eq!(found("s").as_deref(), Some("a/small"));
assert_eq!(found("a/s").as_deref(), Some("a/small"));
assert_eq!(found("small"), None, "a leaf of the name is no alias");
}
#[test]
fn test_the_qualified_id() {
assert_eq!(
build("hf/openai/whisper-tiny", &[]).qualified_id("hf"),
"hf:openai/whisper-tiny"
);
assert_eq!(
build("openai/whisper/tiny", &[]).qualified_id("catalog"),
"catalog:openai/whisper/tiny"
);
assert_eq!(build("hfx/a", &[]).qualified_id("hf"), "hf:hfx/a");
}
}