Skip to content

[flake8-import-conventions] Syntax check aliases supplied in configuration for unconventional-import-alias (ICN001) #14477

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Nov 21, 2024
Merged
Show file tree
Hide file tree
Changes from 6 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
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

70 changes: 70 additions & 0 deletions crates/ruff/tests/lint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1966,3 +1966,73 @@ fn nested_implicit_namespace_package() -> Result<()> {

Ok(())
}

#[test]
fn flake8_import_convention_invalid_aliases_config_alias_name() -> Result<()> {
let tempdir = TempDir::new()?;
let ruff_toml = tempdir.path().join("ruff.toml");
fs::write(
&ruff_toml,
r#"
[lint.flake8-import-conventions.aliases]
"module.name" = "invalid.alias"
"#,
)?;

insta::with_settings!({
filters => vec![(tempdir_filter(&tempdir).as_str(), "[TMP]/")]
}, {
assert_cmd_snapshot!(Command::new(get_cargo_bin(BIN_NAME))
.args(STDIN_BASE_OPTIONS)
.arg("--config")
.arg(&ruff_toml)
, @r#"
success: false
exit_code: 2
----- stdout -----

----- stderr -----
ruff failed
Cause: Failed to parse [TMP]/ruff.toml
Cause: TOML parse error at line 2, column 2
|
2 | [lint.flake8-import-conventions.aliases]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm. The errors aren't great. Let's at least include the alias in the error message to help users figure out what's going on. The same for the module name.

| ^^^^
alias must be a valid identifier"#);});
Ok(())
}

#[test]
fn flake8_import_convention_invalid_aliases_config_module_name() -> Result<()> {
let tempdir = TempDir::new()?;
let ruff_toml = tempdir.path().join("ruff.toml");
fs::write(
&ruff_toml,
r#"
[lint.flake8-import-conventions.aliases]
"module..invalid" = "alias"
"#,
)?;

insta::with_settings!({
filters => vec![(tempdir_filter(&tempdir).as_str(), "[TMP]/")]
}, {
assert_cmd_snapshot!(Command::new(get_cargo_bin(BIN_NAME))
.args(STDIN_BASE_OPTIONS)
.arg("--config")
.arg(&ruff_toml)
, @r#"
success: false
exit_code: 2
----- stdout -----

----- stderr -----
ruff failed
Cause: Failed to parse [TMP]/ruff.toml
Cause: TOML parse error at line 2, column 2
|
2 | [lint.flake8-import-conventions.aliases]
| ^^^^
module must be a valid identifier separated by single periods"#);});
Ok(())
}
1 change: 1 addition & 0 deletions crates/ruff_workspace/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ ruff_macros = { workspace = true }
ruff_python_ast = { workspace = true }
ruff_python_formatter = { workspace = true, features = ["serde"] }
ruff_python_semantic = { workspace = true, features = ["serde"] }
ruff_python_stdlib = {workspace = true}
ruff_source_file = { workspace = true }

anyhow = { workspace = true }
Expand Down
29 changes: 28 additions & 1 deletion crates/ruff_workspace/src/options.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use regex::Regex;
use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};
use serde::{Deserialize, Serialize};
use serde::de::{self};
use serde::{Deserialize, Deserializer, Serialize};
use std::collections::BTreeMap;
use std::path::PathBuf;
use strum::IntoEnumIterator;
Expand Down Expand Up @@ -34,6 +35,7 @@ use ruff_macros::{CombineOptions, OptionsMetadata};
use ruff_python_ast::name::Name;
use ruff_python_formatter::{DocstringCodeLineWidth, QuoteStyle};
use ruff_python_semantic::NameImports;
use ruff_python_stdlib::identifiers::is_identifier;

#[derive(Clone, Debug, PartialEq, Eq, Default, OptionsMetadata, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
Expand Down Expand Up @@ -1327,6 +1329,7 @@ pub struct Flake8ImportConventionsOptions {
scipy = "sp"
"#
)]
#[serde(deserialize_with = "deserialize_and_validate_aliases")]
pub aliases: Option<FxHashMap<String, String>>,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We would probably get better error messages if you create a newtype for ModuleName and Alias and implement Deserialize for them. I would expect that serde can then narrow the error message to the specific line rather than the entire table

Copy link
Member

@AlexWaygood AlexWaygood Nov 21, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR does actually already seem to be a small improvement on the status quo when it comes to line numbers. Currently if I make this change to typeshed's pyproject.toml file:

diff --git a/pyproject.toml b/pyproject.toml
index 46014bcd2..927da6162 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -111,6 +111,9 @@ ignore = [
     "E501", # Line too long
 ]
 
+[tool.ruff.lint.flake8-import-conventions.aliases]
+"pandas" = 42
+

Then Ruff v0.7.1 gives me this error message:

ruff failed
  Cause: Failed to parse /Users/alexw/dev/typeshed/pyproject.toml
  Cause: TOML parse error at line 27, column 1
   |
27 | [tool.ruff.lint]
   | ^^^^^^^^^^^^^^^^
invalid type: integer `42`, expected a string


/// A mapping from module to conventional import alias. These aliases will
Expand Down Expand Up @@ -1370,6 +1373,30 @@ pub struct Flake8ImportConventionsOptions {
pub banned_from: Option<FxHashSet<String>>,
}

fn deserialize_and_validate_aliases<'de, D>(
deserializer: D,
) -> Result<Option<FxHashMap<String, String>>, D::Error>
where
D: Deserializer<'de>,
{
let Some(aliases) = Option::<FxHashMap<String, String>>::deserialize(deserializer)? else {
return Ok(None);
};

for (module, alias) in &aliases {
if module.is_empty() || module.split('.').any(|part| !is_identifier(part)) {
return Err(de::Error::custom(
"module must be a valid identifier separated by single periods",
));
}
if !is_identifier(alias) {
return Err(de::Error::custom("alias must be a valid identifier"));
}
}

Ok(Some(aliases)) // Return the validated map.
}

impl Flake8ImportConventionsOptions {
pub fn into_settings(self) -> flake8_import_conventions::settings::Settings {
let mut aliases = match self.aliases {
Expand Down
Loading