summaryrefslogtreecommitdiff
path: root/src/flake8/options
diff options
context:
space:
mode:
authorIan Stapleton Cordasco <graffatcolmingov@gmail.com>2018-10-20 07:31:42 -0500
committerIan Stapleton Cordasco <graffatcolmingov@gmail.com>2018-10-20 12:37:14 -0500
commitc58a4662d8920cf70ea688edd9eaf9d783a856a7 (patch)
tree6dda552de1b7250ccd1347a7ebc62dc69b9ff0c0 /src/flake8/options
parenta2b7a7e4c590d73acc77a17ff8b0450e3b9b81d8 (diff)
downloadflake8-c58a4662d8920cf70ea688edd9eaf9d783a856a7.tar.gz
Use black to reformat Flake8
Instead of just using Flake8 and pylint to keep Flake8 clean, let's also use black to make it less manual for clean-up.
Diffstat (limited to 'src/flake8/options')
-rw-r--r--src/flake8/options/aggregator.py30
-rw-r--r--src/flake8/options/config.py155
-rw-r--r--src/flake8/options/manager.py146
3 files changed, 199 insertions, 132 deletions
diff --git a/src/flake8/options/aggregator.py b/src/flake8/options/aggregator.py
index 5b8ab9c..304f53c 100644
--- a/src/flake8/options/aggregator.py
+++ b/src/flake8/options/aggregator.py
@@ -37,26 +37,28 @@ def aggregate_options(manager, config_finder, arglist=None, values=None):
# Make our new configuration file mergerator
config_parser = config.MergedConfigParser(
- option_manager=manager,
- config_finder=config_finder,
+ option_manager=manager, config_finder=config_finder
)
# Get the parsed config
- parsed_config = config_parser.parse(original_values.config,
- original_values.isolated)
+ parsed_config = config_parser.parse(
+ original_values.config, original_values.isolated
+ )
# Extend the default ignore value with the extended default ignore list,
# registered by plugins.
extended_default_ignore = manager.extended_default_ignore.copy()
- LOG.debug('Extended default ignore list: %s',
- list(extended_default_ignore))
+ LOG.debug(
+ "Extended default ignore list: %s", list(extended_default_ignore)
+ )
extended_default_ignore.update(default_values.ignore)
default_values.ignore = list(extended_default_ignore)
- LOG.debug('Merged default ignore list: %s', default_values.ignore)
+ LOG.debug("Merged default ignore list: %s", default_values.ignore)
extended_default_select = manager.extended_default_select.copy()
- LOG.debug('Extended default select list: %s',
- list(extended_default_select))
+ LOG.debug(
+ "Extended default select list: %s", list(extended_default_select)
+ )
default_values.extended_default_select = extended_default_select
# Merge values parsed from config onto the default values returned
@@ -67,10 +69,12 @@ def aggregate_options(manager, config_finder, arglist=None, values=None):
if not hasattr(default_values, config_name):
dest_name = config_parser.config_options[config_name].dest
- LOG.debug('Overriding default value of (%s) for "%s" with (%s)',
- getattr(default_values, dest_name, None),
- dest_name,
- value)
+ LOG.debug(
+ 'Overriding default value of (%s) for "%s" with (%s)',
+ getattr(default_values, dest_name, None),
+ dest_name,
+ value,
+ )
# Override the default values with the config values
setattr(default_values, dest_name, value)
diff --git a/src/flake8/options/config.py b/src/flake8/options/config.py
index ba9442a..9325495 100644
--- a/src/flake8/options/config.py
+++ b/src/flake8/options/config.py
@@ -9,13 +9,13 @@ from flake8 import utils
LOG = logging.getLogger(__name__)
-__all__ = ('ConfigFileFinder', 'MergedConfigParser')
+__all__ = ("ConfigFileFinder", "MergedConfigParser")
class ConfigFileFinder(object):
"""Encapsulate the logic for finding and reading config files."""
- PROJECT_FILENAMES = ('setup.cfg', 'tox.ini')
+ PROJECT_FILENAMES = ("setup.cfg", "tox.ini")
def __init__(self, program_name, args, extra_config_files):
"""Initialize object to find config files.
@@ -31,25 +31,27 @@ class ConfigFileFinder(object):
extra_config_files = extra_config_files or []
self.extra_config_files = [
# Ensure the paths are absolute paths for local_config_files
- os.path.abspath(f) for f in extra_config_files
+ os.path.abspath(f)
+ for f in extra_config_files
]
# Platform specific settings
- self.is_windows = sys.platform == 'win32'
- self.xdg_home = os.environ.get('XDG_CONFIG_HOME',
- os.path.expanduser('~/.config'))
+ self.is_windows = sys.platform == "win32"
+ self.xdg_home = os.environ.get(
+ "XDG_CONFIG_HOME", os.path.expanduser("~/.config")
+ )
# Look for '.<program_name>' files
- self.program_config = '.' + program_name
+ self.program_config = "." + program_name
self.program_name = program_name
# List of filenames to find in the local/project directory
- self.project_filenames = ('setup.cfg', 'tox.ini', self.program_config)
+ self.project_filenames = ("setup.cfg", "tox.ini", self.program_config)
self.local_directory = os.path.abspath(os.curdir)
if not args:
- args = ['.']
+ args = ["."]
self.parent = self.tail = os.path.abspath(os.path.commonprefix(args))
# caches to avoid double-reading config files
@@ -61,7 +63,7 @@ class ConfigFileFinder(object):
@staticmethod
def _read_config(files):
config = configparser.RawConfigParser()
- if isinstance(files, (str, type(u''))):
+ if isinstance(files, (str, type(u""))):
files = [files]
found_files = []
@@ -69,13 +71,17 @@ class ConfigFileFinder(object):
try:
found_files.extend(config.read(filename))
except UnicodeDecodeError:
- LOG.exception("There was an error decoding a config file."
- "The file with a problem was %s.",
- filename)
+ LOG.exception(
+ "There was an error decoding a config file."
+ "The file with a problem was %s.",
+ filename,
+ )
except configparser.ParsingError:
- LOG.exception("There was an error trying to parse a config "
- "file. The file with a problem was %s.",
- filename)
+ LOG.exception(
+ "There was an error trying to parse a config "
+ "file. The file with a problem was %s.",
+ filename,
+ )
return (config, found_files)
def cli_config(self, files):
@@ -83,7 +89,7 @@ class ConfigFileFinder(object):
if files not in self._cli_configs:
config, found_files = self._read_config(files)
if found_files:
- LOG.debug('Found cli configuration files: %s', found_files)
+ LOG.debug("Found cli configuration files: %s", found_files)
self._cli_configs[files] = config
return self._cli_configs[files]
@@ -94,8 +100,9 @@ class ConfigFileFinder(object):
found_config_files = False
while tail and not found_config_files:
for project_filename in self.project_filenames:
- filename = os.path.abspath(os.path.join(parent,
- project_filename))
+ filename = os.path.abspath(
+ os.path.join(parent, project_filename)
+ )
if os.path.exists(filename):
yield filename
found_config_files = True
@@ -117,8 +124,7 @@ class ConfigFileFinder(object):
"""
exists = os.path.exists
return [
- filename
- for filename in self.generate_possible_local_files()
+ filename for filename in self.generate_possible_local_files()
] + [f for f in self.extra_config_files if exists(f)]
def local_configs_with_files(self):
@@ -129,7 +135,7 @@ class ConfigFileFinder(object):
if self._local_configs is None:
config, found_files = self._read_config(self.local_config_files())
if found_files:
- LOG.debug('Found local configuration files: %s', found_files)
+ LOG.debug("Found local configuration files: %s", found_files)
self._local_configs = config
self._local_found_files = found_files
return (self._local_configs, self._local_found_files)
@@ -141,7 +147,7 @@ class ConfigFileFinder(object):
def user_config_file(self):
"""Find the user-level config file."""
if self.is_windows:
- return os.path.expanduser('~\\' + self.program_config)
+ return os.path.expanduser("~\\" + self.program_config)
return os.path.join(self.xdg_home, self.program_name)
def user_config(self):
@@ -149,7 +155,7 @@ class ConfigFileFinder(object):
if self._user_config is None:
config, found_files = self._read_config(self.user_config_file())
if found_files:
- LOG.debug('Found user configuration files: %s', found_files)
+ LOG.debug("Found user configuration files: %s", found_files)
self._user_config = config
return self._user_config
@@ -164,10 +170,10 @@ class MergedConfigParser(object):
#: Set of types that should use the
#: :meth:`~configparser.RawConfigParser.getint` method.
- GETINT_TYPES = {'int', 'count'}
+ GETINT_TYPES = {"int", "count"}
#: Set of actions that should use the
#: :meth:`~configparser.RawConfigParser.getbool` method.
- GETBOOL_ACTIONS = {'store_true', 'store_false'}
+ GETBOOL_ACTIONS = {"store_true", "store_false"}
def __init__(self, option_manager, config_finder):
"""Initialize the MergedConfigParser instance.
@@ -189,26 +195,32 @@ class MergedConfigParser(object):
def _normalize_value(self, option, value):
final_value = option.normalize(
+ value, self.config_finder.local_directory
+ )
+ LOG.debug(
+ '%r has been normalized to %r for option "%s"',
value,
- self.config_finder.local_directory,
+ final_value,
+ option.config_name,
)
- LOG.debug('%r has been normalized to %r for option "%s"',
- value, final_value, option.config_name)
return final_value
def _parse_config(self, config_parser):
config_dict = {}
for option_name in config_parser.options(self.program_name):
if option_name not in self.config_options:
- LOG.debug('Option "%s" is not registered. Ignoring.',
- option_name)
+ LOG.debug(
+ 'Option "%s" is not registered. Ignoring.', option_name
+ )
continue
option = self.config_options[option_name]
# Use the appropriate method to parse the config value
method = config_parser.get
- if (option.type in self.GETINT_TYPES or
- option.action in self.GETINT_TYPES):
+ if (
+ option.type in self.GETINT_TYPES
+ or option.action in self.GETINT_TYPES
+ ):
method = config_parser.getint
elif option.action in self.GETBOOL_ACTIONS:
method = config_parser.getboolean
@@ -229,33 +241,39 @@ class MergedConfigParser(object):
"""Parse and return the local configuration files."""
config = self.config_finder.local_configs()
if not self.is_configured_by(config):
- LOG.debug('Local configuration files have no %s section',
- self.program_name)
+ LOG.debug(
+ "Local configuration files have no %s section",
+ self.program_name,
+ )
return {}
- LOG.debug('Parsing local configuration files.')
+ LOG.debug("Parsing local configuration files.")
return self._parse_config(config)
def parse_user_config(self):
"""Parse and return the user configuration files."""
config = self.config_finder.user_config()
if not self.is_configured_by(config):
- LOG.debug('User configuration files have no %s section',
- self.program_name)
+ LOG.debug(
+ "User configuration files have no %s section",
+ self.program_name,
+ )
return {}
- LOG.debug('Parsing user configuration files.')
+ LOG.debug("Parsing user configuration files.")
return self._parse_config(config)
def parse_cli_config(self, config_path):
"""Parse and return the file specified by --config."""
config = self.config_finder.cli_config(config_path)
if not self.is_configured_by(config):
- LOG.debug('CLI configuration files have no %s section',
- self.program_name)
+ LOG.debug(
+ "CLI configuration files have no %s section",
+ self.program_name,
+ )
return {}
- LOG.debug('Parsing CLI configuration files.')
+ LOG.debug("Parsing CLI configuration files.")
return self._parse_config(config)
def merge_user_and_local_config(self):
@@ -293,14 +311,19 @@ class MergedConfigParser(object):
dict
"""
if isolated:
- LOG.debug('Refusing to parse configuration files due to user-'
- 'requested isolation')
+ LOG.debug(
+ "Refusing to parse configuration files due to user-"
+ "requested isolation"
+ )
return {}
if cli_config:
- LOG.debug('Ignoring user and locally found configuration files. '
- 'Reading only configuration from "%s" specified via '
- '--config by the user', cli_config)
+ LOG.debug(
+ "Ignoring user and locally found configuration files. "
+ 'Reading only configuration from "%s" specified via '
+ "--config by the user",
+ cli_config,
+ )
return self.parse_cli_config(cli_config)
return self.merge_user_and_local_config()
@@ -325,13 +348,18 @@ def get_local_plugins(config_finder, cli_config=None, isolated=False):
"""
local_plugins = LocalPlugins(extension=[], report=[], paths=[])
if isolated:
- LOG.debug('Refusing to look for local plugins in configuration'
- 'files due to user-requested isolation')
+ LOG.debug(
+ "Refusing to look for local plugins in configuration"
+ "files due to user-requested isolation"
+ )
return local_plugins
if cli_config:
- LOG.debug('Reading local plugins only from "%s" specified via '
- '--config by the user', cli_config)
+ LOG.debug(
+ 'Reading local plugins only from "%s" specified via '
+ "--config by the user",
+ cli_config,
+ )
config = config_finder.cli_config(cli_config)
config_files = [cli_config]
else:
@@ -339,28 +367,31 @@ def get_local_plugins(config_finder, cli_config=None, isolated=False):
base_dirs = {os.path.dirname(cf) for cf in config_files}
- section = '%s:local-plugins' % config_finder.program_name
- for plugin_type in ['extension', 'report']:
+ section = "%s:local-plugins" % config_finder.program_name
+ for plugin_type in ["extension", "report"]:
if config.has_option(section, plugin_type):
local_plugins_string = config.get(section, plugin_type).strip()
plugin_type_list = getattr(local_plugins, plugin_type)
- plugin_type_list.extend(utils.parse_comma_separated_list(
- local_plugins_string,
- regexp=utils.LOCAL_PLUGIN_LIST_RE,
- ))
- if config.has_option(section, 'paths'):
+ plugin_type_list.extend(
+ utils.parse_comma_separated_list(
+ local_plugins_string, regexp=utils.LOCAL_PLUGIN_LIST_RE
+ )
+ )
+ if config.has_option(section, "paths"):
raw_paths = utils.parse_comma_separated_list(
- config.get(section, 'paths').strip()
+ config.get(section, "paths").strip()
)
norm_paths = []
for base_dir in base_dirs:
norm_paths.extend(
- path for path in
- utils.normalize_paths(raw_paths, parent=base_dir)
+ path
+ for path in utils.normalize_paths(raw_paths, parent=base_dir)
if os.path.exists(path)
)
local_plugins.paths.extend(norm_paths)
return local_plugins
-LocalPlugins = collections.namedtuple('LocalPlugins', 'extension report paths')
+LocalPlugins = collections.namedtuple(
+ "LocalPlugins", "extension report paths"
+)
diff --git a/src/flake8/options/manager.py b/src/flake8/options/manager.py
index 5b4796f..3f4e883 100644
--- a/src/flake8/options/manager.py
+++ b/src/flake8/options/manager.py
@@ -11,15 +11,28 @@ LOG = logging.getLogger(__name__)
class Option(object):
"""Our wrapper around an optparse.Option object to add features."""
- def __init__(self, short_option_name=None, long_option_name=None,
- # Options below here are taken from the optparse.Option class
- action=None, default=None, type=None, dest=None,
- nargs=None, const=None, choices=None, callback=None,
- callback_args=None, callback_kwargs=None, help=None,
- metavar=None,
- # Options below here are specific to Flake8
- parse_from_config=False, comma_separated_list=False,
- normalize_paths=False):
+ def __init__(
+ self,
+ short_option_name=None,
+ long_option_name=None,
+ # Options below here are taken from the optparse.Option class
+ action=None,
+ default=None,
+ type=None,
+ dest=None,
+ nargs=None,
+ const=None,
+ choices=None,
+ callback=None,
+ callback_args=None,
+ callback_kwargs=None,
+ help=None,
+ metavar=None,
+ # Options below here are specific to Flake8
+ parse_from_config=False,
+ comma_separated_list=False,
+ normalize_paths=False,
+ ):
"""Initialize an Option instance wrapping optparse.Option.
The following are all passed directly through to optparse.
@@ -73,18 +86,18 @@ class Option(object):
x for x in (short_option_name, long_option_name) if x is not None
]
self.option_kwargs = {
- 'action': action,
- 'default': default,
- 'type': type,
- 'dest': self._make_dest(dest),
- 'nargs': nargs,
- 'const': const,
- 'choices': choices,
- 'callback': callback,
- 'callback_args': callback_args,
- 'callback_kwargs': callback_kwargs,
- 'help': help,
- 'metavar': metavar,
+ "action": action,
+ "default": default,
+ "type": type,
+ "dest": self._make_dest(dest),
+ "nargs": nargs,
+ "const": const,
+ "choices": choices,
+ "callback": callback,
+ "callback_args": callback_args,
+ "callback_kwargs": callback_kwargs,
+ "help": help,
+ "metavar": metavar,
}
# Set attributes for our option arguments
for key, value in self.option_kwargs.items():
@@ -98,27 +111,32 @@ class Option(object):
self.config_name = None
if parse_from_config:
if not long_option_name:
- raise ValueError('When specifying parse_from_config=True, '
- 'a long_option_name must also be specified.')
- self.config_name = long_option_name[2:].replace('-', '_')
+ raise ValueError(
+ "When specifying parse_from_config=True, "
+ "a long_option_name must also be specified."
+ )
+ self.config_name = long_option_name[2:].replace("-", "_")
self._opt = None
def __repr__(self): # noqa: D105
return (
- 'Option({0}, {1}, action={action}, default={default}, '
- 'dest={dest}, type={type}, callback={callback}, help={help},'
- ' callback={callback}, callback_args={callback_args}, '
- 'callback_kwargs={callback_kwargs}, metavar={metavar})'
- ).format(self.short_option_name, self.long_option_name,
- **self.option_kwargs)
+ "Option({0}, {1}, action={action}, default={default}, "
+ "dest={dest}, type={type}, callback={callback}, help={help},"
+ " callback={callback}, callback_args={callback_args}, "
+ "callback_kwargs={callback_kwargs}, metavar={metavar})"
+ ).format(
+ self.short_option_name,
+ self.long_option_name,
+ **self.option_kwargs
+ )
def _make_dest(self, dest):
if dest:
return dest
if self.long_option_name:
- return self.long_option_name[2:].replace('-', '_')
+ return self.long_option_name[2:].replace("-", "_")
return self.short_option_name[1]
def normalize(self, value, *normalize_args):
@@ -136,33 +154,36 @@ class Option(object):
def normalize_from_setuptools(self, value):
"""Normalize the value received from setuptools."""
value = self.normalize(value)
- if self.type == 'int' or self.action == 'count':
+ if self.type == "int" or self.action == "count":
return int(value)
- if self.action in ('store_true', 'store_false'):
+ if self.action in ("store_true", "store_false"):
value = str(value).upper()
- if value in ('1', 'T', 'TRUE', 'ON'):
+ if value in ("1", "T", "TRUE", "ON"):
return True
- if value in ('0', 'F', 'FALSE', 'OFF'):
+ if value in ("0", "F", "FALSE", "OFF"):
return False
return value
def to_optparse(self):
"""Convert a Flake8 Option to an optparse Option."""
if self._opt is None:
- self._opt = optparse.Option(*self.option_args,
- **self.option_kwargs)
+ self._opt = optparse.Option(
+ *self.option_args, **self.option_kwargs
+ )
return self._opt
-PluginVersion = collections.namedtuple("PluginVersion",
- ["name", "version", "local"])
+PluginVersion = collections.namedtuple(
+ "PluginVersion", ["name", "version", "local"]
+)
class OptionManager(object):
"""Manage Options and OptionParser while adding post-processing."""
- def __init__(self, prog=None, version=None,
- usage='%prog [options] file file ...'):
+ def __init__(
+ self, prog=None, version=None, usage="%prog [options] file file ..."
+ ):
"""Initialize an instance of an OptionManager.
:param str prog:
@@ -172,8 +193,9 @@ class OptionManager(object):
:param str usage:
Basic usage string used by the OptionParser.
"""
- self.parser = optparse.OptionParser(prog=prog, version=version,
- usage=usage)
+ self.parser = optparse.OptionParser(
+ prog=prog, version=version, usage=usage
+ )
self.config_options_dict = {}
self.options = []
self.program_name = prog
@@ -198,7 +220,7 @@ class OptionManager(object):
``short_option_name`` and ``long_option_name`` may be specified
positionally as they are with optparse normally.
"""
- if len(args) == 1 and args[0].startswith('--'):
+ if len(args) == 1 and args[0].startswith("--"):
args = (None, args[0])
option = Option(*args, **kwargs)
self.parser.add_option(option.to_optparse())
@@ -206,7 +228,7 @@ class OptionManager(object):
if option.parse_from_config:
name = option.config_name
self.config_options_dict[name] = option
- self.config_options_dict[name.replace('_', '-')] = option
+ self.config_options_dict[name.replace("_", "-")] = option
LOG.debug('Registered option "%s".', option)
def remove_from_default_ignore(self, error_codes):
@@ -216,13 +238,16 @@ class OptionManager(object):
List of strings that are the error/warning codes to attempt to
remove from the extended default ignore list.
"""
- LOG.debug('Removing %r from the default ignore list', error_codes)
+ LOG.debug("Removing %r from the default ignore list", error_codes)
for error_code in error_codes:
try:
self.extended_default_ignore.remove(error_code)
except (ValueError, KeyError):
- LOG.debug('Attempted to remove %s from default ignore'
- ' but it was not a member of the list.', error_code)
+ LOG.debug(
+ "Attempted to remove %s from default ignore"
+ " but it was not a member of the list.",
+ error_code,
+ )
def extend_default_ignore(self, error_codes):
"""Extend the default ignore list with the error codes provided.
@@ -231,7 +256,7 @@ class OptionManager(object):
List of strings that are the error/warning codes with which to
extend the default ignore list.
"""
- LOG.debug('Extending default ignore list with %r', error_codes)
+ LOG.debug("Extending default ignore list with %r", error_codes)
self.extended_default_ignore.update(error_codes)
def extend_default_select(self, error_codes):
@@ -241,11 +266,12 @@ class OptionManager(object):
List of strings that are the error/warning codes with which
to extend the default select list.
"""
- LOG.debug('Extending default select list with %r', error_codes)
+ LOG.debug("Extending default select list with %r", error_codes)
self.extended_default_select.update(error_codes)
- def generate_versions(self, format_str='%(name)s: %(version)s',
- join_on=', '):
+ def generate_versions(
+ self, format_str="%(name)s: %(version)s", join_on=", "
+ ):
"""Generate a comma-separated list of versions of plugins."""
return join_on.join(
format_str % self.format_plugin(plugin)
@@ -255,14 +281,17 @@ class OptionManager(object):
def update_version_string(self):
"""Update the flake8 version string."""
self.parser.version = (
- self.version + ' (' + self.generate_versions() + ') ' +
- utils.get_python_version()
+ self.version
+ + " ("
+ + self.generate_versions()
+ + ") "
+ + utils.get_python_version()
)
def generate_epilog(self):
"""Create an epilog with the version and name of each of plugin."""
- plugin_version_format = '%(name)s: %(version)s'
- self.parser.epilog = 'Installed plugins: ' + self.generate_versions(
+ plugin_version_format = "%(name)s: %(version)s"
+ self.parser.epilog = "Installed plugins: " + self.generate_versions(
plugin_version_format
)
@@ -303,7 +332,10 @@ class OptionManager(object):
# Unfortunately, we need to rely on a private method here.
try:
self.parser._process_args(largs, rargs, values)
- except (optparse.BadOptionError, optparse.OptionValueError) as err:
+ except (
+ optparse.BadOptionError,
+ optparse.OptionValueError,
+ ) as err:
self.parser.largs.append(err.opt_str)
args = largs + rargs