Skip to content

Commit a495e82

Browse files
committed
feat(oxfmt): support associations config to specify language over filepath (#27437)
Closes #17852 (finally!), closes #26257. --- Introduce `associations` config field (inspired by dprint). ```json { "associations": [ { "files": ["**/*.html"], "excludeFiles": ["index.html"], "language": "angular-html" }, { "files": ["**/*.wxml"], "language": "html" }, { "files": ["**/*.conf"], "language": "json" } ] } ``` Precedence is solved by an array instead of an object, later wins like `overrides`. For `language`, use Shiki ids. It's intuitive and already used in our codebase. In the CLI, this bypasses selecting a formatter based on the filename and behaves as if one had been determined.
1 parent ffc6a71 commit a495e82

32 files changed

Lines changed: 599 additions & 51 deletions

File tree

‎apps/oxfmt/src-js/config.generated.ts‎

Lines changed: 50 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,33 @@
44
*/
55

66
export type ArrowParensConfig = "always" | "avoid";
7+
/**
8+
* A set of glob patterns.
9+
* Patterns are matched against paths relative to the configuration file's directory.
10+
*/
11+
export type GlobSet = string[];
12+
export type Language =
13+
| "javascript"
14+
| "jsx"
15+
| "typescript"
16+
| "tsx"
17+
| "json"
18+
| "jsonc"
19+
| "json5"
20+
| "css"
21+
| "scss"
22+
| "less"
23+
| "graphql"
24+
| "yaml"
25+
| "markdown"
26+
| "toml"
27+
| "html"
28+
| "angular-html"
29+
| "vue"
30+
| "svelte"
31+
| "astro"
32+
| "handlebars"
33+
| "mdx";
734
export type AstroUserConfig = boolean | AstroConfig;
835
export type AstroCompressHtmlConfig = "jsx" | "html" | "none";
936
export type EmbeddedLanguageFormattingConfig = "auto" | "off";
@@ -14,11 +41,6 @@ export type JsdocUserConfig = boolean | JsdocConfig;
1441
export type CommentLineStrategyConfig = "singleLine" | "multiline" | "keep";
1542
export type LineWrappingStyleConfig = "greedy" | "balance";
1643
export type ObjectWrapConfig = "preserve" | "collapse";
17-
/**
18-
* A set of glob patterns.
19-
* Patterns are matched against paths relative to the configuration file's directory.
20-
*/
21-
export type GlobSet = string[];
2244
export type ProseWrapConfig = "always" | "never" | "preserve";
2345
export type QuotePropsConfig = "as-needed" | "consistent" | "preserve";
2446
export type SortImportsUserConfig = boolean | SortImportsConfig;
@@ -63,6 +85,14 @@ export interface Oxfmtrc {
6385
* - Default: `"always"`
6486
*/
6587
arrowParens?: ArrowParensConfig;
88+
/**
89+
* Format matched files as the given language, instead of detecting it from the file name.
90+
* e.g. Angular templates named `*.html`, or `*.wxml` files formatted as HTML.
91+
* When a file matches multiple associations, the later one takes precedence (array order matters).
92+
*
93+
* - Default: `[]`
94+
*/
95+
associations?: OxfmtAssociationConfig[];
6696
/**
6797
* Options for `prettier-plugin-astro`.
6898
*
@@ -320,6 +350,21 @@ export interface Oxfmtrc {
320350
vueIndentScriptAndStyle?: boolean;
321351
[k: string]: unknown;
322352
}
353+
export interface OxfmtAssociationConfig {
354+
/**
355+
* Glob patterns to exclude from this association.
356+
*/
357+
excludeFiles?: GlobSet;
358+
/**
359+
* Glob patterns to match files for this association.
360+
*/
361+
files: GlobSet;
362+
/**
363+
* The language to format matched files as, named by its Shiki id (as in Markdown code fences).
364+
*/
365+
language: Language;
366+
[k: string]: unknown;
367+
}
323368
export interface AstroConfig {
324369
/**
325370
* Whether to normalize matching identifier attributes to shorthand or explicit form.

‎apps/oxfmt/src/cli/stdin_runner.rs‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,7 @@ use oxc_diagnostics::{DiagnosticService, GraphicalReportHandler};
99
use super::{CliRunResult, FormatCommand, Mode};
1010
use crate::core::{
1111
ConfigScopes, ExternalServices, FormatResult, JsConfigLoaderCb, ResolveOutcome,
12-
SourceFormatter, build_global_ignore_matchers, classify_file, is_ignored, resolve_ignore_paths,
13-
utils,
12+
SourceFormatter, build_global_ignore_matchers, is_ignored, resolve_ignore_paths, utils,
1413
};
1514

1615
pub struct StdinRunner {
@@ -116,7 +115,7 @@ impl StdinRunner {
116115
return CliRunResult::FormatSucceeded;
117116
}
118117

119-
let Some(strategy) = classify_file(&filepath) else {
118+
let Some(strategy) = config_resolver.classify(&filepath, None) else {
120119
utils::print_and_flush(stderr, "Unsupported file type for stdin-filepath\n");
121120
return CliRunResult::InvalidOptionConfig;
122121
};

‎apps/oxfmt/src/cli/walk.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ use oxc_diagnostics::{DiagnosticSender, DiagnosticService, OxcDiagnostic};
1616

1717
use crate::core::{
1818
ConfigResolver, ConfigScopes, FormatPlan, ResolveOutcome, build_global_ignore_matchers,
19-
classify_file, is_ignored,
19+
is_ignored,
2020
};
2121

2222
/// Orchestrates file discovery with nested config and ignore handling.
@@ -640,7 +640,7 @@ fn resolve_format_plan(
640640
tx_error: &DiagnosticSender,
641641
cwd: &Path,
642642
) -> Option<FormatPlan> {
643-
let strategy = classify_file(path)?;
643+
let strategy = resolver.classify(path, None)?;
644644
match resolver.resolve(path, strategy) {
645645
Ok(ResolveOutcome::Format(plan)) => Some(plan),
646646
Ok(ResolveOutcome::MissingPlugin(_)) => None,
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
use std::path::{Path, PathBuf};
2+
3+
use crate::core::{Language, oxfmtrc::OxfmtAssociationConfig};
4+
5+
use super::relative_path;
6+
7+
/// Resolved `associations` for file-specific language matching.
8+
/// Like `OxfmtrcOverrides`, but picks a language instead of merging options.
9+
#[derive(Debug)]
10+
pub struct OxfmtrcAssociations {
11+
base_dir: Option<PathBuf>,
12+
entries: Vec<OxfmtAssociationConfig>,
13+
}
14+
15+
impl OxfmtrcAssociations {
16+
pub fn new(associations: Vec<OxfmtAssociationConfig>, base_dir: Option<PathBuf>) -> Self {
17+
Self { base_dir, entries: associations }
18+
}
19+
20+
/// The language of the last association matching `path`, if any.
21+
pub fn matching(&self, path: &Path) -> Option<Language> {
22+
let relative = relative_path(self.base_dir.as_deref(), path);
23+
self.entries
24+
.iter()
25+
.rev()
26+
.find(|e| e.files.is_match(&relative) && !e.exclude_files.is_match(&relative))
27+
.map(|e| e.language)
28+
}
29+
}

‎apps/oxfmt/src/core/config/mod.rs‎

Lines changed: 36 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
mod associations;
12
mod editorconfig;
23
#[cfg(feature = "napi")]
34
mod js_config;
@@ -11,6 +12,7 @@ pub use nested::NestedConfigCtx;
1112
pub use scopes::ConfigScopes;
1213

1314
use std::{
15+
borrow::Cow,
1416
path::{Path, PathBuf},
1517
sync::Arc,
1618
};
@@ -24,18 +26,26 @@ use tracing::instrument;
2426
use oxc_config::{ConfigDiscovery, DiscoveredConfigFile, is_js_config_path, vp_version};
2527

2628
use self::{
29+
associations::OxfmtrcAssociations,
2730
editorconfig::{apply_editorconfig, resolve_editorconfig_overrides, root_properties},
2831
overrides::OxfmtrcOverrides,
2932
};
3033
use super::{
31-
FormatPlan,
34+
FormatPlan, Language,
3235
global_ignore::matches_with_ancestors,
3336
options::{ValidatedOptions, validate},
3437
oxfmtrc::{FormatConfig, Oxfmtrc},
35-
support::FormatStrategy,
38+
support::{FormatStrategy, classify_as, classify_file},
3639
utils,
3740
};
3841

42+
/// `path` relative to the config directory, as written glob patterns expect.
43+
fn relative_path<'a>(base_dir: Option<&Path>, path: &'a Path) -> Cow<'a, str> {
44+
// NOTE: On Windows, `to_string_lossy()` produces `\`-separated paths.
45+
// This is OK since `fast_glob::glob_match()` supports both `/` and `\` via `std::path::is_separator`.
46+
base_dir.and_then(|dir| path.strip_prefix(dir).ok()).unwrap_or(path).to_string_lossy()
47+
}
48+
3949
pub fn config_discovery() -> ConfigDiscovery {
4050
if cfg!(feature = "napi") && vp_version().is_some() {
4151
ConfigDiscovery::vite_plus()
@@ -275,6 +285,8 @@ pub struct ConfigResolver {
275285
base: Option<(Arc<FormatConfig>, Arc<ValidatedOptions>)>,
276286
/// Resolved overrides from `.oxfmtrc` for file-specific matching.
277287
oxfmtrc_overrides: Option<OxfmtrcOverrides>,
288+
/// Resolved `associations` from `.oxfmtrc`, consulted before the built-in classification.
289+
associations: Option<OxfmtrcAssociations>,
278290
/// Ignore glob built from this config's `ignorePatterns`.
279291
ignore_glob: Option<Gitignore>,
280292
/// Parsed `.editorconfig`, if any.
@@ -295,6 +307,7 @@ impl ConfigResolver {
295307
config_dir,
296308
base: None,
297309
oxfmtrc_overrides: None,
310+
associations: None,
298311
ignore_glob: None,
299312
editorconfig,
300313
}
@@ -348,6 +361,7 @@ impl ConfigResolver {
348361
/// - `self.base` is set to the validated `FormatConfig` snapshot
349362
/// (with `.editorconfig` `[*]` already folded in) paired with its gate artifacts
350363
/// - `self.oxfmtrc_overrides` is set if `overrides` exists
364+
/// - `self.associations` is set if `associations` is not empty
351365
/// - `self.ignore_glob` is built from `ignorePatterns`
352366
///
353367
/// Validation runs eagerly via `validate()`,
@@ -359,10 +373,14 @@ impl ConfigResolver {
359373
pub fn build_and_validate(&mut self) -> Result<(), String> {
360374
let oxfmtrc = Oxfmtrc::deserialize(&self.raw_config).map_err(|err| err.to_string())?;
361375

362-
// Resolve `overrides` from `Oxfmtrc` for later per-file matching
363-
let base_dir = self.config_dir.clone();
364-
self.oxfmtrc_overrides =
365-
oxfmtrc.overrides.map(|overrides| OxfmtrcOverrides::new(overrides, base_dir));
376+
// Resolve `overrides` and `associations` from `Oxfmtrc` for later per-file matching
377+
self.oxfmtrc_overrides = oxfmtrc
378+
.overrides
379+
.map(|overrides| OxfmtrcOverrides::new(overrides, self.config_dir.clone()));
380+
self.associations = oxfmtrc
381+
.associations
382+
.filter(|associations| !associations.is_empty())
383+
.map(|associations| OxfmtrcAssociations::new(associations, self.config_dir.clone()));
366384

367385
let mut format_config = oxfmtrc.format_config;
368386

@@ -390,6 +408,18 @@ impl ConfigResolver {
390408
Ok(())
391409
}
392410

411+
/// Classify `path`: the given `language` first (e.g. LSP `languageId`),
412+
/// then this config's `associations`, then the file name.
413+
///
414+
/// A given or matched language decides alone, see [`classify_as`] for when it yields `None`.
415+
pub fn classify(&self, path: &Path, language: Option<Language>) -> Option<FormatStrategy> {
416+
let language = language.or_else(|| self.associations.as_ref()?.matching(path));
417+
match language {
418+
Some(language) => classify_as(language, path),
419+
None => classify_file(path),
420+
}
421+
}
422+
393423
/// Resolve options for a pre-classified file and build a [`ResolveOutcome`].
394424
///
395425
/// Returns `Err` only when the merged config (after override application) fails validation.

‎apps/oxfmt/src/core/config/overrides.rs‎

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ use oxc_config::GlobSet;
44

55
use crate::core::oxfmtrc::{FormatConfig, OxfmtOverrideConfig};
66

7+
use super::relative_path;
8+
79
/// Resolved overrides for file-specific matching.
810
/// Similar to `EditorConfig`, this also handles `FormatConfig` override resolution.
911
#[derive(Debug)]
@@ -30,14 +32,7 @@ impl OxfmtrcOverrides {
3032
/// Collect the options of every override matching `path`, in config order.
3133
/// Empty when nothing matches, so callers can gate on `is_empty()` without a separate probe.
3234
pub fn matching(&self, path: &Path) -> Vec<&FormatConfig> {
33-
// NOTE: On Windows, `to_string_lossy()` produces `\`-separated paths.
34-
// This is OK since `fast_glob::glob_match()` supports both `/` and `\` via `std::path::is_separator`.
35-
let relative = self
36-
.base_dir
37-
.as_ref()
38-
.and_then(|dir| path.strip_prefix(dir).ok())
39-
.unwrap_or(path)
40-
.to_string_lossy();
35+
let relative = relative_path(self.base_dir.as_deref(), path);
4136

4237
self.entries
4338
.iter()

‎apps/oxfmt/src/core/language.rs‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@
44
//! The aliases used by embedded code, the LSP `languageId`s and the fake path extension all live here,
55
//! so adding a language never needs syncing several tables.
66
7+
use schemars::JsonSchema;
8+
use serde::{Deserialize, Serialize};
9+
710
use oxc_formatter_css::CssVariant;
811
use oxc_formatter_json::JsonVariant;
912
use oxc_span::{FileExtension, SourceType};
@@ -35,7 +38,8 @@ pub enum Route {
3538
Unsupported,
3639
}
3740

38-
#[derive(Clone, Copy)]
41+
#[derive(Debug, Clone, Copy, Deserialize, Serialize, JsonSchema)]
42+
#[serde(rename_all = "kebab-case")]
3943
pub enum Language {
4044
Javascript,
4145
Jsx,
@@ -110,7 +114,7 @@ impl Language {
110114
}
111115

112116
/// LSP only: the extension of the fake path for an in-memory document,
113-
/// which `classify_file` and `overrides` see as a real file.
117+
/// so that config scopes, `ignorePatterns` and `overrides` see it as a file of this language.
114118
#[cfg(feature = "napi")]
115119
pub fn to_lsp_extension(self) -> &'static str {
116120
match self {
@@ -170,6 +174,19 @@ impl Language {
170174
mod tests {
171175
use super::*;
172176

177+
/// The config ids (serde names) are the canonical embedded names, so both stay one vocabulary.
178+
#[test]
179+
fn serde_names_are_embedded_names() {
180+
let schema = serde_json::to_value(schemars::schema_for!(Language)).unwrap();
181+
let names = schema["enum"].as_array().expect("`Language` is a plain string enum");
182+
for name in names {
183+
let name = name.as_str().unwrap();
184+
let language = Language::from_embedded(name)
185+
.unwrap_or_else(|| panic!("`{name}` is not an embedded name"));
186+
assert_eq!(serde_json::to_value(language).unwrap(), name);
187+
}
188+
}
189+
173190
/// Prettier-served fences (native ones are covered by `every_native_language_dispatches`)
174191
/// and the LSP ids that differ from embedded names or extensions.
175192
#[test]

‎apps/oxfmt/src/core/mod.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@ pub use config::{ConfigResolver, ConfigScopes, ResolveOutcome, config_discovery}
1616
pub use config::{JsConfigLoaderCb, JsLoadJsConfigCb, create_js_config_loader, resolve_for_api};
1717
pub use format::{FormatPlan, FormatResult, SourceFormatter};
1818
pub use global_ignore::{build_global_ignore_matchers, is_ignored, resolve_ignore_paths};
19-
#[cfg(feature = "napi")]
2019
pub use language::Language;
20+
#[cfg(feature = "napi")]
2121
pub use support::classify_file;
2222

2323
#[cfg(feature = "napi")]

‎apps/oxfmt/src/core/oxfmtrc.rs‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use serde_json::Value;
66

77
use oxc_config::GlobSet;
88

9-
use crate::core::utils;
9+
use crate::core::{Language, utils};
1010

1111
/// Configuration options for Oxfmt.
1212
///
@@ -23,6 +23,13 @@ pub struct Oxfmtrc {
2323
/// - Default: `[]`
2424
#[serde(skip_serializing_if = "Option::is_none")]
2525
pub overrides: Option<Vec<OxfmtOverrideConfig>>,
26+
/// Format matched files as the given language, instead of detecting it from the file name.
27+
/// e.g. Angular templates named `*.html`, or `*.wxml` files formatted as HTML.
28+
/// When a file matches multiple associations, the later one takes precedence (array order matters).
29+
///
30+
/// - Default: `[]`
31+
#[serde(skip_serializing_if = "Option::is_none")]
32+
pub associations: Option<Vec<OxfmtAssociationConfig>>,
2633
/// Ignore files matching these glob patterns.
2734
/// Patterns use gitignore-style matching, rooted at the directory containing the configuration file.
2835
/// Files outside that directory cannot be matched; patterns containing `..` are rejected as a configuration error.
@@ -50,6 +57,20 @@ pub struct OxfmtOverrideConfig {
5057

5158
// ---
5259

60+
#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
61+
#[serde(rename_all = "camelCase")]
62+
pub struct OxfmtAssociationConfig {
63+
/// Glob patterns to match files for this association.
64+
pub files: GlobSet,
65+
/// Glob patterns to exclude from this association.
66+
#[serde(default, skip_serializing_if = "GlobSet::is_empty")]
67+
pub exclude_files: GlobSet,
68+
/// The language to format matched files as, named by its Shiki id (as in Markdown code fences).
69+
pub language: Language,
70+
}
71+
72+
// ---
73+
5374
// NOTE: All fields are typed as `Option` to distinguish between user-specified values and defaults.
5475
#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
5576
#[serde(rename_all = "camelCase", default)]

0 commit comments

Comments
 (0)