Repository: psf/black
File: src/black/__init__.py (Python)

Code before:
def re_compile_maybe_verbose(regex: str) -> Pattern[str]:
    """Compile a regular expression string in `regex`.

    If it contains newlines, use verbose mode.
    """
    if "\n" in regex:
        regex = "(?x)" + regex
    compiled: Pattern[str] = re.compile(regex)
    return compiled


def enumerate_reversed(sequence: Sequence[T]) -> Iterator[Tuple[Index, T]]:
    """Like `reversed(enumerate(sequence))` if that were possible."""
    index = len(sequence) - 1
    for element in reversed(sequence):
        yield (index, element)
        index -= 1


def enumerate_with_length(
    line: Line, reversed: bool = False
) -> Iterator[Tuple[Index, Leaf, int]]:
    """Return an enumeration of leaves with their length.

    Stops prematurely on multiline strings and standalone comments.
    """
    op = cast(
        Callable[[Sequence[Leaf]], Iterator[Tuple[Index, Leaf]]],
        enumerate_reversed if reversed else enumerate,
    )
    for index, leaf in op(line.leaves):
        length = len(leaf.prefix) + len(leaf.value)
        if "\n" in leaf.value:
            return  # Multiline strings, we can't continue.

        for comment in line.comments_after(leaf):
            length += len(comment.value)

        yield index, leaf, length


def is_line_short_enough(line: Line, *, line_length: int, line_str: str = "") -> bool:
    """Return True if `line` is no longer than `line_length`.

    Uses the provided `line_str` rendering, if any, otherwise computes a new one.
    """
    if not line_str:
        line_str = line_to_string(line)
    return (
        len(line_str) <= line_length
        and "\n" not in line_str  # multiline strings

Review comment (bug):
To someone like me, the `diff_lines.append("\\ No newline at end of file\n")` link just looks plain wrong. I would suggest explaining that this code is using a special feature of the patch specification(?) to work around a Python bug. Also linking the BPO would be the cherry on the cake!

edit: I'm pretty sure I've got my wording terribly wrong, just TL;DR is please explain the seemingly wrong code to someone who has no idea that this thing exists: https://www.gnu.org/software/diffutils/manual/html_node/Incomplete-Lines.html#Incomplete-Lines

Code after:
def nullcontext() -> Iterator[None]:
    """Return an empty context manager.

    To be used like `nullcontext` in Python 3.7.
    """
    yield


def diff(a: str, b: str, a_name: str, b_name: str) -> str:
    """Return a unified diff string between strings `a` and `b`."""
    import difflib

    a_lines = [line for line in a.splitlines(keepends=True)]
    b_lines = [line for line in b.splitlines(keepends=True)]
    diff_lines = []
    for line in difflib.unified_diff(
        a_lines, b_lines, fromfile=a_name, tofile=b_name, n=5
    ):
        # Work around https://bugs.python.org/issue2142
        # See https://www.gnu.org/software/diffutils/manual/html_node/Incomplete-Lines.html
        if line[-1] == "\n":
            diff_lines.append(line)
        else:
            diff_lines.append(line + "\n")
            diff_lines.append("\\ No newline at end of file\n")
    return "".join(diff_lines)


def cancel(tasks: Iterable["asyncio.Task[Any]"]) -> None:
    """asyncio signal handler that cancels all `tasks` and reports to stderr."""
    err("Aborted!")
    for task in tasks:
        task.cancel()


def shutdown(loop: asyncio.AbstractEventLoop) -> None:
    """Cancel all pending tasks on `loop`, wait for them, and close the loop."""
    try:
        if sys.version_info[:2] >= (3, 7):
            all_tasks = asyncio.all_tasks
        else:
            all_tasks = asyncio.Task.all_tasks
        # This part is borrowed from asyncio/runners.py in Python 3.7b2.
        to_cancel = [task for task in all_tasks(loop) if not task.done()]
        if not to_cancel:
            return

        for task in to_cancel:
            task.cancel()
        loop.run_until_complete(
            asyncio.gather(*to_cancel, loop=loop, return_exceptions=True)