def load_black_mode(toml_filename=None):
    """Load a black configuration TOML file (or return defaults) as FileMode."""
    if not toml_filename:
        return black.FileMode(
            target_versions=set(),
            line_length=black.DEFAULT_LINE_LENGTH,  # Expect to be 88
            string_normalization=True,
        )

    LOG.info("flake8-black: loading black settings from %s", toml_filename)
    try:
        pyproject_toml = toml.load(str(toml_filename))
    except toml.decoder.TomlDecodeError:
        LOG.info("flake8-black: invalid TOML file %s", toml_filename)
        raise BadBlackConfig(path.relpath(toml_filename))
    config = pyproject_toml.get("tool", {}).get("black", {})
    black_config = {
        k.replace("--", "").replace("-", "_"): v
        for k, v in config.items()
    }

    # Extract the fields we care about:
    return black.FileMode(
        target_versions={
            black.TargetVersion[val.upper()]
            for val in black_config.get("target_version", [])
        },
        line_length=black_config.get("line_length", black.DEFAULT_LINE_LENGTH),
        string_normalization=not black_config.get("skip_string_normalization",
                                                  False),
    )
    def _file_mode(self):
        """Return black.FileMode object, using local pyproject.toml as needed."""
        if self.override_config:
            return self.override_config

        # Unless using override, we look for pyproject.toml
        project_root = black.find_project_root(
            ("." if self.filename in self.STDIN_NAMES else self.filename, ))
        path = project_root / "pyproject.toml"

        if path in black_config:
            # Already loaded
            LOG.debug("flake8-black: %s using pre-loaded %s", self.filename,
                      path)
            return black_config[path]
        elif path.is_file():
            # Use this pyproject.toml for this python file,
            # (unless configured with global override config)
            # This should be thread safe - does not matter even if
            # two workers load and cache this file at the same time
            black_config[path] = load_black_mode(path)
            LOG.debug("flake8-black: %s using newly loaded %s", self.filename,
                      path)
            return black_config[path]
        else:
            # No project specific file, use default
            LOG.debug("flake8-black: %s using defaults", self.filename)
            return black_config[None]
    def parse_options(cls, optmanager, options, extra_args):
        """Adding black-config option."""
        # We have one and only one flake8 plugin configuration
        if options.black_config is None:
            LOG.info("flake8-black: No black configuration set")
            cls.override_config = None
            return
        elif not options.black_config:
            LOG.info(
                "flake8-black: Explicitly using no black configuration file")
            cls.override_config = black_config[None]  # explicitly use defaults
            return

        # Validate the path setting - handling relative paths ourselves,
        # see https://gitlab.com/pycqa/flake8/issues/562
        black_config_path = Path(options.black_config)
        if options.config:
            # Assume black config path was via flake8 config file
            base_path = Path(path.dirname(path.abspath(options.config)))
            black_config_path = base_path / black_config_path
        if not black_config_path.is_file():
            # Want flake8 to abort, see:
            # https://gitlab.com/pycqa/flake8/issues/559
            raise ValueError(
                "Plugin flake8-black could not find specified black config file: "
                "--black-config %s" % black_config_path)

        # Now load the TOML file, and the black section within it
        # This configuration is to override any local pyproject.toml
        try:
            cls.override_config = black_config[
                black_config_path] = load_black_mode(black_config_path)
        except BadBlackConfig:
            # Could raise BLK997, but view this as an abort condition
            raise ValueError(
                "Plugin flake8-black could not parse specified black config file: "
                "--black-config %s" % black_config_path)
Example #4
0
# Copyright 2016-2018 Dirk Thomas
# Copyright 2018 Mickael Gaillard
# Licensed under the Apache License, Version 2.0

import logging
from pathlib import Path
import sys

from flake8 import LOG
from flake8.api.legacy import get_style_guide

# avoid debug and info messages from flake8 internals
LOG.setLevel(logging.WARN)


def test_flake8():
    style_guide = get_style_guide(
        ignore=['D100', 'D104'],
        show_source=True,
    )
    style_guide_tests = get_style_guide(
        ignore=['D100', 'D101', 'D102', 'D103', 'D104', 'D105', 'D107'],
        show_source=True,
    )

    stdout = sys.stdout
    sys.stdout = sys.stderr
    # implicitly calls report_errors()
    report = style_guide.check_files([
        str(Path(__file__).parents[1] / 'colcon_cmake'),
    ])
Example #5
0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import logging
import os
import sys

from flake8 import LOG
from flake8.api.legacy import get_style_guide

# suppress warning messages from flake8
LOG.setLevel(logging.ERROR)


def test_flake8():
    style_guide = get_style_guide(
        extend_ignore=['D100', 'D104', 'W503'],
        show_source=True,
    )
    style_guide_tests = get_style_guide(
        extend_ignore=['D100', 'D101', 'D102', 'D103', 'D104', 'D105', 'D107'],
        show_source=True,
    )

    report = style_guide.check_files([
        os.path.join(os.path.dirname(__file__), '..', 'rosdoc2'),
    ])
# Copyright 2016-2018 Dirk Thomas
# Licensed under the Apache License, Version 2.0

import logging
from pathlib import Path
import sys

from flake8 import LOG
from flake8.api.legacy import get_style_guide
from pydocstyle.utils import log

# avoid debug and info messages from flake8 internals
LOG.setLevel(logging.WARNING)


def test_flake8():
    # for some reason the pydocstyle logger changes to an effective level of 1
    # set higher level to prevent the output to be flooded with debug messages
    log.setLevel(logging.WARNING)

    style_guide = get_style_guide(
        extend_ignore=['D100', 'D104'],
        show_source=True,
    )
    style_guide_tests = get_style_guide(
        extend_ignore=['D100', 'D101', 'D102', 'D103', 'D104', 'D105', 'D107'],
        show_source=True,
    )

    stdout = sys.stdout
    sys.stdout = sys.stderr