Skip to content

Commit

Permalink
Simplify the code base (#268)
Browse files Browse the repository at this point in the history
* Simplify code

* Simplify code

* chore: auto fixes from pre-commit.com hooks

* Always make the directory

* Add skipdir test

* Rename funcs

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
cidrblock and pre-commit-ci[bot] authored Jul 26, 2024
1 parent f8f85cd commit a27578f
Show file tree
Hide file tree
Showing 10 changed files with 251 additions and 461 deletions.
2 changes: 2 additions & 0 deletions .config/dictionary.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
addopts
antsibull
argcomplete
argnames
argvalues
capsys
Expand Down Expand Up @@ -30,6 +31,7 @@ rulebook
rulebooks
sysargs
templated
templating
testcol
testname
testns
Expand Down
4 changes: 4 additions & 0 deletions .sonarlint/connectedMode.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"sonarCloudOrganization": "ansible",
"projectKey": "ansible_ansible-creator"
}
4 changes: 4 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,9 @@
"python.testing.unittestEnabled": false,
"triggerTaskOnSave.tasks": {
"pydoclint": ["*.py"]
},
"sonarlint.connectedMode.project": {
"connectionId": "ansible",
"projectKey": "ansible_ansible-creator"
}
}
40 changes: 18 additions & 22 deletions src/ansible_creator/arg_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ def parse_args(self: Parser) -> tuple[argparse.Namespace, list[Msg]]:

return self.args, self.pending_logs

def _add(self: Parser, subparser: SubParser) -> None:
def _add(self: Parser, subparser: SubParser[ArgumentParser]) -> None:
"""Add resources to an existing Ansible project.
Args:
Expand Down Expand Up @@ -224,7 +224,7 @@ def _add_args_plugin_common(self, parser: ArgumentParser) -> None:
"current working directory.",
)

def _add_resource(self: Parser, subparser: SubParser) -> None:
def _add_resource(self: Parser, subparser: SubParser[ArgumentParser]) -> None:
"""Add resources to an existing Ansible project.
Args:
Expand All @@ -244,7 +244,7 @@ def _add_resource(self: Parser, subparser: SubParser) -> None:
self._add_resource_devfile(subparser=subparser)
self._add_resource_role(subparser=subparser)

def _add_resource_devcontainer(self: Parser, subparser: SubParser) -> None:
def _add_resource_devcontainer(self: Parser, subparser: SubParser[ArgumentParser]) -> None:
"""Add devcontainer files to an existing Ansible project.
Args:
Expand All @@ -266,7 +266,7 @@ def _add_resource_devcontainer(self: Parser, subparser: SubParser) -> None:

self._add_args_common(parser)

def _add_resource_devfile(self: Parser, subparser: SubParser) -> None:
def _add_resource_devfile(self: Parser, subparser: SubParser[ArgumentParser]) -> None:
"""Add a devfile file to an existing Ansible project.
Args:
Expand All @@ -286,7 +286,7 @@ def _add_resource_devfile(self: Parser, subparser: SubParser) -> None:
)
self._add_args_common(parser)

def _add_resource_role(self: Parser, subparser: SubParser) -> None:
def _add_resource_role(self: Parser, subparser: SubParser[ArgumentParser]) -> None:
"""Add a role to an existing Ansible collection.
Args:
Expand All @@ -310,7 +310,7 @@ def _add_resource_role(self: Parser, subparser: SubParser) -> None:
)
self._add_args_common(parser)

def _add_plugin(self: Parser, subparser: SubParser) -> None:
def _add_plugin(self: Parser, subparser: SubParser[ArgumentParser]) -> None:
"""Add a plugin to an Ansible project.
Args:
Expand All @@ -331,7 +331,7 @@ def _add_plugin(self: Parser, subparser: SubParser) -> None:
self._add_plugin_filter(subparser=subparser)
self._add_plugin_lookup(subparser=subparser)

def _add_plugin_action(self: Parser, subparser: SubParser) -> None:
def _add_plugin_action(self: Parser, subparser: SubParser[ArgumentParser]) -> None:
"""Add an action plugin to an existing Ansible collection project.
Args:
Expand All @@ -345,7 +345,7 @@ def _add_plugin_action(self: Parser, subparser: SubParser) -> None:
self._add_args_common(parser)
self._add_args_plugin_common(parser)

def _add_plugin_filter(self: Parser, subparser: SubParser) -> None:
def _add_plugin_filter(self: Parser, subparser: SubParser[ArgumentParser]) -> None:
"""Add a filter plugin to an existing Ansible collection project.
Args:
Expand All @@ -359,7 +359,7 @@ def _add_plugin_filter(self: Parser, subparser: SubParser) -> None:
self._add_args_common(parser)
self._add_args_plugin_common(parser)

def _add_plugin_lookup(self: Parser, subparser: SubParser) -> None:
def _add_plugin_lookup(self: Parser, subparser: SubParser[ArgumentParser]) -> None:
"""Add a lookup plugin to an existing Ansible collection project.
Args:
Expand All @@ -373,7 +373,7 @@ def _add_plugin_lookup(self: Parser, subparser: SubParser) -> None:
self._add_args_common(parser)
self._add_args_plugin_common(parser)

def _init(self: Parser, subparser: SubParser) -> None:
def _init(self: Parser, subparser: SubParser[ArgumentParser]) -> None:
"""Initialize an Ansible project.
Args:
Expand All @@ -393,7 +393,7 @@ def _init(self: Parser, subparser: SubParser) -> None:
self._init_collection(subparser=subparser)
self._init_playbook(subparser=subparser)

