Skip to content

Commit

Permalink
Appendable state
Browse files Browse the repository at this point in the history
  • Loading branch information
jennydaman committed Feb 26, 2022
1 parent d68c813 commit 1c79ba4
Show file tree
Hide file tree
Showing 6 changed files with 56 additions and 21 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
It is particularly useful for seeding a setup for testing or development,
though it could also (work and) be useful for deployments.

![Screen recording](https://ipfs.babymri.org/ipfs/QmXYHhAfgJDvHrAJsAkt77s9UrP4Snz4P7FWTnSayweMcs/chrisomatic.gif)
![Screen recording](https://ipfs.babymri.org/ipfs/QmV98NzC6St94GjHdSs7qQmxpvkMLgjCWMm4VHafP6DH3C/chrisomatic.gif)

## Usage

Expand Down
6 changes: 4 additions & 2 deletions chrisomatic/core/plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,13 +240,15 @@ async def _get_json_representation(self, emit: State) -> Optional[str]:
)
if pull_result == PullResult.error:
return None
emit.status = "attempting to produce JSON representation..."
if pull_result == PullResult.pulled:
emit.append = True
guessing_methods: list[Callable[[State], Awaitable[Optional[str]]]] = [
self._json_from_chris_plugin_info,
self._json_from_old_chrisapp,
]
for guess_method in guessing_methods:
json_representation = await guess_method(emit)
emit.append = False
if json_representation is not None:
return json_representation
return None
Expand All @@ -261,7 +263,7 @@ async def _json_from_old_chrisapp(self, emit: State) -> Optional[str]:
return await self._try_run(emit, (cmd[0], "--json"))

async def _try_run(self, emit: State, command: Sequence[str]) -> Optional[str]:
emit.status = f"Running {command}"
emit.status = f"Running `{' '.join(command)}`"
try:
return await check_output(self.docker, self.plugin.dock_image, command)
except aiodocker.DockerContainerError:
Expand Down
38 changes: 36 additions & 2 deletions chrisomatic/framework/task.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,55 @@
import abc
from typing import TypeVar, Generic, Optional
from dataclasses import dataclass
from dataclasses import dataclass, InitVar, field
from chrisomatic.framework.outcome import Outcome
from rich.console import RenderableType
from rich.console import Group
from rich.highlighter import ReprHighlighter
from rich.text import Text

_R = TypeVar("_R")
highlighter = ReprHighlighter()


@dataclass
class State:
"""
Mutable object used to relay information between `ChrisomaticTask.run`
and a live display.
When setting its `status` property while `append=False`, its status will be overwritten.
But when `append=True`, setting `status` will instead append it to a list of its
previous values. Getting `status` returns a
[`rich.group.Group`](https://rich.readthedocs.io/en/latest/group.html)
"""

title: str
status: RenderableType
status: InitVar[RenderableType]
append: bool = False
__rows: list[RenderableType] = field(init=False, default_factory=list)

def __post_init__(self, status: RenderableType):
self.__rows.append(status)

@property
def status(self) -> RenderableType:
return Group(*self.__rows)

@status.setter
def status(self, value: RenderableType):
highlighted = self.__highlight(value)
if self.append:
self.__rows.append(highlighted)
else:
self.__rows[-1] = highlighted

@staticmethod
def __highlight(s: RenderableType) -> RenderableType:
if isinstance(s, (int, float, bool, str, list, tuple, set, frozenset)):
text = Text(str(s))
highlighter.highlight(text)
return text
return s


class ChrisomaticTask(abc.ABC, Generic[_R]):
Expand Down
21 changes: 6 additions & 15 deletions chrisomatic/framework/taskrunner.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,10 @@
from rich.table import Table, Column
from rich.progress import Progress, TaskID
from rich.spinner import Spinner
from rich.highlighter import ReprHighlighter
from typing import Sequence, ClassVar, TypeVar, Generic, Awaitable
from dataclasses import dataclass, InitVar
from chrisomatic.framework.task import State, ChrisomaticTask, Outcome

highlighter = ReprHighlighter()
_R = TypeVar("_R")


Expand All @@ -31,7 +29,7 @@ def __post_init__(self, chrisomatic_task: ChrisomaticTask):
self.task = asyncio.create_task(chrisomatic_task.run(self.state))

def to_row(self) -> tuple[RenderableType, RenderableType, RenderableType]:
return self.__get_icon(), self.__get_title(), self.__highlighted_status()
return self.__get_icon(), self.__get_title(), self.state.status

def done(self) -> bool:
return self.task.done()
Expand All @@ -51,13 +49,6 @@ def __get_icon(self) -> RenderableType:
def __get_title(self) -> RenderableType:
return Text(self.state.title, style=self.outcome.style if self.done() else None)

def __highlighted_status(self) -> RenderableType:
if isinstance(self.state.status, str):
text = Text(str(self.state.status))
highlighter.highlight(text)
return text
return self.state.status


@dataclass
class TaskRunner(Generic[_R]):
Expand Down Expand Up @@ -179,8 +170,8 @@ async def run_and_update() -> tuple[Outcome, _R]:
return run_and_update()

@staticmethod
def __format_noise(outcome: Outcome, state: State) -> Text:
t = Text()
t.append(f"[{state.title}]", style=outcome.style)
t.append(f" {state.status}")
return t
def __format_noise(outcome: Outcome, state: State) -> RenderableType:
title = Text(f"[{state.title}] ", style=outcome.style)
table = Table.grid(Column(ratio=3), Column(ratio=8), expand=True)
table.add_row(title, state.status)
return table
4 changes: 4 additions & 0 deletions docs/scratch.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,11 @@ def initial_state(self) -> State:
async def run(self, emit: State) -> tuple[Outcome, str]:
async with aiodocker.Docker() as docker:
await rich_pull(docker, "fnndsc/pl-re-sub", emit)
emit.append = True
emit.status = "will delete now..."
await docker.images.delete("fnndsc/pl-re-sub:latest")
emit.status = "deleted"

return Outcome.CHANGE, "ok"


Expand Down
6 changes: 5 additions & 1 deletion testing_harness/scripts/create_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,11 @@
"dock_image": "ghcr.io/fnndsc/pl-nums2mask:1.0.0",
"compute_resource": [f"try-{stamp}-cr-b"],
},
{"name": "pl-dircopy", "version": "2.1.1"},
{
"name": "pl-dircopy",
"version": "2.1.1",
"dock_image": "fnndsc/pl-dircopy",
},
],
},
}
Expand Down

0 comments on commit 1c79ba4

Please sign in to comment.