Skip to content

Commit

Permalink
refactor commands
Browse files Browse the repository at this point in the history
  • Loading branch information
andreas-stuerz committed Mar 21, 2024
1 parent 6ab01cd commit 3cac633
Show file tree
Hide file tree
Showing 177 changed files with 3,617 additions and 759 deletions.
5 changes: 3 additions & 2 deletions .coveragerc
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ omit =
*private*
*/local/*
*venv*
opnsense_cli/tests/*
opnsense_cli/fixtures/*
*tests/*
*tests/fixtures/*
*test_base.py
*output*
/usr/lib/python*

Expand Down
4 changes: 2 additions & 2 deletions opnsense_cli/click_addons/callbacks.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import yaml
import os

from opnsense_cli.facades.commands.base import CommandFacade
from opnsense_cli.commands.service_base import CommandService
from opnsense_cli.formatters.cli_output.output_format_factory import CliOutputFormatFactory
from opnsense_cli.formatters.cli_output.output_formats import Format
from opnsense_cli import __cli_name__
Expand Down Expand Up @@ -72,6 +72,6 @@ def resolve_linked_names_to_uuids(ctx, param, value):
option_name = param.opts[0].replace("--", "")
resolve_map = ctx.obj.uuid_resolver_map[option_name]

if value and isinstance(ctx.obj, CommandFacade):
if value and isinstance(ctx.obj, CommandService):
return ctx.obj.resolve_linked_uuids(resolve_map, value)
return value
16 changes: 10 additions & 6 deletions opnsense_cli/click_addons/command_autoloader.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ def __init__(self, click_core_group):
self.loaded_classes = []
self.click_core_group = click_core_group

def autoload(self, module_name=None):
def autoload(self, module_name=None, ignore_dirs=None):
"""
Autoloads all click commands from the specified module.
Each command group must be in a single subpackage.
Expand All @@ -18,23 +18,27 @@ def autoload(self, module_name=None):
e.g. for module name opnsense_cli.commands.core
opnsense_cli/commands
├── core
│ ├── firewall
opnsense_cli/commands/
├── core/
│ ├── firewall/
│ │ ├── tests/ (put your tests here)
│ │ ├── services/ (put your services here)
│ │ ├── __init__.py (main @click.group firewall)
│ │ ├── alias.py (subgroup alias with commands from firewall)
│ │ └── rule.py (subgroup rule with commands from firewall)
:param module_name: python module name e.g. opnsense_cli.commands.core
:return: click.core.Group
"""
if ignore_dirs is None:
ignore_dirs = ['__pycache__', 'tests', 'services']

spec = importlib.util.find_spec(module_name)
path = spec.submodule_search_locations[0]

(root_dir, command_group_dirs, files) = list(os.walk(path))[0]

if "__pycache__" in command_group_dirs:
command_group_dirs.remove("__pycache__")
command_group_dirs = [directory for directory in command_group_dirs if directory not in ignore_dirs]

if not command_group_dirs:
path, file = os.path.split(root_dir)
Expand Down
8 changes: 1 addition & 7 deletions opnsense_cli/code_generators/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,10 @@


class CodeGenerator(ABC):
def write_code(self, output_dir):
def write_code(self, path):
code = self.get_code()
filename = self._get_filename()
path = os.path.join(output_dir, f"{filename}")
return self._write_to_file(code, path)

@abstractmethod
def _get_filename(self):
"""This method should be implemented."""

def _write_to_file(self, content, path):
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w") as file:
Expand Down
2 changes: 0 additions & 2 deletions opnsense_cli/code_generators/opn_cli/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,3 @@ def __init__(
self._model_xml_tag = model_xml_tag
self._module_type = module_type

def _get_filename(self):
return f"{self._click_command}.py"
18 changes: 9 additions & 9 deletions opnsense_cli/code_generators/opn_cli/command/template.py.j2
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{% set facade = "{g}{c}Facade".format(g=vars.click_group.capitalize(), c=vars.click_command.capitalize()) -%}
{% set service_facade = "{g}{c}Service".format(g=vars.click_group.capitalize(), c=vars.click_command.capitalize()) -%}
{% set service = "{g}_{c}_svc".format(g=vars.click_group, c=vars.click_command) -%}

import click
Expand All @@ -11,10 +11,10 @@ from opnsense_cli.click_addons.param_type_csv import CSV
from opnsense_cli.commands.{{ vars.module_type }}.{{ vars.click_group }} import {{ vars.click_group }}
from opnsense_cli.api.client import ApiClient
from opnsense_cli.api.{{ vars.module_type }}.{{ vars.click_group }} import Settings, Service
from opnsense_cli.facades.commands.{{ vars.module_type }}.{{ vars.click_group }}.{{ vars.click_command }} import {{ facade }}
from opnsense_cli.commands.{{ vars.module_type }}.{{ vars.click_group }}.services.{{ vars.click_group }}_{{ vars.click_command }}_service import {{ service_facade }}

pass_api_client = click.make_pass_decorator(ApiClient)
pass_{{ vars.click_group }}_{{ vars.click_command }}_svc = click.make_pass_decorator({{ facade }})
pass_{{ vars.click_group }}_{{ vars.click_command }}_svc = click.make_pass_decorator({{ service_facade }})


@{{ vars.click_group }}.group()
Expand All @@ -26,7 +26,7 @@ def {{ vars.click_command }}(ctx, api_client: ApiClient, **kwargs):
"""
settings_api = Settings(api_client)
service_api = Service(api_client)
ctx.obj = {{ facade }}(settings_api, service_api)
ctx.obj = {{ service_facade }}(settings_api, service_api)


@{{ vars.click_command }}.command()
Expand All @@ -47,7 +47,7 @@ def {{ vars.click_command }}(ctx, api_client: ApiClient, **kwargs):
show_default=True,
)
@pass_{{ service }}
def list({{ service }}: {{ facade }}, **kwargs):
def list({{ service }}: {{ service_facade }}, **kwargs):
"""
Show all {{ vars.click_command }}
"""
Expand Down Expand Up @@ -75,7 +75,7 @@ def list({{ service }}: {{ facade }}, **kwargs):
show_default=True,
)
@pass_{{ service }}
def show({{ service }}: {{ facade }}, **kwargs):
def show({{ service }}: {{ service_facade }}, **kwargs):
"""
Show details for {{ vars.click_command }}
"""
Expand Down Expand Up @@ -103,7 +103,7 @@ def show({{ service }}: {{ facade }}, **kwargs):
show_default=True,
)
@pass_{{ service }}
def create({{ service }}: {{ facade }}, **kwargs):
def create({{ service }}: {{ service_facade }}, **kwargs):
"""
Create a new {{ vars.click_command }}
"""
Expand Down Expand Up @@ -140,7 +140,7 @@ def create({{ service }}: {{ facade }}, **kwargs):
show_default=True,
)
@pass_{{ service }}
def update({{ service }}: {{ facade }}, **kwargs):
def update({{ service }}: {{ service_facade }}, **kwargs):
"""
Update a {{ vars.click_command }}.
"""
Expand Down Expand Up @@ -174,7 +174,7 @@ def update({{ service }}: {{ facade }}, **kwargs):
show_default=True,
)
@pass_{{ service }}
def delete({{ service }}: {{ facade }}, **kwargs):
def delete({{ service }}: {{ service_facade }}, **kwargs):
"""
Delete {{ vars.click_command }}
"""
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from opnsense_cli.code_generators.opn_cli.base import CommandCodeGenerator
from opnsense_cli.code_generators.opn_cli.facade.template_vars import CommandFacadeTemplateVars
from opnsense_cli.code_generators.opn_cli.service.template_vars import CommandServiceTemplateVars
from bs4.element import Tag


class ClickCommandFacadeCodeGenerator(CommandCodeGenerator):
class ClickCommandServiceCodeGenerator(CommandCodeGenerator):
def _get_template_vars(self):
resolver_map = {}
for tag in self._tag_content.findChildren(recursive=False):
Expand All @@ -12,7 +12,7 @@ def _get_template_vars(self):
if resolver_item:
resolver_map.update(resolver_item)

return CommandFacadeTemplateVars(
return CommandServiceTemplateVars(
click_command=self._click_command,
click_group=self._click_group,
model_xml_tag=self._model_xml_tag,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
{% set facade = "{g}{c}Facade".format(g=vars.click_group.capitalize(), c=vars.click_command.capitalize()) -%}
{% set service = "{g}{c}Service".format(g=vars.click_group.capitalize(), c=vars.click_command.capitalize()) -%}
from opnsense_cli.commands.exceptions import CommandException
from opnsense_cli.facades.commands.base import CommandFacade
from opnsense_cli.commands.service_base import CommandService
from opnsense_cli.api.{{ vars.module_type }}.{{ vars.click_group }} import Settings, Service


class {{ facade }}(CommandFacade):
class {{ service }}(CommandService):
jsonpath_base = '$.{{ vars.click_group }}.{{ vars.model_xml_tag }}.{{ vars.click_command }}'
uuid_resolver_map = {
{% for key, config in vars.resolver_map.items() -%}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@


@dataclass
class CommandFacadeTemplateVars:
class CommandServiceTemplateVars:
click_command: str
click_group: str
model_xml_tag: str
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import os
from bs4 import BeautifulSoup
from opnsense_cli.code_generators.opn_cli.factories import (
ClickOptionCodeTypeFactory,
Expand All @@ -7,14 +8,14 @@
ClickChoice,
ClickTextLinkedItem,
)
from opnsense_cli.tests.base import BaseTestCase
from opnsense_cli.test_base import BaseTestCase
from opnsense_cli.factories import FactoryException


class TestClickOptionCodeTypeFactory(BaseTestCase):
def setUp(self):
self._factory = ClickOptionCodeTypeFactory()
self._model_data_file = self._read_fixture_file("new/command/plugin/model.xml")
self._model_data_file = self._read_fixture_file("fixtures/model.xml", base_dir=os.path.dirname(__file__))
self._model_content = BeautifulSoup(self._model_data_file, "xml")

self._UnkownField = BeautifulSoup('<enabled type="UnkownField"></enabled>', "xml")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@


class ClickCommandTestCodeGenerator(CommandCodeGenerator):
def _get_filename(self):
return f"test_{self._click_group}_{self._click_command}.py"

def _get_template_vars(self):
return CommandTestTemplateVars(
Expand Down
4 changes: 2 additions & 2 deletions opnsense_cli/code_generators/opn_cli/unit_test/template.py.j2
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from unittest.mock import patch, Mock
from opnsense_cli.commands.{{ vars.module_type }}.{{ vars.click_group }}.{{ vars.click_command }} import {{ vars.click_command }}
from opnsense_cli.tests.commands.base import CommandTestCase
from opnsense_cli.commands.test_base import CommandTestCase


class Test{{ vars.click_group.capitalize() }}{{ vars.click_command.capitalize() }}Commands(CommandTestCase):
Expand Down Expand Up @@ -38,7 +38,7 @@ class Test{{ vars.click_group.capitalize() }}{{ vars.click_command.capitalize()
}
}
}
self._api_data_fixtures_list = self._read_json_fixture('{{ vars.module_type }}/{{ vars.click_group }}/model_data.json')
self._api_data_fixtures_list = self._read_json_fixture("fixtures/model_data.json", base_dir=os.path.dirname(__file__))
self._api_client_args_fixtures = [
'api_key',
'api_secret',
Expand Down
3 changes: 0 additions & 3 deletions opnsense_cli/code_generators/opnsense_api/codegenerator.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,6 @@ def __init__(self, template_engine: TemplateEngine, template, controllers, modul
self._controllers = controllers
self._module_name = module_name

def _get_filename(self):
return f"{self._module_name}.py"

def _get_template_vars(self):
return OpnsenseApiTemplateVars(module_name=self._module_name, controllers=self._controllers)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,6 @@ def __init__(
self._template = template
self._update_command_params = update_command_params

def _get_filename(self):
return f"opnsense_{self._click_group}_{self._click_command}_spec.rb"

def _get_template_vars(self):
return PuppetAcceptanceTestTemplateVars(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,6 @@ def __init__(
self._template = template
self._update_command_params = update_command_params

def _get_filename(self):
return f"opnsense_{self._click_group}_{self._click_command}/opnsense_{self._click_group}_{self._click_command}.rb"

def _get_template_vars(self):
return PuppetProviderTemplateVars(
click_command=self._click_command,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,6 @@ def __init__(
self._template = template
self._update_command_params = update_command_params

def _get_filename(self):
return f"opnsense_{self._click_group}_{self._click_command}_spec.rb"

def _get_template_vars(self):
return PuppetProviderUnitTestTemplateVars(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from opnsense_cli.code_generators.puppet_code.factories import PuppetCodeFragmentFactory
from opnsense_cli.tests.base import BaseTestCase
from opnsense_cli.test_base import BaseTestCase
from opnsense_cli.factories import FactoryException


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,6 @@ def __init__(
self._template = template
self._update_command_params = update_command_params

def _get_filename(self):
return f"opnsense_{self._click_group}_{self._click_command}.rb"

def _get_template_vars(self):
return PuppetTypeTemplateVars(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,6 @@ def __init__(
self._template = template
self._update_command_params = update_command_params

def _get_filename(self):
return f"opnsense_{self._click_group}_{self._click_command}_spec.rb"

def _get_template_vars(self):
return PuppetTypeUnitTestTemplateVars(
Expand Down
File renamed without changes.
8 changes: 4 additions & 4 deletions opnsense_cli/commands/core/configbackup/backup.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
from opnsense_cli.commands.core.configbackup import configbackup
from opnsense_cli.api.client import ApiClient
from opnsense_cli.api.core.configbackup import Backup
from opnsense_cli.facades.commands.core.configbackup.backup import ApibackupBackupFacade
from opnsense_cli.commands.core.configbackup.services.backup_service import ConfigBackupService

pass_api_client = click.make_pass_decorator(ApiClient)
pass_apibackup_backup_svc = click.make_pass_decorator(ApibackupBackupFacade)
pass_apibackup_backup_svc = click.make_pass_decorator(ConfigBackupService)


@configbackup.group()
Expand All @@ -18,7 +18,7 @@ def backup(ctx, api_client: ApiClient, **kwargs):
Manage api-backup
"""
backup_api = Backup(api_client)
ctx.obj = ApibackupBackupFacade(backup_api)
ctx.obj = ConfigBackupService(backup_api)


@backup.command()
Expand Down Expand Up @@ -51,7 +51,7 @@ def backup(ctx, api_client: ApiClient, **kwargs):
show_default=True,
)
@pass_apibackup_backup_svc
def download(apibackup_backup_svc: ApibackupBackupFacade, **kwargs):
def download(apibackup_backup_svc: ConfigBackupService, **kwargs):
"""
Download config.xml from OPNsense.
"""
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from opnsense_cli.api.core.configbackup import Backup
from opnsense_cli.facades.commands.base import CommandFacade
from opnsense_cli.commands.service_base import CommandService


class ApibackupBackupFacade(CommandFacade):
class ConfigBackupService(CommandService):
def __init__(self, backup_api: Backup):
self._backup_api = backup_api

Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
from unittest.mock import patch
import os
from opnsense_cli.commands.core.configbackup.backup import backup
from opnsense_cli.tests.commands.base import CommandTestCase
from opnsense_cli.commands.test_base import CommandTestCase


class TestApibackupCommands(CommandTestCase):
def setUp(self):
self._setup_fakefs()

self._api_data_fixtures_download = self._read_fixture_file("core/configbackup/config.xml.sample")
self._api_data_fixtures_download = self._read_fixture_file("fixtures/config.xml.sample", base_dir=os.path.dirname(__file__))
self._api_client_args_fixtures = ["api_key", "api_secret", "https://127.0.0.1/api", True, "~/.opn-cli/ca.pem", 60]

@patch("opnsense_cli.commands.core.configbackup.backup.ApiClient.execute")
Expand Down
Loading

0 comments on commit 3cac633

Please sign in to comment.