Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add line wrapping to summaries of docstrings #14

Merged
merged 2 commits into from
Apr 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ Current usage of ``pydocstringformatter``:
[--summary-quotes-same-line]
[--split-summary-body --no-split-summary-body]
[--strip-whitespaces --no-strip-whitespaces]
[--linewrap-full-docstring --no-linewrap-full-docstring]
[--beginning-quotes --no-beginning-quotes]
[--closing-quotes --no-closing-quotes]
[--capitalize-first-letter --no-capitalize-first-letter]
Expand Down Expand Up @@ -79,3 +80,7 @@ Current usage of ``pydocstringformatter``:
currently optional as its considered somwehat
opinionated and might require major refactoring for
existing projects. (default: False)
--linewrap-full-docstring, --no-linewrap-full-docstring
Activate or deactivate linewrap-full-docstring:
Linewrap the docstring by the pre-defined line length.
(default: False)
2 changes: 2 additions & 0 deletions pydocstringformatter/formatting/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
CapitalizeFirstLetterFormatter,
ClosingQuotesFormatter,
FinalPeriodFormatter,
LineWrapperFormatter,
QuotesTypeFormatter,
SplitSummaryAndDocstringFormatter,
StripWhitespacesFormatter,
Expand All @@ -21,6 +22,7 @@
FORMATTERS: List[Formatter] = [
SplitSummaryAndDocstringFormatter(),
StripWhitespacesFormatter(),
LineWrapperFormatter(),
BeginningQuotesFormatter(),
ClosingQuotesFormatter(),
CapitalizeFirstLetterFormatter(),
Expand Down
20 changes: 17 additions & 3 deletions pydocstringformatter/formatting/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,13 @@ class SummaryAndDescriptionFormatter(StringAndQuotesFormatter):
"""Base class for formatter that modifies the summary and description."""

@abc.abstractmethod
def _treat_summary(self, summary: str, indent_length: int) -> str:
def _treat_summary(
self,
summary: str,
indent_length: int,
quotes_length: Literal[1, 3],
description_exists: bool,
) -> str:
"""Return a modified summary."""

@abc.abstractmethod
Expand Down Expand Up @@ -156,7 +162,9 @@ def _treat_string(
quotes_length,
)

new_summary = self._treat_summary(summary, indent_length)
new_summary = self._treat_summary(
summary, indent_length, quotes_length, bool(description)
)
docstring = f"{quotes}{prefix}{new_summary}"

if description:
Expand All @@ -173,7 +181,13 @@ class SummaryFormatter(SummaryAndDescriptionFormatter):
"""Base class for formatter that only modifies the summary of a docstring."""

@abc.abstractmethod
def _treat_summary(self, summary: str, indent_length: int) -> str:
def _treat_summary(
self,
summary: str,
indent_length: int,
quotes_length: Literal[1, 3],
description_exists: bool,
) -> str:
"""Return a modified summary."""

def _treat_description(self, description: str, indent_length: int) -> str:
Expand Down
61 changes: 59 additions & 2 deletions pydocstringformatter/formatting/formatter.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import re
import textwrap
import tokenize
from typing import Literal

Expand Down Expand Up @@ -54,6 +55,50 @@ def _treat_string(self, tokeninfo: tokenize.TokenInfo, _: int) -> str:
return new_string or tokeninfo.string


class LineWrapperFormatter(SummaryFormatter):
"""Linewrap the docstring by the pre-defined line length."""

name = "linewrap-full-docstring"
optional = True

def _treat_summary(
self,
summary: str,
indent_length: int,
quotes_length: Literal[1, 3],
description_exists: bool,
) -> str:
"""Wrap the summary of a docstring."""

# We need to deduct ending quotes if there is no description
line_length = 88 if description_exists else 88 - quotes_length
summary_lines = summary.splitlines()

new_summary = "\n".join(
textwrap.wrap(
summary_lines[0],
width=line_length,
initial_indent=" " * (indent_length + quotes_length),
subsequent_indent=" " * indent_length,
replace_whitespace=True,
)
)[indent_length + quotes_length :]

if len(summary_lines) > 1:
for line in summary_lines[1:]:
new_summary += "\n"
new_summary += "\n".join(
textwrap.wrap(
line,
width=line_length,
subsequent_indent=" " * indent_length,
replace_whitespace=True,
)
)

return new_summary


class ClosingQuotesFormatter(StringFormatter):
"""Fix the position of the closing quotes."""

Expand Down Expand Up @@ -83,7 +128,13 @@ class FinalPeriodFormatter(SummaryFormatter):
name = "final-period"
END_OF_SENTENCE_PUNCTUATION = {".", "?", "!", "‽", ":", ";"}

def _treat_summary(self, summary: str, indent_length: int) -> str:
def _treat_summary(
self,
summary: str,
indent_length: int,
quotes_length: Literal[1, 3],
description_exists: bool,
) -> str:
"""Add a period to the end of single-line docstrings and summaries."""
if summary[-1] in self.END_OF_SENTENCE_PUNCTUATION:
return summary
Expand Down Expand Up @@ -120,7 +171,13 @@ class SplitSummaryAndDocstringFormatter(SummaryFormatter):
"""Pattern to match against an end of sentence period."""

# pylint: disable-next=too-many-branches
def _treat_summary(self, summary: str, indent_length: int) -> str:
def _treat_summary(
self,
summary: str,
indent_length: int,
quotes_length: Literal[1, 3],
description_exists: bool,
) -> str:
"""Split a summary and body if there is a period after the summary."""
new_summary = None

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
--linewrap-full-docstring
27 changes: 27 additions & 0 deletions tests/data/format/linewrap_summary/function_docstrings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
def func():
"""A very long summary line that needs to be wrapped. A very long summary line that needs to be wrapped.

A description that is not too long.
"""


def func():
"""A very long multi-line summary line that needs to be wrapped. A very long multi-line summary line that needs to be wrapped.
A very long summary line that needs to be wrapped.

A description that is not too long.
"""


def func():
"""A multi-line summary that can be on one line.
But it has a new line so it isn't.

A description that is not too long.
"""


# Since the ending quotes will be appended on the same line this
# exceeds the max length.
def func():
"""A multi-line summary that can be on one line. Something that is just too longgg."""
31 changes: 31 additions & 0 deletions tests/data/format/linewrap_summary/function_docstrings.py.out
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
def func():
"""A very long summary line that needs to be wrapped. A very long summary line that
needs to be wrapped.

A description that is not too long.
"""


def func():
"""A very long multi-line summary line that needs to be wrapped. A very long multi-
line summary line that needs to be wrapped.
A very long summary line that needs to be wrapped.

A description that is not too long.
"""


def func():
"""A multi-line summary that can be on one line.
But it has a new line so it isn't.

A description that is not too long.
"""


# Since the ending quotes will be appended on the same line this
# exceeds the max length.
def func():
"""A multi-line summary that can be on one line. Something that is just too
longgg.
"""