Skip to content

Commit

Permalink
add TriggeredTask
Browse files Browse the repository at this point in the history
  • Loading branch information
goFrendiAsgard committed Nov 25, 2023
1 parent 7202f16 commit 222208c
Show file tree
Hide file tree
Showing 17 changed files with 426 additions and 25 deletions.
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ dependencies = [
"ruamel.yaml ~= 0.17.32",
"setuptools ~= 68.0.0",
"autopep8 ~= 2.0.2",
"croniter ~= 2.0.1",
]

[project.optional-dependencies]
Expand Down
3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
flit==3.9.0 # better builder
twine==4.0.2 # pip package uploader
keyring==24.2.0 # authenticator (used by twine)
tomli~=2.0.1

# Zrb dependencies (should be copied to `pyproject.toml`)
click~=8.1.4 # CLI framework
Expand All @@ -15,7 +16,7 @@ jsons~=1.6.3
ruamel.yaml~=0.17.32
setuptools~=68.0.0
autopep8~=2.0.2 # Autoformatter
tomli~=2.0.1
croniter~=2.0.1

# Zrb dev dependencies (should be copied to `pyproject.toml`)
flake8~=6.0.0 # Linter
Expand Down
1 change: 1 addition & 0 deletions src/zrb/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
ResourceMaker, Replacement, ReplacementMutator
)
from zrb.task.flow_task import FlowTask
from zrb.task.triggered_task import TriggeredTask
from zrb.task_input.any_input import AnyInput
from zrb.task_input.task_input import Input
from zrb.task_input.bool_input import BoolInput
Expand Down
6 changes: 6 additions & 0 deletions src/zrb/builtin/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@
from zrb.builtin import devtool
from zrb.builtin import generator
from zrb.builtin import process
from zrb.builtin import say
from zrb.builtin import watch
from zrb.builtin import remind

assert base64
assert env
Expand All @@ -25,3 +28,6 @@
assert devtool
assert generator
assert process
assert say
assert watch
assert remind
1 change: 0 additions & 1 deletion src/zrb/builtin/explain.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from zrb.helper.python_task import show_lines
from zrb.builtin.group import explain_group
from zrb.task.decorator import python_task
from zrb.task.task import Task
from zrb.runner import runner


Expand Down
37 changes: 37 additions & 0 deletions src/zrb/builtin/remind.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
from zrb.task.any_task import AnyTask
from zrb.task.triggered_task import TriggeredTask
from zrb.task.decorator import python_task
from zrb.task_input.str_input import StrInput
from zrb.runner import runner


@python_task(
name='show-message',
inputs=[
StrInput(
name='message',
default='👋',
prompt='Message',
description='Message'
),
]
)
def _show_message(*args, **kwargs):
task: AnyTask = kwargs['_task']
task.print_out(kwargs.get('message', '👋'))


remind = TriggeredTask(
name='remind',
inputs=[
StrInput(
name='schedule',
default='* * * * *',
prompt='Schedule cron pattern (minute hour day(month) month day(week)', # noqa
description='Schedule cron pattern to show the message'
),
],
schedule='{{input.schedule}}',
task=_show_message
)
runner.register(remind)
137 changes: 137 additions & 0 deletions src/zrb/builtin/say.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
from zrb.helper.typing import Any, List
from zrb.helper.python_task import show_lines
from zrb.task.decorator import python_task
from zrb.task_input.str_input import StrInput
from zrb.task_input.int_input import IntInput
from zrb.runner import runner
import datetime
import random

