use std::fmt;
use std::path::Path;
use std::sync::{PoisonError, RwLock};
use super::format::Format;
use super::{Input, InputError, read_text};
#[derive(Clone)]
pub struct Formats {
registered: Vec<&'static dyn Format>,
}
impl Formats {
#[must_use]
pub fn builtin() -> Self {
let formats = Self::empty();
#[cfg(feature = "yaml")]
let formats = formats.add(&super::format::YAML);
#[cfg(feature = "json")]
let formats = formats.add(&super::format::JSON);
#[cfg(feature = "toml")]
let formats = formats.add(&super::format::TOML);
formats
}
#[must_use]
pub const fn empty() -> Self {
Self {
registered: Vec::new(),
}
}
#[must_use]
#[expect(
clippy::should_implement_trait,
reason = "a builder named for what it does, as `remove` is; `Add` has no meaning here"
)]
pub fn add(mut self, format: &'static dyn Format) -> Self {
let name = format.name();
match self.registered.iter_mut().find(|held| held.name() == name) {
Some(held) => *held = format,
None => self.registered.push(format),
}
self
}
#[must_use]
pub fn remove(mut self, name: &str) -> Self {
self.registered.retain(|held| held.name() != name);
self
}
#[must_use]
pub fn get(&self, name: &str) -> Option<&'static dyn Format> {
self.registered
.iter()
.copied()
.find(|format| format.name() == name)
}
pub fn names(&self) -> impl Iterator<Item = &'static str> + '_ {
self.registered.iter().map(|format| format.name())
}
pub fn of(&self, path: &Path) -> Result<&'static dyn Format, InputError> {
let name = path.display().to_string();
let extension = path
.extension()
.map(|extension| extension.to_string_lossy().to_ascii_lowercase());
let found = extension.as_deref().and_then(|extension| {
self.registered
.iter()
.copied()
.find(|format| format.extensions().contains(&extension))
});
if let Some(format) = found {
return Ok(format);
}
let accepted = self.accepted();
match extension.as_deref() {
#[cfg(not(feature = "yaml"))]
Some(yaml @ ("yaml" | "yml")) => Err(InputError::whole(
name,
format!("`.{yaml}` needs ctl-core's input-yaml feature; {accepted}"),
)),
#[cfg(not(feature = "json"))]
Some("json") => Err(InputError::whole(
name,
format!("`.json` needs ctl-core's input-json feature; {accepted}"),
)),
#[cfg(not(feature = "toml"))]
Some("toml") => Err(InputError::whole(
name,
format!("`.toml` needs ctl-core's input-toml feature; {accepted}"),
)),
Some(other) => Err(InputError::whole(
name,
format!("unsupported extension .{other}; {accepted}"),
)),
None => Err(InputError::whole(
name,
format!("no file extension; {accepted}"),
)),
}
}
pub fn open(&self, path: &Path) -> Result<Input, InputError> {
let format = self.of(path)?;
let (name, text) = read_text(path)?;
Ok(Input::new_with_format(name, text, format))
}
fn accepted(&self) -> String {
let mut extensions: Vec<String> = Vec::new();
for extension in self
.registered
.iter()
.flat_map(|format| format.extensions())
{
let entry = format!("*.{extension}");
let at = extensions.partition_point(|held| *held < entry);
extensions.insert(at, entry);
}
match extensions.as_slice() {
[] => "no format is registered".to_owned(),
[only] => format!("name the file {only}"),
[first, second] => format!("name the file {first} or {second}"),
[rest @ .., last] => {
let mut listed = String::new();
for extension in rest {
listed.push_str(extension);
listed.push_str(", ");
}
format!("name the file {listed}or {last}")
}
}
}
}
impl fmt::Debug for Formats {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("Formats")
.field("names", &self.names().collect::<Vec<_>>())
.finish()
}
}
static PROCESS: RwLock<Option<Formats>> = RwLock::new(None);
pub fn set_default_formats(formats: Formats) {
*PROCESS.write().unwrap_or_else(PoisonError::into_inner) = Some(formats);
}
#[must_use]
pub fn default_formats() -> Formats {
PROCESS
.read()
.unwrap_or_else(PoisonError::into_inner)
.clone()
.unwrap_or_else(Formats::builtin)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_process_default_replaces_the_builtin_registry() {
let builtin = default_formats().names().count();
assert!(builtin > 0, "without a call the process uses the built-ins");
set_default_formats(Formats::empty());
assert_eq!(default_formats().names().count(), 0);
set_default_formats(Formats::builtin());
assert_eq!(default_formats().names().count(), builtin);
}
}