forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

format.rs140 lines, 5.1 KiBHistoryRawDownload
1//! Code formatting for the editor's `POST /format` endpoint. Maps a canonical language id
2//! to its formatter. Errors are short messages that go back to the user as they are.
3
4use std::path::Path;
5
6/// Formats `code` as `language` (a canonical lowercase id). The output keeps the input's
7/// trailing-newline state: a formatter's added newline is removed when the input had none.
8pub fn format(language: &str, code: &str) -> Result<String, String> {
9 let out = match language {
10 "rust" => format_rust(code)?,
11 "javascript" => format_typescript(code, "js")?,
12 "typescript" => format_typescript(code, "tsx")?,
13 "json" => format_json(code)?,
14 "css" => malva::format_text(code, malva::Syntax::Css, &Default::default())
15 .map_err(|err| err.to_string())?,
16 "html" => markup_fmt::format_text(
17 code,
18 markup_fmt::Language::Html,
19 &Default::default(),
20 |code, _| Ok(code.into()),
21 )
22 .map_err(|err| err.to_string())?,
23 "yaml" => pretty_yaml::format_text(code, &Default::default())
24 .map_err(|err| err.to_string())?,
25 "toml" => format_toml(code)?,
26 "sql" => format_sql(code),
27 "markdown" => format_markdown(code)?,
28 _ => return Err(format!("unsupported language: {language}")),
29 };
30 Ok(keep_trailing_newline(code, out))
31}
32
33/// A whole file if it parses, else a snippet of statements: the snippet is wrapped in a
34/// function, formatted, and its body is taken back out with one indent level removed.
35fn format_rust(code: &str) -> Result<String, String> {
36 if let Ok(file) = syn::parse_file(code) {
37 return Ok(prettyplease::unparse(&file));
38 }
39 let wrapped = format!("fn __snippet__() {{\n{code}\n}}");
40 let file = syn::parse_file(&wrapped).map_err(|err| err.to_string())?;
41 let out = prettyplease::unparse(&file);
42 let body = out
43 .strip_prefix("fn __snippet__() {\n")
44 .and_then(|rest| rest.strip_suffix("}\n"))
45 .unwrap_or("");
46 let lines: Vec<&str> = body
47 .lines()
48 .map(|line| line.strip_prefix(" ").unwrap_or(line))
49 .collect();
50 Ok(lines.join("\n") + "\n")
51}
52
53fn format_typescript(code: &str, extension: &str) -> Result<String, String> {
54 let config = dprint_plugin_typescript::configuration::ConfigurationBuilder::new()
55 .indent_width(2)
56 .build();
57 let file_name = format!("snippet.{extension}");
58 let options = dprint_plugin_typescript::FormatTextOptions {
59 path: Path::new(&file_name),
60 extension: Some(extension),
61 text: code.to_owned(),
62 config: &config,
63 external_formatter: None,
64 };
65 let out = dprint_plugin_typescript::format_text(options).map_err(|err| err.to_string())?;
66 Ok(out.unwrap_or_else(|| code.to_owned()))
67}
68
69fn format_json(code: &str) -> Result<String, String> {
70 let config = dprint_plugin_json::configuration::ConfigurationBuilder::new()
71 .indent_width(2)
72 .build();
73 let out = dprint_plugin_json::format_text(Path::new("snippet.json"), code, &config)
74 .map_err(|err| err.to_string())?;
75 Ok(out.unwrap_or_else(|| code.to_owned()))
76}
77
78fn format_markdown(code: &str) -> Result<String, String> {
79 let config = dprint_plugin_markdown::configuration::ConfigurationBuilder::new().build();
80 let out = dprint_plugin_markdown::format_text(code, &config, |_, _, _| Ok(None))
81 .map_err(|err| err.to_string())?;
82 Ok(out.unwrap_or_else(|| code.to_owned()))
83}
84
85/// Taplo formats what it can and skips broken ranges, so the parse errors are checked first.
86fn format_toml(code: &str) -> Result<String, String> {
87 match taplo::parser::parse(code).errors.first() {
88 Some(err) => Err(err.message.clone()),
89 None => Ok(taplo::formatter::format(code, Default::default())),
90 }
91}
92
93fn format_sql(code: &str) -> String {
94 let options = sqlformat::FormatOptions {
95 indent: sqlformat::Indent::Spaces(2),
96 uppercase: Some(true),
97 ..Default::default()
98 };
99 sqlformat::format(code, &sqlformat::QueryParams::None, &options)
100}
101
102/// Adds or removes the final newline so it matches the input.
103fn keep_trailing_newline(code: &str, mut out: String) -> String {
104 match (code.ends_with('\n'), out.ends_with('\n')) {
105 (true, false) => out.push('\n'),
106 (false, true) => {
107 out.pop();
108 }
109 _ => {}
110 }
111 out
112}
113
114#[cfg(test)]
115mod tests {
116 use super::format;
117
118 #[test]
119 fn rust_statement_snippet() {
120 assert_eq!(
121 format("rust", "let x=1;\nfoo(x);").unwrap(),
122 "let x = 1;\nfoo(x);"
123 );
124 assert!(format("rust", "let = ;").is_err());
125 }
126
127 #[test]
128 fn json_keeps_key_order_and_missing_newline() {
129 let out = format("json", r#"{"b":1,"a":2}"#).unwrap();
130 assert!(!out.ends_with('\n'));
131 assert!(out.find("\"b\"") < out.find("\"a\""));
132 }
133
134 #[test]
135 fn typescript_formats_and_rejects_garbage() {
136 let out = format("typescript", "const a:number=1").unwrap();
137 assert!(out.contains("const a: number = 1"), "{out}");
138 assert!(format("typescript", "const = ;").is_err());
139 }
140}