refactor: replace str.format with f-strings (#521)

This commit is contained in:
Robert Kaussow 2023-01-09 11:59:25 +01:00 committed by GitHub
parent cc385df566
commit b4bf13d734
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 75 additions and 144 deletions

View File

@ -59,9 +59,7 @@ def main():
"-q", dest="logging.level", action="append_const", const=1, help="decrease log level"
)
parser.add_argument("rules.files", nargs="*")
parser.add_argument(
"-V", "--version", action="version", version="%(prog)s {}".format(__version__)
)
parser.add_argument("-V", "--version", action="version", version=f"%(prog)s {__version__}")
args = parser.parse_args().__dict__
@ -78,16 +76,16 @@ def main():
candidate = Candidate.classify(filename, settings)
if candidate:
if candidate.binary:
LOG.info("Not reviewing binary file {name}".format(name=filename))
LOG.info(f"Not reviewing binary file {filename}")
continue
if candidate.vault:
LOG.info("Not reviewing vault file {name}".format(name=filename))
LOG.info(f"Not reviewing vault file {filename}")
continue
else:
LOG.info("Reviewing all of {candidate}".format(candidate=candidate))
LOG.info(f"Reviewing all of {candidate}")
tasks.append(candidate)
else:
LOG.info("Couldn't classify file {name}".format(name=filename))
LOG.info(f"Couldn't classify file {filename}")
errors = (sum(p.map(_review_wrapper, tasks)))
p.close()

View File

@ -41,6 +41,7 @@ class Candidate(object):
self.binary = True
def _get_version(self):
name = type(self).__name__
path = self.path
version = None
config_version = self.config["rules"]["version"].strip()
@ -73,25 +74,17 @@ class Candidate(object):
if self.expected_version:
if isinstance(self, RoleFile):
LOG.warning(
"{name} {path} is in a role that contains a meta/main.yml without a "
"declared standards version. "
"Using latest standards version {version}".format(
name=type(self).__name__, path=self.path, version=version
)
f"{name} {path} is in a role that contains a "
"meta/main.yml without a declared standards version. "
f"Using latest standards version {version}"
)
else:
LOG.warning(
"{name} {path} does not present standards version. "
"Using latest standards version {version}".format(
name=type(self).__name__, path=self.path, version=version
)
f"{name} {path} does not present standards version. "
f"Using latest standards version {version}"
)
else:
LOG.info(
"{name} {path} declares standards version {version}".format(
name=type(self).__name__, path=self.path, version=version
)
)
LOG.info(f"{name} {path} declares standards version {version}")
return version
@ -122,9 +115,7 @@ class Candidate(object):
if not result:
LOG.error(
"Standard '{id}' returns an empty result object. Check failed!".format(
id=standard.sid
)
f"Standard '{standard.sid}' returns an empty result object. Check failed!"
)
continue
@ -141,36 +132,26 @@ class Candidate(object):
for err in result.errors:
err_labels = copy.copy(labels)
err_labels["passed"] = False
sid = self._format_id(standard.sid)
path = self.path
description = standard.description
if isinstance(err, StandardBase.Error):
err_labels.update(err.to_dict())
if not standard.version:
LOG.warning(
"{sid}Best practice '{description}' not met:\n{path}:{error}".format(
sid=self._format_id(standard.sid),
description=standard.description,
path=self.path,
error=err
),
f"{sid}Best practice '{description}' not met:\n{path}:{err}",
extra=flag_extra(err_labels)
)
elif LooseVersion(standard.version) > LooseVersion(self.version):
LOG.warning(
"{sid}Future standard '{description}' not met:\n{path}:{error}".format(
sid=self._format_id(standard.sid),
description=standard.description,
path=self.path,
error=err
),
f"{sid}Future standard '{description}' not met:\n{path}:{err}",
extra=flag_extra(err_labels)
)
else:
msg = "{sid}Standard '{description}' not met:\n{path}:{error}".format(
sid=self._format_id(standard.sid),
description=standard.description,
path=self.path,
error=err
)
msg = f"{sid}Standard '{description}' not met:\n{path}:{err}"
if standard.sid not in self.config["rules"]["warning_filter"]:
LOG.error(msg, extra=flag_extra(err_labels))
@ -222,13 +203,14 @@ class Candidate(object):
return None
def _format_id(self, standard_id):
if standard_id and standard_id.strip():
standard_id = "[{id}] ".format(id=standard_id.strip())
sid = standard_id.strip()
if sid:
standard_id = f"[{sid}] "
return standard_id
def __repr__(self): # noqa
return "{name} ({path})".format(name=type(self).__name__, path=self.path)
return f"{type(self).__name__} ({self.path})"
def __getitem__(self, item): # noqa
return self.__dict__.get(item)

