peterjc / flake8-black

flake8 plugin to run black for checking Python coding style
MIT License
165 stars 10 forks source link

Graceful handling of missing black config (if set) #12

Open peterjc opened 5 years ago

peterjc commented 5 years ago

For #9, pull request #11 added flake8 --black-config /path/to/black.toml support (also possible via your flake8 configuration file).

If this configuration is not set, the current behaviour is fine (follow black in looking for pyproject.toml and failing that, use black's defaults).

If this path is set, but the file does not exist, we should error explicitly and as early as possible:

We could introduce a validation code and raise this on every file checked instead of calling black (perhaps reuse BLK998) - but I think there ought to be a way to tell flake8 to abort gracefully:

https://gitlab.com/pycqa/flake8/issues/559

peterjc commented 5 years ago

Something like this - if raising an exception in parse_options is encouraged:

    @classmethod
    def add_options(cls, parser):
        """Adding black-config option."""
        parser.add_option(
            "--black-config",
            default=None,
            action="store",
            type="string",
            parse_from_config=True,
            help="Path to black configuration file "
            "(overrides the default pyproject.toml)",
        )

    @classmethod
    def parse_options(cls, options):
        """Adding black-config option."""
        cls.flake8_black_config = None
        if options.black_config:
            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(self.flake8_config)))
                black_config_path = base_path / black_config_path
            if not black_config_path.is_file():
                raise ValueError(
                    "Plugin flake8-black could not find specified black config file: "
                    "--black-config %s" % black_config_path
                )
            cls.flake8_black_config = black_config_path

With a test,

echo "Checking we report an error when can't find specified config file"
flake8 --black-config does_not_exist.toml 2>&1  | grep -i "could not find"
peterjc commented 5 years ago

Looks like we'll need an update to flake8 itself to solve this with a graceful abort, but they seem willing: https://gitlab.com/pycqa/flake8/issues/559