mirror of
https://github.com/thegeeklab/ansible-later.git
synced 2024-11-24 22:00:40 +00:00
refactor: replace str.format with f-strings (#521)
This commit is contained in:
parent
cc385df566
commit
b4bf13d734
@ -59,9 +59,7 @@ def main():
|
|||||||
"-q", dest="logging.level", action="append_const", const=1, help="decrease log level"
|
"-q", dest="logging.level", action="append_const", const=1, help="decrease log level"
|
||||||
)
|
)
|
||||||
parser.add_argument("rules.files", nargs="*")
|
parser.add_argument("rules.files", nargs="*")
|
||||||
parser.add_argument(
|
parser.add_argument("-V", "--version", action="version", version=f"%(prog)s {__version__}")
|
||||||
"-V", "--version", action="version", version="%(prog)s {}".format(__version__)
|
|
||||||
)
|
|
||||||
|
|
||||||
args = parser.parse_args().__dict__
|
args = parser.parse_args().__dict__
|
||||||
|
|
||||||
@ -78,16 +76,16 @@ def main():
|
|||||||
candidate = Candidate.classify(filename, settings)
|
candidate = Candidate.classify(filename, settings)
|
||||||
if candidate:
|
if candidate:
|
||||||
if candidate.binary:
|
if candidate.binary:
|
||||||
LOG.info("Not reviewing binary file {name}".format(name=filename))
|
LOG.info(f"Not reviewing binary file {filename}")
|
||||||
continue
|
continue
|
||||||
if candidate.vault:
|
if candidate.vault:
|
||||||
LOG.info("Not reviewing vault file {name}".format(name=filename))
|
LOG.info(f"Not reviewing vault file {filename}")
|
||||||
continue
|
continue
|
||||||
else:
|
else:
|
||||||
LOG.info("Reviewing all of {candidate}".format(candidate=candidate))
|
LOG.info(f"Reviewing all of {candidate}")
|
||||||
tasks.append(candidate)
|
tasks.append(candidate)
|
||||||
else:
|
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)))
|
errors = (sum(p.map(_review_wrapper, tasks)))
|
||||||
p.close()
|
p.close()
|
||||||
|
@ -41,6 +41,7 @@ class Candidate(object):
|
|||||||
self.binary = True
|
self.binary = True
|
||||||
|
|
||||||
def _get_version(self):
|
def _get_version(self):
|
||||||
|
name = type(self).__name__
|
||||||
path = self.path
|
path = self.path
|
||||||
version = None
|
version = None
|
||||||
config_version = self.config["rules"]["version"].strip()
|
config_version = self.config["rules"]["version"].strip()
|
||||||
@ -73,25 +74,17 @@ class Candidate(object):
|
|||||||
if self.expected_version:
|
if self.expected_version:
|
||||||
if isinstance(self, RoleFile):
|
if isinstance(self, RoleFile):
|
||||||
LOG.warning(
|
LOG.warning(
|
||||||
"{name} {path} is in a role that contains a meta/main.yml without a "
|
f"{name} {path} is in a role that contains a "
|
||||||
"declared standards version. "
|
"meta/main.yml without a declared standards version. "
|
||||||
"Using latest standards version {version}".format(
|
f"Using latest standards version {version}"
|
||||||
name=type(self).__name__, path=self.path, version=version
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
LOG.warning(
|
LOG.warning(
|
||||||
"{name} {path} does not present standards version. "
|
f"{name} {path} does not present standards version. "
|
||||||
"Using latest standards version {version}".format(
|
f"Using latest standards version {version}"
|
||||||
name=type(self).__name__, path=self.path, version=version
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
LOG.info(
|
LOG.info(f"{name} {path} declares standards version {version}")
|
||||||
"{name} {path} declares standards version {version}".format(
|
|
||||||
name=type(self).__name__, path=self.path, version=version
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
return version
|
return version
|
||||||
|
|
||||||
@ -122,9 +115,7 @@ class Candidate(object):
|
|||||||
|
|
||||||
if not result:
|
if not result:
|
||||||
LOG.error(
|
LOG.error(
|
||||||
"Standard '{id}' returns an empty result object. Check failed!".format(
|
f"Standard '{standard.sid}' returns an empty result object. Check failed!"
|
||||||
id=standard.sid
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
@ -141,36 +132,26 @@ class Candidate(object):
|
|||||||
for err in result.errors:
|
for err in result.errors:
|
||||||
err_labels = copy.copy(labels)
|
err_labels = copy.copy(labels)
|
||||||
err_labels["passed"] = False
|
err_labels["passed"] = False
|
||||||
|
|
||||||
|
sid = self._format_id(standard.sid)
|
||||||
|
path = self.path
|
||||||
|
description = standard.description
|
||||||
|
|
||||||
if isinstance(err, StandardBase.Error):
|
if isinstance(err, StandardBase.Error):
|
||||||
err_labels.update(err.to_dict())
|
err_labels.update(err.to_dict())
|
||||||
|
|
||||||
if not standard.version:
|
if not standard.version:
|
||||||
LOG.warning(
|
LOG.warning(
|
||||||
"{sid}Best practice '{description}' not met:\n{path}:{error}".format(
|
f"{sid}Best practice '{description}' not met:\n{path}:{err}",
|
||||||
sid=self._format_id(standard.sid),
|
|
||||||
description=standard.description,
|
|
||||||
path=self.path,
|
|
||||||
error=err
|
|
||||||
),
|
|
||||||
extra=flag_extra(err_labels)
|
extra=flag_extra(err_labels)
|
||||||
)
|
)
|
||||||
elif LooseVersion(standard.version) > LooseVersion(self.version):
|
elif LooseVersion(standard.version) > LooseVersion(self.version):
|
||||||
LOG.warning(
|
LOG.warning(
|
||||||
"{sid}Future standard '{description}' not met:\n{path}:{error}".format(
|
f"{sid}Future standard '{description}' not met:\n{path}:{err}",
|
||||||
sid=self._format_id(standard.sid),
|
|
||||||
description=standard.description,
|
|
||||||
path=self.path,
|
|
||||||
error=err
|
|
||||||
),
|
|
||||||
extra=flag_extra(err_labels)
|
extra=flag_extra(err_labels)
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
msg = "{sid}Standard '{description}' not met:\n{path}:{error}".format(
|
msg = f"{sid}Standard '{description}' not met:\n{path}:{err}"
|
||||||
sid=self._format_id(standard.sid),
|
|
||||||
description=standard.description,
|
|
||||||
path=self.path,
|
|
||||||
error=err
|
|
||||||
)
|
|
||||||
|
|
||||||
if standard.sid not in self.config["rules"]["warning_filter"]:
|
if standard.sid not in self.config["rules"]["warning_filter"]:
|
||||||
LOG.error(msg, extra=flag_extra(err_labels))
|
LOG.error(msg, extra=flag_extra(err_labels))
|
||||||
@ -222,13 +203,14 @@ class Candidate(object):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
def _format_id(self, standard_id):
|
def _format_id(self, standard_id):
|
||||||
if standard_id and standard_id.strip():
|
sid = standard_id.strip()
|
||||||
standard_id = "[{id}] ".format(id=standard_id.strip())
|
if sid:
|
||||||
|
standard_id = f"[{sid}] "
|
||||||
|
|
||||||
return standard_id
|
return standard_id
|
||||||
|
|
||||||
def __repr__(self): # noqa
|
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
|
def __getitem__(self, item): # noqa
|
||||||
return self.__dict__.get(item)
|
return self.__dict__.get(item)
|
||||||
|
@ -8,7 +8,7 @@ class LaterError(Exception):
|
|||||||
|
|
||||||
def __init__(self, msg, original):
|
def __init__(self, msg, original):
|
||||||
"""Initialize new exception."""
|
"""Initialize new exception."""
|
||||||
super(LaterError, self).__init__("{msg}: {org}".format(msg=msg, org=original))
|
super(LaterError, self).__init__(f"{msg}: {original}")
|
||||||
self.original = original
|
self.original = original
|
||||||
|
|
||||||
|
|
||||||
|
@ -61,7 +61,7 @@ class MultilineFormatter(logging.Formatter):
|
|||||||
"""Logging Formatter to reset color after newline characters."""
|
"""Logging Formatter to reset color after newline characters."""
|
||||||
|
|
||||||
def format(self, record): # noqa
|
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"
|
record.msg = record.msg + "\n"
|
||||||
return logging.Formatter.format(self, record)
|
return logging.Formatter.format(self, record)
|
||||||
|
|
||||||
@ -185,4 +185,4 @@ def color_text(color, msg):
|
|||||||
|
|
||||||
"""
|
"""
|
||||||
msg = msg.format(colorama.Style.BRIGHT, colorama.Style.NORMAL)
|
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}"
|
||||||
|
@ -24,7 +24,7 @@ class CheckMetaChangeFromDefault(StandardBase):
|
|||||||
|
|
||||||
if not errors:
|
if not errors:
|
||||||
for field, default in field_defaults:
|
for field, default in field_defaults:
|
||||||
pair = "{field}: {default}".format(field=field, default=default)
|
pair = f"{field}: {default}"
|
||||||
lookup = nested_lookup(field, content)
|
lookup = nested_lookup(field, content)
|
||||||
if lookup and default in nested_lookup(field, content):
|
if lookup and default in nested_lookup(field, content):
|
||||||
errors.append(self.Error(None, self.helptext.format(field=pair)))
|
errors.append(self.Error(None, self.helptext.format(field=pair)))
|
||||||
|
@ -26,7 +26,7 @@ class CheckRelativeRolePaths(StandardBase):
|
|||||||
path_to_check = None
|
path_to_check = None
|
||||||
|
|
||||||
if module in module_to_path_folder and "src" in task["action"]:
|
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"]:
|
if path_to_check and path_to_check in task["action"]["src"]:
|
||||||
errors.append(self.Error(task["__line__"], self.helptext))
|
errors.append(self.Error(task["__line__"], self.helptext))
|
||||||
|
@ -9,7 +9,7 @@ class CheckYamlColons(StandardBase):
|
|||||||
types = ["playbook", "task", "handler", "rolevars", "hostvars", "groupvars", "meta"]
|
types = ["playbook", "task", "handler", "rolevars", "hostvars", "groupvars", "meta"]
|
||||||
|
|
||||||
def check(self, candidate, settings):
|
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)
|
errors = self.run_yamllint(candidate, options)
|
||||||
|
|
||||||
return self.Result(candidate.path, errors)
|
return self.Result(candidate.path, errors)
|
||||||
|
@ -9,9 +9,7 @@ class CheckYamlDocumentEnd(StandardBase):
|
|||||||
types = ["playbook", "task", "handler", "rolevars", "hostvars", "groupvars", "meta"]
|
types = ["playbook", "task", "handler", "rolevars", "hostvars", "groupvars", "meta"]
|
||||||
|
|
||||||
def check(self, candidate, settings):
|
def check(self, candidate, settings):
|
||||||
options = "rules: {{document-end: {conf}}}".format(
|
options = f"rules: {{document-end: {settings['yamllint']['document-end']}}}"
|
||||||
conf=settings["yamllint"]["document-end"]
|
|
||||||
)
|
|
||||||
errors = self.run_yamllint(candidate, options)
|
errors = self.run_yamllint(candidate, options)
|
||||||
|
|
||||||
return self.Result(candidate.path, errors)
|
return self.Result(candidate.path, errors)
|
||||||
|
@ -9,9 +9,7 @@ class CheckYamlDocumentStart(StandardBase):
|
|||||||
types = ["playbook", "task", "handler", "rolevars", "hostvars", "groupvars", "meta"]
|
types = ["playbook", "task", "handler", "rolevars", "hostvars", "groupvars", "meta"]
|
||||||
|
|
||||||
def check(self, candidate, settings):
|
def check(self, candidate, settings):
|
||||||
options = "rules: {{document-start: {conf}}}".format(
|
options = f"rules: {{document-start: {settings['yamllint']['document-start']}}}"
|
||||||
conf=settings["yamllint"]["document-start"]
|
|
||||||
)
|
|
||||||
errors = self.run_yamllint(candidate, options)
|
errors = self.run_yamllint(candidate, options)
|
||||||
|
|
||||||
return self.Result(candidate.path, errors)
|
return self.Result(candidate.path, errors)
|
||||||
|
@ -9,7 +9,7 @@ class CheckYamlEmptyLines(StandardBase):
|
|||||||
types = ["playbook", "task", "handler", "rolevars", "hostvars", "groupvars", "meta"]
|
types = ["playbook", "task", "handler", "rolevars", "hostvars", "groupvars", "meta"]
|
||||||
|
|
||||||
def check(self, candidate, settings):
|
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)
|
errors = self.run_yamllint(candidate, options)
|
||||||
|
|
||||||
return self.Result(candidate.path, errors)
|
return self.Result(candidate.path, errors)
|
||||||
|
@ -9,7 +9,7 @@ class CheckYamlHyphens(StandardBase):
|
|||||||
types = ["playbook", "task", "handler", "rolevars", "hostvars", "groupvars", "meta"]
|
types = ["playbook", "task", "handler", "rolevars", "hostvars", "groupvars", "meta"]
|
||||||
|
|
||||||
def check(self, candidate, settings):
|
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)
|
errors = self.run_yamllint(candidate, options)
|
||||||
|
|
||||||
return self.Result(candidate.path, errors)
|
return self.Result(candidate.path, errors)
|
||||||
|
@ -9,9 +9,7 @@ class CheckYamlIndent(StandardBase):
|
|||||||
types = ["playbook", "task", "handler", "rolevars", "hostvars", "groupvars", "meta"]
|
types = ["playbook", "task", "handler", "rolevars", "hostvars", "groupvars", "meta"]
|
||||||
|
|
||||||
def check(self, candidate, settings):
|
def check(self, candidate, settings):
|
||||||
options = "rules: {{document-start: {conf}}}".format(
|
options = f"rules: {{document-start: {settings['yamllint']['document-start']}}}"
|
||||||
conf=settings["yamllint"]["document-start"]
|
|
||||||
)
|
|
||||||
errors = self.run_yamllint(candidate, options)
|
errors = self.run_yamllint(candidate, options)
|
||||||
|
|
||||||
return self.Result(candidate.path, errors)
|
return self.Result(candidate.path, errors)
|
||||||
|
@ -188,18 +188,16 @@ class Settings(object):
|
|||||||
anyconfig.validate(config, self.schema, ac_schema_safe=False)
|
anyconfig.validate(config, self.schema, ac_schema_safe=False)
|
||||||
return True
|
return True
|
||||||
except jsonschema.exceptions.ValidationError as e:
|
except jsonschema.exceptions.ValidationError as e:
|
||||||
schema_error = (
|
validator = e.validator
|
||||||
"Error while loading configuration:\n"
|
path = format_as_index(
|
||||||
"Failed validating '{validator}' at {path}"
|
list(e.absolute_path)[0],
|
||||||
).format(
|
list(e.absolute_path)[1:],
|
||||||
validator=e.validator,
|
|
||||||
path=format_as_index(
|
|
||||||
list(e.absolute_path)[0],
|
|
||||||
list(e.absolute_path)[1:],
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
|
msg = e.message
|
||||||
|
|
||||||
utils.sysexit_with_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):
|
def _update_filelist(self):
|
||||||
|
@ -56,9 +56,7 @@ class StandardBase(object, metaclass=StandardExtendedMeta):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
def __repr__(self): # noqa
|
def __repr__(self): # noqa
|
||||||
return "Standard: {description} (version: {version}, types: {types})".format(
|
return f"Standard: {self.description} (version: {self.version}, types: {self.types})"
|
||||||
description=self.description, version=self.version, types=self.types
|
|
||||||
)
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_tasks(candidate, settings):
|
def get_tasks(candidate, settings):
|
||||||
@ -72,15 +70,11 @@ class StandardBase(object, metaclass=StandardExtendedMeta):
|
|||||||
except LaterError as ex:
|
except LaterError as ex:
|
||||||
e = ex.original
|
e = ex.original
|
||||||
errors.append(
|
errors.append(
|
||||||
StandardBase.Error(
|
StandardBase.Error(e.problem_mark.line + 1, f"syntax error: {e.problem}")
|
||||||
e.problem_mark.line + 1, "syntax error: {msg}".format(msg=e.problem)
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
candidate.faulty = True
|
candidate.faulty = True
|
||||||
except LaterAnsibleError as e:
|
except LaterAnsibleError as e:
|
||||||
errors.append(
|
errors.append(StandardBase.Error(e.line, f"syntax error: {e.message}"))
|
||||||
StandardBase.Error(e.line, "syntax error: {msg}".format(msg=e.message))
|
|
||||||
)
|
|
||||||
candidate.faulty = True
|
candidate.faulty = True
|
||||||
|
|
||||||
return yamllines, errors
|
return yamllines, errors
|
||||||
@ -100,13 +94,11 @@ class StandardBase(object, metaclass=StandardExtendedMeta):
|
|||||||
except LaterError as ex:
|
except LaterError as ex:
|
||||||
e = ex.original
|
e = ex.original
|
||||||
errors.append(
|
errors.append(
|
||||||
StandardBase.Error(
|
StandardBase.Error(e.problem_mark.line + 1, f"syntax error: {e.problem}")
|
||||||
e.problem_mark.line + 1, "syntax error: {msg}".format(msg=e.problem)
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
candidate.faulty = True
|
candidate.faulty = True
|
||||||
except LaterAnsibleError as e:
|
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
|
candidate.faulty = True
|
||||||
|
|
||||||
return tasks, errors
|
return tasks, errors
|
||||||
@ -124,15 +116,11 @@ class StandardBase(object, metaclass=StandardExtendedMeta):
|
|||||||
except LaterError as ex:
|
except LaterError as ex:
|
||||||
e = ex.original
|
e = ex.original
|
||||||
errors.append(
|
errors.append(
|
||||||
StandardBase.Error(
|
StandardBase.Error(e.problem_mark.line + 1, f"syntax error: {e.problem}")
|
||||||
e.problem_mark.line + 1, "syntax error: {msg}".format(msg=e.problem)
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
candidate.faulty = True
|
candidate.faulty = True
|
||||||
except LaterAnsibleError as e:
|
except LaterAnsibleError as e:
|
||||||
errors.append(
|
errors.append(StandardBase.Error(e.line, f"syntax error: {e.message}"))
|
||||||
StandardBase.Error(e.line, "syntax error: {msg}".format(msg=e.message))
|
|
||||||
)
|
|
||||||
candidate.faulty = True
|
candidate.faulty = True
|
||||||
|
|
||||||
return normalized, errors
|
return normalized, errors
|
||||||
@ -172,15 +160,11 @@ class StandardBase(object, metaclass=StandardExtendedMeta):
|
|||||||
except LaterError as ex:
|
except LaterError as ex:
|
||||||
e = ex.original
|
e = ex.original
|
||||||
errors.append(
|
errors.append(
|
||||||
StandardBase.Error(
|
StandardBase.Error(e.problem_mark.line + 1, f"syntax error: {e.problem}")
|
||||||
e.problem_mark.line + 1, "syntax error: {msg}".format(msg=e.problem)
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
candidate.faulty = True
|
candidate.faulty = True
|
||||||
except LaterAnsibleError as e:
|
except LaterAnsibleError as e:
|
||||||
errors.append(
|
errors.append(StandardBase.Error(e.line, f"syntax error: {e.message}"))
|
||||||
StandardBase.Error(e.line, "syntax error: {msg}".format(msg=e.message))
|
|
||||||
)
|
|
||||||
candidate.faulty = True
|
candidate.faulty = True
|
||||||
|
|
||||||
return normalized, errors
|
return normalized, errors
|
||||||
@ -201,15 +185,11 @@ class StandardBase(object, metaclass=StandardExtendedMeta):
|
|||||||
except LaterError as ex:
|
except LaterError as ex:
|
||||||
e = ex.original
|
e = ex.original
|
||||||
errors.append(
|
errors.append(
|
||||||
StandardBase.Error(
|
StandardBase.Error(e.problem_mark.line + 1, f"syntax error: {e.problem}")
|
||||||
e.problem_mark.line + 1, "syntax error: {msg}".format(msg=e.problem)
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
candidate.faulty = True
|
candidate.faulty = True
|
||||||
except LaterAnsibleError as e:
|
except LaterAnsibleError as e:
|
||||||
errors.append(
|
errors.append(StandardBase.Error(e.line, f"syntax error: {e.message}"))
|
||||||
StandardBase.Error(e.line, "syntax error: {msg}".format(msg=e.message))
|
|
||||||
)
|
|
||||||
candidate.faulty = True
|
candidate.faulty = True
|
||||||
|
|
||||||
return yamllines, errors
|
return yamllines, errors
|
||||||
@ -231,9 +211,7 @@ class StandardBase(object, metaclass=StandardExtendedMeta):
|
|||||||
content = yaml.safe_load(f)
|
content = yaml.safe_load(f)
|
||||||
except yaml.YAMLError as e:
|
except yaml.YAMLError as e:
|
||||||
errors.append(
|
errors.append(
|
||||||
StandardBase.Error(
|
StandardBase.Error(e.problem_mark.line + 1, f"syntax error: {e.problem}")
|
||||||
e.problem_mark.line + 1, "syntax error: {msg}".format(msg=e.problem)
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
candidate.faulty = True
|
candidate.faulty = True
|
||||||
|
|
||||||
@ -250,9 +228,7 @@ class StandardBase(object, metaclass=StandardExtendedMeta):
|
|||||||
errors.append(StandardBase.Error(problem.line, problem.desc))
|
errors.append(StandardBase.Error(problem.line, problem.desc))
|
||||||
except yaml.YAMLError as e:
|
except yaml.YAMLError as e:
|
||||||
errors.append(
|
errors.append(
|
||||||
StandardBase.Error(
|
StandardBase.Error(e.problem_mark.line + 1, f"syntax error: {e.problem}")
|
||||||
e.problem_mark.line + 1, "syntax error: {msg}".format(msg=e.problem)
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
candidate.faulty = True
|
candidate.faulty = True
|
||||||
|
|
||||||
@ -288,9 +264,9 @@ class StandardBase(object, metaclass=StandardExtendedMeta):
|
|||||||
|
|
||||||
def __repr__(self): # noqa
|
def __repr__(self): # noqa
|
||||||
if self.lineno:
|
if self.lineno:
|
||||||
return "{no}: {msg}".format(no=self.lineno, msg=self.message)
|
return f"{self.lineno}: {self.message}"
|
||||||
else:
|
else:
|
||||||
return " {msg}".format(msg=self.message)
|
return f" {self.message}"
|
||||||
|
|
||||||
def to_dict(self):
|
def to_dict(self):
|
||||||
result = dict(lineno=self.lineno, message=self.message)
|
result = dict(lineno=self.lineno, message=self.message)
|
||||||
@ -306,7 +282,7 @@ class StandardBase(object, metaclass=StandardExtendedMeta):
|
|||||||
self.errors = errors or []
|
self.errors = errors or []
|
||||||
|
|
||||||
def message(self):
|
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():
|
class StandardLoader():
|
||||||
@ -326,18 +302,14 @@ class StandardLoader():
|
|||||||
try:
|
try:
|
||||||
spec.loader.exec_module(module)
|
spec.loader.exec_module(module)
|
||||||
except (ImportError, NameError) as e:
|
except (ImportError, NameError) as e:
|
||||||
sysexit_with_message(
|
sysexit_with_message(f"Failed to load roles file {filename}: \n {str(e)}")
|
||||||
"Failed to load roles file {module}: \n {msg}".format(
|
|
||||||
msg=str(e), module=filename
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
for name, obj in inspect.getmembers(module):
|
for name, obj in inspect.getmembers(module):
|
||||||
if self._is_plugin(obj):
|
if self._is_plugin(obj):
|
||||||
self.rules.append(obj())
|
self.rules.append(obj())
|
||||||
except TypeError as e:
|
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()
|
self.validate()
|
||||||
|
|
||||||
|
@ -22,10 +22,8 @@ def test_critical(capsys, mocker):
|
|||||||
_, stderr = capsys.readouterr()
|
_, stderr = capsys.readouterr()
|
||||||
|
|
||||||
print(
|
print(
|
||||||
"{}{}CRITICAL:{} foo\n{}".format(
|
f"{colorama.Fore.RED}{colorama.Style.BRIGHT}CRITICAL:{colorama.Style.NORMAL} foo\n"
|
||||||
colorama.Fore.RED, colorama.Style.BRIGHT, colorama.Style.NORMAL,
|
f"{colorama.Style.RESET_ALL}"
|
||||||
colorama.Style.RESET_ALL
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
x, _ = capsys.readouterr()
|
x, _ = capsys.readouterr()
|
||||||
|
|
||||||
@ -38,10 +36,8 @@ def test_error(capsys, mocker):
|
|||||||
_, stderr = capsys.readouterr()
|
_, stderr = capsys.readouterr()
|
||||||
|
|
||||||
print(
|
print(
|
||||||
"{}{}ERROR:{} foo\n{}".format(
|
f"{colorama.Fore.RED}{colorama.Style.BRIGHT}ERROR:{colorama.Style.NORMAL} foo\n"
|
||||||
colorama.Fore.RED, colorama.Style.BRIGHT, colorama.Style.NORMAL,
|
f"{colorama.Style.RESET_ALL}"
|
||||||
colorama.Style.RESET_ALL
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
x, _ = capsys.readouterr()
|
x, _ = capsys.readouterr()
|
||||||
|
|
||||||
@ -54,10 +50,8 @@ def test_warn(capsys, mocker):
|
|||||||
stdout, _ = capsys.readouterr()
|
stdout, _ = capsys.readouterr()
|
||||||
|
|
||||||
print(
|
print(
|
||||||
"{}{}WARNING:{} foo\n{}".format(
|
f"{colorama.Fore.YELLOW}{colorama.Style.BRIGHT}WARNING:{colorama.Style.NORMAL} foo\n"
|
||||||
colorama.Fore.YELLOW, colorama.Style.BRIGHT, colorama.Style.NORMAL,
|
f"{colorama.Style.RESET_ALL}"
|
||||||
colorama.Style.RESET_ALL
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
x, _ = capsys.readouterr()
|
x, _ = capsys.readouterr()
|
||||||
|
|
||||||
@ -70,10 +64,8 @@ def test_info(capsys, mocker):
|
|||||||
stdout, _ = capsys.readouterr()
|
stdout, _ = capsys.readouterr()
|
||||||
|
|
||||||
print(
|
print(
|
||||||
"{}{}INFO:{} foo\n{}".format(
|
f"{colorama.Fore.BLUE}{colorama.Style.BRIGHT}INFO:{colorama.Style.NORMAL} foo\n"
|
||||||
colorama.Fore.BLUE, colorama.Style.BRIGHT, colorama.Style.NORMAL,
|
f"{colorama.Style.RESET_ALL}"
|
||||||
colorama.Style.RESET_ALL
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
x, _ = capsys.readouterr()
|
x, _ = capsys.readouterr()
|
||||||
|
|
||||||
|
@ -41,7 +41,7 @@ def get_property(prop):
|
|||||||
currentdir = os.path.dirname(os.path.realpath(__file__))
|
currentdir = os.path.dirname(os.path.realpath(__file__))
|
||||||
parentdir = os.path.dirname(currentdir)
|
parentdir = os.path.dirname(currentdir)
|
||||||
result = re.search(
|
result = re.search(
|
||||||
r'{}\s*=\s*[\'"]([^\'"]*)[\'"]'.format(prop),
|
rf'{prop}\s*=\s*[\'"]([^\'"]*)[\'"]',
|
||||||
open(os.path.join(parentdir, "__init__.py")).read()
|
open(os.path.join(parentdir, "__init__.py")).read()
|
||||||
)
|
)
|
||||||
return result.group(1)
|
return result.group(1)
|
||||||
|
@ -248,7 +248,7 @@ def play_children(basedir, item, parent_type, playbook_dir):
|
|||||||
|
|
||||||
def _include_children(basedir, k, v, parent_type):
|
def _include_children(basedir, k, v, parent_type):
|
||||||
# handle include: filename.yml tags=blah
|
# 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])
|
result = path_dwim(basedir, args[0])
|
||||||
if not os.path.exists(result) and not basedir.endswith("tasks"):
|
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:
|
else:
|
||||||
raise SystemExit(
|
raise SystemExit(f"role dict {role} does not contain a 'role' or 'name' key")
|
||||||
"role dict {0} does not contain a 'role' "
|
|
||||||
"or 'name' key".format(role)
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
results.extend(_look_for_role_files(basedir, role, main=main))
|
results.extend(_look_for_role_files(basedir, role, main=main))
|
||||||
return results
|
return results
|
||||||
@ -497,9 +494,7 @@ def extract_from_list(blocks, candidates):
|
|||||||
results.extend(add_action_type(block[candidate], candidate, meta_data))
|
results.extend(add_action_type(block[candidate], candidate, meta_data))
|
||||||
elif block[candidate] is not None:
|
elif block[candidate] is not None:
|
||||||
raise RuntimeError(
|
raise RuntimeError(
|
||||||
"Key '{candidate}' defined, but bad value: '{block}'".format(
|
f"Key '{candidate}' defined, but bad value: '{str(block[candidate])}'"
|
||||||
candidate=candidate, block=str(block[candidate])
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
return results
|
return results
|
||||||
|
|
||||||
@ -551,7 +546,7 @@ def parse_yaml_linenumbers(data, filename):
|
|||||||
except (yaml.parser.ParserError, yaml.scanner.ScannerError) as e:
|
except (yaml.parser.ParserError, yaml.scanner.ScannerError) as e:
|
||||||
raise LaterError("syntax error", e)
|
raise LaterError("syntax error", e)
|
||||||
except (yaml.composer.ComposerError) as 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)
|
raise LaterError("syntax error", e)
|
||||||
return data
|
return data
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user