Skip to content

Commit 7e153d4

Browse files
committed
refactor: Change Formatter to format_text as it's no longer needed.
- Fixes #49 - Adds better support for mjs files.
1 parent b7cfe52 commit 7e153d4

File tree

9 files changed

+94
-109
lines changed

9 files changed

+94
-109
lines changed

Cargo.lock

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
name = "dprint-plugin-typescript"
33
description = "TypeScript code formatting plugin for dprint."
44
keywords = ["formatting", "formatter", "typescript"]
5-
version = "0.30.3"
5+
version = "0.31.0"
66
authors = ["David Sherret <[email protected]>"]
77
edition = "2018"
88
license = "MIT"

src/format_text.rs

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
use std::path::Path;
2+
3+
use dprint_core::formatting::*;
4+
use dprint_core::configuration::{resolve_new_line_kind};
5+
6+
use super::parsing::parse;
7+
use super::swc::parse_swc_ast;
8+
use super::configuration::Configuration;
9+
10+
/// Formats a file.
11+
///
12+
/// Returns the file text `Ok(formatted_text)` or an error when it failed to parse.
13+
///
14+
/// # Example
15+
///
16+
/// ```
17+
/// use std::path::PathBuf;
18+
/// use dprint_plugin_typescript::*;
19+
/// use dprint_plugin_typescript::configuration::*;
20+
///
21+
/// // build the configuration once
22+
/// let config = ConfigurationBuilder::new()
23+
/// .line_width(80)
24+
/// .prefer_hanging(true)
25+
/// .prefer_single_line(false)
26+
/// .quote_style(QuoteStyle::PreferSingle)
27+
/// .next_control_flow_position(NextControlFlowPosition::SameLine)
28+
/// .build();
29+
///
30+
/// // now format many files (it is recommended to parallelize this)
31+
/// let files_to_format = vec![(PathBuf::from("path/to/file.ts"), "const t = 5 ;")];
32+
/// for (file_path, file_text) in files_to_format.iter() {
33+
/// let result = format_text(file_path, file_text, &config);
34+
/// // save result here...
35+
/// }
36+
/// ```
37+
pub fn format_text(file_path: &Path, file_text: &str, config: &Configuration) -> Result<String, String> {
38+
if has_ignore_comment(file_text, config) {
39+
return Ok(String::from(file_text));
40+
}
41+
42+
let parsed_source_file = parse_swc_ast(file_path, file_text)?;
43+
let print_items = parse(&parsed_source_file, config);
44+
45+
// println!("{}", print_items.get_as_text());
46+
47+
return Ok(print(print_items, PrintOptions {
48+
indent_width: config.indent_width,
49+
max_width: config.line_width,
50+
use_tabs: config.use_tabs,
51+
new_line_text: resolve_new_line_kind(file_text, config.new_line_kind),
52+
}));
53+
54+
fn has_ignore_comment(file_text: &str, config: &Configuration) -> bool {
55+
let mut iterator = super::utils::CharIterator::new(file_text.chars());
56+
iterator.skip_whitespace();
57+
if iterator.move_next() != Some('/') { return false; }
58+
match iterator.move_next() {
59+
Some('/') | Some('*') => {},
60+
_ => return false,
61+
}
62+
iterator.skip_whitespace();
63+
iterator.check_text(&config.ignore_file_comment_text)
64+
}
65+
}

src/formatter.rs

Lines changed: 0 additions & 80 deletions
This file was deleted.

src/lib.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@ extern crate dprint_core;
22

33
pub mod configuration;
44
mod parsing;
5-
mod formatter;
5+
mod format_text;
66
mod swc;
77
mod utils;
88

9-
pub use formatter::Formatter;
9+
pub use format_text::format_text;
1010

1111
#[cfg(feature = "wasm")]
1212
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]

src/swc/parse_swc_ast.rs

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use std::collections::{HashMap};
2-
use std::path::PathBuf;
2+
use std::path::Path;
33
use std::rc::Rc;
44
use swc_common::{
55
errors::{Handler, Emitter, DiagnosticBuilder},
@@ -17,7 +17,7 @@ pub struct ParsedSourceFile<'a> {
1717
pub trailing_comments: HashMap<BytePos, Vec<Comment>>,
1818
}
1919

20-
pub fn parse_swc_ast<'a>(file_path: &PathBuf, file_text: &'a str) -> Result<ParsedSourceFile<'a>, String> {
20+
pub fn parse_swc_ast<'a>(file_path: &Path, file_text: &'a str) -> Result<ParsedSourceFile<'a>, String> {
2121
match parse_inner(file_path, file_text) {
2222
Ok(result) => Ok(result),
2323
Err(err) => {
@@ -35,7 +35,7 @@ pub fn parse_swc_ast<'a>(file_path: &PathBuf, file_text: &'a str) -> Result<Pars
3535
}
3636
}
3737

38-
fn parse_inner<'a>(file_path: &PathBuf, file_text: &'a str) -> Result<ParsedSourceFile<'a>, String> {
38+
fn parse_inner<'a>(file_path: &Path, file_text: &'a str) -> Result<ParsedSourceFile<'a>, String> {
3939
let handler = Handler::with_emitter(false, false, Box::new(EmptyEmitter {}));
4040

