Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ working directory:
"typescript",
"oxc"
],
"jsPlugins": null,
"categories": {},
"rules": {
"eqeqeq": [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ working directory: fixtures
"typescript",
"oxc"
],
"jsPlugins": null,
"categories": {},
"rules": {},
"settings": {
Expand Down
15 changes: 14 additions & 1 deletion apps/oxlint/test/e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@ interface TestOptions {
snapshotName?: string;
// Function to get extra data to include in the snapshot
getExtraSnapshotData?: (dirPath: string) => Promise<{ [key: string]: string }>;

/**
* Override the `files` directory within the fixture to lint.
* This is useful when the fixture has a different structure, e.g. when testing nested configs.
* Defaults to `files`.
*/
overrideFiles?: string;
}

/**
Expand All @@ -29,7 +36,7 @@ async function testFixture(fixtureName: string, options?: TestOptions): Promise<
// Use current NodeJS executable, rather than `node`, to avoid problems with a Node version manager
// installed on system resulting in using wrong NodeJS version
command: process.execPath,
args: [CLI_PATH, ...args, 'files'],
args: [CLI_PATH, ...args, options?.overrideFiles ?? 'files'],
fixtureName,
snapshotName: options?.snapshotName ?? 'output',
getExtraSnapshotData: options?.getExtraSnapshotData,
Expand Down Expand Up @@ -73,6 +80,12 @@ describe('oxlint CLI', () => {
await testFixture('basic_custom_plugin_many_files');
});

it('should load a custom plugin correctly when extending in a nested config', async () => {
await testFixture('custom_plugin_nested_config', {
overrideFiles: '.',
});
});

it('should load a custom plugin when configured in overrides', async () => {
await testFixture('custom_plugin_via_overrides');
});
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"jsPlugins": ["./plugin.ts"],
"rules": {
"basic-custom-plugin/no-debugger": "error"
},
"categories": { "correctness": "off" }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": ["../.oxlintrc.json"]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
debugger;
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Exit code
1

# stdout
```
x basic-custom-plugin(no-debugger): Unexpected Debugger Statement
,-[nested/index.ts:1:1]
1 | debugger;
: ^^^^^^^^^
`----

Found 0 warnings and 1 error.
Finished in Xms on 2 files using X threads.
```

# stderr
```
WARNING: JS plugins are experimental and not subject to semver.
Breaking changes are possible while JS plugins support is under development.
```
23 changes: 23 additions & 0 deletions apps/oxlint/test/fixtures/custom_plugin_nested_config/plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import type { Plugin } from '../../../dist/index.js';

const plugin: Plugin = {
meta: {
name: 'basic-custom-plugin',
},
rules: {
'no-debugger': {
create(context) {
return {
DebuggerStatement(debuggerStatement) {
context.report({
message: 'Unexpected Debugger Statement',
node: debuggerStatement,
});
},
};
},
},
},
};

export default plugin;
28 changes: 15 additions & 13 deletions crates/oxc_linter/src/config/config_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,15 +147,16 @@ impl ConfigStoreBuilder {
let (oxlintrc, extended_paths) = resolve_oxlintrc_config(oxlintrc)?;

// Collect external plugins from both base config and overrides
let mut external_plugins = FxHashSet::default();
let mut external_plugins: FxHashSet<(&PathBuf, &str)> = FxHashSet::default();

if let Some(base_external_plugins) = &oxlintrc.external_plugins {
external_plugins.extend(base_external_plugins.iter().cloned());
external_plugins.extend(base_external_plugins.iter().map(|(k, v)| (k, v.as_str())));
}

for r#override in &oxlintrc.overrides {
if let Some(override_external_plugins) = &r#override.external_plugins {
external_plugins.extend(override_external_plugins.iter().cloned());
external_plugins
.extend(override_external_plugins.iter().map(|(k, v)| (k, v.as_str())));
}
}

Expand All @@ -165,8 +166,10 @@ impl ConfigStoreBuilder {
if !external_plugins.is_empty() && external_plugin_store.is_enabled() {
let Some(external_linter) = external_linter else {
#[expect(clippy::missing_panics_doc, reason = "infallible")]
let plugin_specifier = external_plugins.iter().next().unwrap().clone();
return Err(ConfigBuilderError::NoExternalLinterConfigured { plugin_specifier });
let (_, original_specifier) = external_plugins.iter().next().unwrap();
return Err(ConfigBuilderError::NoExternalLinterConfigured {
plugin_specifier: (*original_specifier).to_string(),
});
};

let resolver = Resolver::new(ResolveOptions {
Expand All @@ -175,19 +178,17 @@ impl ConfigStoreBuilder {
..Default::default()
});

#[expect(clippy::missing_panics_doc, reason = "oxlintrc.path is always a file path")]
let oxlintrc_dir = oxlintrc.path.parent().unwrap();

for plugin_specifier in &external_plugins {
for (config_path, specifier) in &external_plugins {
Self::load_external_plugin(
oxlintrc_dir,
plugin_specifier,
config_path,
specifier,
external_linter,
&resolver,
external_plugin_store,
)?;
}
}

let plugins = oxlintrc.plugins.unwrap_or_default();

let rules =
Expand Down Expand Up @@ -505,7 +506,7 @@ impl ConfigStoreBuilder {
}

fn load_external_plugin(
oxlintrc_dir_path: &Path,
resolve_dir: &Path,
plugin_specifier: &str,
external_linter: &ExternalLinter,
resolver: &Resolver,
Expand All @@ -521,7 +522,8 @@ impl ConfigStoreBuilder {
);
}

let resolved = resolver.resolve(oxlintrc_dir_path, plugin_specifier).map_err(|e| {
// Resolve the specifier relative to the config directory
let resolved = resolver.resolve(resolve_dir, plugin_specifier).map_err(|e| {
ConfigBuilderError::PluginLoadFailed {
plugin_specifier: plugin_specifier.to_string(),
error: e.to_string(),
Expand Down
42 changes: 39 additions & 3 deletions crates/oxc_linter/src/config/overrides.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use std::{
borrow::Cow,
ops::{Deref, DerefMut},
path::PathBuf,
};

use rustc_hash::FxHashSet;
use schemars::{JsonSchema, r#gen, schema::Schema};
use serde::{Deserialize, Deserializer, Serialize};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::{LintPlugins, OxlintEnv, OxlintGlobals, config::OxlintRules};

Expand Down Expand Up @@ -97,8 +98,17 @@ pub struct OxlintOverride {
///
/// Note: JS plugins are experimental and not subject to semver.
/// They are not supported in language server at present.
#[serde(rename = "jsPlugins")]
pub external_plugins: Option<FxHashSet<String>>,
#[serde(
rename = "jsPlugins",
deserialize_with = "deserialize_external_plugins_override",
serialize_with = "serialize_external_plugins_override",
default,
skip_serializing_if = "Option::is_none"
)]
#[schemars(with = "Option<FxHashSet<String>>")]
pub external_plugins: Option<
FxHashSet<(PathBuf /* config file directory */, String /* plugin specifier */)>,
>,

#[serde(default)]
pub rules: OxlintRules,
Expand Down Expand Up @@ -139,6 +149,32 @@ impl GlobSet {
}
}

