Skip to content

Commit

Permalink
refactor: separate load files logic
Browse files Browse the repository at this point in the history
  • Loading branch information
pythoninja committed Dec 15, 2023
1 parent 33d234f commit aa5d70d
Show file tree
Hide file tree
Showing 7 changed files with 74 additions and 34 deletions.
7 changes: 4 additions & 3 deletions sshgen/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,11 @@ def generate_hosts_file(hosts_file: Annotated[str, typer.Option('--hosts-file',
Example usage: sshconf generate -o my_ssh_config
"""

hosts_file = FileUtils.as_file(file_path=hosts_file)
output_file = FileUtils.as_file(file_path=output)
hosts_file = FileUtils.get_hosts_path(file_path=hosts_file)
output_file = FileUtils.get_output_path(file_path=output)

AppUtils(hosts_file, output_file).generate_ssh_config()
sshgen = AppUtils(hosts_file, output_file)
sshgen.generate_ssh_config()


def _version_callback(value: bool) -> None:
Expand Down
12 changes: 3 additions & 9 deletions sshgen/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,6 @@


def init_logger(level: LogLevel) -> None:
match level:
case LogLevel.INFO:
logging.basicConfig(level=logging.INFO,
format='[%(asctime)s] [%(levelname)s] - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
case LogLevel.DEBUG:
logging.basicConfig(level=logging.DEBUG,
format='[%(asctime)s] [%(levelname)s] - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
logging.basicConfig(level=level.value,
format='[%(asctime)s] [%(levelname)s] - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
9 changes: 5 additions & 4 deletions sshgen/models/loglevel.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
#!/usr/bin/env python
from enum import StrEnum, auto
import logging
from enum import Enum


class LogLevel(StrEnum):
INFO = auto()
DEBUG = auto()
class LogLevel(Enum):
INFO = logging.INFO
DEBUG = logging.DEBUG
2 changes: 1 addition & 1 deletion sshgen/parsers/ansible.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class AnsibleHostsParser:
def __init__(self, hosts_file_path: Path | None = None):
self._yaml = YAML()
self._default_hosts_file = 'examples/hosts.yml'
self._file_path: Path = hosts_file_path or FileUtils.as_file(self._default_hosts_file)
self._file_path: Path = hosts_file_path or FileUtils.get_hosts_path(self._default_hosts_file)

def as_map(self) -> CommentedMap:
log.debug('Loading ansible hosts file: %s', self._file_path)
Expand Down
22 changes: 19 additions & 3 deletions sshgen/run.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,29 @@
#!/usr/bin/env python
import logging

from sshgen.logger import init_logger
from sshgen.models.loglevel import LogLevel
from sshgen.utils.app import AppUtils
from sshgen.utils.file import FileUtils

log = logging.getLogger(__name__)


def run() -> None:
hosts_file = FileUtils.as_file(file_path='../examples/hosts.yml')
output_file = FileUtils.as_file(file_path='../config')
init_logger(level=LogLevel.DEBUG)
hosts_file = './examples/hosts.yml'
config_file = './config'

log.info('Starting sshgen with pre-defined settings')
log.debug('Debug mode is ON')
log.debug('Reading hosts from %s', hosts_file)
log.debug('Saving generated config to %s', config_file)

hosts_file = FileUtils.get_hosts_path(file_path=hosts_file)
output_file = FileUtils.get_output_path(file_path=config_file)

AppUtils(hosts_file, output_file).generate_ssh_config()
sshgen = AppUtils(hosts_file, output_file)
sshgen.generate_ssh_config()


if __name__ == '__main__':
Expand Down
14 changes: 14 additions & 0 deletions sshgen/utils/common.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
#!/usr/bin/env python
import logging
import sys

log = logging.getLogger(__name__)


class CommonUtils:
@staticmethod
def check_and_exit(condition: bool, message: str, exit_code: int = 1) -> None:
if not condition:
log.error(message)
log.debug('Exiting with code: %s', exit_code)
sys.exit(exit_code)
42 changes: 28 additions & 14 deletions sshgen/utils/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,33 @@
import sys
from pathlib import Path

from sshgen.utils.common import CommonUtils

log = logging.getLogger(__name__)


class FileUtils:
@staticmethod
def as_file(file_path: str) -> Path:
resolved_path = FileUtils._get_base_path() / Path(file_path)
def get_hosts_path(file_path: str) -> Path:
resolved_path = FileUtils.resolve_path(file_path)

if FileUtils._is_yaml_file(resolved_path):
if resolved_path.exists() and FileUtils._is_empty(resolved_path):
log.error('Ansible hosts file %s is empty. Exiting...', resolved_path)
sys.exit(1)
elif not resolved_path.exists():
log.error('Ansible hosts file does not exists at %s. Exiting...', resolved_path)
sys.exit(1)
CommonUtils.check_and_exit(resolved_path.exists(),
f'Ansible hosts file does not exists at {resolved_path}. Exiting...')
CommonUtils.check_and_exit(FileUtils.is_yaml_file(resolved_path),
'Ansible hosts file is not a yaml file. Valid extensions are: yaml or yml.'
'Exiting...')
CommonUtils.check_and_exit(not FileUtils.is_empty(resolved_path),
f'Ansible hosts file {resolved_path} is empty. Exiting...')

FileUtils._create_file(resolved_path)
return resolved_path

@staticmethod
def get_output_path(file_path: str) -> Path:
resolved_path = FileUtils.resolve_path(file_path)

if not resolved_path.exists():
log.debug('Path %s is not exists, creating required directories', resolved_path)
FileUtils.create_file(resolved_path)

return resolved_path

Expand All @@ -28,19 +38,23 @@ def as_package_file(file_path: str) -> Path:
return Path(__file__).resolve().parent.parent / Path(file_path)

@staticmethod
def _get_base_path() -> Path:
def resolve_path(file_path: str) -> Path:
return FileUtils.get_base_path() / Path(file_path)

@staticmethod
def get_base_path() -> Path:
return Path(__file__).cwd().resolve()

@staticmethod
def _is_yaml_file(file_path: Path) -> bool:
def is_yaml_file(file_path: Path) -> bool:
return file_path.suffix in {'.yml', '.yaml'}

@staticmethod
def _is_empty(file_path: Path) -> bool:
def is_empty(file_path: Path) -> bool:
return file_path.is_file() and file_path.stat().st_size == 0

@staticmethod
def _create_file(file_path: Path) -> None:
def create_file(file_path: Path) -> None:
if not file_path.is_file():
try:
file_path.parent.mkdir(parents=True, exist_ok=True)
Expand Down

0 comments on commit aa5d70d

Please sign in to comment.