Skip to content

Commit

Permalink
[AddImportsVisitor] generate deterministic add import output by sorti…
Browse files Browse the repository at this point in the history
…ng the sets.
  • Loading branch information
jimmylai committed Mar 26, 2020
1 parent 1b9a52b commit 0dc3995
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
15 changes: 9 additions & 6 deletions libcst/codemod/visitors/_add_imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,17 +228,20 @@ def leave_ImportFrom(

# Now, do the actual update.
return updated_node.with_changes(
names=(
*[libcst.ImportAlias(name=libcst.Name(imp)) for imp in imports_to_add],
*[
names=[
*(
libcst.ImportAlias(name=libcst.Name(imp))
for imp in sorted(imports_to_add)
),
*(
libcst.ImportAlias(
name=libcst.Name(imp),
asname=libcst.AsName(name=libcst.Name(alias)),
)
for (imp, alias) in aliases_to_add
],
for (imp, alias) in sorted(aliases_to_add)
),
*updated_node.names,
)
]
)

def _split_module(
Expand Down
18 changes: 18 additions & 0 deletions libcst/codemod/visitors/tests/test_add_imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -620,3 +620,21 @@ def bar() -> int:
[("a.b.c", "D", None)],
context_override=CodemodContext(full_module_name="a.b.foobar"),
)

def test_import_order(self) -> None:
"""
The imports should be in alphabetic order of added imports, added import alias, original imports.
"""
before = """
from a import b, e, h
"""
after = """
from a import c, f, d as x, g as y, b, e, h
"""

self.assertCodemod(
before,
after,
[("a", "f", None), ("a", "g", "y"), ("a", "c", None), ("a", "d", "x")],
context_override=CodemodContext(full_module_name="a.b.foobar"),
)

0 comments on commit 0dc3995

Please sign in to comment.