|
| 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 | +} |
0 commit comments