View File

@ -8,7 +8,7 @@ class LaterError(Exception):
def __init__(self, msg, original):
"""Initialize new exception."""
super(LaterError, self).__init__("{msg}: {org}".format(msg=msg, org=original))
super(LaterError, self).__init__(f"{msg}: {original}")
self.original = original

View File

@ -61,7 +61,7 @@ class MultilineFormatter(logging.Formatter):
"""Logging Formatter to reset color after newline characters."""
def format(self, record): # noqa
record.msg = record.msg.replace("\n", "\n{}... ".format(colorama.Style.RESET_ALL))
record.msg = record.msg.replace("\n", f"\n{colorama.Style.RESET_ALL}... ")
record.msg = record.msg + "\n"
return logging.Formatter.format(self, record)
@ -185,4 +185,4 @@ def color_text(color, msg):
"""
msg = msg.format(colorama.Style.BRIGHT, colorama.Style.NORMAL)
return "{}{}{}".format(color, msg, colorama.Style.RESET_ALL)
return f"{color}{msg}{colorama.Style.RESET_ALL}"

View File

@ -24,7 +24,7 @@ class CheckMetaChangeFromDefault(StandardBase):
if not errors:
for field, default in field_defaults:
pair = "{field}: {default}".format(field=field, default=default)
pair = f"{field}: {default}"
lookup = nested_lookup(field, content)
if lookup and default in nested_lookup(field, content):
errors.append(self.Error(None, self.helptext.format(field=pair)))

View File

@ -26,7 +26,7 @@ class CheckRelativeRolePaths(StandardBase):
path_to_check = None
if module in module_to_path_folder and "src" in task["action"]:
path_to_check = "../{}".format(module_to_path_folder[module])
path_to_check = f"../{module_to_path_folder[module]}"
if path_to_check and path_to_check in task["action"]["src"]:
errors.append(self.Error(task["__line__"], self.helptext))

View File

@ -9,7 +9,7 @@ class CheckYamlColons(StandardBase):
types = ["playbook", "task", "handler", "rolevars", "hostvars", "groupvars", "meta"]
def check(self, candidate, settings):
options = "rules: {{colons: {conf}}}".format(conf=settings["yamllint"]["colons"])
options = f"rules: {{colons: {settings['yamllint']['colons']}}}"
errors = self.run_yamllint(candidate, options)
return self.Result(candidate.path, errors)

View File

@ -9,9 +9,7 @@ class CheckYamlDocumentEnd(StandardBase):
types = ["playbook", "task", "handler", "rolevars", "hostvars", "groupvars", "meta"]
def check(self, candidate, settings):
options = "rules: {{document-end: {conf}}}".format(
conf=settings["yamllint"]["document-end"]
)
options = f"rules: {{document-end: {settings['yamllint']['document-end']}}}"
errors = self.run_yamllint(candidate, options)
return self.Result(candidate.path, errors)

View File

@ -9,9 +9,7 @@ class CheckYamlDocumentStart(StandardBase):
types = ["playbook", "task", "handler", "rolevars", "hostvars", "groupvars", "meta"]
def check(self, candidate, settings):
options = "rules: {{document-start: {conf}}}".format(
conf=settings["yamllint"]["document-start"]
)
options = f"rules: {{document-start: {settings['yamllint']['document-start']}}}"
errors = self.run_yamllint(candidate, options)
return self.Result(candidate.path, errors)

View File

@ -9,7 +9,7 @@ class CheckYamlEmptyLines(StandardBase):
types = ["playbook", "task", "handler", "rolevars", "hostvars", "groupvars", "meta"]
def check(self, candidate, settings):
options = "rules: {{empty-lines: {conf}}}".format(conf=settings["yamllint"]["empty-lines"])
options = f"rules: {{empty-lines: {settings['yamllint']['empty-lines']}}}"
errors = self.run_yamllint(candidate, options)
return self.Result(candidate.path, errors)

View File

@ -9,7 +9,7 @@ class CheckYamlHyphens(StandardBase):
types = ["playbook", "task", "handler", "rolevars", "hostvars", "groupvars", "meta"]
def check(self, candidate, settings):
options = "rules: {{hyphens: {conf}}}".format(conf=settings["yamllint"]["hyphens"])
options = f"rules: {{hyphens: {settings['yamllint']['hyphens']}}}"
errors = self.run_yamllint(candidate, options)
return self.Result(candidate.path, errors)

View File

@ -9,9 +9,7 @@ class CheckYamlIndent(StandardBase):
types = ["playbook", "task", "handler", "rolevars", "hostvars", "groupvars", "meta"]
def check(self, candidate, settings):
options = "rules: {{document-start: {conf}}}".format(
conf=settings["yamllint"]["document-start"]
)
options = f"rules: {{document-start: {settings['yamllint']['document-start']}}}"
errors = self.run_yamllint(candidate, options)
return self.Result(candidate.path, errors)

View File

@ -188,18 +188,16 @@ class Settings(object):
anyconfig.validate(config, self.schema, ac_schema_safe=False)
return True
except jsonschema.exceptions.ValidationError as e:
schema_error = (
"Error while loading configuration:\n"
"Failed validating '{validator}' at {path}"
).format(
validator=e.validator,
path=format_as_index(
validator = e.validator
path = format_as_index(
list(e.absolute_path)[0],
list(e.absolute_path)[1:],
)
)
msg = e.message
utils.sysexit_with_message(
"{schema}: {msg}".format(schema=schema_error, msg=e.message)
"Error while loading configuration:\n"
f"Failed validating '{validator}' at {path}: {msg}"
)
def _update_filelist(self):

View File

@ -56,9 +56,7 @@ class StandardBase(object, metaclass=StandardExtendedMeta):
pass
def __repr__(self): # noqa
return "Standard: {description} (version: {version}, types: {types})".format(
description=self.description, version=self.version, types=self.types
)
return f"Standard: {self.description} (version: {self.version}, types: {self.types})"
@staticmethod
def get_tasks(candidate, settings):
@ -72,15 +70,11 @@ class StandardBase(object, metaclass=StandardExtendedMeta):
except LaterError as ex:
e = ex.original
errors.append(
StandardBase.Error(
e.problem_mark.line + 1, "syntax error: {msg}".format(msg=e.problem)
)
StandardBase.Error(e.problem_mark.line + 1, f"syntax error: {e.problem}")
)
candidate.faulty = True
except LaterAnsibleError as e:
errors.append(
StandardBase.Error(e.line, "syntax error: {msg}".format(msg=e.message))
)
errors.append(StandardBase.Error(e.line, f"syntax error: {e.message}"))
candidate.faulty = True
return yamllines, errors
@ -100,13 +94,11 @@ class StandardBase(object, metaclass=StandardExtendedMeta):
except LaterError as ex:
e = ex.original
errors.append(
StandardBase.Error(
e.problem_mark.line + 1, "syntax error: {msg}".format(msg=e.problem)
)
StandardBase.Error(e.problem_mark.line + 1, f"syntax error: {e.problem}")
)
candidate.faulty = True
except LaterAnsibleError as e:
errors.append(StandardBase.Error(e.line, "syntax error: {}".format(e.message)))
errors.append(StandardBase.Error(e.line, f"syntax error: {e.message}"))
candidate.faulty = True
return tasks, errors
@ -124,15 +116,11 @@ class StandardBase(object, metaclass=StandardExtendedMeta):
except LaterError as ex:
e = ex.original
errors.append(
StandardBase.Error(
e.problem_mark.line + 1, "syntax error: {msg}".format(msg=e.problem)
)
StandardBase.Error(e.problem_mark.line + 1, f"syntax error: {e.problem}")
)
candidate.faulty = True
except LaterAnsibleError as e:
errors.append(
StandardBase.Error(e.line, "syntax error: {msg}".format(msg=e.message))
)
errors.append(StandardBase.Error(e.line, f"syntax error: {e.message}"))
candidate.faulty = True
return normalized, errors
@ -172,15 +160,11 @@ class StandardBase(object, metaclass=StandardExtendedMeta):
except LaterError as ex:
e = ex.original
errors.append(
StandardBase.Error(
e.problem_mark.line + 1, "syntax error: {msg}".format(msg=e.problem)
)
StandardBase.Error(e.problem_mark.line + 1, f"syntax error: {e.problem}")
)
candidate.faulty = True
except LaterAnsibleError as e:
errors.append(
StandardBase.Error(e.line, "syntax error: {msg}".format(msg=e.message))
)
errors.append(StandardBase.Error(e.line, f"syntax error: {e.message}"))
candidate.faulty = True
return normalized, errors
@ -201,15 +185,11 @@ class StandardBase(object, metaclass=StandardExtendedMeta):
except LaterError as ex:
e = ex.original
errors.append(
StandardBase.Error(
e.problem_mark.line + 1, "syntax error: {msg}".format(msg=e.problem)
)
StandardBase.Error(e.problem_mark.line + 1, f"syntax error: {e.problem}")
)
candidate.faulty = True
except LaterAnsibleError as e:
errors.append(
StandardBase.Error(e.line, "syntax error: {msg}".format(msg=e.message))
)
errors.append(StandardBase.Error(e.line, f"syntax error: {e.message}"))
candidate.faulty = True
return yamllines, errors
@ -231,9 +211,7 @@ class StandardBase(object, metaclass=StandardExtendedMeta):
content = yaml.safe_load(f)
except yaml.YAMLError as e:
errors.append(
StandardBase.Error(
e.problem_mark.line + 1, "syntax error: {msg}".format(msg=e.problem)
)
StandardBase.Error(e.problem_mark.line + 1, f"syntax error: {e.problem}")
)
candidate.faulty = True
@ -250,9 +228,7 @@ class StandardBase(object, metaclass=StandardExtendedMeta):
errors.append(StandardBase.Error(problem.line, problem.desc))
except yaml.YAMLError as e:
errors.append(
StandardBase.Error(
e.problem_mark.line + 1, "syntax error: {msg}".format(msg=e.problem)
)
StandardBase.Error(e.problem_mark.line + 1, f"syntax error: {e.problem}")
)
candidate.faulty = True
@ -288,9 +264,9 @@ class StandardBase(object, metaclass=StandardExtendedMeta):
def __repr__(self): # noqa
if self.lineno:
return "{no}: {msg}".format(no=self.lineno, msg=self.message)
return f"{self.lineno}: {self.message}"
else:
return " {msg}".format(msg=self.message)
return f" {self.message}"
def to_dict(self):
result = dict(lineno=self.lineno, message=self.message)
@ -306,7 +282,7 @@ class StandardBase(object, metaclass=StandardExtendedMeta):
self.errors = errors or []
def message(self):
return "\n".join(["{0}:{1}".format(self.candidate, error) for error in self.errors])
return "\n".join([f"{self.candidate}:{error}" for error in self.errors])
class StandardLoader():
@ -326,18 +302,14 @@ class StandardLoader():
try:
spec.loader.exec_module(module)
except (ImportError, NameError) as e:
sysexit_with_message(
"Failed to load roles file {module}: \n {msg}".format(
msg=str(e), module=filename
)
)
sysexit_with_message(f"Failed to load roles file {filename}: \n {str(e)}")
try:
for name, obj in inspect.getmembers(module):
if self._is_plugin(obj):
self.rules.append(obj())
except TypeError as e:
sysexit_with_message("Failed to load roles file: \n {msg}".format(msg=str(e)))
sysexit_with_message(f"Failed to load roles file: \n {str(e)}")
self.validate()

View File

@ -22,10 +22,8 @@ def test_critical(capsys, mocker):
_, stderr = capsys.readouterr()
print(
"{}{}CRITICAL:{} foo\n{}".format(
colorama.Fore.RED, colorama.Style.BRIGHT, colorama.Style.NORMAL,
colorama.Style.RESET_ALL
)
f"{colorama.Fore.RED}{colorama.Style.BRIGHT}CRITICAL:{colorama.Style.NORMAL} foo\n"
f"{colorama.Style.RESET_ALL}"
)
x, _ = capsys.readouterr()
@ -38,10 +36,8 @@ def test_error(capsys, mocker):
_, stderr = capsys.readouterr()
print(
"{}{}ERROR:{} foo\n{}".format(
colorama.Fore.RED, colorama.Style.BRIGHT, colorama.Style.NORMAL,
colorama.Style.RESET_ALL
)
f"{colorama.Fore.RED}{colorama.Style.BRIGHT}ERROR:{colorama.Style.NORMAL} foo\n"
f"{colorama.Style.RESET_ALL}"
)
x, _ = capsys.readouterr()
@ -54,10 +50,8 @@ def test_warn(capsys, mocker):
stdout, _ = capsys.readouterr()
print(
"{}{}WARNING:{} foo\n{}".format(
colorama.Fore.YELLOW, colorama.Style.BRIGHT, colorama.Style.NORMAL,
colorama.Style.RESET_ALL
)
f"{colorama.Fore.YELLOW}{colorama.Style.BRIGHT}WARNING:{colorama.Style.NORMAL} foo\n"
f"{colorama.Style.RESET_ALL}"
)
x, _ = capsys.readouterr()
@ -70,10 +64,8 @@ def test_info(capsys, mocker):
stdout, _ = capsys.readouterr()
print(
"{}{}INFO:{} foo\n{}".format(
colorama.Fore.BLUE, colorama.Style.BRIGHT, colorama.Style.NORMAL,
colorama.Style.RESET_ALL
)
f"{colorama.Fore.BLUE}{colorama.Style.BRIGHT}INFO:{colorama.Style.NORMAL} foo\n"
f"{colorama.Style.RESET_ALL}"
)
x, _ = capsys.readouterr()

View File

@ -41,7 +41,7 @@ def get_property(prop):
currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
result = re.search(
r'{}\s*=\s*[\'"]([^\'"]*)[\'"]'.format(prop),
rf'{prop}\s*=\s*[\'"]([^\'"]*)[\'"]',
open(os.path.join(parentdir, "__init__.py")).read()
)
return result.group(1)

View File

@ -248,7 +248,7 @@ def play_children(basedir, item, parent_type, playbook_dir):
def _include_children(basedir, k, v, parent_type):
# handle include: filename.yml tags=blah
(command, args, kwargs) = tokenize("{0}: {1}".format(k, v))
(command, args, kwargs) = tokenize(f"{k}: {v}")
result = path_dwim(basedir, args[0])
if not os.path.exists(result) and not basedir.endswith("tasks"):
@ -317,10 +317,7 @@ def _roles_children(basedir, k, v, parent_type, main="main"):
)
)
else:
raise SystemExit(
"role dict {0} does not contain a 'role' "
"or 'name' key".format(role)
)
raise SystemExit(f"role dict {role} does not contain a 'role' or 'name' key")
else:
results.extend(_look_for_role_files(basedir, role, main=main))
return results
@ -497,9 +494,7 @@ def extract_from_list(blocks, candidates):
results.extend(add_action_type(block[candidate], candidate, meta_data))
elif block[candidate] is not None:
raise RuntimeError(
"Key '{candidate}' defined, but bad value: '{block}'".format(
candidate=candidate, block=str(block[candidate])
)
f"Key '{candidate}' defined, but bad value: '{str(block[candidate])}'"
)
return results
@ -551,7 +546,7 @@ def parse_yaml_linenumbers(data, filename):
except (yaml.parser.ParserError, yaml.scanner.ScannerError) as e:
raise LaterError("syntax error", e)
except (yaml.composer.ComposerError) as e:
e.problem = "{} {}".format(e.context, e.problem)
e.problem = f"{e.context} {e.problem}"
raise LaterError("syntax error", e)
return data