Skip to content

Commit fb2f6cc

Browse files
committed
Improve removal of unnecessary or double white lines
1 parent ad9de23 commit fb2f6cc

File tree

3 files changed

+70
-6
lines changed

3 files changed

+70
-6
lines changed

pydocstringformatter/formatting/formatter.py

+26-6
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from __future__ import annotations
2+
13
import re
24
import textwrap
35
import tokenize
@@ -237,17 +239,35 @@ def _treat_string(
237239
) -> str:
238240
"""Strip whitespaces."""
239241
lines = tokeninfo.string[quotes_length:-quotes_length].split("\n")
242+
new_lines: list[str] = []
243+
240244
for index, line in enumerate(lines):
245+
if line == "":
246+
# Remove double white lines
247+
if index and lines[index - 1] == "":
248+
continue
249+
250+
# On the first line strip from both sides
241251
if index == 0: # pylint: disable=compare-to-zero
242-
lines[index] = line.lstrip().rstrip()
252+
new_lines.append(line.lstrip().rstrip())
253+
254+
# Check last line
243255
elif index == len(lines) - 1:
244-
# Remove whitespaces if last line is completely empty
245-
if len(line) > indent_length and line.count(" ") == len(line):
246-
lines[index] = ""
256+
# If completely whitespace, just return the indent_length
257+
if line.count(" ") == len(line):
258+
new_lines.append(indent_length * " ")
259+
else:
260+
new_lines.append(line)
261+
262+
# Else, only strip right side
247263
else:
248-
lines[index] = line.rstrip()
264+
new_lines.append(line.rstrip())
265+
266+
# Remove a final white line
267+
if len(new_lines) > 3 and new_lines[-2] == "":
268+
new_lines.pop(-2)
249269

250-
return quotes + "\n".join(lines) + quotes
270+
return quotes + "\n".join(new_lines) + quotes
251271

252272

253273
class QuotesTypeFormatter(StringAndQuotesFormatter):

tests/data/format/whitespace_stripper/function_docstrings.py

+25
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,28 @@ def inner_func():
1414
""" A multi-line
1515
docstring
1616
"""
17+
18+
19+
def func():
20+
"""Summary.
21+
22+
Body.
23+
24+
"""
25+
26+
def inner_func():
27+
"""Summary.
28+
29+
Body.
30+
31+
32+
33+
"""
34+
35+
def inner_func():
36+
"""Summary.
37+
38+
39+
Body.
40+
41+
"""

tests/data/format/whitespace_stripper/function_docstrings.py.out

+19
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,22 @@ def func():
1616

1717
docstring
1818
"""
19+
20+
21+
def func():
22+
"""Summary.
23+
24+
Body.
25+
"""
26+
27+
def inner_func():
28+
"""Summary.
29+
30+
Body.
31+
"""
32+
33+
def inner_func():
34+
"""Summary.
35+
36+
Body.
37+
"""

0 commit comments

Comments
 (0)