1use std::fmt;
5use std::path::Path;
6use std::sync::{PoisonError, RwLock};
7
8use super::format::Format;
9use super::{Input, InputError, read_text};
10
11#[derive(Clone)]
28pub struct Formats {
29 registered: Vec<&'static dyn Format>,
30}
31
32impl Formats {
33 #[must_use]
36 pub fn builtin() -> Self {
37 let formats = Self::empty();
38 #[cfg(feature = "yaml")]
39 let formats = formats.add(&super::format::YAML);
40 #[cfg(feature = "json")]
41 let formats = formats.add(&super::format::JSON);
42 #[cfg(feature = "toml")]
43 let formats = formats.add(&super::format::TOML);
44 formats
45 }
46
47 #[must_use]
49 pub const fn empty() -> Self {
50 Self {
51 registered: Vec::new(),
52 }
53 }
54
55 #[must_use]
58 #[expect(
59 clippy::should_implement_trait,
60 reason = "a builder named for what it does, as `remove` is; `Add` has no meaning here"
61 )]
62 pub fn add(mut self, format: &'static dyn Format) -> Self {
63 let name = format.name();
64 match self.registered.iter_mut().find(|held| held.name() == name) {
65 Some(held) => *held = format,
66 None => self.registered.push(format),
67 }
68 self
69 }
70
71 #[must_use]
73 pub fn remove(mut self, name: &str) -> Self {
74 self.registered.retain(|held| held.name() != name);
75 self
76 }
77
78 #[must_use]
80 pub fn get(&self, name: &str) -> Option<&'static dyn Format> {
81 self.registered
82 .iter()
83 .copied()
84 .find(|format| format.name() == name)
85 }
86
87 pub fn names(&self) -> impl Iterator<Item = &'static str> + '_ {
89 self.registered.iter().map(|format| format.name())
90 }
91
92 pub fn of(&self, path: &Path) -> Result<&'static dyn Format, InputError> {
102 let name = path.display().to_string();
103 let extension = path
104 .extension()
105 .map(|extension| extension.to_string_lossy().to_ascii_lowercase());
106 let found = extension.as_deref().and_then(|extension| {
107 self.registered
108 .iter()
109 .copied()
110 .find(|format| format.extensions().contains(&extension))
111 });
112 if let Some(format) = found {
113 return Ok(format);
114 }
115 let accepted = self.accepted();
116 match extension.as_deref() {
117 #[cfg(not(feature = "yaml"))]
118 Some(yaml @ ("yaml" | "yml")) => Err(InputError::whole(
119 name,
120 format!("`.{yaml}` needs ctl-core's input-yaml feature; {accepted}"),
121 )),
122 #[cfg(not(feature = "json"))]
123 Some("json") => Err(InputError::whole(
124 name,
125 format!("`.json` needs ctl-core's input-json feature; {accepted}"),
126 )),
127 #[cfg(not(feature = "toml"))]
128 Some("toml") => Err(InputError::whole(
129 name,
130 format!("`.toml` needs ctl-core's input-toml feature; {accepted}"),
131 )),
132 Some(other) => Err(InputError::whole(
133 name,
134 format!("unsupported extension .{other}; {accepted}"),
135 )),
136 None => Err(InputError::whole(
137 name,
138 format!("no file extension; {accepted}"),
139 )),
140 }
141 }
142
143 pub fn open(&self, path: &Path) -> Result<Input, InputError> {
154 let format = self.of(path)?;
155 let (name, text) = read_text(path)?;
156 Ok(Input::new_with_format(name, text, format))
157 }
158
159 fn accepted(&self) -> String {
162 let mut extensions: Vec<String> = Vec::new();
163 for extension in self
164 .registered
165 .iter()
166 .flat_map(|format| format.extensions())
167 {
168 let entry = format!("*.{extension}");
169 let at = extensions.partition_point(|held| *held < entry);
170 extensions.insert(at, entry);
171 }
172 match extensions.as_slice() {
173 [] => "no format is registered".to_owned(),
174 [only] => format!("name the file {only}"),
175 [first, second] => format!("name the file {first} or {second}"),
176 [rest @ .., last] => {
177 let mut listed = String::new();
178 for extension in rest {
179 listed.push_str(extension);
180 listed.push_str(", ");
181 }
182 format!("name the file {listed}or {last}")
183 }
184 }
185 }
186}
187
188impl fmt::Debug for Formats {
190 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
191 formatter
192 .debug_struct("Formats")
193 .field("names", &self.names().collect::<Vec<_>>())
194 .finish()
195 }
196}
197
198static PROCESS: RwLock<Option<Formats>> = RwLock::new(None);
199
200pub fn set_default_formats(formats: Formats) {
204 *PROCESS.write().unwrap_or_else(PoisonError::into_inner) = Some(formats);
205}
206
207#[must_use]
213pub fn default_formats() -> Formats {
214 PROCESS
215 .read()
216 .unwrap_or_else(PoisonError::into_inner)
217 .clone()
218 .unwrap_or_else(Formats::builtin)
219}
220
221#[cfg(test)]
222mod tests {
223 use super::*;
224
225 #[test]
227 fn the_process_default_replaces_the_builtin_registry() {
228 let builtin = default_formats().names().count();
229 assert!(builtin > 0, "without a call the process uses the built-ins");
230 set_default_formats(Formats::empty());
231 assert_eq!(default_formats().names().count(), 0);
232 set_default_formats(Formats::builtin());
233 assert_eq!(default_formats().names().count(), builtin);
234 }
235}