Skip to content

Commandline <> Lib communication using generators #37

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

Merged
merged 16 commits into from
Aug 31, 2017
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
57 changes: 54 additions & 3 deletions libiocage/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,53 @@
exit(1)


def print_events(generator):
lines = {}
for event in generator:

if event.identifier is None:
identifier = "generic"
else:
identifier = event.identifier

if event.type not in lines:
lines[event.type] = {}

# output fragments
running_indicator = "+" if (event.done or event.skipped) else "-"
name = event.type
if event.identifier is not None:
name += f"@{event.identifier}"

output = f"[{running_indicator}] {name}: "

if event.message is not None:
output += event.message
else:
output += event.get_state_string(
done="OK",
error="FAILED",
skipped="SKIPPED",
pending="..."
)

if event.duration is not None:
output += " [" + str(round(event.duration, 3)) + "s]"

# new line or update of previous
if identifier not in lines[event.type]:
# Indent if previous task is not finished
lines[event.type][identifier] = logger.screen(
output,
indent=event.parent_count
)
else:
lines[event.type][identifier].edit(
output,
indent=event.parent_count
)


class IOCageCLI(click.MultiCommand):
"""
Iterates in the 'cli' directory and will load any module's cli definition.
Expand All @@ -77,7 +124,7 @@ def list_commands(self, ctx):
return rv

def get_command(self, ctx, name):
ctx.logger = logger
ctx.print_events = print_events
try:
mod = __import__(f"libiocage.cli.{name}", None, None, ["cli"])

Expand All @@ -99,8 +146,12 @@ def get_command(self, ctx, name):
return


@click.option("--log-level", "-d", default=None)
@click.command(cls=IOCageCLI)
@click.version_option(version="0.9.10 07/30/2017", prog_name="iocage",
@click.version_option(version="0.2.11 08/29/2017", prog_name="ioc",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Where are you getting this versioning scheme from? Besides our placeholder release, we haven't discussed versioning much.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I started with 0.0.1 and everytime it will introduce new features I'd love to bump the minor version. For breaking changes (after 1.0.0) the major version number will increase. We should discuss and document the versioning system!

message="%(version)s")
def cli():
@click.pass_context
def cli(ctx, log_level):
"""A jail manager."""
logger.print_level = log_level
ctx.logger = logger
11 changes: 4 additions & 7 deletions libiocage/cli/create.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ def validate_count(ctx, param, value):


@click.command(name="create", help="Create a jail.")
@click.pass_context
@click.option("--count", "-c", callback=validate_count, default="1",
help="Designate a number of jails to create. Jails are"
" numbered sequentially.")
Expand Down Expand Up @@ -76,17 +77,13 @@ def validate_count(ctx, param, value):
help="Do not automatically fetch releases")
@click.option("--force", "-f", is_flag=True, default=False,
help="Skip the interactive question.")
@click.option("--log-level", "-d", default=None)
@click.argument("props", nargs=-1)
def cli(release, template, count, props, pkglist, basejail, basejail_type,
empty, name, no_fetch, force, log_level):
def cli(ctx, release, template, count, props, pkglist, basejail, basejail_type,
empty, name, no_fetch, force):
zfs = libiocage.lib.helpers.get_zfs()
logger = libiocage.lib.Logger.Logger()
logger = ctx.parent.logger
host = libiocage.lib.Host.Host(logger=logger, zfs=zfs)

if log_level is not None:
logger.print_level = log_level

jail_data = {}

if release is None:
Expand Down
57 changes: 8 additions & 49 deletions libiocage/cli/fetch.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,26 +25,13 @@
import click

import libiocage.lib.Host
import libiocage.lib.Logger
import libiocage.lib.Prompts
import libiocage.lib.Release
import libiocage.lib.errors

__rootcmd__ = True

__rootcmd__ = True

# ToDo: remove disabled feature
# def _prettify_release_names(x):
# if x.name == host.release_version:
# return f"\033[1m{x.name}\033[0m"
# else:
# return x.name
# def release_choice():
# version =
# return click.Choice(list(map(
# _prettify_release_names,
# host.distribution.releases
# )))

@click.command(context_settings=dict(
max_content_width=400, ),
Expand All @@ -59,8 +46,7 @@
# type=release_choice(),
help="The FreeBSD release to fetch.")
@click.option("--update/--no-update", "-U/-NU", default=True,
help="Decide whether or not to update the fetch to the latest "
"patch level.")
help="Update the release to the latest patch level.")
@click.option("--fetch-updates/--no-fetch-updates", default=True,
help="Skip fetching release updates")
# Compat
Expand All @@ -70,16 +56,8 @@
@click.option("--files", multiple=True,
help="Specify the files to fetch from the mirror. "
"(Deprecared: renamed to --file)")
@click.option("--log-level", "-d", default=None)
# @click.option("--auth", "-a", default=None, help="Authentication method for "
# "HTTP fetching. Valid "
# "values: basic, digest")
# @click.option("--verify/--noverify", "-V/-NV", default=True,
# help="Enable or disable verifying SSL cert for HTTP fetching.")
# def cli(url, files, release, update):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are we removing current CLI flags?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because they were not implemented yet, so I removed it to clean up the file. Most probably #43 will cause need to re-apply and use this option. I've updated the CLI criteria for signature checking, so that it's not forgotten.

def cli(ctx, **kwargs):
logger = ctx.parent.logger
logger.print_level = kwargs["log_level"]
host = libiocage.lib.Host.Host(logger=logger)
prompts = libiocage.lib.Prompts.Prompts(host=host, logger=logger)

Expand All @@ -91,7 +69,7 @@ def cli(ctx, **kwargs):
exit(1)
else:
try:
release = libiocage.lib.Release.Release(
release = libiocage.lib.Release.ReleaseGenerator(
name=release_input,
host=host,
logger=logger
Expand All @@ -100,9 +78,6 @@ def cli(ctx, **kwargs):
logger.error(f"Invalid Release '{release_input}'")
exit(1)

if kwargs["log_level"] is not None:
logger.print_level = kwargs["log_level"]

url_or_files_selected = False

if is_option_enabled(kwargs, "url"):
Expand All @@ -117,28 +92,12 @@ def cli(ctx, **kwargs):
logger.error(f"The release '{release.name}' is not available")
exit(1)

if release.fetched:
msg = f"Release '{release.name}' is already fetched"
if kwargs["update"] is True:
logger.log(f"{msg} - updating only")
else:
logger.log(f"{msg} - skipping download and updates")
exit(0)
else:
logger.log(
f"Fetching release '{release.name}' from '{release.mirror_url}'"
)
release.fetch(update=False, fetch_updates=False)

if kwargs["fetch_updates"] is True:
logger.log("Fetching updates")
release.fetch_updates()

if kwargs["update"] is True:
logger.log("Updating release")
release.update()
fetch_updates = bool(kwargs["fetch_updates"])
ctx.parent.print_events(release.fetch(
update=kwargs["update"],
fetch_updates=fetch_updates
))

logger.log('done')
exit(0)


Expand Down
2 changes: 1 addition & 1 deletion libiocage/cli/get.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def cli(ctx, prop, _all, _pool, jail, log_level):
)

if not jail.exists:
logger.error("Jail '{jail}' does not exist")
logger.error(f"Jail '{jail.name}' does not exist")
exit(1)

if _all is True:
Expand Down
Loading