Skip to content

Commit ad7fbfa

Browse files
committed
clean python imports
1 parent 5c68ff9 commit ad7fbfa

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

gazelle/python/file_parser.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,14 @@ func parseImportStatement(node *sitter.Node, code []byte) (Module, bool) {
144144
return Module{}, false
145145
}
146146

147+
// cleanImportString removes backslashes and all whitespace from the string.
148+
func cleanImportString(s string) string {
149+
s = strings.ReplaceAll(s, "\\", "")
150+
s = strings.ReplaceAll(s, " ", "")
151+
s = strings.ReplaceAll(s, "\n", "")
152+
return s
153+
}
154+
147155
// parseImportStatements parses a node for import statements, returning true if the node is
148156
// an import statement. It updates FileParser.output.Modules with the `module` that the
149157
// import represents.
@@ -154,6 +162,7 @@ func (p *FileParser) parseImportStatements(node *sitter.Node) bool {
154162
if !ok {
155163
continue
156164
}
165+
m.From = cleanImportString(m.From)
157166
m.Filepath = p.relFilepath
158167
m.TypeCheckingOnly = p.inTypeCheckingBlock
159168
if strings.HasPrefix(m.Name, ".") {
@@ -163,6 +172,7 @@ func (p *FileParser) parseImportStatements(node *sitter.Node) bool {
163172
}
164173
} else if node.Type() == sitterNodeTypeImportFromStatement {
165174
from := node.Child(1).Content(p.code)
175+
from = cleanImportString(from)
166176
// If the import is from the current package, we don't need to add it to the modules i.e. from . import Class1.
167177
// If the import is from a different relative package i.e. from .package1 import foo, we need to add it to the modules.
168178
if from == "." {

gazelle/python/file_parser_test.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,3 +291,32 @@ def example_function():
291291
}
292292
}
293293
}
294+
295+
func TestParseImportStatements_MultilineWithBackslashAndWhitespace(t *testing.T) {
296+
p := NewFileParser()
297+
code := []byte(`from foo.bar.\
298+
baz import (
299+
Something,
300+
AnotherThing
301+
)
302+
`)
303+
p.SetCodeAndFile(code, "", "test.py")
304+
output, err := p.Parse(context.Background())
305+
assert.NoError(t, err)
306+
// Should parse as: from foo.bar.baz import Something, AnotherThing
307+
expected := []Module{
308+
{
309+
Name: "foo.bar.baz.Something",
310+
LineNumber: 3,
311+
Filepath: "test.py",
312+
From: "foo.bar.baz",
313+
},
314+
{
315+
Name: "foo.bar.baz.AnotherThing",
316+
LineNumber: 4,
317+
Filepath: "test.py",
318+
From: "foo.bar.baz",
319+
},
320+
}
321+
assert.Equal(t, expected, output.Modules)
322+
}

0 commit comments

Comments
 (0)