Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: drop yapf and favor of the ruff formatter #595

Merged
merged 1 commit into from
Nov 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .woodpecker/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ steps:
- git fetch --depth=2147483647
- pip install poetry poetry-dynamic-versioning -qq
- poetry install
- poetry run yapf -dr ./${CI_REPO_NAME//-/}
- poetry run ruff format --check --diff ./${CI_REPO_NAME//-/}
environment:
PY_COLORS: "1"

Expand Down
8 changes: 4 additions & 4 deletions ansibledoctor/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,31 +47,31 @@ def _cli_args(self):
dest="recursive",
action="store_true",
default=None,
help="run recursively over the base directory subfolders"
help="run recursively over the base directory subfolders",
)
parser.add_argument(
"-f",
"--force",
dest="force_overwrite",
action="store_true",
default=None,
help="force overwrite output file"
help="force overwrite output file",
)
parser.add_argument(
"-d",
"--dry-run",
dest="dry_run",
action="store_true",
default=None,
help="dry run without writing"
help="dry run without writing",
)
parser.add_argument(
"-n",
"--no-role-detection",
dest="role_detection",
action="store_false",
default=None,
help="disable automatic role detection"
help="disable automatic role detection",
)
parser.add_argument(
"-v", dest="logging.level", action="append_const", const=-1, help="increase log level"
Expand Down
55 changes: 29 additions & 26 deletions ansibledoctor/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,96 +32,96 @@ class Config:
"config_file": {
"default": default_config_file,
"env": "CONFIG_FILE",
"type": environs.Env().str
"type": environs.Env().str,
},
"base_dir": {
"default": os.getcwd(),
"refresh": os.getcwd,
"env": "BASE_DIR",
"type": environs.Env().str
"type": environs.Env().str,
},
"role_name": {
"default": "",
"env": "ROLE_NAME",
"type": environs.Env().str
"type": environs.Env().str,
},
"dry_run": {
"default": False,
"env": "DRY_RUN",
"file": True,
"type": environs.Env().bool
"type": environs.Env().bool,
},
"logging.level": {
"default": "WARNING",
"env": "LOG_LEVEL",
"file": True,
"type": environs.Env().str
"type": environs.Env().str,
},
"logging.json": {
"default": False,
"env": "LOG_JSON",
"file": True,
"type": environs.Env().bool
"type": environs.Env().bool,
},
"output_dir": {
"default": os.getcwd(),
"refresh": os.getcwd,
"env": "OUTPUT_DIR",
"file": True,
"type": environs.Env().str
"type": environs.Env().str,
},
"recursive": {
"default": False,
"env": "RECURSIVE",
"type": environs.Env().bool
"type": environs.Env().bool,
},
"template_dir": {
"default": os.path.join(os.path.dirname(os.path.realpath(__file__)), "templates"),
"env": "TEMPLATE_DIR",
"file": True,
"type": environs.Env().str
"type": environs.Env().str,
},
"template": {
"default": "readme",
"env": "TEMPLATE",
"file": True,
"type": environs.Env().str
"type": environs.Env().str,
},
"template_autotrim": {
"default": True,
"env": "TEMPLATE_AUTOTRIM",
"file": True,
"type": environs.Env().bool
"type": environs.Env().bool,
},
"force_overwrite": {
"default": False,
"env": "FORCE_OVERWRITE",
"file": True,
"type": environs.Env().bool
"type": environs.Env().bool,
},
"custom_header": {
"default": "",
"env": "CUSTOM_HEADER",
"file": True,
"type": environs.Env().str
"type": environs.Env().str,
},
"exclude_files": {
"default": [],
"env": "EXCLUDE_FILES",
"file": True,
"type": environs.Env().list
"type": environs.Env().list,
},
"exclude_tags": {
"default": [],
"env": "EXCLUDE_TAGS",
"file": True,
"type": environs.Env().list
"type": environs.Env().list,
},
"role_detection": {
"default": True,
"env": "ROLE_DETECTION",
"file": True,
"type": environs.Env().bool
"type": environs.Env().bool,
},
}

Expand All @@ -130,31 +130,31 @@ class Config:
"name": "meta",
"automatic": True,
"subtypes": ["value"],
"allow_multiple": False
"allow_multiple": False,
},
"todo": {
"name": "todo",
"automatic": True,
"subtypes": ["value"],
"allow_multiple": True
"allow_multiple": True,
},
"var": {
"name": "var",
"automatic": True,
"subtypes": ["value", "example", "description", "type", "deprecated"],
"allow_multiple": False
"allow_multiple": False,
},
"example": {
"name": "example",
"automatic": True,
"subtypes": [],
"allow_multiple": False
"allow_multiple": False,
},
"tag": {
"name": "tag",
"automatic": True,
"subtypes": ["value", "description"],
"allow_multiple": False
"allow_multiple": False,
},
}

Expand Down Expand Up @@ -263,14 +263,15 @@ def set_config(self, base_dir=None):
source_files.append((os.path.join(os.getcwd(), ".ansibledoctor.yml"), True))
source_files.append((os.path.join(os.getcwd(), ".ansibledoctor.yaml"), True))

