CST transformer that inserts docstrings into stub file nodes.
| 88 | |
| 89 | |
| 90 | class DocstringInserter(libcst.CSTTransformer): |
| 91 | """CST transformer that inserts docstrings into stub file nodes.""" |
| 92 | |
| 93 | def __init__(self, module, namespace): |
| 94 | self.module = module |
| 95 | self.base_namespace = namespace |
| 96 | self.stack = [] |
| 97 | self.indentation = 0 |
| 98 | |
| 99 | def _full_name(self): |
| 100 | name = ".".join(self.stack) |
| 101 | return f"{self.base_namespace}.{name}" if self.base_namespace else name |
| 102 | |
| 103 | def leave_Module(self, original_node, updated_node): |
| 104 | new_body = [] |
| 105 | clone_matcher = m.SimpleStatementLine( |
| 106 | body=[m.Assign(value=m.Call(func=m.Name(value="_clone_signature"))), |
| 107 | m.ZeroOrMore()] |
| 108 | ) |
| 109 | for stmt in updated_node.body: |
| 110 | new_body.append(stmt) |
| 111 | if m.matches(stmt, clone_matcher): |
| 112 | name = stmt.body[0].targets[0].target.value |
| 113 | if self.base_namespace: |
| 114 | name = f"{self.base_namespace}.{name}" |
| 115 | docstring = _get_docstring(name, self.module, 0) |
| 116 | if docstring: |
| 117 | new_body.append(libcst.SimpleStatementLine( |
| 118 | body=[libcst.Expr(value=libcst.SimpleString(docstring))])) |
| 119 | return updated_node.with_changes(body=new_body) |
| 120 | |
| 121 | def visit_ClassDef(self, node): |
| 122 | self.stack.append(node.name.value) |
| 123 | self.indentation += 1 |
| 124 | |
| 125 | def leave_ClassDef(self, original_node, updated_node): |
| 126 | name = self._full_name() |
| 127 | docstring = _get_docstring(name, self.module, self.indentation) |
| 128 | |
| 129 | if docstring: |
| 130 | ellipsis_class = m.ClassDef(body=m.IndentedBlock(body=[ |
| 131 | m.SimpleStatementLine(body=[ |
| 132 | m.Expr(m.Ellipsis()), m.ZeroOrMore()]), m.ZeroOrMore()])) |
| 133 | func_class = m.ClassDef(body=m.IndentedBlock( |
| 134 | body=[m.FunctionDef(), m.ZeroOrMore()])) |
| 135 | |
| 136 | if m.matches(updated_node, ellipsis_class): |
| 137 | updated_node = updated_node.deep_replace( |
| 138 | updated_node.body.body[0].body[0].value, |
| 139 | libcst.SimpleString(value=docstring)) |
| 140 | elif m.matches(updated_node, func_class): |
| 141 | docstring_stmt = libcst.SimpleStatementLine( |
| 142 | body=[libcst.Expr(value=libcst.SimpleString(value=docstring))]) |
| 143 | updated_node = updated_node.with_changes( |
| 144 | body=updated_node.body.with_changes( |
| 145 | body=[docstring_stmt] + list(updated_node.body.body))) |
| 146 | |
| 147 | self.stack.pop() |
no outgoing calls
no test coverage detected