Skip to main content

ctl_input/
formats.rs

1//! The registry of input formats, and the process default an input takes it
2//! from.
3
4use std::fmt;
5use std::path::Path;
6use std::sync::{PoisonError, RwLock};
7
8use super::format::Format;
9use super::{Input, InputError, read_text};
10
11/// The input formats a CLI reads, in the order they were registered.
12///
13/// [`Self::builtin`] holds `yaml`, `json` and then `toml`, each with its
14/// feature. A CLI adds a format, replaces a built-in of the same name, or
15/// removes one, then installs the set with [`set_default_formats`]. Every
16/// builder takes and returns `self`, as ctl-core's output registry does.
17///
18/// ```
19/// # #[cfg(all(feature = "yaml", feature = "json", feature = "toml"))]
20/// # {
21/// use ctl_input::Formats;
22///
23/// let formats = Formats::builtin().remove("json").remove("toml");
24/// assert_eq!(formats.names().collect::<Vec<_>>(), ["yaml"]);
25/// # }
26/// ```
27#[derive(Clone)]
28pub struct Formats {
29    registered: Vec<&'static dyn Format>,
30}
31
32impl Formats {
33    /// `yaml` with the `yaml` feature, then `json` with the `json` feature,
34    /// then `toml` with the `toml` feature.
35    #[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    /// No format: [`Self::of`] refuses every extension.
48    #[must_use]
49    pub const fn empty() -> Self {
50        Self {
51            registered: Vec::new(),
52        }
53    }
54
55    /// Register `format`, or replace the registered format of the same name.
56    /// A replacement keeps its place in the list.
57    #[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    /// Take the format called `name` out.
72    #[must_use]
73    pub fn remove(mut self, name: &str) -> Self {
74        self.registered.retain(|held| held.name() != name);
75        self
76    }
77
78    /// The registered format called `name`.
79    #[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    /// The registered names, in the order registered.
88    pub fn names(&self) -> impl Iterator<Item = &'static str> + '_ {
89        self.registered.iter().map(|format| format.name())
90    }
91
92    /// The registered format that reads a file's extension, compared without
93    /// regard to case: with the built-ins, `.toml` is TOML, `.json` is JSON,
94    /// and `.yaml` and `.yml` are YAML.
95    ///
96    /// # Errors
97    ///
98    /// An [`InputError`] with no line for any other extension or none, naming
99    /// the extension and the accepted ones. One naming the feature for a
100    /// built-in extension whose feature is off.
101    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    /// Read a file with the format this registry has for its extension. The
144    /// extension is checked before the file is read, so a file no registered
145    /// format reads is refused without being opened.
146    ///
147    /// [`Input::open`] does the same through the registry the process uses.
148    ///
149    /// # Errors
150    ///
151    /// An [`InputError`] for an extension [`Self::of`] refuses, or with the I/O
152    /// failure.
153    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    /// What a refusal tells a person to name the file: every registered
160    /// extension, sorted, as `*.ext`.
161    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
188/// Names the registered formats: a format has no `Debug`.
189impl 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
200/// Set the process-wide registry, which [`Input::open`] reads through. Without
201/// a call, the process uses [`Formats::builtin`]. [`Formats::open`] reads
202/// through a registry of the caller's instead.
203pub fn set_default_formats(formats: Formats) {
204    *PROCESS.write().unwrap_or_else(PoisonError::into_inner) = Some(formats);
205}
206
207/// The registry [`Input::open`] reads through: what [`set_default_formats`]
208/// installed, or else [`Formats::builtin`].
209///
210/// A caller that reads a file with a format it picked by name uses it to find
211/// that name, so it accepts what `Input::open` accepts.
212#[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    /// The process default is global, so this is the one test that sets it.
226    #[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}