From f6a5622379951133cabac0b2185fbd4a225561b4 Mon Sep 17 00:00:00 2001 From: Alex Waygood Date: Tue, 15 Jul 2025 12:39:41 +0100 Subject: [PATCH] Don't add newlines to the start of docstrings --- add_docstrings.py | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/add_docstrings.py b/add_docstrings.py index 6c8be88..8329fab 100644 --- a/add_docstrings.py +++ b/add_docstrings.py @@ -46,7 +46,7 @@ class DocumentableObject(NamedTuple): def clean_docstring(docstring: str) -> str: - return docstring.strip().replace("\\", "\\\\") + return docstring.rstrip().replace("\\", "\\\\") def add_docstring_to_libcst_node( @@ -77,7 +77,23 @@ def add_docstring_to_libcst_node( return updated_node indentation = " " * 4 * level - indented_docstring = f'"""\n{textwrap.indent(clean_docstring(docstring), indentation)}\n{indentation}"""' + + # For a single-line docstring, this can result in funny things like: + # + # ```py + # def foo(): + # """A docstring. + # """ + # ``` + # + # But we don't need to worry about that here: Black sorts that out for us and turns it into: + # + # ```py + # def foo(): + # """A docstring.""" + # ``` + indented_docstring = f'"""{textwrap.indent(clean_docstring(docstring), indentation).lstrip(" ")}\n{indentation}"""' + docstring_node = libcst.Expr(libcst.SimpleString(indented_docstring)) # If the body is just a `...`, replace it with just the docstring.