_MIN_WIDTH = 50
_MOTIVATIONAL_QUOTES = [
[
'The best time to plant a tree was 20 years ago.',
'The second best time is now.',
'~ Chinese Proverb'
],
[
'The only way to do great work is to love what you do.',
'~ Steve Jobs'
],
[
'Believe you can and you\'re halfway there.',
'~ Theodore Roosevelt'
],
[
'It does not matter how slowly you go as long as you do not stop.',
'~ Confucius'
],
[
'Everything you\'ve ever wanted is on the other side of fear.',
'~ George Addair'
],
[
'Success is not final, failure is not fatal:',
'It is the courage to continue that counts.',
'~ Winston Churchill'
],
[
'Hardships often prepare ordinary people',
'for an extraordinary destiny.',
'~ C.S. Lewis'
],
[
'Your time is limited, don\'t waste it living someone else\'s life.',
'~ Steve Jobs'
],
[
'Don’t watch the clock; do what it does. Keep going.',
'~ Sam Levenson'
],
[
'You are never too old to set another goal or to dream a new dream.',
'~ C.S. Lewis'
],
[
'The only limit to our realization of tomorrow',
'will be our doubts of today.',
'~ Franklin D. Roosevelt'
],
[
'Believe in yourself.',
'You are braver than you think, more talented than you know,'
'and capable of more than you imagine.',
'~ Roy T. Bennett'
],
[
'I can\'t change the direction of the wind,',
'but I can adjust my sails to always reach my destination.',
'~ Jimmy Dean'
],
[
'You are enough just as you are.',
'~ Meghan Markle'
],
[
'The future belongs to those',
'who believe in the beauty of their dreams.',
'~ Eleanor Roosevelt'
]
]


@python_task(
name='say',
inputs=[
StrInput(name='text', default=''),
IntInput(name='width', default=80)
],
runner=runner
)
def say(*args: Any, **kwargs: Any):
width: int = kwargs.get('width', 50)
if width < _MIN_WIDTH:
width = _MIN_WIDTH
text: str = kwargs.get('text', '')
top_border = '┌' + '─' * (width + 2) + '┐'
content = [
'| ' + line + ' |' for line in _get_content(text, width)
]
bottom_border = '└' + '─' * (width + 2) + '┘'
lines = [top_border] + content + [bottom_border] + [
' \\',
' \\',
' o ___ o',
' | ┌-------┐ |',
' |(| o o |)|',
' | └---┘ |',
' └-------┘',
]
show_lines(kwargs['_task'], *lines)


def _get_content(text: str, width: int) -> List[str]:
if text == '':
now = datetime.datetime.now()
today = 'Today is ' + now.strftime('%A, %B %d, %Y')
current_time = 'Current time is ' + now.strftime('%I:%M %p')
motivational_quote = random.choice(_MOTIVATIONAL_QUOTES)
return [
today.ljust(width),
current_time.ljust(width),
''.ljust(width),
] + [
line.ljust(width) for line in motivational_quote
]
return _split_text_by_width(text, width)


def _split_text_by_width(text: str, width: int) -> List[str]:
original_lines = text.split('\n')
new_lines = []
for original_line in original_lines:
new_lines += [
original_line[i:i+width].ljust(width)
for i in range(0, len(original_line), width)
]
return new_lines
31 changes: 31 additions & 0 deletions src/zrb/builtin/watch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from zrb.task.triggered_task import TriggeredTask
from zrb.task.cmd_task import CmdTask
from zrb.task_input.str_input import StrInput
from zrb.runner import runner


watch = TriggeredTask(
name='watch',
inputs=[
StrInput(
name='pattern',
default='*.*',
prompt='File pattern',
description='File pattern to be watched'
),
],
watched_path='{{input.pattern}}',
task=CmdTask(
name='run-command',
inputs=[
StrInput(
name='command',
default='echo "change detected"',
prompt='Command to be executed',
description='Command to be executed when changes detected'
),
],
cmd='{{input.command}}'
)
)
runner.register(watch)
3 changes: 2 additions & 1 deletion src/zrb/task/any_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ def to_function(
self,
env_prefix: str = '',
raise_error: bool = True,
is_async: bool = False
is_async: bool = False,
show_done_info: bool = True
) -> Callable[..., Any]:
pass

