Skip to main content

adam_fmt/
lib.rs

1//! `adam-fmt`'s core: reads one adam-lang `.adm2` file, formats it with
2//! [`adam_lang::format_source`] — the same logic `adam-lsp`'s `textDocument/formatting` handler
3//! uses, so `adam-fmt` and an editor's "Format Document" agree exactly — and writes the result
4//! back in place, only touching the file when its contents actually change.
5//!
6//! # Example
7//!
8//! ```no_run
9//! use std::path::Path;
10//!
11//! let path = Path::new("sheet.adm2");
12//! match adam_fmt::format_file(path) {
13//!     Ok(true) => println!("formatted"),
14//!     Ok(false) => println!("already formatted"),
15//!     Err(error) => eprint!("{}", adam_fmt::render_error(path, &error)),
16//! }
17//! ```
18
19use std::io;
20use std::path::Path;
21
22use adam_lang::FormatSourceError;
23use annotate_snippets::Renderer;
24
25/// Describes an I/O failure or retains the source and diagnostic for refused formatting.
26///
27/// [`format_file`] stores the original source in [`Self::Format`] without changing the file.
28///
29/// # Examples
30///
31/// ```
32/// use adam_fmt::{FormatFileError, render_error};
33/// use std::{io, path::Path};
34///
35/// let error = FormatFileError::Io(io::Error::other("unavailable"));
36/// assert_eq!(
37///     render_error(Path::new("sheet.adm2"), &error),
38///     "adam-fmt: sheet.adm2: unavailable\n"
39/// );
40/// ```
41#[derive(Debug)]
42pub enum FormatFileError {
43    /// `path` could not be read, or (only after formatting succeeds and differs) written back.
44    Io(io::Error),
45    /// `path`'s contents could not be safely formatted.
46    Format {
47        /// `path`'s original contents, needed by [`render_error`] to render a source-anchored
48        /// diagnostic.
49        source: String,
50        /// Why formatting was refused.
51        error: FormatSourceError,
52    },
53}
54
55/// Formats the adam-lang source file at `path` in place.
56///
57/// - Postcondition: on `Ok(true)`, `path`'s contents are replaced with
58///   [`adam_lang::format_source`]'s output. On `Ok(false)`, `path` is left untouched because it
59///   already matched that output exactly (no write performed).
60/// - Complexity: for n input bytes and m output bytes, reads and compares O(n + m)
61///   bytes and writes O(m) bytes when changed. Uses O(n + m) space, in addition to
62///   [`adam_lang::format_source`]'s time and space.
63///
64/// # Errors
65///
66/// Returns [`FormatFileError::Io`] if `path` can't be read, or (only after formatting succeeds
67/// and differs from the original) can't be written back. Returns [`FormatFileError::Format`] if
68/// `path`'s contents can't be safely formatted (see [`adam_lang::format_source`]'s `# Errors`).
69/// A read or format error leaves the file untouched; a write error may leave a partial write.
70///
71/// # Examples
72///
73/// ```no_run
74/// use std::path::Path;
75///
76/// let path = Path::new("sheet.adm2");
77/// let changed = adam_fmt::format_file(path)?;
78/// assert!(!adam_fmt::format_file(path)?);
79/// # Ok::<(), adam_fmt::FormatFileError>(())
80/// ```
81pub fn format_file(path: &Path) -> Result<bool, FormatFileError> {
82    let source = std::fs::read_to_string(path).map_err(FormatFileError::Io)?;
83    match adam_lang::format_source(&source) {
84        Ok(formatted) if formatted == source => Ok(false),
85        Ok(formatted) => {
86            std::fs::write(path, formatted).map_err(FormatFileError::Io)?;
87            Ok(true)
88        }
89        Err(error) => Err(FormatFileError::Format { source, error }),
90    }
91}
92
93/// Renders `error` as a human-readable diagnostic naming `path`, using `rustc`-style source
94/// snippets for a [`FormatFileError::Format`].
95///
96/// I/O diagnostics end with `\n`. Format diagnostics preserve the source renderer's
97/// styling and line endings. Print the returned string directly with `eprint!`.
98///
99/// - Complexity: copies O(p) path bytes and returns O(r) rendered bytes. Additional
100///   time and space follow the source diagnostic renderer for each format error.
101///
102/// # Examples
103///
104/// ```
105/// use adam_fmt::{FormatFileError, render_error};
106/// use std::{io, path::Path};
107///
108/// let error = FormatFileError::Io(io::Error::other("cannot read"));
109/// let diagnostic = render_error(Path::new("sheet.adm2"), &error);
110/// assert_eq!(diagnostic, "adam-fmt: sheet.adm2: cannot read\n");
111/// ```
112#[must_use]
113pub fn render_error(path: &Path, error: &FormatFileError) -> String {
114    match error {
115        FormatFileError::Io(io_error) => format!("adam-fmt: {}: {io_error}\n", path.display()),
116        FormatFileError::Format { source, error } => {
117            let renderer = Renderer::styled();
118            let filename = path.display().to_string();
119            match error {
120                FormatSourceError::Parse(parse_error) => {
121                    parse_error.format_rustc_style(source, &filename, 1, &renderer)
122                }
123                FormatSourceError::Recovered(errors) => errors
124                    .iter()
125                    .map(|e| e.format_rustc_style(source, &filename, 1, &renderer))
126                    .collect(),
127            }
128        }
129    }
130}
131
132#[cfg(test)]
133mod tests {
134    use super::*;
135
136    /// Classifies denied rewrites as I/O errors when the filesystem enforces read-only modes.
137    #[cfg(unix)]
138    #[test]
139    fn format_file_classifies_write_permission_failures() {
140        let directory = tempfile::tempdir_in(env!("CARGO_MANIFEST_DIR")).unwrap();
141        let path = directory.path().join("readonly.adm2");
142        std::fs::write(&path, "sheet   s{}").unwrap();
143        let mut permissions = std::fs::metadata(&path).unwrap().permissions();
144        permissions.set_readonly(true);
145        std::fs::set_permissions(&path, permissions).unwrap();
146        if std::fs::OpenOptions::new().write(true).open(&path).is_ok() {
147            return;
148        }
149        assert!(matches!(
150            format_file(&path),
151            Err(FormatFileError::Io(error)) if error.kind() == io::ErrorKind::PermissionDenied
152        ));
153    }
154
155    /// Retains every recovered diagnostic and leaves malformed declarations untouched on disk.
156    #[test]
157    fn format_file_preserves_source_with_recovered_errors() {
158        let directory = tempfile::tempdir_in(env!("CARGO_MANIFEST_DIR")).unwrap();
159        let path = directory.path().join("recovered.adm2");
160        let original = "sheet s {\ncell first broken;\nsource second broken;\n}";
161        std::fs::write(&path, original).unwrap();
162        assert!(matches!(
163            format_file(&path),
164            Err(FormatFileError::Format {
165                source,
166                error: FormatSourceError::Recovered(errors),
167            }) if source == original && errors.len() == 2
168        ));
169        assert_eq!(std::fs::read_to_string(path).unwrap(), original);
170    }
171
172    /// Replaces unformatted source with canonical output and reports a change.
173    #[test]
174    fn format_file_rewrites_an_unformatted_file_and_reports_a_change() {
175        let dir = tempfile::tempdir_in(env!("CARGO_MANIFEST_DIR")).unwrap();
176        let path = dir.path().join("sheet.adm2");
177        std::fs::write(&path, "sheet   s{cell x:i32=1;}").unwrap();
178
179        assert!(matches!(format_file(&path), Ok(true)));
180        assert_eq!(
181            std::fs::read_to_string(&path).unwrap(),
182            "sheet s {\n    cell x: i32 = 1;\n}\n"
183        );
184    }
185
186    /// Reports no change for canonical source and preserves its contents and modification time.
187    #[test]
188    fn format_file_leaves_an_already_formatted_file_untouched() {
189        let dir = tempfile::tempdir_in(env!("CARGO_MANIFEST_DIR")).unwrap();
190        let path = dir.path().join("sheet.adm2");
191        let formatted = "sheet s {\n    cell x: i32 = 1;\n}\n";
192        std::fs::write(&path, formatted).unwrap();
193        let modified = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_000_000);
194        std::fs::File::options()
195            .write(true)
196            .open(&path)
197            .unwrap()
198            .set_modified(modified)
199            .unwrap();
200        let modified = std::fs::metadata(&path).unwrap().modified().unwrap();
201
202        assert!(matches!(format_file(&path), Ok(false)));
203        assert_eq!(std::fs::read_to_string(&path).unwrap(), formatted);
204        assert_eq!(
205            std::fs::metadata(&path).unwrap().modified().unwrap(),
206            modified
207        );
208    }
209
210    /// Reports an I/O error for a missing path without creating the file.
211    #[test]
212    fn format_file_errors_on_a_missing_path() {
213        let dir = tempfile::tempdir_in(env!("CARGO_MANIFEST_DIR")).unwrap();
214        let path = dir.path().join("does-not-exist.adm2");
215
216        assert!(matches!(format_file(&path), Err(FormatFileError::Io(_))));
217        assert!(!path.exists());
218    }
219
220    /// Retains unparsable source in the error and leaves the file untouched.
221    #[test]
222    fn format_file_errors_on_unparsable_source_without_writing() {
223        let dir = tempfile::tempdir_in(env!("CARGO_MANIFEST_DIR")).unwrap();
224        let path = dir.path().join("sheet.adm2");
225        std::fs::write(&path, "not a sheet at all").unwrap();
226
227        assert!(matches!(
228            format_file(&path),
229            Err(FormatFileError::Format { source, .. }) if source == "not a sheet at all"
230        ));
231        assert_eq!(
232            std::fs::read_to_string(&path).unwrap(),
233            "not a sheet at all"
234        );
235    }
236
237    /// Rejects non-UTF-8 input as an I/O error without changing its bytes.
238    #[test]
239    fn format_file_errors_on_non_utf8_source_without_writing() {
240        let dir = tempfile::tempdir_in(env!("CARGO_MANIFEST_DIR")).unwrap();
241        let path = dir.path().join("sheet.adm2");
242        std::fs::write(&path, [0xff]).unwrap();
243
244        assert!(matches!(format_file(&path), Err(FormatFileError::Io(_))));
245        assert_eq!(std::fs::read(&path).unwrap(), [0xff]);
246    }
247
248    /// Names the path and I/O failure and terminates the diagnostic with a newline.
249    #[test]
250    fn render_error_reports_the_path_for_an_io_error() {
251        let error = FormatFileError::Io(io::Error::other("boom"));
252        let rendered = render_error(Path::new("missing.adm2"), &error);
253        assert!(rendered.contains("missing.adm2"));
254        assert!(rendered.contains("boom"));
255        assert!(rendered.ends_with('\n'));
256    }
257
258    /// Names the path and shows the rejected source in a parse diagnostic.
259    #[test]
260    fn render_error_reports_a_source_snippet_for_a_format_error() {
261        let source = "not a sheet at all".to_string();
262        let error = adam_lang::format_source(&source).unwrap_err();
263        let rendered = render_error(
264            Path::new("sheet.adm2"),
265            &FormatFileError::Format { source, error },
266        );
267        assert!(rendered.contains("sheet.adm2"));
268        assert!(rendered.contains("not a sheet at all"));
269    }
270
271    /// Includes each recovered diagnostic with its path and source.
272    #[test]
273    fn render_error_reports_a_source_snippet_for_each_recovered_error() {
274        // Exercises FormatSourceError::Recovered specifically (as opposed to ::Parse, covered
275        // above), since that's the variant whose `.collect()` a reviewer once mistakenly flagged
276        // as failing to compile (`String` does implement `FromIterator<String>`).
277        let source = "sheet s {\ncell x unknown_syntax;\ncell y unknown_syntax;\n}".to_string();
278        let error = adam_lang::format_source(&source).unwrap_err();
279        assert!(
280            matches!(&error, adam_lang::FormatSourceError::Recovered(errors) if errors.len() == 2)
281        );
282        let rendered = render_error(
283            Path::new("sheet.adm2"),
284            &FormatFileError::Format { source, error },
285        );
286        assert!(rendered.contains("sheet.adm2"));
287        assert!(rendered.contains("cell x unknown_syntax"));
288        assert!(rendered.contains("cell y unknown_syntax"));
289    }
290}