for (config, first_found) in source_files:
for config, first_found in source_files:
if config and os.path.exists(config):
with open(config, encoding="utf8") as stream:
s = stream.read()
try:
file_dict = ruamel.yaml.safe_load(s)
except (
ruamel.yaml.composer.ComposerError, ruamel.yaml.scanner.ScannerError
ruamel.yaml.composer.ComposerError,
ruamel.yaml.scanner.ScannerError,
) as e:
message = f"{e.context} {e.problem}"
raise ansibledoctor.exception.ConfigError(
Expand Down Expand Up @@ -314,17 +315,19 @@ def _validate(self, config):
schema_error = "Failed validating '{validator}' in schema{schema}\n{message}".format(
validator=e.validator,
schema=format_as_index(list(e.relative_schema_path)[:-1]),
message=e.message
message=e.message,
)
raise ansibledoctor.exception.ConfigError("Configuration error", schema_error) from e

return True

def _add_dict_branch(self, tree, vector, value):
key = vector[0]
tree[key] = value \
if len(vector) == 1 \
tree[key] = (
value
if len(vector) == 1
else self._add_dict_branch(tree[key] if key in tree else {}, vector[1:], value)
)
return tree

def get_annotations_definition(self, automatic=True):
Expand Down
20 changes: 10 additions & 10 deletions ansibledoctor/doc_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def _scan_template(self):
self.log.sysexit_with_message(f"Can not open template dir {template_dir}")

for file in glob.iglob(template_dir + "/**/*." + self.extension, recursive=True):
relative_file = file[len(template_dir) + 1:]
relative_file = file[len(template_dir) + 1 :]
if ntpath.basename(file)[:1] != "_":
self.logger.debug(f"Found template file: {relative_file}")
self.template_files.append(relative_file)
Expand All @@ -63,8 +63,7 @@ def _write_doc(self):

for file in self.template_files:
doc_file = os.path.join(
self.config.config.get("output_dir"),
os.path.splitext(file)[0]
self.config.config.get("output_dir"), os.path.splitext(file)[0]
)
if os.path.isfile(doc_file):
files_to_overwite.append(doc_file)
Expand All @@ -81,7 +80,8 @@ def _write_doc(self):
self.log.sysexit_with_message(f"Can not open custom header file\n{e!s}")

if (
len(files_to_overwite) > 0 and self.config.config.get("force_overwrite") is False
len(files_to_overwite) > 0
and self.config.config.get("force_overwrite") is False
and not self.config.config["dry_run"]
):
files_to_overwite_string = "\n".join(files_to_overwite)
Expand All @@ -96,8 +96,7 @@ def _write_doc(self):

for file in self.template_files:
doc_file = os.path.join(
self.config.config.get("output_dir"),
os.path.splitext(file)[0]
self.config.config.get("output_dir"), os.path.splitext(file)[0]
)
source_file = self.config.get_template() + "/" + file

Expand All @@ -115,7 +114,7 @@ def _write_doc(self):
loader=FileSystemLoader(self.config.get_template()),
lstrip_blocks=True,
trim_blocks=True,
autoescape=jinja2.select_autoescape()
autoescape=jinja2.select_autoescape(),
)
jenv.filters["to_nice_yaml"] = self._to_nice_yaml
jenv.filters["deep_get"] = self._deep_get
Expand All @@ -133,7 +132,7 @@ def _write_doc(self):
except (
jinja2.exceptions.UndefinedError,
jinja2.exceptions.TemplateSyntaxError,
jinja2.exceptions.TemplateRuntimeError
jinja2.exceptions.TemplateRuntimeError,
) as e:
self.log.sysexit_with_message(
f"Jinja2 templating error while loading file: '{file}'\n{e!s}"
Expand All @@ -154,8 +153,9 @@ def _to_nice_yaml(self, a, indent=4, **kw):
def _deep_get(self, _, dictionary, keys):
default = None
return reduce(
lambda d, key: d.get(key, default)
if isinstance(d, dict) else default, keys.split("."), dictionary
lambda d, key: d.get(key, default) if isinstance(d, dict) else default,
keys.split("."),
dictionary,
)

@pass_eval_context
Expand Down
16 changes: 10 additions & 6 deletions ansibledoctor/doc_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,11 @@ def _yaml_remove_comments(self, d):
self._yaml_remove_comments(elem)

with suppress(AttributeError):
attr = "comment" if isinstance(
d, ruamel.yaml.scalarstring.ScalarString
) else ruamel.yaml.comments.Comment.attrib
attr = (
"comment"
if isinstance(d, ruamel.yaml.scalarstring.ScalarString)
else ruamel.yaml.comments.Comment.attrib
)
delattr(d, attr)

def _parse_var_files(self):
Expand All @@ -54,7 +56,7 @@ def _parse_var_files(self):
ruamel.yaml.add_constructor(
UnsafeTag.yaml_tag,
UnsafeTag.yaml_constructor,
constructor=ruamel.yaml.SafeConstructor
constructor=ruamel.yaml.SafeConstructor,
)

raw = ruamel.yaml.YAML(typ="rt").load(yaml_file)
Expand Down Expand Up @@ -94,7 +96,8 @@ def _parse_meta_file(self):
"value": data.get("dependencies")
}
except (
ruamel.yaml.composer.ComposerError, ruamel.yaml.scanner.ScannerError
ruamel.yaml.composer.ComposerError,
ruamel.yaml.scanner.ScannerError,
) as e:
message = f"{e.context} {e.problem}"
self.log.sysexit_with_message(
Expand All @@ -115,7 +118,8 @@ def _parse_task_tags(self):
]:
self._data["tag"][tag] = {"value": tag}
except (
ruamel.yaml.composer.ComposerError, ruamel.yaml.scanner.ScannerError
ruamel.yaml.composer.ComposerError,
ruamel.yaml.scanner.ScannerError,
) as e:
message = f"{e.context} {e.problem}"
self.log.sysexit_with_message(
Expand Down
2 changes: 1 addition & 1 deletion ansibledoctor/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def strtobool(value):
"f": False,
"false": False,
"off": False,
"0": False
"0": False,
}

try:
Expand Down
Loading