From ff047ac9ad61b559e6f6c5d49d285015d0849eee Mon Sep 17 00:00:00 2001 From: Antti Kaihola <13725+akaihola@users.noreply.github.com> Date: Wed, 9 Oct 2024 10:46:04 +0300 Subject: [PATCH] refactor: build options for the Black call in a helper method [black-as-plugin] Thanks @clintonsteiner! --- src/darker/formatters/black_formatter.py | 31 ++++++++++++++---------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/src/darker/formatters/black_formatter.py b/src/darker/formatters/black_formatter.py index baf5fc61e..540283b05 100644 --- a/src/darker/formatters/black_formatter.py +++ b/src/darker/formatters/black_formatter.py @@ -153,6 +153,23 @@ def run(self, content: TextDocument) -> TextDocument: :return: The reformatted content """ + contents_for_black = content.string_with_newline("\n") + if contents_for_black.strip(): + dst_contents = format_str( + contents_for_black, mode=self._make_black_options() + ) + else: + # The custom handling of empty and all-whitespace files was needed until + # Black 22.12.0. See https://github.com/psf/black/pull/2484 + dst_contents = "\n" if "\n" in content.string else "" + return TextDocument.from_str( + dst_contents, + encoding=content.encoding, + override_newline=content.newline, + ) + + def _make_black_options(self) -> Mode: + """Create a Black ``Mode`` object from the configuration options.""" # Collect relevant Black configuration options from ``self.config`` in order to # pass them to Black's ``format_str()``. File exclusion options aren't needed # since at this point we already have a single file's content to work on. @@ -182,19 +199,7 @@ def run(self, content: TextDocument) -> TextDocument: mode["string_normalization"] = not self.config["skip_string_normalization"] if "preview" in self.config: mode["preview"] = self.config["preview"] - - contents_for_black = content.string_with_newline("\n") - if contents_for_black.strip(): - dst_contents = format_str(contents_for_black, mode=Mode(**mode)) - else: - # The custom handling of empty and all-whitespace files was needed until - # Black 22.12.0. See https://github.com/psf/black/pull/2484 - dst_contents = "\n" if "\n" in content.string else "" - return TextDocument.from_str( - dst_contents, - encoding=content.encoding, - override_newline=content.newline, - ) + return Mode(**mode) def get_config_path(self) -> str | None: """Get the path of the Black configuration file."""