1use std::io;
20use std::path::Path;
21
22use adam_lang::FormatSourceError;
23use annotate_snippets::Renderer;
24
25#[derive(Debug)]
42pub enum FormatFileError {
43 Io(io::Error),
45 Format {
47 source: String,
50 error: FormatSourceError,
52 },
53}
54
55pub 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#[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[test]
273 fn render_error_reports_a_source_snippet_for_each_recovered_error() {
274 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}