Skip to content

Commit 8c2d09f

Browse files
committed
refactor(formatter/sort-imports): Resolve default options.(internalPattern|groups) in options.rs (#16375)
Yet another pure refactoring.
1 parent e5a78ed commit 8c2d09f

File tree

7 files changed

+51
-58
lines changed

7 files changed

+51
-58
lines changed

crates/oxc_formatter/examples/sort_imports.rs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,10 @@
33
use std::{fs, path::Path};
44

55
use oxc_allocator::Allocator;
6-
use oxc_formatter::{FormatOptions, Formatter, SortImportsOptions, SortOrder, get_parse_options};
6+
use oxc_formatter::{
7+
FormatOptions, Formatter, SortImportsOptions, SortOrder, default_groups,
8+
default_internal_patterns, get_parse_options,
9+
};
710
use oxc_parser::Parser;
811
use oxc_span::SourceType;
912
use pico_args::Arguments;
@@ -28,8 +31,8 @@ fn main() -> Result<(), String> {
2831
sort_side_effects,
2932
ignore_case,
3033
newlines_between,
31-
internal_pattern: None,
32-
groups: None,
34+
internal_pattern: default_internal_patterns(),
35+
groups: default_groups(),
3336
};
3437

3538
// Read source file

crates/oxc_formatter/src/ir_transform/sort_imports/compute_metadata.rs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -364,10 +364,7 @@ fn to_path_kind(source: &str, options: &SortImportsOptions) -> ImportPathKind {
364364
}
365365

366366
// Check if source matches any internal pattern
367-
if match &options.internal_pattern {
368-
Some(patterns) => patterns.iter().any(|p| source.starts_with(p.as_str())),
369-
None => ["~/", "@/"].iter().any(|p| source.starts_with(*p)),
370-
} {
367+
if options.internal_pattern.iter().any(|p| source.starts_with(p.as_str())) {
371368
return ImportPathKind::Internal;
372369
}
373370

crates/oxc_formatter/src/ir_transform/sort_imports/group_config.rs

Lines changed: 0 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,3 @@
1-
/// Default groups configuration.
2-
pub fn default_groups() -> Vec<Vec<GroupName>> {
3-
use ImportModifier as M;
4-
use ImportSelector as S;
5-
6-
vec![
7-
vec![GroupName::with_modifier(S::Import, M::Type)],
8-
vec![
9-
GroupName::with_modifier(S::Builtin, M::Value),
10-
GroupName::with_modifier(S::External, M::Value),
11-
],
12-
vec![GroupName::with_modifier(S::Internal, M::Type)],
13-
vec![GroupName::with_modifier(S::Internal, M::Value)],
14-
vec![
15-
GroupName::with_modifier(S::Parent, M::Type),
16-
GroupName::with_modifier(S::Sibling, M::Type),
17-
GroupName::with_modifier(S::Index, M::Type),
18-
],
19-
vec![
20-
GroupName::with_modifier(S::Parent, M::Value),
21-
GroupName::with_modifier(S::Sibling, M::Value),
22-
GroupName::with_modifier(S::Index, M::Value),
23-
],
24-
vec![GroupName::new(S::Unknown)],
25-
]
26-
}
27-
281
/// Parse groups from string-based configuration.
292
/// If parsing fails (= undefined), it falls back to `Unknown` selector.
303
pub fn parse_groups_from_strings(string_groups: &Vec<Vec<String>>) -> Vec<Vec<GroupName>> {

crates/oxc_formatter/src/ir_transform/sort_imports/mod.rs

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ use oxc_allocator::{Allocator, Vec as ArenaVec};
1010
use crate::{
1111
formatter::format_element::{FormatElement, LineMode, document::Document},
1212
ir_transform::sort_imports::{
13-
group_config::{GroupName, default_groups, parse_groups_from_strings},
13+
group_config::{GroupName, parse_groups_from_strings},
1414
partitioned_chunk::PartitionedChunk,
1515
source_line::SourceLine,
1616
},
@@ -27,11 +27,7 @@ pub struct SortImportsTransform {
2727
impl SortImportsTransform {
2828
pub fn new(options: options::SortImportsOptions) -> Self {
2929
// Parse string based groups into our internal representation for performance
30-
let groups = if let Some(groups) = &options.groups {
31-
parse_groups_from_strings(groups)
32-
} else {
33-
default_groups()
34-
};
30+
let groups = parse_groups_from_strings(&options.groups);
3531
Self { options, groups }
3632
}
3733

crates/oxc_formatter/src/ir_transform/sort_imports/options.rs

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,11 @@ pub struct SortImportsOptions {
2525
/// NOTE: Cannot be used together with `partition_by_newline: true`.
2626
pub newlines_between: bool,
2727
/// Prefixes for internal imports.
28-
/// If `None`, uses the default internal patterns.
29-
pub internal_pattern: Option<Vec<String>>,
28+
/// Defaults to `["~/", "@/"]`.
29+
pub internal_pattern: Vec<String>,
3030
/// Groups configuration for organizing imports.
3131
/// Each inner `Vec` represents a group, and multiple group names in the same `Vec` are treated as one.
32-
/// If `None`, uses the default groups.
33-
pub groups: Option<Vec<Vec<String>>>,
32+
pub groups: Vec<Vec<String>>,
3433
}
3534

3635
impl Default for SortImportsOptions {
@@ -42,12 +41,14 @@ impl Default for SortImportsOptions {
4241
order: SortOrder::default(),
4342
ignore_case: true,
4443
newlines_between: true,
45-
internal_pattern: None,
46-
groups: None,
44+
internal_pattern: default_internal_patterns(),
45+
groups: default_groups(),
4746
}
4847
}
4948
}
5049

50+
// ---
51+
5152
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
5253
pub enum SortOrder {
5354
/// Sort in ascending order (A-Z).
@@ -88,3 +89,21 @@ impl fmt::Display for SortOrder {
8889
f.write_str(s)
8990
}
9091
}
92+
93+
/// Returns default prefixes for identifying internal imports: `["~/", "@/"]`.
94+
pub fn default_internal_patterns() -> Vec<String> {
95+
["~/", "@/"].iter().map(|s| (*s).to_string()).collect()
96+
}
97+
98+
/// Returns default groups configuration for organizing imports.
99+
pub fn default_groups() -> Vec<Vec<String>> {
100+
vec![
101+
vec!["type-import".to_string()],
102+
vec!["value-builtin".to_string(), "value-external".to_string()],
103+
vec!["type-internal".to_string()],
104+
vec!["value-internal".to_string()],
105+
vec!["type-parent".to_string(), "type-sibling".to_string(), "type-index".to_string()],
106+
vec!["value-parent".to_string(), "value-sibling".to_string(), "value-index".to_string()],
107+
vec!["unknown".to_string()],
108+
]
109+
}

crates/oxc_formatter/src/service/oxfmtrc.rs

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use crate::{
77
ArrowParentheses, AttributePosition, BracketSameLine, BracketSpacing,
88
EmbeddedLanguageFormatting, Expand, FormatOptions, IndentStyle, IndentWidth, LineEnding,
99
LineWidth, QuoteProperties, QuoteStyle, Semicolons, SortImportsOptions, SortOrder,
10-
TrailingCommas,
10+
TrailingCommas, default_groups, default_internal_patterns,
1111
};
1212

1313
/// Configuration options for the formatter.
@@ -375,14 +375,16 @@ impl Oxfmtrc {
375375
partition_by_newline: sort_imports_config.partition_by_newline,
376376
partition_by_comment: sort_imports_config.partition_by_comment,
377377
sort_side_effects: sort_imports_config.sort_side_effects,
378-
order: sort_imports_config.order.map_or(SortOrder::Asc, |o| match o {
378+
order: sort_imports_config.order.map_or(SortOrder::default(), |o| match o {
379379
SortOrderConfig::Asc => SortOrder::Asc,
380380
SortOrderConfig::Desc => SortOrder::Desc,
381381
}),
382382
ignore_case: sort_imports_config.ignore_case,
383383
newlines_between: sort_imports_config.newlines_between,
384-
internal_pattern: sort_imports_config.internal_pattern,
385-
groups: sort_imports_config.groups,
384+
internal_pattern: sort_imports_config
385+
.internal_pattern
386+
.unwrap_or_else(default_internal_patterns),
387+
groups: sort_imports_config.groups.unwrap_or_else(default_groups),
386388
});
387389
}
388390

@@ -563,10 +565,9 @@ mod tests {
563565
)
564566
.unwrap();
565567
let sort_imports = config.into_format_options().unwrap().experimental_sort_imports.unwrap();
566-
let groups = sort_imports.groups.as_ref().unwrap();
567-
assert_eq!(groups.len(), 5);
568-
assert_eq!(groups[0], vec!["builtin".to_string()]);
569-
assert_eq!(groups[1], vec!["external".to_string(), "internal".to_string()]);
570-
assert_eq!(groups[4], vec!["index".to_string()]);
568+
assert_eq!(sort_imports.groups.len(), 5);
569+
assert_eq!(sort_imports.groups[0], vec!["builtin".to_string()]);
570+
assert_eq!(sort_imports.groups[1], vec!["external".to_string(), "internal".to_string()]);
571+
assert_eq!(sort_imports.groups[4], vec!["index".to_string()]);
571572
}
572573
}

napi/playground/src/lib.rs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,8 @@ use oxc::{
3131
use oxc_formatter::{
3232
ArrowParentheses, AttributePosition, BracketSameLine, BracketSpacing, Expand, FormatOptions,
3333
Formatter, IndentStyle, IndentWidth, LineEnding, LineWidth, QuoteProperties, QuoteStyle,
34-
Semicolons, SortImportsOptions, SortOrder, TrailingCommas, get_parse_options,
34+
Semicolons, SortImportsOptions, SortOrder, TrailingCommas, default_groups,
35+
default_internal_patterns, get_parse_options,
3536
};
3637
use oxc_linter::{
3738
ConfigStore, ConfigStoreBuilder, ContextSubHost, ExternalPluginStore, LintOptions, Linter,
@@ -510,8 +511,11 @@ impl Oxc {
510511
order,
511512
ignore_case: sort_imports_config.ignore_case.unwrap_or(true),
512513
newlines_between: sort_imports_config.newlines_between.unwrap_or(true),
513-
internal_pattern: sort_imports_config.internal_pattern.clone(),
514-
groups: sort_imports_config.groups.clone(),
514+
internal_pattern: sort_imports_config
515+
.internal_pattern
516+
.clone()
517+
.unwrap_or_else(default_internal_patterns),
518+
groups: sort_imports_config.groups.clone().unwrap_or_else(default_groups),
515519
});
516520
}
517521

0 commit comments

Comments
 (0)