From 0dc39950f935e23069909d6f8e1e277ffe25e7b6 Mon Sep 17 00:00:00 2001 From: Jimmy Lai Date: Wed, 25 Mar 2020 16:15:19 -0700 Subject: [PATCH] [AddImportsVisitor] generate deterministic add import output by sorting the sets. --- libcst/codemod/visitors/_add_imports.py | 15 +++++++++------ .../codemod/visitors/tests/test_add_imports.py | 18 ++++++++++++++++++ 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/libcst/codemod/visitors/_add_imports.py b/libcst/codemod/visitors/_add_imports.py index 1028e8d61..929cf8866 100644 --- a/libcst/codemod/visitors/_add_imports.py +++ b/libcst/codemod/visitors/_add_imports.py @@ -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( diff --git a/libcst/codemod/visitors/tests/test_add_imports.py b/libcst/codemod/visitors/tests/test_add_imports.py index 95b6d0aca..5ca4747df 100644 --- a/libcst/codemod/visitors/tests/test_add_imports.py +++ b/libcst/codemod/visitors/tests/test_add_imports.py @@ -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"), + )