fn deserialize_external_plugins_override<'de, D>(
deserializer: D,
) -> Result<Option<FxHashSet<(PathBuf, String)>>, D::Error>
where
D: Deserializer<'de>,
{
let opt_set: Option<FxHashSet<String>> = Option::deserialize(deserializer)?;
Ok(opt_set
.map(|set| set.into_iter().map(|specifier| (PathBuf::default(), specifier)).collect()))
}

#[expect(clippy::ref_option)]
fn serialize_external_plugins_override<S>(
plugins: &Option<FxHashSet<(PathBuf, String)>>,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
// Serialize as an array of original specifiers (the values in the map)
match plugins {
Some(set) => serializer.collect_seq(set.iter().map(|(_, specifier)| specifier)),
None => serializer.serialize_none(),
}
}

#[cfg(test)]
mod test {
use crate::config::{globals::GlobalValue, plugins::LintPlugins};
Expand Down
57 changes: 54 additions & 3 deletions crates/oxc_linter/src/config/oxlintrc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::{

use rustc_hash::{FxHashMap, FxHashSet};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use oxc_diagnostics::OxcDiagnostic;

Expand Down Expand Up @@ -68,8 +68,15 @@ pub struct Oxlintrc {
///
/// Note: JS plugins are experimental and not subject to semver.
/// They are not supported in language server at present.
#[serde(rename = "jsPlugins")]
pub external_plugins: Option<FxHashSet<String>>,
#[serde(
rename = "jsPlugins",
deserialize_with = "deserialize_external_plugins",
serialize_with = "serialize_external_plugins",
default,
skip_serializing_if = "Option::is_none"
)]
#[schemars(with = "Option<FxHashSet<String>>")]
pub external_plugins: Option<FxHashSet<(PathBuf, String)>>,
pub categories: OxlintCategories,
/// Example
///
Expand Down Expand Up @@ -152,6 +159,24 @@ impl Oxlintrc {

config.path = path.to_path_buf();

#[expect(clippy::missing_panics_doc)]
let config_dir = config.path.parent().unwrap();
if let Some(external_plugins) = &mut config.external_plugins {
*external_plugins = std::mem::take(external_plugins)
.into_iter()
.map(|(_, specifier)| (config_dir.to_path_buf(), specifier))
.collect();
}

for override_config in config.overrides.iter_mut() {
if let Some(external_plugins) = &mut override_config.external_plugins {
*external_plugins = std::mem::take(external_plugins)
.into_iter()
.map(|(_, specifier)| (config_dir.to_path_buf(), specifier))
.collect();
}
}

Ok(config)
}

Expand Down Expand Up @@ -232,6 +257,32 @@ fn is_json_ext(ext: &str) -> bool {
ext == "json" || ext == "jsonc"
}

fn deserialize_external_plugins<'de, D>(
deserializer: D,
) -> Result<Option<FxHashSet<(PathBuf, String)>>, D::Error>
where
D: Deserializer<'de>,
{
let opt_set: Option<FxHashSet<String>> = Option::deserialize(deserializer)?;
Ok(opt_set
.map(|set| set.into_iter().map(|specifier| (PathBuf::default(), specifier)).collect()))
}

