Skip to content

Commit d284772

Browse files
ntBreJkhall81
authored andcommitted
add a bad test case
1 parent b582792 commit d284772

3 files changed

Lines changed: 22 additions & 7 deletions

File tree

crates/ruff_linter/resources/test/fixtures/pylint/import_private_name/submodule/__main__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,3 +44,5 @@ class Class:
4444

4545
def __init__(self, arg: vv) -> "zz":
4646
pass
47+
48+
from foo. _bar import baz

crates/ruff_linter/src/rules/pylint/rules/import_private_name.rs

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@ use itertools::Itertools;
55
use ruff_macros::{ViolationMetadata, derive_message_formats};
66
use ruff_python_ast::{self as ast, helpers::is_dunder, name::QualifiedName};
77
use ruff_python_semantic::{FromImport, Import, Imported, ResolvedReference, Scope};
8-
use ruff_text_size::{Ranged, TextLen, TextRange, TextSize};
8+
use ruff_python_trivia::{SimpleTokenKind, SimpleTokenizer};
9+
use ruff_text_size::Ranged;
910

1011
use crate::Violation;
1112
use crate::checkers::ast::Checker;
@@ -141,12 +142,15 @@ pub(crate) fn import_private_name(checker: &Checker, scope: &Scope) {
141142
Some(ast::Stmt::ImportFrom(ast::StmtImportFrom { module, names, .. })) => {
142143
if index < import_info.module_name.len() {
143144
module.as_ref().map_or(binding.range(), |module| {
144-
let offset: TextSize = import_info.qualified_name.segments()[..index]
145-
.iter()
146-
.map(|segment| segment.text_len() + TextSize::new(1))
147-
.sum();
148-
149-
TextRange::at(module.start() + offset, private_name.text_len())
145+
SimpleTokenizer::starts_at(module.start(), checker.locator().contents())
146+
.skip_trivia()
147+
.find(|token| {
148+
token.kind == SimpleTokenKind::Name
149+
&& checker.locator().slice(token.range()) == *private_name
150+
})
151+
.map_or(binding.range(), |token: ruff_python_trivia::SimpleToken| {
152+
token.range()
153+
})
150154
})
151155
} else {
152156
names

crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLC2701_import_private_name__submodule____main__.py.snap

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,3 +75,12 @@ PLC2701 Private name import `_ddd` from external module `bbb.ccc`
7575
9 |
7676
10 | # Non-errors.
7777
|
78+
79+
PLC2701 Private name import `_bar` from external module `foo`
80+
--> __main__.py:48:14
81+
|
82+
46 | pass
83+
47 |
84+
48 | from foo. _bar import baz
85+
| ^^^^
86+
|

0 commit comments

Comments
 (0)