Skip to content

Commit

Permalink
Add support for black config
Browse files Browse the repository at this point in the history
  • Loading branch information
Mystic-Mirage committed Apr 15, 2020
1 parent 6059676 commit c220e7b
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 9 deletions.
11 changes: 7 additions & 4 deletions src/darker/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import logging
import sys
from pathlib import Path
from typing import Iterable, List, Set
from typing import Iterable, List, Optional, Set

from darker.black_diff import diff_and_get_opcodes, opcodes_to_chunks, run_black
from darker.chooser import choose_lines
Expand All @@ -20,7 +20,9 @@
MAX_CONTEXT_LINES = 1000


def format_edited_parts(srcs: Iterable[Path], isort: bool) -> None:
def format_edited_parts(
srcs: Iterable[Path], isort: bool, config: Optional[str]
) -> None:
"""Black (and optional isort) formatting for chunks with edits since the last commit
1. run isort on each edited file
Expand All @@ -40,6 +42,7 @@ def format_edited_parts(srcs: Iterable[Path], isort: bool) -> None:
:param srcs: Directories and files to re-format
:param isort: ``True`` to also run ``isort`` first on each changed file
:param config: Path to the black configuration file (optional)
"""
remaining_srcs: Set[Path] = set(srcs)
Expand All @@ -65,7 +68,7 @@ def format_edited_parts(srcs: Iterable[Path], isort: bool) -> None:
continue

# 4. run black
edited, formatted = run_black(src)
edited, formatted = run_black(src, config)
logger.debug("Read %s lines from edited file %s", len(edited), src)
logger.debug("Black reformat resulted in %s lines", len(formatted))

Expand Down Expand Up @@ -134,7 +137,7 @@ def main(argv: List[str] = None) -> None:
exit(1)

paths = {Path(p) for p in args.src}
format_edited_parts(paths, args.isort)
format_edited_parts(paths, args.isort, args.config)


if __name__ == "__main__":
Expand Down
30 changes: 26 additions & 4 deletions src/darker/black_diff.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,22 +74,44 @@

import logging
from difflib import SequenceMatcher
from functools import lru_cache
from pathlib import Path
from typing import Generator, List, Tuple
from typing import Dict, Generator, List, Optional, Tuple, Union

from black import FileMode, format_str
from black import FileMode, format_str, read_pyproject_toml
from click import Command, Context, Option

logger = logging.getLogger(__name__)


def run_black(src: Path) -> Tuple[List[str], List[str]]:
@lru_cache(maxsize=1)
def read_black_config(
src: Path, value: Optional[str]
) -> Dict[str, Union[bool, int, set]]:
"""Read the black configuration from pyproject.toml"""
command = Command("main")

context = Context(command)
context.params["src"] = (str(src),)

parameter = Option(("--config",))

read_pyproject_toml(context, parameter, value)

return context.default_map or {}


def run_black(src: Path, config: Optional[str]) -> Tuple[List[str], List[str]]:
"""Run the black formatter for the contents of the given Python file
Return lines of the original file as well as the formatted content.
"""
defaults = read_black_config(src, config)
mode = FileMode(**defaults)

src_contents = src.read_text()
dst_contents = format_str(src_contents, mode=FileMode())
dst_contents = format_str(src_contents, mode=mode)
return src_contents.splitlines(), dst_contents.splitlines()


Expand Down
3 changes: 3 additions & 0 deletions src/darker/command_line.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ def parse_command_line(argv: List[str]) -> Namespace:
parser.add_argument(
"-i", "--isort", action="store_true", help="".join(isort_help),
)
parser.add_argument(
"-c", "--config", metavar="PATH", help="Read configuration from PATH."
)
parser.add_argument(
"-v",
"--verbose",
Expand Down
16 changes: 15 additions & 1 deletion src/darker/tests/test_black_diff.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
from pathlib import Path
from textwrap import dedent

import pytest
from black import FileMode, format_str

from darker.black_diff import diff_and_get_opcodes, opcodes_to_chunks
from darker.black_diff import diff_and_get_opcodes, opcodes_to_chunks, read_black_config

FUNCTIONS2_PY = dedent(
'''\
Expand Down Expand Up @@ -147,3 +149,15 @@ def test_mixed():
[' print("Inner defs should breathe a little.")'],
),
]


@pytest.mark.parametrize("config,line_length", ((None, 79), ("custom.toml", 99)))
def test_black_config(tmpdir, config, line_length):
tmpdir = Path(tmpdir)
src = tmpdir / "src.py"
toml = tmpdir / (config or "pyproject.toml")

toml.write_text("[tool.black]\nline-length = {}\n".format(line_length))

config = read_black_config(src, config and str(toml))
assert config == {"line_length": line_length}

0 comments on commit c220e7b

Please sign in to comment.