4141
let file_bytes = file_text.as_bytes();
@@ -87,9 +87,9 @@ fn parse_inner<'a>(file_path: &PathBuf, file_text: &'a str) -> Result<ParsedSour
8787
file_bytes,
8888
});
8989

90-
fn should_parse_as_jsx(file_path: &PathBuf) -> bool {
90+
fn should_parse_as_jsx(file_path: &Path) -> bool {
9191
if let Some(extension) = get_lowercase_extension(file_path) {
92-
return extension == "tsx" || extension == "jsx" || extension == "js";
92+
return extension == "tsx" || extension == "jsx" || extension == "js" || extension == "mjs";
9393
}
9494
return true;
9595
}
@@ -106,7 +106,7 @@ fn parse_inner<'a>(file_path: &PathBuf, file_text: &'a str) -> Result<ParsedSour
106106
}
107107
}
108108

109-
fn get_lowercase_extension(file_path: &PathBuf) -> Option<String> {
109+
fn get_lowercase_extension(file_path: &Path) -> Option<String> {
110110
file_path.extension().and_then(|e| e.to_str()).map(|f| f.to_lowercase())
111111
}
112112

@@ -135,6 +135,7 @@ fn format_diagnostic(error: &DiagnosticBuilder, file_text: &str) -> String {
135135
#[cfg(test)]
136136
mod tests {
137137
use super::*;
138+
use std::path::PathBuf;
138139

139140
#[test]
140141
fn should_error_on_syntax_diagnostic() {

src/wasm_plugin.rs

Lines changed: 2 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
11
use std::path::PathBuf;
22
use dprint_core::generate_plugin_code;
33
use super::configuration::{Configuration, resolve_config};
4-
use super::formatter::Formatter;
54

65
fn get_plugin_config_key() -> String {
76
String::from("typescript")
87
}
98

109
fn get_plugin_file_extensions() -> Vec<String> {
11-
vec![String::from("ts"), String::from("tsx"), String::from("js"), String::from("jsx")]
10+
vec![String::from("ts"), String::from("tsx"), String::from("js"), String::from("jsx"), String::from("mjs")]
1211
}
1312

1413
fn get_plugin_help_url() -> String {
@@ -19,19 +18,8 @@ fn get_plugin_config_schema_url() -> String {
1918
String::new() // none until https://github.com/microsoft/vscode/issues/98443 is resolved
2019
}
2120

22-
static mut FORMATTER: Option<Formatter> = None;
23-
2421
fn format_text(file_path: &PathBuf, file_text: &str, config: &Configuration) -> Result<String, String> {
25-
let formatter = unsafe {
26-
if let Some(formatter) = FORMATTER.as_ref() {
27-
formatter
28-
} else {
29-
let formatter = Formatter::new(config.clone());
30-
FORMATTER.replace(formatter);
31-
FORMATTER.as_ref().unwrap()
32-
}
33-
};
34-
formatter.format_text(&file_path, &file_text)
22+
super::format_text(file_path, file_text, config)
3523
}
3624

3725
fn get_plugin_license_text() -> String {
@@ -43,7 +31,6 @@ fn get_plugin_license_text() -> String {
4331
pub fn reset_config() {
4432
unsafe {
4533
RESOLVE_CONFIGURATION_RESULT.take();
46-
FORMATTER.take();
4734
}
4835
}
4936

tests/specs/common/MjsFile_All.txt

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
-- fileName: test.mjs --
2+
== should format mjs file ==
3+
class Test{ prop = 5}
4+
5+
[expect]
6+
class Test {
7+
prop = 5;
8+
}
9+
10+
== should support JSX in mjs file ==
11+
const test = <Test>Test</Test>;
12+
13+
[expect]
14+
const test = <Test>Test</Test>;

tests/test.rs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,13 +24,12 @@ fn test_performance() {
2424
.quote_style(QuoteStyle::PreferSingle)
2525
.build();
2626
let file_text = fs::read_to_string("tests/performance/checker.txt").expect("Expected to read.");
27-
let formatter = Formatter::new(config);
2827

2928
//debug_here!();
3029

3130
for i in 0..10 {
3231
let start = Instant::now();
33-
let result = formatter.format_text(&PathBuf::from("checker.ts"), &file_text).expect("Could not parse...");
32+
let result = format_text(&PathBuf::from("checker.ts"), &file_text, &config).expect("Could not parse...");
3433

3534
println!("{}ms", start.elapsed().as_millis());
3635
println!("---");
@@ -54,8 +53,7 @@ fn test_specs() {
5453
let config_result = resolve_config(parse_config_key_map(spec_config), &global_config);
5554
ensure_no_diagnostics(&config_result.diagnostics);
5655

57-
let formatter = Formatter::new(config_result.config);
58-
formatter.format_text(&file_name, &file_text)
56+
format_text(&file_name, &file_text, &config_result.config)
5957
}
6058
)
6159
}

0 commit comments

Comments
 (0)