#[expect(clippy::ref_option)]
fn serialize_external_plugins<S>(
plugins: &Option<FxHashSet<(PathBuf, String)>>,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
// Serialize as an array of original specifiers (the values in the map)
match plugins {
Some(set) => serializer.collect_seq(set.iter().map(|(_, specifier)| specifier)),
None => serializer.serialize_none(),
}
}

#[cfg(test)]
mod test {
use serde_json::json;
Expand Down
1 change: 0 additions & 1 deletion crates/oxc_linter/src/snapshots/schema_json.snap
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ expression: json
},
"jsPlugins": {
"description": "JS plugins.\n\nNote: JS plugins are experimental and not subject to semver.\nThey are not supported in language server at present.",
"default": null,
"type": [
"array",
"null"
Expand Down
1 change: 0 additions & 1 deletion npm/oxlint/configuration_schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@
},
"jsPlugins": {
"description": "JS plugins.\n\nNote: JS plugins are experimental and not subject to semver.\nThey are not supported in language server at present.",
"default": null,
"type": [
"array",
"null"
Expand Down
1 change: 0 additions & 1 deletion tasks/website/src/linter/snapshots/schema_markdown.snap
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,6 @@ Globs to ignore during linting. These are resolved from the configuration file p

type: `string[]`

default: `null`

JS plugins.

Expand Down
Loading