//! Code formatting for the editor's `POST /format` endpoint. Maps a canonical language id //! to its formatter. Errors are short messages that go back to the user as they are. use std::path::Path; /// Formats `code` as `language` (a canonical lowercase id). The output keeps the input's /// trailing-newline state: a formatter's added newline is removed when the input had none. pub fn format(language: &str, code: &str) -> Result { let out = match language { "rust" => format_rust(code)?, "javascript" => format_typescript(code, "js")?, "typescript" => format_typescript(code, "tsx")?, "json" => format_json(code)?, "css" => malva::format_text(code, malva::Syntax::Css, &Default::default()) .map_err(|err| err.to_string())?, "html" => markup_fmt::format_text( code, markup_fmt::Language::Html, &Default::default(), |code, _| Ok(code.into()), ) .map_err(|err| err.to_string())?, "yaml" => pretty_yaml::format_text(code, &Default::default()) .map_err(|err| err.to_string())?, "toml" => format_toml(code)?, "sql" => format_sql(code), "markdown" => format_markdown(code)?, _ => return Err(format!("unsupported language: {language}")), }; Ok(keep_trailing_newline(code, out)) } /// A whole file if it parses, else a snippet of statements: the snippet is wrapped in a /// function, formatted, and its body is taken back out with one indent level removed. fn format_rust(code: &str) -> Result { if let Ok(file) = syn::parse_file(code) { return Ok(prettyplease::unparse(&file)); } let wrapped = format!("fn __snippet__() {{\n{code}\n}}"); let file = syn::parse_file(&wrapped).map_err(|err| err.to_string())?; let out = prettyplease::unparse(&file); let body = out .strip_prefix("fn __snippet__() {\n") .and_then(|rest| rest.strip_suffix("}\n")) .unwrap_or(""); let lines: Vec<&str> = body .lines() .map(|line| line.strip_prefix(" ").unwrap_or(line)) .collect(); Ok(lines.join("\n") + "\n") } fn format_typescript(code: &str, extension: &str) -> Result { let config = dprint_plugin_typescript::configuration::ConfigurationBuilder::new() .indent_width(2) .build(); let file_name = format!("snippet.{extension}"); let options = dprint_plugin_typescript::FormatTextOptions { path: Path::new(&file_name), extension: Some(extension), text: code.to_owned(), config: &config, external_formatter: None, }; let out = dprint_plugin_typescript::format_text(options).map_err(|err| err.to_string())?; Ok(out.unwrap_or_else(|| code.to_owned())) } fn format_json(code: &str) -> Result { let config = dprint_plugin_json::configuration::ConfigurationBuilder::new() .indent_width(2) .build(); let out = dprint_plugin_json::format_text(Path::new("snippet.json"), code, &config) .map_err(|err| err.to_string())?; Ok(out.unwrap_or_else(|| code.to_owned())) } fn format_markdown(code: &str) -> Result { let config = dprint_plugin_markdown::configuration::ConfigurationBuilder::new().build(); let out = dprint_plugin_markdown::format_text(code, &config, |_, _, _| Ok(None)) .map_err(|err| err.to_string())?; Ok(out.unwrap_or_else(|| code.to_owned())) } /// Taplo formats what it can and skips broken ranges, so the parse errors are checked first. fn format_toml(code: &str) -> Result { match taplo::parser::parse(code).errors.first() { Some(err) => Err(err.message.clone()), None => Ok(taplo::formatter::format(code, Default::default())), } } fn format_sql(code: &str) -> String { let options = sqlformat::FormatOptions { indent: sqlformat::Indent::Spaces(2), uppercase: Some(true), ..Default::default() }; sqlformat::format(code, &sqlformat::QueryParams::None, &options) } /// Adds or removes the final newline so it matches the input. fn keep_trailing_newline(code: &str, mut out: String) -> String { match (code.ends_with('\n'), out.ends_with('\n')) { (true, false) => out.push('\n'), (false, true) => { out.pop(); } _ => {} } out } #[cfg(test)] mod tests { use super::format; #[test] fn rust_statement_snippet() { assert_eq!( format("rust", "let x=1;\nfoo(x);").unwrap(), "let x = 1;\nfoo(x);" ); assert!(format("rust", "let = ;").is_err()); } #[test] fn json_keeps_key_order_and_missing_newline() { let out = format("json", r#"{"b":1,"a":2}"#).unwrap(); assert!(!out.ends_with('\n')); assert!(out.find("\"b\"") < out.find("\"a\"")); } #[test] fn typescript_formats_and_rejects_garbage() { let out = format("typescript", "const a:number=1").unwrap(); assert!(out.contains("const a: number = 1"), "{out}"); assert!(format("typescript", "const = ;").is_err()); } }