|
| 1 | +use std::path::{Path, PathBuf}; |
| 2 | + |
| 3 | +use anyhow::{anyhow, Context}; |
| 4 | +use codespan_reporting::files::SimpleFile; |
| 5 | +use rhai_common::{environment::Environment, util::Normalize}; |
| 6 | +use rhai_fmt::format_syntax; |
| 7 | + |
| 8 | +use crate::{args::FmtCommand, Rhai}; |
| 9 | + |
| 10 | +impl<E: Environment> Rhai<E> { |
| 11 | + pub async fn execute_fmt(&mut self, cmd: FmtCommand) -> Result<(), anyhow::Error> { |
| 12 | + let cwd = self |
| 13 | + .env |
| 14 | + .cwd() |
| 15 | + .context("invalid working directory")? |
| 16 | + .normalize(); |
| 17 | + |
| 18 | + let hir = self.load_hir(&cwd).await?; |
| 19 | + |
| 20 | + if let Some(mut files) = cmd.files { |
| 21 | + if self.env.is_dir(Path::new(&files)) { |
| 22 | + files = PathBuf::from(files) |
| 23 | + .join("**/*.rhai") |
| 24 | + .normalize() |
| 25 | + .to_string_lossy() |
| 26 | + .into(); |
| 27 | + } |
| 28 | + |
| 29 | + self.config.source.include = Some(vec![files]); |
| 30 | + self.config.source.exclude = None; |
| 31 | + } |
| 32 | + |
| 33 | + self.config.prepare( |
| 34 | + &self.env, |
| 35 | + &self.env.cwd().context("invalid working directory")?, |
| 36 | + )?; |
| 37 | + |
| 38 | + let files = self.collect_files(&cwd, &self.config, true).await?; |
| 39 | + |
| 40 | + let mut result = Ok(()); |
| 41 | + |
| 42 | + let mut format_opts = rhai_fmt::Options::default(); |
| 43 | + format_opts.update(self.config.fmt.options.clone()); |
| 44 | + |
| 45 | + for path in files { |
| 46 | + let f = self.env.read_file(&path).await?; |
| 47 | + let source = String::from_utf8_lossy(&f).into_owned(); |
| 48 | + |
| 49 | + let parser = rhai_rowan::Parser::new(&source).with_operators(hir.parser_operators()); |
| 50 | + |
| 51 | + let p = if rhai_rowan::util::is_rhai_def(&source) { |
| 52 | + parser.parse_def() |
| 53 | + } else { |
| 54 | + parser.parse_script() |
| 55 | + }; |
| 56 | + |
| 57 | + if !p.errors.is_empty() { |
| 58 | + self.print_parse_errors( |
| 59 | + &SimpleFile::new(&*path.to_string_lossy(), source.as_str()), |
| 60 | + &p.errors, |
| 61 | + ) |
| 62 | + .await?; |
| 63 | + |
| 64 | + if !cmd.force { |
| 65 | + if cmd.check { |
| 66 | + result = Err(anyhow!("some files had syntax errors")); |
| 67 | + } else { |
| 68 | + result = Err(anyhow!( |
| 69 | + "some files were not formatted due to syntax errors" |
| 70 | + )); |
| 71 | + } |
| 72 | + |
| 73 | + continue; |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + let formatted = format_syntax(p.into_syntax(), format_opts.clone()); |
| 78 | + |
| 79 | + if source != formatted { |
| 80 | + if cmd.check { |
| 81 | + tracing::error!(?path, "the file is not properly formatted"); |
| 82 | + result = Err(anyhow!("some files were not properly formatted")); |
| 83 | + } else { |
| 84 | + self.env.write_file(&path, formatted.as_bytes()).await?; |
| 85 | + } |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + result |
| 90 | + } |
| 91 | +} |
0 commit comments