pub trait Packager: Send + Sync {
fn name(&self) -> &str;
fn files(&self) -> &[&str];
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Npm;
impl Packager for Npm {
fn name(&self) -> &str {
"npm"
}
fn files(&self) -> &[&str] {
&["package.json", "package-lock.json"]
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Pnpm;
impl Packager for Pnpm {
fn name(&self) -> &str {
"pnpm"
}
fn files(&self) -> &[&str] {
&["pnpm-lock.yaml"]
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Yarn;
impl Packager for Yarn {
fn name(&self) -> &str {
"yarn"
}
fn files(&self) -> &[&str] {
&["yarn.lock"]
}
}
#[derive(Default)]
pub struct PackagerDetector {
options: Vec<Box<dyn Packager>>,
inputs: Vec<String>,
}
impl PackagerDetector {
pub fn new() -> Self {
Self::default()
}
pub fn add_option(&mut self, option: impl Packager + 'static) -> &mut Self {
self.options.push(Box::new(option));
self
}
pub fn add_input(&mut self, file: impl Into<String>) -> &mut Self {
self.inputs.push(file.into());
self
}
pub fn detect(&self) -> Option<&dyn Packager> {
self.options.iter().find(|p| p.files().iter().any(|f| self.inputs.iter().any(|i| i == f))).map(|p| p.as_ref())
}
}
impl std::fmt::Debug for PackagerDetector {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PackagerDetector")
.field("options", &self.options.iter().map(|o| o.name()).collect::<Vec<_>>())
.field("inputs", &self.inputs)
.finish()
}
}