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

otk/ui: introduce some sort of ui #272

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
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
11 changes: 10 additions & 1 deletion src/otk/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@

from . import __version__
from .document import Omnifest
from . import ui

log = logging.getLogger(__name__)
log = ui.Terminal(logging.getLogger(__name__))


def root() -> int:
Expand All @@ -28,6 +29,8 @@ def run(argv: List[str]) -> int:
print(f"otk {__version__}")
return 0

log.motd()

if arguments.command == "compile":
return compile(arguments)
if arguments.command == "validate":
Expand All @@ -49,6 +52,8 @@ def _process(arguments: argparse.Namespace, dry_run: bool) -> int:
else:
paths = extra + [pathlib.Path(arguments.input)]

log.info(f"Compiling {paths}")

# First pass of resolving the otk file is "shallow", it will not run
# externals and not resolve anything under otk.target.*
#
Expand All @@ -70,12 +75,16 @@ def _process(arguments: argparse.Namespace, dry_run: bool) -> int:
log.fatal("requested target %r does not exist in INPUT", target_requested)
return 1

log.info(f"Selected the {target_requested} target")

# Now do the real resolve that takes the target into account. It needs
# a full run so that resolving includes works correctly.
warn_duplicated_defs = any(arg in getattr(arguments, "warn", [])
for arg in ["duplicate-definition", "all"])
doc = Omnifest(paths, target=target_requested, warn_duplicated_defs=warn_duplicated_defs)

log.info("Done")

# and then output by writing to the output
if not dry_run:
dst.write(doc.as_target_string())
Expand Down
3 changes: 2 additions & 1 deletion src/otk/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@
TransformVariableIndexRangeError,
TransformVariableIndexTypeError,
TransformVariableLookupError, TransformVariableTypeError)
from . import ui

log = logging.getLogger(__name__)
log = ui.Terminal(logging.getLogger(__name__))


def validate_var_name(name):
Expand Down
3 changes: 0 additions & 3 deletions src/otk/document.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import logging
import pathlib
from copy import deepcopy
from typing import Any
Expand All @@ -10,8 +9,6 @@
from .traversal import State
from .target import OSBuildTarget

log = logging.getLogger(__name__)


class Omnifest:
_tree: dict[str, Any]
Expand Down
9 changes: 7 additions & 2 deletions src/otk/external.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,14 @@
import os
from typing import Any

from . import ui

from .constant import PREFIX_EXTERNAL
from .error import ExternalFailedError
from .traversal import State

log = logging.getLogger(__name__)

log = ui.Terminal(logging.getLogger(__name__))


def call(state: State, directive: str, tree: Any) -> Any:
Expand All @@ -26,7 +29,9 @@ def call(state: State, directive: str, tree: Any) -> Any:
}
)

process = subprocess.run([exe], input=data, encoding="utf8", capture_output=True, check=False)
with log.spinner(f"Executing external {os.path.basename(exe)}"):
process = subprocess.run([exe], input=data, encoding="utf8", capture_output=True, check=False)

if process.returncode != 0:
msg = f"call {exe} {directive!r} failed: stdout={process.stdout!r}, stderr={process.stderr!r}"
log.error(msg)
Expand Down
5 changes: 3 additions & 2 deletions src/otk/transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,9 @@
)
from .external import call
from .traversal import State
from . import ui

log = logging.getLogger(__name__)
log = ui.Terminal(logging.getLogger(__name__))


# from https://gist.github.com/pypt/94d747fe5180851196eb?permalink_comment_id=4653474#gistcomment-4653474
Expand Down Expand Up @@ -223,7 +224,7 @@ def process_include(ctx: Context, state: State, path: pathlib.Path) -> dict:
if not path.is_absolute():
cur_path = state.path.parent
path = (cur_path / pathlib.Path(path)).resolve()
log.info("resolving %s", path)
log.debug("resolving %s", path)
try:
with path.open(encoding="utf8") as fp:
data = yaml.load(fp, Loader=SafeUniqueKeyLoader)
Expand Down
69 changes: 69 additions & 0 deletions src/otk/ui.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import logging
import sys
import time
import threading

from typing import Optional, Type, Any
from types import TracebackType

from . import __version__


class _Spinner:
"""Render a spinner with an optional prompt to stderr, if stderr isn't a
tty this only prints the prompt."""

active: bool
thread: threading.Thread

def __init__(self, prompt: str) -> None:
self.prompt = prompt

def _loop(self):
sys.stderr.write(self.prompt)
sys.stderr.flush()

# No spinner business if we aren't printing to tty's.
if sys.stderr.isatty():
while self.active:
sys.stderr.write(".")
sys.stderr.flush()
time.sleep(0.1)

# Only write a newline if the prompt was actually there
if self.prompt:
sys.stderr.write("\n")
sys.stderr.flush()

def __enter__(self, prompt: str = "") -> None:
self.active = True
self.thread = threading.Thread(target=self._loop)
self.thread.start()

def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> bool:
self.active = False
self.thread.join()

return True


class Terminal:
def __init__(self, log: logging.Logger):
self.log = log

def motd(self) -> None:
# Note, this is the local print function
self.log.info(f"otk {__version__} -- https://www.osbuild.org/")

def spinner(self, prompt: str) -> _Spinner:
return _Spinner(prompt)

# Everything not defined is delegated to our underlying `Logger` instance,
# this allows `Terminal` to be used as a `Logger` wrapper.
def __getattr__(self, name: str) -> Any:
return getattr(self.log, name)
2 changes: 1 addition & 1 deletion test/test_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def test_otk_define_empty(tmp_path, caplog):


def test_verbose_logs_processed_files(tmp_path, caplog):
caplog.set_level(logging.INFO)
caplog.set_level(logging.DEBUG)

test_otk = tmp_path / "foo.yaml"
test_otk.write_text(TEST_OTK)
Expand Down
Loading