in usort/translate.py [0:0]
def import_from_node(node: cst.SimpleStatementLine, config: Config) -> SortableImport:
# TODO: This duplicates (differently) what's in the LibCST import metadata visitor.
stem: Optional[str] = None
items: List[SortableImportItem] = []
comments = import_comments_from_node(node)
# There are 4 basic types of import
# Additionally some forms z can have leading dots for relative
# imports, and there can be multiple on the right-hand side.
#
if isinstance(node.body[0], cst.Import):
# import z
# import z as y
items = [item_from_node(name) for name in node.body[0].names]
elif isinstance(node.body[0], cst.ImportFrom):
# from z import x
# from z import x as y
# This is treated as a barrier and should never get this far.
assert not isinstance(node.body[0].names, cst.ImportStar)
stem = with_dots(node.body[0].module) if node.body[0].module else ""
if node.body[0].relative:
stem = "." * len(node.body[0].relative) + stem
for name in node.body[0].names:
items.append(item_from_node(name, stem, comments.initial))
comments.initial = []
else:
raise TypeError
# assume that "following" comments are actually meant for an item after that
prev: Optional[SortableImportItem] = None
for item in items:
if prev is not None and prev.comments.following:
item.comments.before.extend(prev.comments.following)
prev.comments.following.clear()
prev = item
# following comments on the last item should maybe be on the import itself
if prev is not None and prev.comments.following:
comments.final.extend(prev.comments.following)
prev.comments.following.clear()
imp = SortableImport(
stem=stem,
items=items,
comments=comments,
config=config,
node=node,
indent="",
)
return imp