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 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)