def _init_collection(self: Parser, subparser: SubParser) -> None:
def _init_collection(self: Parser, subparser: SubParser[ArgumentParser]) -> None:
"""Initialize an Ansible collection.
Args:
Expand Down Expand Up @@ -422,7 +422,7 @@ def _init_collection(self: Parser, subparser: SubParser) -> None:
self._add_args_common(parser)
self._add_args_init_common(parser)

def _init_playbook(self: Parser, subparser: SubParser) -> None:
def _init_playbook(self: Parser, subparser: SubParser[ArgumentParser]) -> None:
"""Initialize an Ansible playbook.
Args:
Expand Down Expand Up @@ -453,7 +453,7 @@ def _init_playbook(self: Parser, subparser: SubParser) -> None:
self._add_args_common(parser)
self._add_args_init_common(parser)

def _valid_collection_name(self, collection: str) -> str | Msg:
def _valid_collection_name(self, collection: str) -> str:
"""Validate the collection name.
Args:
Expand All @@ -464,22 +464,18 @@ def _valid_collection_name(self, collection: str) -> str | Msg:
"""
fqcn = collection.split(".", maxsplit=1)
expected_parts = 2
name_filter = re.compile(r"^(?!_)[a-z0-9_]+$")

if len(fqcn) != expected_parts:
msg = "Collection name must be in the format '<namespace>.<name>'."
self.pending_logs.append(Msg(prefix=Level.CRITICAL, message=msg))
return collection

name_filter = re.compile(r"^(?!_)[a-z0-9_]+$")

if not name_filter.match(fqcn[0]) or not name_filter.match(fqcn[1]):
elif not name_filter.match(fqcn[0]) or not name_filter.match(fqcn[1]):
msg = (
"Collection name can only contain lower case letters, underscores, and numbers"
" and cannot begin with an underscore."
)
self.pending_logs.append(Msg(prefix=Level.CRITICAL, message=msg))
return collection

if len(fqcn[0]) <= MIN_COLLECTION_NAME_LEN or len(fqcn[1]) <= MIN_COLLECTION_NAME_LEN:
elif len(fqcn[0]) <= MIN_COLLECTION_NAME_LEN or len(fqcn[1]) <= MIN_COLLECTION_NAME_LEN:
msg = "Both the collection namespace and name must be longer than 2 characters."
self.pending_logs.append(Msg(prefix=Level.CRITICAL, message=msg))
return collection
Expand Down Expand Up @@ -584,7 +580,7 @@ def add_argument_group(


if TYPE_CHECKING:
SubParser: TypeAlias = argparse._SubParsersAction[ArgumentParser] # noqa: SLF001
SubParser: TypeAlias = argparse._SubParsersAction # noqa: SLF001


class CustomHelpFormatter(HelpFormatter):
Expand Down
55 changes: 1 addition & 54 deletions src/ansible_creator/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,9 @@

from __future__ import annotations

import re

from dataclasses import dataclass
from typing import TYPE_CHECKING

from ansible_creator.constants import MIN_COLLECTION_NAME_LEN
from ansible_creator.exceptions import CreatorError
from ansible_creator.utils import expand_path


Expand Down Expand Up @@ -46,62 +42,13 @@ class Config:
project: str = ""
scm_org: str | None = None
scm_project: str | None = None

# TO-DO: Add instance variables for other 'create' and 'sample'

collection_name: str | None = None
namespace: str = ""

def __post_init__(self: Config) -> None:
"""Post process config values.
Raises:
CreatorError: When required values are missing or invalid.
"""
# Validation for: ansible-creator init
if not self.collection and self.project == "collection":
msg = "The argument 'collection' is required when scaffolding a collection."
raise CreatorError(msg)

# Validation for: ansible-creator init --project=ansible-project
if self.project == "ansible-project" and (self.scm_org is None or self.scm_project is None):
msg = (
"Parameters 'scm-org' and 'scm-project' are required when "
"scaffolding an ansible-project."
)
raise CreatorError(msg)

# Validation for: ansible-creator init testorg.testname --scm-org=weather
# --scm-project=demo --project=collection
if (self.scm_org or self.scm_project) and self.project != "ansible-project":
msg = (
"The parameters 'scm-org' and 'scm-project' have no effect when"
" project is not set to ansible-project."
)
self.output.warning(msg)

# Validation for: ansible-creator init testorg.testname --project=ansible-project
# --scm-org weather --scm-project demo
if self.collection and self.project != "collection":
msg = "Collection name has no effect when project is set to ansible-project."
self.output.warning(msg)

# Validation for collection name according to Ansible requirements
"""Post process config values."""
if self.collection:
fqcn = self.collection.split(".", maxsplit=1)
name_filter = re.compile(r"^(?!_)[a-z0-9_]+$")

if not name_filter.match(fqcn[0]) or not name_filter.match(fqcn[-1]):
msg = (
"Collection name can only contain lower case letters, underscores, and numbers"
" and cannot begin with an underscore."
)
raise CreatorError(msg)

if len(fqcn[0]) <= MIN_COLLECTION_NAME_LEN or len(fqcn[-1]) <= MIN_COLLECTION_NAME_LEN:
msg = "Collection namespace and name must be longer than 2 characters."
raise CreatorError(msg)

object.__setattr__(self, "namespace", fqcn[0])
object.__setattr__(self, "collection_name", fqcn[-1])

Expand Down
Loading

0 comments on commit a27578f

Please sign in to comment.