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

Add rudimentary CLI implementation #18

Merged
merged 5 commits into from
Jan 8, 2024
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
1 change: 1 addition & 0 deletions changelog.d/13.added
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Enable setuptools-scm
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ cobbler-tftp = "cobbler_tftp.cli:cli"
[tool.isort]
profile = "black"

[tool.setuptools_scm]

[tool.towncrier]
directory = "changelog.d"
filename = "changelog/v{version}.md"
Expand Down
8 changes: 6 additions & 2 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ packages = find:
include_package_data = True
setup_requires =
setuptools
setuptools-scm
setuptools-scm>=6.4.2; python_version>"3.6"
setuptools-scm==6.4.2; python_version=="3.6"
wheel
install_requires =
fbtftp>=0.5
Expand All @@ -30,6 +31,7 @@ install_requires =
pyyaml>=6.0
click>=8.0.4; python_version>"3.6"
click==8.0.4; python_version=="3.6"
importlib-metadata==3.10.1; python_version=="3.6"
importlib-resources==5.4.0; python_version=="3.6"
schema>=0.6.7; python_version>"3.6"
schema==0.6.7; python_version=="3.6"
Expand All @@ -42,6 +44,8 @@ tests_require =
pytest-cov==3.0.0; python_version=="3.6"

lint_requires =
importlib-metadata>=3.10.1
importlib-resources>=5.4.0
pre-commit>=2.0.1
black>=22.1.0
pyright>=0.0.13
Expand All @@ -59,4 +63,4 @@ dev_requires =
[options.packages.find]
where=src
exclude =
tests*
tests*
120 changes: 120 additions & 0 deletions src/cobbler_tftp/cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
"""

Check notice on line 1 in src/cobbler_tftp/cli.py

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

src/cobbler_tftp/cli.py#L1

One-line docstring should fit on one line with quotes (found 3) (D200)
Cobbler-tftp will be managable as a command-line service.
"""

import click
import yaml

try:
import importlib.metadata as importlib_metadata
except ImportError: # use backport for Python versions older than 3.8
import importlib_metadata

from cobbler_tftp.settings import SettingsFactory

try:
__version__ = importlib_metadata.version("cobbler_tftp")
except importlib_metadata.PackageNotFoundError:
__version__ = "unknown (not installed)"

with open(
"src/cobbler_tftp/settings/data/settings.yml", "r", encoding="utf-8"
) as stream:
try:
SETTINGS = yaml.safe_load(stream)
except yaml.YAMLError as exc:
print(exc)

_context_settings = dict(help_option_names=["-h", "--help"])

Check notice on line 28 in src/cobbler_tftp/cli.py

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

src/cobbler_tftp/cli.py#L28

Consider using '{"help_option_names": ['-h', '--help']}' instead of a call to 'dict'. (use-dict-literal)


@click.group(context_settings=_context_settings, invoke_without_command=True)
@click.pass_context
def cli(ctx):
"""
Cobbler-TFTP - Copyright (c) 2022 The Cobbler Team. (github.com/cobbler)\n
Licensed under the terms of the GPLv2.0 license.
"""
if ctx.invoked_subcommand is None:
click.echo(
"No commands given, try 'cobbler-tftp -h' or 'cobbler-tftp --help' to view usage."
)

# Possible default behavior can be invoked here


@cli.command()
@click.option(
"--no-daemon",
"-dd",
is_flag=True,
default=not SETTINGS["is_daemon"], # type: ignore
help="Stop cobbler-tftp from running as daemon.",
)
@click.option(
"--enable-automigration",
is_flag=True,
default=SETTINGS["auto_migrate_settings"], # type: ignore
help="Enable auto migration of settings.",
)
@click.option(
"--config", "-c", type=click.Path(), help="Set location of configuration file."
)
@click.option(
"--settings",
"-s",
multiple=True,
help="""Set custom settings in format:\n
<PARENT_YAML_KEY>.<CHILD_YAML_KEY>.<...>.<KEY_NAME>=<VALUE>.\n
Your settings must use single quotes. If a single quote appears within a value it must be escaped.""",
)
def start(no_daemon: bool, enable_automigration, config, settings):

Check notice on line 71 in src/cobbler_tftp/cli.py

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

src/cobbler_tftp/cli.py#L71

Unused argument 'enable_automigration' (unused-argument)
"""
Start the cobbler-tftp server.
"""
click.echo(cli.__doc__)
click.echo("Initializing Cobbler-tftp server...")
if no_daemon:
click.echo("'--no-daemon' flag set. Server running in the foreground...")
settings_factory: SettingsFactory = SettingsFactory()
# settings_file = SettingsFactory.load_config_file(settings_factory, config)
# environment_variables = SettingsFactory.load_env_variables(settings_factory)
# cli_arguments = SettingsFactory.load_cli_options(
# settings_factory, daemon, enable_automigration, settings
# )
application_settings = SettingsFactory.build_settings(

Check warning on line 85 in src/cobbler_tftp/cli.py

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

src/cobbler_tftp/cli.py#L85

Unused variable 'application_settings'

Check notice on line 85 in src/cobbler_tftp/cli.py

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

src/cobbler_tftp/cli.py#L85

Unused variable 'application_settings' (unused-variable)
settings_factory, config, settings
)
else:
click.echo("Cobbler-tftp will be running as a daemon in the background.")


@cli.command()
def version():
"""
Check cobbler-tftp version. If there are any cobbler servers connected their versions will be printed as well.
"""
click.echo(f"Cobbler-tftp {__version__}")


@cli.command()
def print_default_config():
"""
Print the default application parameters.
"""
settings_factory: SettingsFactory = SettingsFactory()
click.echo(settings_factory.build_settings(None, []))


@cli.command()
def stop():
"""
Stop the cobbler-tftp server daemon if it is running
"""
pass

Check warning on line 114 in src/cobbler_tftp/cli.py

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

src/cobbler_tftp/cli.py#L114

Unnecessary pass statement

Check notice on line 114 in src/cobbler_tftp/cli.py

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

src/cobbler_tftp/cli.py#L114

Unnecessary pass statement (unnecessary-pass)


cli.add_command(start)
cli.add_command(version)
cli.add_command(print_default_config)
cli.add_command(stop)
10 changes: 7 additions & 3 deletions src/cobbler_tftp/settings/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import os
from pathlib import Path
from typing import Dict, Optional, Union
from typing import Dict, List, Optional, Union

import yaml

Expand Down Expand Up @@ -92,10 +92,14 @@ def __init__(self) -> None:
"""Initialize a new Settings dicitionary."""
self._settings_dict: SettingsDict = {}

def build_settings(self, config_path: Optional[Path], cli_flags) -> Settings:
def build_settings(
self, config_path: Optional[Path], cli_arguments: List[str]
) -> Settings:
"""
Build new Settings object using parameters from all sources.

:param config_path: Path to the configuration file
:param cli_arguments: List of all CLI configuration options
:return: Settings object
"""

Expand All @@ -106,7 +110,7 @@ def build_settings(self, config_path: Optional[Path], cli_flags) -> Settings:
self.load_env_variables()

# Load CLI options
self.load_cli_options(cli_flags)
self.load_cli_options(cli_arguments)

if not migrations.validate(self._settings_dict):
raise ValueError(
Expand Down
Loading