|
| 1 | +#![expect(clippy::print_stdout)] |
| 2 | + |
| 3 | +use std::{fs, path::Path}; |
| 4 | + |
| 5 | +use oxc_allocator::Allocator; |
| 6 | +use oxc_formatter::{FormatOptions, Formatter, SortImports}; |
| 7 | +use oxc_parser::{ParseOptions, Parser}; |
| 8 | +use oxc_span::SourceType; |
| 9 | +use pico_args::Arguments; |
| 10 | + |
| 11 | +/// Format a JavaScript or TypeScript file |
| 12 | +fn main() -> Result<(), String> { |
| 13 | + let mut args = Arguments::from_env(); |
| 14 | + let show_ir = args.contains("--ir"); |
| 15 | + let name = args.free_from_str().unwrap_or_else(|_| "test.js".to_string()); |
| 16 | + |
| 17 | + // Read source file |
| 18 | + let path = Path::new(&name); |
| 19 | + let source_text = fs::read_to_string(path).map_err(|_| format!("Missing '{name}'"))?; |
| 20 | + let source_type = SourceType::from_path(path).unwrap(); |
| 21 | + let allocator = Allocator::new(); |
| 22 | + |
| 23 | + // Parse the source code |
| 24 | + let ret = Parser::new(&allocator, &source_text, source_type) |
| 25 | + .with_options(ParseOptions { |
| 26 | + parse_regular_expression: false, |
| 27 | + // Enable all syntax features |
| 28 | + allow_v8_intrinsics: true, |
| 29 | + allow_return_outside_function: true, |
| 30 | + // `oxc_formatter` expects this to be false |
| 31 | + preserve_parens: false, |
| 32 | + }) |
| 33 | + .parse(); |
| 34 | + |
| 35 | + // Report any parsing errors |
| 36 | + for error in ret.errors { |
| 37 | + let error = error.with_source_code(source_text.clone()); |
| 38 | + println!("{error:?}"); |
| 39 | + println!("Parsed with Errors."); |
| 40 | + } |
| 41 | + |
| 42 | + // Format the parsed code |
| 43 | + let options = FormatOptions { |
| 44 | + experimental_sort_imports: Some(SortImports { |
| 45 | + partition_by_newline: true, |
| 46 | + partition_by_comment: false, |
| 47 | + sort_side_effects: true, |
| 48 | + }), |
| 49 | + ..Default::default() |
| 50 | + }; |
| 51 | + |
| 52 | + let formatter = Formatter::new(&allocator, options); |
| 53 | + if show_ir { |
| 54 | + let doc = formatter.doc(&ret.program); |
| 55 | + println!("["); |
| 56 | + for el in doc.iter() { |
| 57 | + println!(" {el:?},"); |
| 58 | + } |
| 59 | + println!("]"); |
| 60 | + } else { |
| 61 | + let code = formatter.build(&ret.program); |
| 62 | + println!("{code}"); |
| 63 | + } |
| 64 | + |
| 65 | + Ok(()) |
| 66 | +} |
0 commit comments