Expand Down
24 changes: 15 additions & 9 deletions src/zrb/task/base_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,8 @@ def to_function(
self,
env_prefix: str = '',
raise_error: bool = True,
is_async: bool = False
is_async: bool = False,
show_done_info: bool = True
) -> Callable[..., Any]:
'''
Return a function representing the current task.
Expand All @@ -166,7 +167,8 @@ async def function(*args: Any, **kwargs: Any) -> Any:
env_prefix=env_prefix,
raise_error=raise_error,
args=args,
kwargs=kwargs
kwargs=kwargs,
show_done_info=show_done_info
)
if is_async:
return function
Expand Down Expand Up @@ -297,7 +299,8 @@ async def _run_and_check_all(
env_prefix: str,
raise_error: bool,
args: Iterable[Any],
kwargs: Mapping[str, Any]
kwargs: Mapping[str, Any],
show_done_info: bool = True
):
try:
self._start_timer()
Expand All @@ -321,7 +324,9 @@ async def _run_and_check_all(
self._kwargs = new_kwargs
# run the task
coroutines = [
asyncio.create_task(self._loop_check(show_done=True)),
asyncio.create_task(
self._loop_check(show_done_info=show_done_info)
),
asyncio.create_task(self._run_all(*new_args, **new_kwargs))
]
results = await asyncio.gather(*coroutines)
Expand All @@ -333,9 +338,10 @@ async def _run_and_check_all(
if raise_error:
raise
finally:
self._show_env_prefix()
self._show_run_command()
self._play_bell()
if show_done_info:
self._show_env_prefix()
self._show_run_command()
self._play_bell()

def _print_result(self, result: Any):
if result is None:
Expand All @@ -359,13 +365,13 @@ def print_result(self, result: Any):
'''
print(result)

async def _loop_check(self, show_done: bool = False) -> bool:
async def _loop_check(self, show_done_info: bool = False) -> bool:
self.log_info('Start readiness checking')
while not await self._cached_check():
self.log_debug('Task is not ready')
await asyncio.sleep(self._checking_interval)
self._end_timer()
if show_done:
if show_done_info:
if show_advertisement:
selected_advertisement = get_advertisement(advertisements)
selected_advertisement.show()
Expand Down
6 changes: 3 additions & 3 deletions src/zrb/task/base_task_composite.py
Original file line number Diff line number Diff line change
Expand Up @@ -510,8 +510,8 @@ def _get_colored(self, text: str) -> str:
def _get_print_prefix(self) -> str:
common_prefix = self._get_common_prefix(show_time=show_time)
icon = self.get_icon()
truncated_name = self._get_rjust_full_cmd_name()
return f'{common_prefix} {icon} {truncated_name}'
rjust_cmd_name = self._get_rjust_full_cmd_name()
return f'{common_prefix} {icon} {rjust_cmd_name}'

def _get_log_prefix(self) -> str:
common_prefix = self._get_common_prefix(show_time=False)
Expand All @@ -522,7 +522,7 @@ def _get_log_prefix(self) -> str:
def _get_common_prefix(self, show_time: bool) -> str:
attempt = self._get_attempt()
max_attempt = self._get_max_attempt()
pid = self._get_task_pid()
pid = str(self._get_task_pid()).rjust(6)
if show_time:
now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
return f'◷ {now}{pid}{attempt}/{max_attempt}'
Expand Down
7 changes: 5 additions & 2 deletions src/zrb/task/cmd_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,9 +176,12 @@ def to_function(
self,
env_prefix: str = '',
raise_error: bool = True,
is_async: bool = False
is_async: bool = False,
show_done_info: bool = True
) -> Callable[..., CmdResult]:
return super().to_function(env_prefix, raise_error, is_async)
return super().to_function(
env_prefix, raise_error, is_async, show_done_info
)

def print_result(self, result: CmdResult):
if result.output == '':
Expand Down
7 changes: 5 additions & 2 deletions src/zrb/task/http_checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,12 @@ def to_function(
self,
env_prefix: str = '',
raise_error: bool = True,
is_async: bool = False
is_async: bool = False,
show_done_info: bool = True
) -> Callable[..., bool]:
return super().to_function(env_prefix, raise_error, is_async)
return super().to_function(
env_prefix, raise_error, is_async, show_done_info
)

async def run(self, *args: Any, **kwargs: Any) -> bool:
is_https = self.render_bool(self._is_https)
Expand Down
Loading

0 comments on commit 222208c

Please sign in to comment.