From 8f9e8276ea684f048936e7a92d35c8851f2600f9 Mon Sep 17 00:00:00 2001 From: goFrendiAsgard Date: Fri, 8 Dec 2023 19:16:47 +0700 Subject: [PATCH 01/13] Prepare for version 0.1.0 --- .github/workflows/_zrb.yml | 2 +- docs/concepts/tasks/checkers.md | 2 +- docs/getting-started.md | 6 +++--- pyproject.toml | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/_zrb.yml b/.github/workflows/_zrb.yml index 00662a1b..8d7a0bc6 100644 --- a/.github/workflows/_zrb.yml +++ b/.github/workflows/_zrb.yml @@ -17,7 +17,7 @@ jobs: Run-command: runs-on: ubuntu-latest container: - image: stalchmst/zrb:0.0.122 + image: stalchmst/zrb:0.0.123 steps: - name: Check out repository code uses: actions/checkout@v3 diff --git a/docs/concepts/tasks/checkers.md b/docs/concepts/tasks/checkers.md index 6fae7ff7..c95a2122 100644 --- a/docs/concepts/tasks/checkers.md +++ b/docs/concepts/tasks/checkers.md @@ -35,7 +35,7 @@ run_server = CmdTask( Env(name='PORT', os_name='WEB_PORT', default='3000') ], env_files=[ - EnvFile(env_file='src/template.env', prefix='WEB') + EnvFile(path='src/template.env', prefix='WEB') ] cmd='python main.py', cwd='src', diff --git a/docs/getting-started.md b/docs/getting-started.md index 2df58344..9733e202 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -828,7 +828,7 @@ from zrb import EnvFile import os PROJECT_ENV = os.path.join(os.path.dirname(__file__), 'project.env') -env_file = EnvFile(env_file=PROJECT_ENV) +env_file = EnvFile(path=PROJECT_ENV) ``` ### Using Env and EnvFile @@ -856,7 +856,7 @@ hello_cmd = CmdTask( Env(name='MESSAGE', default='Hello world'), ], env_files=[ - EnvFile(env_file=PROJECT_ENV) + EnvFile(path=PROJECT_ENV) ], cmd=[ 'echo Message: {{env.MESSAGE}}', @@ -896,7 +896,7 @@ PROJECT_ENV = os.path.join(os.path.dirname(__file__), 'project.env') Env(name='MESSAGE', default='Hello world'), ], env_files=[ - EnvFile(env_file=PROJECT_ENV) + EnvFile(path=PROJECT_ENV) ], runner=runner ) diff --git a/pyproject.toml b/pyproject.toml index 8752bbfb..7b3b1542 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "flit_core.buildapi" [project] name = "zrb" -version = "0.0.123" +version = "0.1.0" authors = [ { name="Go Frendi Gunawan", email="gofrendiasgard@gmail.com" }, ] From 9b9425557fb1a30fce09b3bef456f56b1d73216b Mon Sep 17 00:00:00 2001 From: goFrendiAsgard Date: Fri, 8 Dec 2023 19:39:33 +0700 Subject: [PATCH 02/13] ensure execution id consistency --- src/zrb/task/base_task/base_task.py | 2 ++ src/zrb/task/recurring_task.py | 16 ++++++++++++---- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/src/zrb/task/base_task/base_task.py b/src/zrb/task/base_task/base_task.py index 22ecded1..f738fc07 100644 --- a/src/zrb/task/base_task/base_task.py +++ b/src/zrb/task/base_task/base_task.py @@ -144,6 +144,8 @@ async def run(self, *args: Any, **kwargs: Any) -> Any: async def on_triggered(self): self.log_info('State: triggered') + execution_id = self.get_execution_id() + self.log_info(f'Execution id: {execution_id}') if self._on_triggered is not None: await run_async(self._on_triggered, self) diff --git a/src/zrb/task/recurring_task.py b/src/zrb/task/recurring_task.py index 630b8685..a552d678 100644 --- a/src/zrb/task/recurring_task.py +++ b/src/zrb/task/recurring_task.py @@ -2,6 +2,7 @@ Any, Callable, Iterable, Mapping, Optional, Union ) from zrb.helper.typecheck import typechecked +from zrb.helper.accessories.name import get_random_name from zrb.task.base_task.base_task import BaseTask from zrb.task.any_task import AnyTask from zrb.task.any_task_event_handler import ( @@ -99,10 +100,15 @@ async def run(self, *args: Any, **kwargs: Any): } is_first_time = True while True: + execution_id = get_random_name( + add_random_digit=True, digit_count=5 + ) # Create trigger functions trigger_functions = [] for trigger in self._triggers: - trigger_function = trigger.copy().to_function( + trigger_copy = trigger.copy() + trigger_copy._set_execution_id(execution_id) + trigger_function = trigger_copy.to_function( is_async=True, raise_error=False, show_done_info=False ) trigger_functions.append(asyncio.create_task( @@ -118,13 +124,15 @@ async def run(self, *args: Any, **kwargs: Any): trigger_functions, return_when=asyncio.FIRST_COMPLETED ) # Cancel the remaining tasks - for task in pending: + for process in pending: try: - task.cancel() + process.cancel() except Exception as e: self.print_err(e) # Run the task - fn = self._task.copy().to_function( + task_copy = self._task.copy() + task_copy._set_execution_id(execution_id) + fn = task_copy.to_function( is_async=True, raise_error=False, show_done_info=False ) self.print_out_dark('Executing the task') From b04500a2b29385d9024000e69a446e23efd48ff4 Mon Sep 17 00:00:00 2001 From: goFrendiAsgard Date: Fri, 8 Dec 2023 20:07:17 +0700 Subject: [PATCH 03/13] add docs --- docs/concepts/tasks/README.md | 80 +++++++++++++++++---- docs/concepts/tasks/checkers.md | 80 +++++++++++++++++---- docs/concepts/tasks/cmd-task.md | 80 +++++++++++++++++---- docs/concepts/tasks/docker-compose-task.md | 80 +++++++++++++++++---- docs/concepts/tasks/flow-task.md | 80 +++++++++++++++++---- docs/concepts/tasks/remote-cmd-task.md | 80 +++++++++++++++++---- docs/concepts/tasks/resource-maker.md | 80 +++++++++++++++++---- docs/concepts/tasks/rsync-task.md | 80 +++++++++++++++++---- src/zrb/task/any_task.py | 83 ++++++++++++++++++++-- 9 files changed, 621 insertions(+), 102 deletions(-) diff --git a/docs/concepts/tasks/README.md b/docs/concepts/tasks/README.md index 543df93e..766a8c77 100644 --- a/docs/concepts/tasks/README.md +++ b/docs/concepts/tasks/README.md @@ -378,8 +378,15 @@ No documentation available. ### `AnyTask.get_execution_id` -No documentation available. +Retrieves the execution ID of the task. + +This method returns the unique identifier associated with the task's execution. +The execution ID is crucial for tracking, logging, and differentiating between +multiple instances or runs of the same task. +__Returns:__ + +`str`: The unique execution ID of the task. ### `AnyTask.get_icon` @@ -742,43 +749,92 @@ class MyTask(Task): ### `AnyTask.set_checking_interval` -No documentation available. +Sets the interval for checking the task's readiness or completion status. +This method defines how frequently the system should check if the task is ready or completed. +It's useful for tasks that have an indeterminate completion time. + +__Arguments:__ + +- `new_checking_interval` (`Union[float, int]`): The time interval (in seconds) for readiness or checks. ### `AnyTask.set_color` -No documentation available. +Defines a new color for the current task. +This method updates the color associated with the task. This can be useful for categorization, +priority indication, or visual differentiation in a UI. + +__Arguments:__ + +- `new_color` (`str`): A string representing the color to be assigned to the task. ### `AnyTask.set_description` -Set current task description. -Usually used to overide copied task's description. +Sets a new description for the current task. + +This method allows updating the task's description to provide more context or details about its purpose and behavior. +Useful for enhancing clarity and maintainability in the task management system. + +__Arguments:__ + +- `new_description` (`str`): A string representing the new description of the task. ### `AnyTask.set_icon` -Set current task icon. -Usually used to overide copied task's icon. +Assigns a new icon to the current task. + +This method is used for setting or updating the task's icon, which can be utilized for visual representation +in a user interface. The icon should ideally be a string identifier that maps to an actual graphical resource. + +__Arguments:__ + +- `new_icon` (`str`): A string representing the icon identifier for the task. ### `AnyTask.set_name` -Set current task name. -Usually used to overide copied task's name. +Sets a new name for the current task. + +This method is used to update the task's name, typically after creating a copy of an existing task. +The new name helps in differentiating the task in the task management system. + +__Arguments:__ + +- `new_name` (`str`): A string representing the new name to be assigned to the task. ### `AnyTask.set_retry` -No documentation available. +Sets the number of retry attempts for the task. + +This method configures how many times the task should be retried in case of failure. +It's essential for tasks that may fail transiently and need multiple attempts for successful execution. + +__Arguments:__ +- `new_retry` (`int`): An integer representing the number of retry attempts. ### `AnyTask.set_retry_interval` -No documentation available. +Specifies the interval between retry attempts for the task. + +This method sets the duration to wait before retrying the task after a failure. +This can help in scenarios where immediate retry is not desirable or effective. + +__Arguments:__ +- `new_retry_interval` (`Union[float, int]`): The time interval (in seconds) to wait before a retry attempt. ### `AnyTask.set_should_execute` -No documentation available. +Determines whether the task should execute. + +This method configures the execution criteria for the task. It can be set as a boolean value, +a string representing a condition, or a callable that returns a boolean. This is useful for +conditional task execution based on dynamic criteria. + +__Arguments:__ +- `should_execute` (`Union[bool, str, Callable[..., bool]]`): The condition to determine if the task should execute. ### `AnyTask.to_function` diff --git a/docs/concepts/tasks/checkers.md b/docs/concepts/tasks/checkers.md index c95a2122..bd45a4cc 100644 --- a/docs/concepts/tasks/checkers.md +++ b/docs/concepts/tasks/checkers.md @@ -479,8 +479,15 @@ No documentation available. ### `Checker.get_execution_id` -No documentation available. +Retrieves the execution ID of the task. + +This method returns the unique identifier associated with the task's execution. +The execution ID is crucial for tracking, logging, and differentiating between +multiple instances or runs of the same task. +__Returns:__ + +`str`: The unique execution ID of the task. ### `Checker.get_icon` @@ -848,43 +855,92 @@ class MyTask(Task): ### `Checker.set_checking_interval` -No documentation available. +Sets the interval for checking the task's readiness or completion status. +This method defines how frequently the system should check if the task is ready or completed. +It's useful for tasks that have an indeterminate completion time. + +__Arguments:__ + +- `new_checking_interval` (`Union[float, int]`): The time interval (in seconds) for readiness or checks. ### `Checker.set_color` -No documentation available. +Defines a new color for the current task. +This method updates the color associated with the task. This can be useful for categorization, +priority indication, or visual differentiation in a UI. + +__Arguments:__ + +- `new_color` (`str`): A string representing the color to be assigned to the task. ### `Checker.set_description` -Set current task description. -Usually used to overide copied task's description. +Sets a new description for the current task. + +This method allows updating the task's description to provide more context or details about its purpose and behavior. +Useful for enhancing clarity and maintainability in the task management system. + +__Arguments:__ + +- `new_description` (`str`): A string representing the new description of the task. ### `Checker.set_icon` -Set current task icon. -Usually used to overide copied task's icon. +Assigns a new icon to the current task. + +This method is used for setting or updating the task's icon, which can be utilized for visual representation +in a user interface. The icon should ideally be a string identifier that maps to an actual graphical resource. + +__Arguments:__ + +- `new_icon` (`str`): A string representing the icon identifier for the task. ### `Checker.set_name` -Set current task name. -Usually used to overide copied task's name. +Sets a new name for the current task. + +This method is used to update the task's name, typically after creating a copy of an existing task. +The new name helps in differentiating the task in the task management system. + +__Arguments:__ + +- `new_name` (`str`): A string representing the new name to be assigned to the task. ### `Checker.set_retry` -No documentation available. +Sets the number of retry attempts for the task. + +This method configures how many times the task should be retried in case of failure. +It's essential for tasks that may fail transiently and need multiple attempts for successful execution. + +__Arguments:__ +- `new_retry` (`int`): An integer representing the number of retry attempts. ### `Checker.set_retry_interval` -No documentation available. +Specifies the interval between retry attempts for the task. + +This method sets the duration to wait before retrying the task after a failure. +This can help in scenarios where immediate retry is not desirable or effective. + +__Arguments:__ +- `new_retry_interval` (`Union[float, int]`): The time interval (in seconds) to wait before a retry attempt. ### `Checker.set_should_execute` -No documentation available. +Determines whether the task should execute. + +This method configures the execution criteria for the task. It can be set as a boolean value, +a string representing a condition, or a callable that returns a boolean. This is useful for +conditional task execution based on dynamic criteria. + +__Arguments:__ +- `should_execute` (`Union[bool, str, Callable[..., bool]]`): The condition to determine if the task should execute. ### `Checker.show_progress` diff --git a/docs/concepts/tasks/cmd-task.md b/docs/concepts/tasks/cmd-task.md index bfa9f70f..01d91b04 100644 --- a/docs/concepts/tasks/cmd-task.md +++ b/docs/concepts/tasks/cmd-task.md @@ -587,8 +587,15 @@ No documentation available. ### `CmdTask.get_execution_id` -No documentation available. +Retrieves the execution ID of the task. + +This method returns the unique identifier associated with the task's execution. +The execution ID is crucial for tracking, logging, and differentiating between +multiple instances or runs of the same task. +__Returns:__ + +`str`: The unique execution ID of the task. ### `CmdTask.get_icon` @@ -951,13 +958,25 @@ class MyTask(Task): ### `CmdTask.set_checking_interval` -No documentation available. +Sets the interval for checking the task's readiness or completion status. +This method defines how frequently the system should check if the task is ready or completed. +It's useful for tasks that have an indeterminate completion time. + +__Arguments:__ + +- `new_checking_interval` (`Union[float, int]`): The time interval (in seconds) for readiness or checks. ### `CmdTask.set_color` -No documentation available. +Defines a new color for the current task. +This method updates the color associated with the task. This can be useful for categorization, +priority indication, or visual differentiation in a UI. + +__Arguments:__ + +- `new_color` (`str`): A string representing the color to be assigned to the task. ### `CmdTask.set_cwd` @@ -966,33 +985,70 @@ No documentation available. ### `CmdTask.set_description` -Set current task description. -Usually used to overide copied task's description. +Sets a new description for the current task. + +This method allows updating the task's description to provide more context or details about its purpose and behavior. +Useful for enhancing clarity and maintainability in the task management system. + +__Arguments:__ + +- `new_description` (`str`): A string representing the new description of the task. ### `CmdTask.set_icon` -Set current task icon. -Usually used to overide copied task's icon. +Assigns a new icon to the current task. + +This method is used for setting or updating the task's icon, which can be utilized for visual representation +in a user interface. The icon should ideally be a string identifier that maps to an actual graphical resource. + +__Arguments:__ + +- `new_icon` (`str`): A string representing the icon identifier for the task. ### `CmdTask.set_name` -Set current task name. -Usually used to overide copied task's name. +Sets a new name for the current task. + +This method is used to update the task's name, typically after creating a copy of an existing task. +The new name helps in differentiating the task in the task management system. + +__Arguments:__ + +- `new_name` (`str`): A string representing the new name to be assigned to the task. ### `CmdTask.set_retry` -No documentation available. +Sets the number of retry attempts for the task. + +This method configures how many times the task should be retried in case of failure. +It's essential for tasks that may fail transiently and need multiple attempts for successful execution. + +__Arguments:__ +- `new_retry` (`int`): An integer representing the number of retry attempts. ### `CmdTask.set_retry_interval` -No documentation available. +Specifies the interval between retry attempts for the task. + +This method sets the duration to wait before retrying the task after a failure. +This can help in scenarios where immediate retry is not desirable or effective. + +__Arguments:__ +- `new_retry_interval` (`Union[float, int]`): The time interval (in seconds) to wait before a retry attempt. ### `CmdTask.set_should_execute` -No documentation available. +Determines whether the task should execute. + +This method configures the execution criteria for the task. It can be set as a boolean value, +a string representing a condition, or a callable that returns a boolean. This is useful for +conditional task execution based on dynamic criteria. + +__Arguments:__ +- `should_execute` (`Union[bool, str, Callable[..., bool]]`): The condition to determine if the task should execute. ### `CmdTask.to_function` diff --git a/docs/concepts/tasks/docker-compose-task.md b/docs/concepts/tasks/docker-compose-task.md index 71a62e29..875d2fd3 100644 --- a/docs/concepts/tasks/docker-compose-task.md +++ b/docs/concepts/tasks/docker-compose-task.md @@ -603,8 +603,15 @@ No documentation available. ### `DockerComposeTask.get_execution_id` -No documentation available. +Retrieves the execution ID of the task. + +This method returns the unique identifier associated with the task's execution. +The execution ID is crucial for tracking, logging, and differentiating between +multiple instances or runs of the same task. +__Returns:__ + +`str`: The unique execution ID of the task. ### `DockerComposeTask.get_icon` @@ -967,13 +974,25 @@ class MyTask(Task): ### `DockerComposeTask.set_checking_interval` -No documentation available. +Sets the interval for checking the task's readiness or completion status. +This method defines how frequently the system should check if the task is ready or completed. +It's useful for tasks that have an indeterminate completion time. + +__Arguments:__ + +- `new_checking_interval` (`Union[float, int]`): The time interval (in seconds) for readiness or checks. ### `DockerComposeTask.set_color` -No documentation available. +Defines a new color for the current task. +This method updates the color associated with the task. This can be useful for categorization, +priority indication, or visual differentiation in a UI. + +__Arguments:__ + +- `new_color` (`str`): A string representing the color to be assigned to the task. ### `DockerComposeTask.set_cwd` @@ -982,33 +1001,70 @@ No documentation available. ### `DockerComposeTask.set_description` -Set current task description. -Usually used to overide copied task's description. +Sets a new description for the current task. + +This method allows updating the task's description to provide more context or details about its purpose and behavior. +Useful for enhancing clarity and maintainability in the task management system. + +__Arguments:__ + +- `new_description` (`str`): A string representing the new description of the task. ### `DockerComposeTask.set_icon` -Set current task icon. -Usually used to overide copied task's icon. +Assigns a new icon to the current task. + +This method is used for setting or updating the task's icon, which can be utilized for visual representation +in a user interface. The icon should ideally be a string identifier that maps to an actual graphical resource. + +__Arguments:__ + +- `new_icon` (`str`): A string representing the icon identifier for the task. ### `DockerComposeTask.set_name` -Set current task name. -Usually used to overide copied task's name. +Sets a new name for the current task. + +This method is used to update the task's name, typically after creating a copy of an existing task. +The new name helps in differentiating the task in the task management system. + +__Arguments:__ + +- `new_name` (`str`): A string representing the new name to be assigned to the task. ### `DockerComposeTask.set_retry` -No documentation available. +Sets the number of retry attempts for the task. + +This method configures how many times the task should be retried in case of failure. +It's essential for tasks that may fail transiently and need multiple attempts for successful execution. + +__Arguments:__ +- `new_retry` (`int`): An integer representing the number of retry attempts. ### `DockerComposeTask.set_retry_interval` -No documentation available. +Specifies the interval between retry attempts for the task. + +This method sets the duration to wait before retrying the task after a failure. +This can help in scenarios where immediate retry is not desirable or effective. + +__Arguments:__ +- `new_retry_interval` (`Union[float, int]`): The time interval (in seconds) to wait before a retry attempt. ### `DockerComposeTask.set_should_execute` -No documentation available. +Determines whether the task should execute. + +This method configures the execution criteria for the task. It can be set as a boolean value, +a string representing a condition, or a callable that returns a boolean. This is useful for +conditional task execution based on dynamic criteria. + +__Arguments:__ +- `should_execute` (`Union[bool, str, Callable[..., bool]]`): The condition to determine if the task should execute. ### `DockerComposeTask.to_function` diff --git a/docs/concepts/tasks/flow-task.md b/docs/concepts/tasks/flow-task.md index 0157c896..df366ef5 100644 --- a/docs/concepts/tasks/flow-task.md +++ b/docs/concepts/tasks/flow-task.md @@ -486,8 +486,15 @@ No documentation available. ### `FlowTask.get_execution_id` -No documentation available. +Retrieves the execution ID of the task. + +This method returns the unique identifier associated with the task's execution. +The execution ID is crucial for tracking, logging, and differentiating between +multiple instances or runs of the same task. +__Returns:__ + +`str`: The unique execution ID of the task. ### `FlowTask.get_icon` @@ -850,43 +857,92 @@ class MyTask(Task): ### `FlowTask.set_checking_interval` -No documentation available. +Sets the interval for checking the task's readiness or completion status. +This method defines how frequently the system should check if the task is ready or completed. +It's useful for tasks that have an indeterminate completion time. + +__Arguments:__ + +- `new_checking_interval` (`Union[float, int]`): The time interval (in seconds) for readiness or checks. ### `FlowTask.set_color` -No documentation available. +Defines a new color for the current task. +This method updates the color associated with the task. This can be useful for categorization, +priority indication, or visual differentiation in a UI. + +__Arguments:__ + +- `new_color` (`str`): A string representing the color to be assigned to the task. ### `FlowTask.set_description` -Set current task description. -Usually used to overide copied task's description. +Sets a new description for the current task. + +This method allows updating the task's description to provide more context or details about its purpose and behavior. +Useful for enhancing clarity and maintainability in the task management system. + +__Arguments:__ + +- `new_description` (`str`): A string representing the new description of the task. ### `FlowTask.set_icon` -Set current task icon. -Usually used to overide copied task's icon. +Assigns a new icon to the current task. + +This method is used for setting or updating the task's icon, which can be utilized for visual representation +in a user interface. The icon should ideally be a string identifier that maps to an actual graphical resource. + +__Arguments:__ + +- `new_icon` (`str`): A string representing the icon identifier for the task. ### `FlowTask.set_name` -Set current task name. -Usually used to overide copied task's name. +Sets a new name for the current task. + +This method is used to update the task's name, typically after creating a copy of an existing task. +The new name helps in differentiating the task in the task management system. + +__Arguments:__ + +- `new_name` (`str`): A string representing the new name to be assigned to the task. ### `FlowTask.set_retry` -No documentation available. +Sets the number of retry attempts for the task. + +This method configures how many times the task should be retried in case of failure. +It's essential for tasks that may fail transiently and need multiple attempts for successful execution. + +__Arguments:__ +- `new_retry` (`int`): An integer representing the number of retry attempts. ### `FlowTask.set_retry_interval` -No documentation available. +Specifies the interval between retry attempts for the task. + +This method sets the duration to wait before retrying the task after a failure. +This can help in scenarios where immediate retry is not desirable or effective. + +__Arguments:__ +- `new_retry_interval` (`Union[float, int]`): The time interval (in seconds) to wait before a retry attempt. ### `FlowTask.set_should_execute` -No documentation available. +Determines whether the task should execute. + +This method configures the execution criteria for the task. It can be set as a boolean value, +a string representing a condition, or a callable that returns a boolean. This is useful for +conditional task execution based on dynamic criteria. + +__Arguments:__ +- `should_execute` (`Union[bool, str, Callable[..., bool]]`): The condition to determine if the task should execute. ### `FlowTask.to_function` diff --git a/docs/concepts/tasks/remote-cmd-task.md b/docs/concepts/tasks/remote-cmd-task.md index 058f6f92..906fb2e5 100644 --- a/docs/concepts/tasks/remote-cmd-task.md +++ b/docs/concepts/tasks/remote-cmd-task.md @@ -461,8 +461,15 @@ No documentation available. ### `RemoteCmdTask.get_execution_id` -No documentation available. +Retrieves the execution ID of the task. + +This method returns the unique identifier associated with the task's execution. +The execution ID is crucial for tracking, logging, and differentiating between +multiple instances or runs of the same task. +__Returns:__ + +`str`: The unique execution ID of the task. ### `RemoteCmdTask.get_icon` @@ -825,43 +832,92 @@ class MyTask(Task): ### `RemoteCmdTask.set_checking_interval` -No documentation available. +Sets the interval for checking the task's readiness or completion status. +This method defines how frequently the system should check if the task is ready or completed. +It's useful for tasks that have an indeterminate completion time. + +__Arguments:__ + +- `new_checking_interval` (`Union[float, int]`): The time interval (in seconds) for readiness or checks. ### `RemoteCmdTask.set_color` -No documentation available. +Defines a new color for the current task. +This method updates the color associated with the task. This can be useful for categorization, +priority indication, or visual differentiation in a UI. + +__Arguments:__ + +- `new_color` (`str`): A string representing the color to be assigned to the task. ### `RemoteCmdTask.set_description` -Set current task description. -Usually used to overide copied task's description. +Sets a new description for the current task. + +This method allows updating the task's description to provide more context or details about its purpose and behavior. +Useful for enhancing clarity and maintainability in the task management system. + +__Arguments:__ + +- `new_description` (`str`): A string representing the new description of the task. ### `RemoteCmdTask.set_icon` -Set current task icon. -Usually used to overide copied task's icon. +Assigns a new icon to the current task. + +This method is used for setting or updating the task's icon, which can be utilized for visual representation +in a user interface. The icon should ideally be a string identifier that maps to an actual graphical resource. + +__Arguments:__ + +- `new_icon` (`str`): A string representing the icon identifier for the task. ### `RemoteCmdTask.set_name` -Set current task name. -Usually used to overide copied task's name. +Sets a new name for the current task. + +This method is used to update the task's name, typically after creating a copy of an existing task. +The new name helps in differentiating the task in the task management system. + +__Arguments:__ + +- `new_name` (`str`): A string representing the new name to be assigned to the task. ### `RemoteCmdTask.set_retry` -No documentation available. +Sets the number of retry attempts for the task. + +This method configures how many times the task should be retried in case of failure. +It's essential for tasks that may fail transiently and need multiple attempts for successful execution. + +__Arguments:__ +- `new_retry` (`int`): An integer representing the number of retry attempts. ### `RemoteCmdTask.set_retry_interval` -No documentation available. +Specifies the interval between retry attempts for the task. + +This method sets the duration to wait before retrying the task after a failure. +This can help in scenarios where immediate retry is not desirable or effective. + +__Arguments:__ +- `new_retry_interval` (`Union[float, int]`): The time interval (in seconds) to wait before a retry attempt. ### `RemoteCmdTask.set_should_execute` -No documentation available. +Determines whether the task should execute. + +This method configures the execution criteria for the task. It can be set as a boolean value, +a string representing a condition, or a callable that returns a boolean. This is useful for +conditional task execution based on dynamic criteria. + +__Arguments:__ +- `should_execute` (`Union[bool, str, Callable[..., bool]]`): The condition to determine if the task should execute. ### `RemoteCmdTask.to_function` diff --git a/docs/concepts/tasks/resource-maker.md b/docs/concepts/tasks/resource-maker.md index 5ff9eb41..20bd8c80 100644 --- a/docs/concepts/tasks/resource-maker.md +++ b/docs/concepts/tasks/resource-maker.md @@ -493,8 +493,15 @@ No documentation available. ### `ResourceMaker.get_execution_id` -No documentation available. +Retrieves the execution ID of the task. + +This method returns the unique identifier associated with the task's execution. +The execution ID is crucial for tracking, logging, and differentiating between +multiple instances or runs of the same task. +__Returns:__ + +`str`: The unique execution ID of the task. ### `ResourceMaker.get_icon` @@ -857,43 +864,92 @@ class MyTask(Task): ### `ResourceMaker.set_checking_interval` -No documentation available. +Sets the interval for checking the task's readiness or completion status. +This method defines how frequently the system should check if the task is ready or completed. +It's useful for tasks that have an indeterminate completion time. + +__Arguments:__ + +- `new_checking_interval` (`Union[float, int]`): The time interval (in seconds) for readiness or checks. ### `ResourceMaker.set_color` -No documentation available. +Defines a new color for the current task. +This method updates the color associated with the task. This can be useful for categorization, +priority indication, or visual differentiation in a UI. + +__Arguments:__ + +- `new_color` (`str`): A string representing the color to be assigned to the task. ### `ResourceMaker.set_description` -Set current task description. -Usually used to overide copied task's description. +Sets a new description for the current task. + +This method allows updating the task's description to provide more context or details about its purpose and behavior. +Useful for enhancing clarity and maintainability in the task management system. + +__Arguments:__ + +- `new_description` (`str`): A string representing the new description of the task. ### `ResourceMaker.set_icon` -Set current task icon. -Usually used to overide copied task's icon. +Assigns a new icon to the current task. + +This method is used for setting or updating the task's icon, which can be utilized for visual representation +in a user interface. The icon should ideally be a string identifier that maps to an actual graphical resource. + +__Arguments:__ + +- `new_icon` (`str`): A string representing the icon identifier for the task. ### `ResourceMaker.set_name` -Set current task name. -Usually used to overide copied task's name. +Sets a new name for the current task. + +This method is used to update the task's name, typically after creating a copy of an existing task. +The new name helps in differentiating the task in the task management system. + +__Arguments:__ + +- `new_name` (`str`): A string representing the new name to be assigned to the task. ### `ResourceMaker.set_retry` -No documentation available. +Sets the number of retry attempts for the task. + +This method configures how many times the task should be retried in case of failure. +It's essential for tasks that may fail transiently and need multiple attempts for successful execution. + +__Arguments:__ +- `new_retry` (`int`): An integer representing the number of retry attempts. ### `ResourceMaker.set_retry_interval` -No documentation available. +Specifies the interval between retry attempts for the task. + +This method sets the duration to wait before retrying the task after a failure. +This can help in scenarios where immediate retry is not desirable or effective. + +__Arguments:__ +- `new_retry_interval` (`Union[float, int]`): The time interval (in seconds) to wait before a retry attempt. ### `ResourceMaker.set_should_execute` -No documentation available. +Determines whether the task should execute. + +This method configures the execution criteria for the task. It can be set as a boolean value, +a string representing a condition, or a callable that returns a boolean. This is useful for +conditional task execution based on dynamic criteria. + +__Arguments:__ +- `should_execute` (`Union[bool, str, Callable[..., bool]]`): The condition to determine if the task should execute. ### `ResourceMaker.to_function` diff --git a/docs/concepts/tasks/rsync-task.md b/docs/concepts/tasks/rsync-task.md index 7c2d1f07..0c59b240 100644 --- a/docs/concepts/tasks/rsync-task.md +++ b/docs/concepts/tasks/rsync-task.md @@ -492,8 +492,15 @@ No documentation available. ### `RsyncTask.get_execution_id` -No documentation available. +Retrieves the execution ID of the task. + +This method returns the unique identifier associated with the task's execution. +The execution ID is crucial for tracking, logging, and differentiating between +multiple instances or runs of the same task. +__Returns:__ + +`str`: The unique execution ID of the task. ### `RsyncTask.get_icon` @@ -856,43 +863,92 @@ class MyTask(Task): ### `RsyncTask.set_checking_interval` -No documentation available. +Sets the interval for checking the task's readiness or completion status. +This method defines how frequently the system should check if the task is ready or completed. +It's useful for tasks that have an indeterminate completion time. + +__Arguments:__ + +- `new_checking_interval` (`Union[float, int]`): The time interval (in seconds) for readiness or checks. ### `RsyncTask.set_color` -No documentation available. +Defines a new color for the current task. +This method updates the color associated with the task. This can be useful for categorization, +priority indication, or visual differentiation in a UI. + +__Arguments:__ + +- `new_color` (`str`): A string representing the color to be assigned to the task. ### `RsyncTask.set_description` -Set current task description. -Usually used to overide copied task's description. +Sets a new description for the current task. + +This method allows updating the task's description to provide more context or details about its purpose and behavior. +Useful for enhancing clarity and maintainability in the task management system. + +__Arguments:__ + +- `new_description` (`str`): A string representing the new description of the task. ### `RsyncTask.set_icon` -Set current task icon. -Usually used to overide copied task's icon. +Assigns a new icon to the current task. + +This method is used for setting or updating the task's icon, which can be utilized for visual representation +in a user interface. The icon should ideally be a string identifier that maps to an actual graphical resource. + +__Arguments:__ + +- `new_icon` (`str`): A string representing the icon identifier for the task. ### `RsyncTask.set_name` -Set current task name. -Usually used to overide copied task's name. +Sets a new name for the current task. + +This method is used to update the task's name, typically after creating a copy of an existing task. +The new name helps in differentiating the task in the task management system. + +__Arguments:__ + +- `new_name` (`str`): A string representing the new name to be assigned to the task. ### `RsyncTask.set_retry` -No documentation available. +Sets the number of retry attempts for the task. + +This method configures how many times the task should be retried in case of failure. +It's essential for tasks that may fail transiently and need multiple attempts for successful execution. + +__Arguments:__ +- `new_retry` (`int`): An integer representing the number of retry attempts. ### `RsyncTask.set_retry_interval` -No documentation available. +Specifies the interval between retry attempts for the task. + +This method sets the duration to wait before retrying the task after a failure. +This can help in scenarios where immediate retry is not desirable or effective. + +__Arguments:__ +- `new_retry_interval` (`Union[float, int]`): The time interval (in seconds) to wait before a retry attempt. ### `RsyncTask.set_should_execute` -No documentation available. +Determines whether the task should execute. + +This method configures the execution criteria for the task. It can be set as a boolean value, +a string representing a condition, or a callable that returns a boolean. This is useful for +conditional task execution based on dynamic criteria. + +__Arguments:__ +- `should_execute` (`Union[bool, str, Callable[..., bool]]`): The condition to determine if the task should execute. ### `RsyncTask.to_function` diff --git a/src/zrb/task/any_task.py b/src/zrb/task/any_task.py index 142ed52a..9d2a9bee 100644 --- a/src/zrb/task/any_task.py +++ b/src/zrb/task/any_task.py @@ -428,51 +428,122 @@ def _set_execution_id(self, execution_id: str): @abstractmethod def set_name(self, new_name: str): ''' - Set current task name. - Usually used to overide copied task's name. + Sets a new name for the current task. + + This method is used to update the task's name, typically after creating a copy of an existing task. + The new name helps in differentiating the task in the task management system. + + Args: + new_name (str): A string representing the new name to be assigned to the task. ''' pass @abstractmethod def set_description(self, new_description: str): ''' - Set current task description. - Usually used to overide copied task's description. + Sets a new description for the current task. + + This method allows updating the task's description to provide more context or details about its purpose and behavior. + Useful for enhancing clarity and maintainability in the task management system. + + Args: + new_description (str): A string representing the new description of the task. ''' pass @abstractmethod def set_icon(self, new_icon: str): ''' - Set current task icon. - Usually used to overide copied task's icon. + Assigns a new icon to the current task. + + This method is used for setting or updating the task's icon, which can be utilized for visual representation + in a user interface. The icon should ideally be a string identifier that maps to an actual graphical resource. + + Args: + new_icon (str): A string representing the icon identifier for the task. ''' pass @abstractmethod def set_color(self, new_color: str): + ''' + Defines a new color for the current task. + + This method updates the color associated with the task. This can be useful for categorization, + priority indication, or visual differentiation in a UI. + + Args: + new_color (str): A string representing the color to be assigned to the task. + ''' pass @abstractmethod def set_should_execute( self, should_execute: Union[bool, str, Callable[..., bool]] ): + ''' + Determines whether the task should execute. + + This method configures the execution criteria for the task. It can be set as a boolean value, + a string representing a condition, or a callable that returns a boolean. This is useful for + conditional task execution based on dynamic criteria. + + Args: + should_execute (Union[bool, str, Callable[..., bool]]): The condition to determine if the task should execute. + ''' pass @abstractmethod def set_retry(self, new_retry: int): + ''' + Sets the number of retry attempts for the task. + + This method configures how many times the task should be retried in case of failure. + It's essential for tasks that may fail transiently and need multiple attempts for successful execution. + + Args: + new_retry (int): An integer representing the number of retry attempts. + ''' pass @abstractmethod def set_retry_interval(self, new_retry_interval: Union[float, int]): + ''' + Specifies the interval between retry attempts for the task. + + This method sets the duration to wait before retrying the task after a failure. + This can help in scenarios where immediate retry is not desirable or effective. + + Args: + new_retry_interval (Union[float, int]): The time interval (in seconds) to wait before a retry attempt. + ''' pass @abstractmethod def set_checking_interval(self, new_checking_interval: Union[float, int]): + ''' + Sets the interval for checking the task's readiness or completion status. + + This method defines how frequently the system should check if the task is ready or completed. + It's useful for tasks that have an indeterminate completion time. + + Args: + new_checking_interval (Union[float, int]): The time interval (in seconds) for readiness or checks. + ''' pass @abstractmethod def get_execution_id(self) -> str: + ''' + Retrieves the execution ID of the task. + + This method returns the unique identifier associated with the task's execution. + The execution ID is crucial for tracking, logging, and differentiating between + multiple instances or runs of the same task. + + Returns: + str: The unique execution ID of the task. + ''' pass @abstractmethod From 17d430a92b8654bc83928f2ab03c0e63061e6ae2 Mon Sep 17 00:00:00 2001 From: goFrendiAsgard Date: Sat, 9 Dec 2023 16:00:45 +0700 Subject: [PATCH 04/13] add more doc-string --- docs/concepts/tasks/README.md | 80 +++++++++++++++++--- docs/concepts/tasks/checkers.md | 80 +++++++++++++++++--- docs/concepts/tasks/cmd-task.md | 80 +++++++++++++++++--- docs/concepts/tasks/docker-compose-task.md | 80 +++++++++++++++++--- docs/concepts/tasks/flow-task.md | 80 +++++++++++++++++--- docs/concepts/tasks/remote-cmd-task.md | 80 +++++++++++++++++--- docs/concepts/tasks/resource-maker.md | 80 +++++++++++++++++--- docs/concepts/tasks/rsync-task.md | 80 +++++++++++++++++--- src/zrb/task/any_task.py | 87 ++++++++++++++++++++++ 9 files changed, 647 insertions(+), 80 deletions(-) diff --git a/docs/concepts/tasks/README.md b/docs/concepts/tasks/README.md index 766a8c77..098ae2bc 100644 --- a/docs/concepts/tasks/README.md +++ b/docs/concepts/tasks/README.md @@ -171,18 +171,36 @@ No documentation available. ### `AnyTask._get_env_files` -No documentation available. +Retrieves the list of environment variable files associated with the task. + +Intended for internal use, this method returns a list of `EnvFile` instances that the task +uses to load environment variables, primarily for setup and configuration purposes. + +__Returns:__ +`List[EnvFile]`: A list of `EnvFile` instances associated with the task. ### `AnyTask._get_envs` -No documentation available. +Retrieves the list of environment variables set for the task. +For internal use, this method returns a list of `Env` instances representing the environment variables +configured for the task, essential for understanding and debugging the task's environment setup. + +__Returns:__ + +`List[Env]`: A list of `Env` instances representing the environment variables of the task. ### `AnyTask._get_full_cli_name` -No documentation available. +Retrieves the full command-line interface (CLI) name of the task. + +Intended for internal use, this method provides the complete CLI name, including any +prefixes or namespaces, used primarily for logging or debugging purposes. + +__Returns:__ +`str`: The full CLI name of the task. ### `AnyTask._get_inputs` @@ -221,8 +239,10 @@ __Arguments:__ ### `AnyTask._set_has_cli_interface` -No documentation available. +Marks the task as having a CLI interface. +This internal method is used to indicate that the task is accessible and executable through a CLI, +enabling the task system to appropriately handle its CLI interactions. ### `AnyTask._set_keyval` @@ -358,18 +378,36 @@ copied_task.set_name('new_name') ### `AnyTask.get_cli_name` -No documentation available. +Gets the command-line interface (CLI) name of the task. + +This method returns the name used to invoke the task via a CLI, facilitating integration with command-line tools +or scripts. + +__Returns:__ +`str`: The CLI name of the task. ### `AnyTask.get_color` -No documentation available. +Retrieves the color associated with the current task. + +This method returns the color of the task, useful for visual differentiation, priority indication, +or categorization in user interfaces or documentation. +__Returns:__ + +`str`: A string representing the color assigned to the task. ### `AnyTask.get_description` -No documentation available. +Fetches the current description of the task. +This method is used to obtain the detailed description of the task, providing insights into its purpose, +functionality, and usage within the task management system. + +__Returns:__ + +`str`: The description of the task. ### `AnyTask.get_env_map` @@ -390,8 +428,14 @@ __Returns:__ ### `AnyTask.get_icon` -No documentation available. +Retrieves the icon identifier of the current task. + +This method is used to get the icon associated with the task, which can be utilized for +visual representation in user interfaces or documentation. +__Returns:__ + +`str`: A string representing the icon identifier for the task ### `AnyTask.get_input_map` @@ -405,12 +449,28 @@ No documentation available. ### `AnyTask.inject_env_files` -No documentation available. +Injects additional `EnvFile` into the task. + +Example: +```python +from zrb import Task +class MyTask(Task): + def inject_env_files(self): + self.add_env_files(EnvFile(path='config.env')) +``` ### `AnyTask.inject_envs` -No documentation available. +Injects environment variables into the task. + +Example: +```python +from zrb import Task +class MyTask(Task): + def inject_envs(self): + self.add_envs(Env(name='DATABASE_URL')) +``` ### `AnyTask.inject_inputs` diff --git a/docs/concepts/tasks/checkers.md b/docs/concepts/tasks/checkers.md index bd45a4cc..3aacbbbe 100644 --- a/docs/concepts/tasks/checkers.md +++ b/docs/concepts/tasks/checkers.md @@ -162,18 +162,36 @@ No documentation available. ### `Checker._get_env_files` -No documentation available. +Retrieves the list of environment variable files associated with the task. + +Intended for internal use, this method returns a list of `EnvFile` instances that the task +uses to load environment variables, primarily for setup and configuration purposes. + +__Returns:__ +`List[EnvFile]`: A list of `EnvFile` instances associated with the task. ### `Checker._get_envs` -No documentation available. +Retrieves the list of environment variables set for the task. +For internal use, this method returns a list of `Env` instances representing the environment variables +configured for the task, essential for understanding and debugging the task's environment setup. + +__Returns:__ + +`List[Env]`: A list of `Env` instances representing the environment variables of the task. ### `Checker._get_full_cli_name` -No documentation available. +Retrieves the full command-line interface (CLI) name of the task. + +Intended for internal use, this method provides the complete CLI name, including any +prefixes or namespaces, used primarily for logging or debugging purposes. + +__Returns:__ +`str`: The full CLI name of the task. ### `Checker._get_inputs` @@ -277,8 +295,10 @@ __Arguments:__ ### `Checker._set_has_cli_interface` -No documentation available. +Marks the task as having a CLI interface. +This internal method is used to indicate that the task is accessible and executable through a CLI, +enabling the task system to appropriately handle its CLI interactions. ### `Checker._set_input_map` @@ -459,18 +479,36 @@ copied_task.set_name('new_name') ### `Checker.get_cli_name` -No documentation available. +Gets the command-line interface (CLI) name of the task. + +This method returns the name used to invoke the task via a CLI, facilitating integration with command-line tools +or scripts. + +__Returns:__ +`str`: The CLI name of the task. ### `Checker.get_color` -No documentation available. +Retrieves the color associated with the current task. + +This method returns the color of the task, useful for visual differentiation, priority indication, +or categorization in user interfaces or documentation. +__Returns:__ + +`str`: A string representing the color assigned to the task. ### `Checker.get_description` -No documentation available. +Fetches the current description of the task. +This method is used to obtain the detailed description of the task, providing insights into its purpose, +functionality, and usage within the task management system. + +__Returns:__ + +`str`: The description of the task. ### `Checker.get_env_map` @@ -491,8 +529,14 @@ __Returns:__ ### `Checker.get_icon` -No documentation available. +Retrieves the icon identifier of the current task. + +This method is used to get the icon associated with the task, which can be utilized for +visual representation in user interfaces or documentation. +__Returns:__ + +`str`: A string representing the icon identifier for the task ### `Checker.get_input_map` @@ -506,12 +550,28 @@ No documentation available. ### `Checker.inject_env_files` -No documentation available. +Injects additional `EnvFile` into the task. + +Example: +```python +from zrb import Task +class MyTask(Task): + def inject_env_files(self): + self.add_env_files(EnvFile(path='config.env')) +``` ### `Checker.inject_envs` -No documentation available. +Injects environment variables into the task. + +Example: +```python +from zrb import Task +class MyTask(Task): + def inject_envs(self): + self.add_envs(Env(name='DATABASE_URL')) +``` ### `Checker.inject_inputs` diff --git a/docs/concepts/tasks/cmd-task.md b/docs/concepts/tasks/cmd-task.md index 01d91b04..55c277cd 100644 --- a/docs/concepts/tasks/cmd-task.md +++ b/docs/concepts/tasks/cmd-task.md @@ -265,18 +265,36 @@ No documentation available. ### `CmdTask._get_env_files` -No documentation available. +Retrieves the list of environment variable files associated with the task. + +Intended for internal use, this method returns a list of `EnvFile` instances that the task +uses to load environment variables, primarily for setup and configuration purposes. + +__Returns:__ +`List[EnvFile]`: A list of `EnvFile` instances associated with the task. ### `CmdTask._get_envs` -No documentation available. +Retrieves the list of environment variables set for the task. +For internal use, this method returns a list of `Env` instances representing the environment variables +configured for the task, essential for understanding and debugging the task's environment setup. + +__Returns:__ + +`List[Env]`: A list of `Env` instances representing the environment variables of the task. ### `CmdTask._get_full_cli_name` -No documentation available. +Retrieves the full command-line interface (CLI) name of the task. + +Intended for internal use, this method provides the complete CLI name, including any +prefixes or namespaces, used primarily for logging or debugging purposes. + +__Returns:__ +`str`: The full CLI name of the task. ### `CmdTask._get_inputs` @@ -380,8 +398,10 @@ __Arguments:__ ### `CmdTask._set_has_cli_interface` -No documentation available. +Marks the task as having a CLI interface. +This internal method is used to indicate that the task is accessible and executable through a CLI, +enabling the task system to appropriately handle its CLI interactions. ### `CmdTask._set_input_map` @@ -562,8 +582,14 @@ copied_task.set_name('new_name') ### `CmdTask.get_cli_name` -No documentation available. +Gets the command-line interface (CLI) name of the task. + +This method returns the name used to invoke the task via a CLI, facilitating integration with command-line tools +or scripts. + +__Returns:__ +`str`: The CLI name of the task. ### `CmdTask.get_cmd_script` @@ -572,13 +598,25 @@ No documentation available. ### `CmdTask.get_color` -No documentation available. +Retrieves the color associated with the current task. + +This method returns the color of the task, useful for visual differentiation, priority indication, +or categorization in user interfaces or documentation. +__Returns:__ + +`str`: A string representing the color assigned to the task. ### `CmdTask.get_description` -No documentation available. +Fetches the current description of the task. +This method is used to obtain the detailed description of the task, providing insights into its purpose, +functionality, and usage within the task management system. + +__Returns:__ + +`str`: The description of the task. ### `CmdTask.get_env_map` @@ -599,8 +637,14 @@ __Returns:__ ### `CmdTask.get_icon` -No documentation available. +Retrieves the icon identifier of the current task. + +This method is used to get the icon associated with the task, which can be utilized for +visual representation in user interfaces or documentation. +__Returns:__ + +`str`: A string representing the icon identifier for the task ### `CmdTask.get_input_map` @@ -614,12 +658,28 @@ No documentation available. ### `CmdTask.inject_env_files` -No documentation available. +Injects additional `EnvFile` into the task. + +Example: +```python +from zrb import Task +class MyTask(Task): + def inject_env_files(self): + self.add_env_files(EnvFile(path='config.env')) +``` ### `CmdTask.inject_envs` -No documentation available. +Injects environment variables into the task. + +Example: +```python +from zrb import Task +class MyTask(Task): + def inject_envs(self): + self.add_envs(Env(name='DATABASE_URL')) +``` ### `CmdTask.inject_inputs` diff --git a/docs/concepts/tasks/docker-compose-task.md b/docs/concepts/tasks/docker-compose-task.md index 875d2fd3..6bccde2c 100644 --- a/docs/concepts/tasks/docker-compose-task.md +++ b/docs/concepts/tasks/docker-compose-task.md @@ -281,18 +281,36 @@ No documentation available. ### `DockerComposeTask._get_env_files` -No documentation available. +Retrieves the list of environment variable files associated with the task. + +Intended for internal use, this method returns a list of `EnvFile` instances that the task +uses to load environment variables, primarily for setup and configuration purposes. + +__Returns:__ +`List[EnvFile]`: A list of `EnvFile` instances associated with the task. ### `DockerComposeTask._get_envs` -No documentation available. +Retrieves the list of environment variables set for the task. +For internal use, this method returns a list of `Env` instances representing the environment variables +configured for the task, essential for understanding and debugging the task's environment setup. + +__Returns:__ + +`List[Env]`: A list of `Env` instances representing the environment variables of the task. ### `DockerComposeTask._get_full_cli_name` -No documentation available. +Retrieves the full command-line interface (CLI) name of the task. + +Intended for internal use, this method provides the complete CLI name, including any +prefixes or namespaces, used primarily for logging or debugging purposes. + +__Returns:__ +`str`: The full CLI name of the task. ### `DockerComposeTask._get_inputs` @@ -396,8 +414,10 @@ __Arguments:__ ### `DockerComposeTask._set_has_cli_interface` -No documentation available. +Marks the task as having a CLI interface. +This internal method is used to indicate that the task is accessible and executable through a CLI, +enabling the task system to appropriately handle its CLI interactions. ### `DockerComposeTask._set_input_map` @@ -578,8 +598,14 @@ copied_task.set_name('new_name') ### `DockerComposeTask.get_cli_name` -No documentation available. +Gets the command-line interface (CLI) name of the task. + +This method returns the name used to invoke the task via a CLI, facilitating integration with command-line tools +or scripts. + +__Returns:__ +`str`: The CLI name of the task. ### `DockerComposeTask.get_cmd_script` @@ -588,13 +614,25 @@ No documentation available. ### `DockerComposeTask.get_color` -No documentation available. +Retrieves the color associated with the current task. + +This method returns the color of the task, useful for visual differentiation, priority indication, +or categorization in user interfaces or documentation. +__Returns:__ + +`str`: A string representing the color assigned to the task. ### `DockerComposeTask.get_description` -No documentation available. +Fetches the current description of the task. +This method is used to obtain the detailed description of the task, providing insights into its purpose, +functionality, and usage within the task management system. + +__Returns:__ + +`str`: The description of the task. ### `DockerComposeTask.get_env_map` @@ -615,8 +653,14 @@ __Returns:__ ### `DockerComposeTask.get_icon` -No documentation available. +Retrieves the icon identifier of the current task. + +This method is used to get the icon associated with the task, which can be utilized for +visual representation in user interfaces or documentation. +__Returns:__ + +`str`: A string representing the icon identifier for the task ### `DockerComposeTask.get_input_map` @@ -630,12 +674,28 @@ No documentation available. ### `DockerComposeTask.inject_env_files` -No documentation available. +Injects additional `EnvFile` into the task. + +Example: +```python +from zrb import Task +class MyTask(Task): + def inject_env_files(self): + self.add_env_files(EnvFile(path='config.env')) +``` ### `DockerComposeTask.inject_envs` -No documentation available. +Injects environment variables into the task. + +Example: +```python +from zrb import Task +class MyTask(Task): + def inject_envs(self): + self.add_envs(Env(name='DATABASE_URL')) +``` ### `DockerComposeTask.inject_inputs` diff --git a/docs/concepts/tasks/flow-task.md b/docs/concepts/tasks/flow-task.md index df366ef5..b874f398 100644 --- a/docs/concepts/tasks/flow-task.md +++ b/docs/concepts/tasks/flow-task.md @@ -164,18 +164,36 @@ No documentation available. ### `FlowTask._get_env_files` -No documentation available. +Retrieves the list of environment variable files associated with the task. + +Intended for internal use, this method returns a list of `EnvFile` instances that the task +uses to load environment variables, primarily for setup and configuration purposes. + +__Returns:__ +`List[EnvFile]`: A list of `EnvFile` instances associated with the task. ### `FlowTask._get_envs` -No documentation available. +Retrieves the list of environment variables set for the task. +For internal use, this method returns a list of `Env` instances representing the environment variables +configured for the task, essential for understanding and debugging the task's environment setup. + +__Returns:__ + +`List[Env]`: A list of `Env` instances representing the environment variables of the task. ### `FlowTask._get_full_cli_name` -No documentation available. +Retrieves the full command-line interface (CLI) name of the task. + +Intended for internal use, this method provides the complete CLI name, including any +prefixes or namespaces, used primarily for logging or debugging purposes. + +__Returns:__ +`str`: The full CLI name of the task. ### `FlowTask._get_inputs` @@ -279,8 +297,10 @@ __Arguments:__ ### `FlowTask._set_has_cli_interface` -No documentation available. +Marks the task as having a CLI interface. +This internal method is used to indicate that the task is accessible and executable through a CLI, +enabling the task system to appropriately handle its CLI interactions. ### `FlowTask._set_input_map` @@ -466,18 +486,36 @@ copied_task.set_name('new_name') ### `FlowTask.get_cli_name` -No documentation available. +Gets the command-line interface (CLI) name of the task. + +This method returns the name used to invoke the task via a CLI, facilitating integration with command-line tools +or scripts. + +__Returns:__ +`str`: The CLI name of the task. ### `FlowTask.get_color` -No documentation available. +Retrieves the color associated with the current task. + +This method returns the color of the task, useful for visual differentiation, priority indication, +or categorization in user interfaces or documentation. +__Returns:__ + +`str`: A string representing the color assigned to the task. ### `FlowTask.get_description` -No documentation available. +Fetches the current description of the task. +This method is used to obtain the detailed description of the task, providing insights into its purpose, +functionality, and usage within the task management system. + +__Returns:__ + +`str`: The description of the task. ### `FlowTask.get_env_map` @@ -498,8 +536,14 @@ __Returns:__ ### `FlowTask.get_icon` -No documentation available. +Retrieves the icon identifier of the current task. + +This method is used to get the icon associated with the task, which can be utilized for +visual representation in user interfaces or documentation. +__Returns:__ + +`str`: A string representing the icon identifier for the task ### `FlowTask.get_input_map` @@ -513,12 +557,28 @@ No documentation available. ### `FlowTask.inject_env_files` -No documentation available. +Injects additional `EnvFile` into the task. + +Example: +```python +from zrb import Task +class MyTask(Task): + def inject_env_files(self): + self.add_env_files(EnvFile(path='config.env')) +``` ### `FlowTask.inject_envs` -No documentation available. +Injects environment variables into the task. + +Example: +```python +from zrb import Task +class MyTask(Task): + def inject_envs(self): + self.add_envs(Env(name='DATABASE_URL')) +``` ### `FlowTask.inject_inputs` diff --git a/docs/concepts/tasks/remote-cmd-task.md b/docs/concepts/tasks/remote-cmd-task.md index 906fb2e5..ba6b47ad 100644 --- a/docs/concepts/tasks/remote-cmd-task.md +++ b/docs/concepts/tasks/remote-cmd-task.md @@ -144,18 +144,36 @@ No documentation available. ### `RemoteCmdTask._get_env_files` -No documentation available. +Retrieves the list of environment variable files associated with the task. + +Intended for internal use, this method returns a list of `EnvFile` instances that the task +uses to load environment variables, primarily for setup and configuration purposes. + +__Returns:__ +`List[EnvFile]`: A list of `EnvFile` instances associated with the task. ### `RemoteCmdTask._get_envs` -No documentation available. +Retrieves the list of environment variables set for the task. +For internal use, this method returns a list of `Env` instances representing the environment variables +configured for the task, essential for understanding and debugging the task's environment setup. + +__Returns:__ + +`List[Env]`: A list of `Env` instances representing the environment variables of the task. ### `RemoteCmdTask._get_full_cli_name` -No documentation available. +Retrieves the full command-line interface (CLI) name of the task. + +Intended for internal use, this method provides the complete CLI name, including any +prefixes or namespaces, used primarily for logging or debugging purposes. + +__Returns:__ +`str`: The full CLI name of the task. ### `RemoteCmdTask._get_inputs` @@ -259,8 +277,10 @@ __Arguments:__ ### `RemoteCmdTask._set_has_cli_interface` -No documentation available. +Marks the task as having a CLI interface. +This internal method is used to indicate that the task is accessible and executable through a CLI, +enabling the task system to appropriately handle its CLI interactions. ### `RemoteCmdTask._set_input_map` @@ -441,18 +461,36 @@ copied_task.set_name('new_name') ### `RemoteCmdTask.get_cli_name` -No documentation available. +Gets the command-line interface (CLI) name of the task. + +This method returns the name used to invoke the task via a CLI, facilitating integration with command-line tools +or scripts. + +__Returns:__ +`str`: The CLI name of the task. ### `RemoteCmdTask.get_color` -No documentation available. +Retrieves the color associated with the current task. + +This method returns the color of the task, useful for visual differentiation, priority indication, +or categorization in user interfaces or documentation. +__Returns:__ + +`str`: A string representing the color assigned to the task. ### `RemoteCmdTask.get_description` -No documentation available. +Fetches the current description of the task. +This method is used to obtain the detailed description of the task, providing insights into its purpose, +functionality, and usage within the task management system. + +__Returns:__ + +`str`: The description of the task. ### `RemoteCmdTask.get_env_map` @@ -473,8 +511,14 @@ __Returns:__ ### `RemoteCmdTask.get_icon` -No documentation available. +Retrieves the icon identifier of the current task. + +This method is used to get the icon associated with the task, which can be utilized for +visual representation in user interfaces or documentation. +__Returns:__ + +`str`: A string representing the icon identifier for the task ### `RemoteCmdTask.get_input_map` @@ -488,12 +532,28 @@ No documentation available. ### `RemoteCmdTask.inject_env_files` -No documentation available. +Injects additional `EnvFile` into the task. + +Example: +```python +from zrb import Task +class MyTask(Task): + def inject_env_files(self): + self.add_env_files(EnvFile(path='config.env')) +``` ### `RemoteCmdTask.inject_envs` -No documentation available. +Injects environment variables into the task. + +Example: +```python +from zrb import Task +class MyTask(Task): + def inject_envs(self): + self.add_envs(Env(name='DATABASE_URL')) +``` ### `RemoteCmdTask.inject_inputs` diff --git a/docs/concepts/tasks/resource-maker.md b/docs/concepts/tasks/resource-maker.md index 20bd8c80..34ea1f46 100644 --- a/docs/concepts/tasks/resource-maker.md +++ b/docs/concepts/tasks/resource-maker.md @@ -171,18 +171,36 @@ No documentation available. ### `ResourceMaker._get_env_files` -No documentation available. +Retrieves the list of environment variable files associated with the task. + +Intended for internal use, this method returns a list of `EnvFile` instances that the task +uses to load environment variables, primarily for setup and configuration purposes. + +__Returns:__ +`List[EnvFile]`: A list of `EnvFile` instances associated with the task. ### `ResourceMaker._get_envs` -No documentation available. +Retrieves the list of environment variables set for the task. +For internal use, this method returns a list of `Env` instances representing the environment variables +configured for the task, essential for understanding and debugging the task's environment setup. + +__Returns:__ + +`List[Env]`: A list of `Env` instances representing the environment variables of the task. ### `ResourceMaker._get_full_cli_name` -No documentation available. +Retrieves the full command-line interface (CLI) name of the task. + +Intended for internal use, this method provides the complete CLI name, including any +prefixes or namespaces, used primarily for logging or debugging purposes. + +__Returns:__ +`str`: The full CLI name of the task. ### `ResourceMaker._get_inputs` @@ -286,8 +304,10 @@ __Arguments:__ ### `ResourceMaker._set_has_cli_interface` -No documentation available. +Marks the task as having a CLI interface. +This internal method is used to indicate that the task is accessible and executable through a CLI, +enabling the task system to appropriately handle its CLI interactions. ### `ResourceMaker._set_input_map` @@ -473,18 +493,36 @@ copied_task.set_name('new_name') ### `ResourceMaker.get_cli_name` -No documentation available. +Gets the command-line interface (CLI) name of the task. + +This method returns the name used to invoke the task via a CLI, facilitating integration with command-line tools +or scripts. + +__Returns:__ +`str`: The CLI name of the task. ### `ResourceMaker.get_color` -No documentation available. +Retrieves the color associated with the current task. + +This method returns the color of the task, useful for visual differentiation, priority indication, +or categorization in user interfaces or documentation. +__Returns:__ + +`str`: A string representing the color assigned to the task. ### `ResourceMaker.get_description` -No documentation available. +Fetches the current description of the task. +This method is used to obtain the detailed description of the task, providing insights into its purpose, +functionality, and usage within the task management system. + +__Returns:__ + +`str`: The description of the task. ### `ResourceMaker.get_env_map` @@ -505,8 +543,14 @@ __Returns:__ ### `ResourceMaker.get_icon` -No documentation available. +Retrieves the icon identifier of the current task. + +This method is used to get the icon associated with the task, which can be utilized for +visual representation in user interfaces or documentation. +__Returns:__ + +`str`: A string representing the icon identifier for the task ### `ResourceMaker.get_input_map` @@ -520,12 +564,28 @@ No documentation available. ### `ResourceMaker.inject_env_files` -No documentation available. +Injects additional `EnvFile` into the task. + +Example: +```python +from zrb import Task +class MyTask(Task): + def inject_env_files(self): + self.add_env_files(EnvFile(path='config.env')) +``` ### `ResourceMaker.inject_envs` -No documentation available. +Injects environment variables into the task. + +Example: +```python +from zrb import Task +class MyTask(Task): + def inject_envs(self): + self.add_envs(Env(name='DATABASE_URL')) +``` ### `ResourceMaker.inject_inputs` diff --git a/docs/concepts/tasks/rsync-task.md b/docs/concepts/tasks/rsync-task.md index 0c59b240..66c07646 100644 --- a/docs/concepts/tasks/rsync-task.md +++ b/docs/concepts/tasks/rsync-task.md @@ -170,18 +170,36 @@ No documentation available. ### `RsyncTask._get_env_files` -No documentation available. +Retrieves the list of environment variable files associated with the task. + +Intended for internal use, this method returns a list of `EnvFile` instances that the task +uses to load environment variables, primarily for setup and configuration purposes. + +__Returns:__ +`List[EnvFile]`: A list of `EnvFile` instances associated with the task. ### `RsyncTask._get_envs` -No documentation available. +Retrieves the list of environment variables set for the task. +For internal use, this method returns a list of `Env` instances representing the environment variables +configured for the task, essential for understanding and debugging the task's environment setup. + +__Returns:__ + +`List[Env]`: A list of `Env` instances representing the environment variables of the task. ### `RsyncTask._get_full_cli_name` -No documentation available. +Retrieves the full command-line interface (CLI) name of the task. + +Intended for internal use, this method provides the complete CLI name, including any +prefixes or namespaces, used primarily for logging or debugging purposes. + +__Returns:__ +`str`: The full CLI name of the task. ### `RsyncTask._get_inputs` @@ -290,8 +308,10 @@ __Arguments:__ ### `RsyncTask._set_has_cli_interface` -No documentation available. +Marks the task as having a CLI interface. +This internal method is used to indicate that the task is accessible and executable through a CLI, +enabling the task system to appropriately handle its CLI interactions. ### `RsyncTask._set_input_map` @@ -472,18 +492,36 @@ copied_task.set_name('new_name') ### `RsyncTask.get_cli_name` -No documentation available. +Gets the command-line interface (CLI) name of the task. + +This method returns the name used to invoke the task via a CLI, facilitating integration with command-line tools +or scripts. + +__Returns:__ +`str`: The CLI name of the task. ### `RsyncTask.get_color` -No documentation available. +Retrieves the color associated with the current task. + +This method returns the color of the task, useful for visual differentiation, priority indication, +or categorization in user interfaces or documentation. +__Returns:__ + +`str`: A string representing the color assigned to the task. ### `RsyncTask.get_description` -No documentation available. +Fetches the current description of the task. +This method is used to obtain the detailed description of the task, providing insights into its purpose, +functionality, and usage within the task management system. + +__Returns:__ + +`str`: The description of the task. ### `RsyncTask.get_env_map` @@ -504,8 +542,14 @@ __Returns:__ ### `RsyncTask.get_icon` -No documentation available. +Retrieves the icon identifier of the current task. + +This method is used to get the icon associated with the task, which can be utilized for +visual representation in user interfaces or documentation. +__Returns:__ + +`str`: A string representing the icon identifier for the task ### `RsyncTask.get_input_map` @@ -519,12 +563,28 @@ No documentation available. ### `RsyncTask.inject_env_files` -No documentation available. +Injects additional `EnvFile` into the task. + +Example: +```python +from zrb import Task +class MyTask(Task): + def inject_env_files(self): + self.add_env_files(EnvFile(path='config.env')) +``` ### `RsyncTask.inject_envs` -No documentation available. +Injects environment variables into the task. + +Example: +```python +from zrb import Task +class MyTask(Task): + def inject_envs(self): + self.add_envs(Env(name='DATABASE_URL')) +``` ### `RsyncTask.inject_inputs` diff --git a/src/zrb/task/any_task.py b/src/zrb/task/any_task.py index 9d2a9bee..5aa81dbf 100644 --- a/src/zrb/task/any_task.py +++ b/src/zrb/task/any_task.py @@ -548,42 +548,129 @@ def get_execution_id(self) -> str: @abstractmethod def get_icon(self) -> str: + ''' + Retrieves the icon identifier of the current task. + + This method is used to get the icon associated with the task, which can be utilized for + visual representation in user interfaces or documentation. + + Returns: + str: A string representing the icon identifier for the task + ''' pass @abstractmethod def get_color(self) -> str: + ''' + Retrieves the color associated with the current task. + + This method returns the color of the task, useful for visual differentiation, priority indication, + or categorization in user interfaces or documentation. + + Returns: + str: A string representing the color assigned to the task. + ''' pass @abstractmethod def get_description(self) -> str: + ''' + Fetches the current description of the task. + + This method is used to obtain the detailed description of the task, providing insights into its purpose, + functionality, and usage within the task management system. + + Returns: + str: The description of the task. + ''' pass @abstractmethod def get_cli_name(self) -> str: + ''' + Gets the command-line interface (CLI) name of the task. + + This method returns the name used to invoke the task via a CLI, facilitating integration with command-line tools + or scripts. + + Returns: + str: The CLI name of the task. + ''' pass @abstractmethod def _get_full_cli_name(self) -> str: + ''' + Retrieves the full command-line interface (CLI) name of the task. + + Intended for internal use, this method provides the complete CLI name, including any + prefixes or namespaces, used primarily for logging or debugging purposes. + + Returns: + str: The full CLI name of the task. + ''' pass @abstractmethod def _set_has_cli_interface(self): + ''' + Marks the task as having a CLI interface. + + This internal method is used to indicate that the task is accessible and executable through a CLI, + enabling the task system to appropriately handle its CLI interactions. + ''' pass @abstractmethod def inject_env_files(self): + ''' + Injects additional `EnvFile` into the task. + + Example: + >>> from zrb import Task + >>> class MyTask(Task): + >>> def inject_env_files(self): + >>> self.add_env_files(EnvFile(path='config.env')) + ''' pass @abstractmethod def _get_env_files(self) -> List[EnvFile]: + ''' + Retrieves the list of environment variable files associated with the task. + + Intended for internal use, this method returns a list of `EnvFile` instances that the task + uses to load environment variables, primarily for setup and configuration purposes. + + Returns: + List[EnvFile]: A list of `EnvFile` instances associated with the task. + ''' pass @abstractmethod def inject_envs(self): + ''' + Injects environment variables into the task. + + Example: + >>> from zrb import Task + >>> class MyTask(Task): + >>> def inject_envs(self): + >>> self.add_envs(Env(name='DATABASE_URL')) + ''' pass @abstractmethod def _get_envs(self) -> List[Env]: + ''' + Retrieves the list of environment variables set for the task. + + For internal use, this method returns a list of `Env` instances representing the environment variables + configured for the task, essential for understanding and debugging the task's environment setup. + + Returns: + List[Env]: A list of `Env` instances representing the environment variables of the task. + ''' pass @abstractmethod From 07ecf2012e99b010583a6d72c41c2c1bbd6509d9 Mon Sep 17 00:00:00 2001 From: goFrendiAsgard Date: Sat, 9 Dec 2023 16:05:36 +0700 Subject: [PATCH 05/13] more doc string --- docs/concepts/tasks/README.md | 78 +++++++++++++++++++-- docs/concepts/tasks/checkers.md | 69 +++++++++++++++++-- docs/concepts/tasks/cmd-task.md | 69 +++++++++++++++++-- docs/concepts/tasks/docker-compose-task.md | 69 +++++++++++++++++-- docs/concepts/tasks/flow-task.md | 69 +++++++++++++++++-- docs/concepts/tasks/remote-cmd-task.md | 69 +++++++++++++++++-- docs/concepts/tasks/resource-maker.md | 69 +++++++++++++++++-- docs/concepts/tasks/rsync-task.md | 69 +++++++++++++++++-- src/zrb/task/any_task.py | 79 ++++++++++++++++++++++ 9 files changed, 591 insertions(+), 49 deletions(-) diff --git a/docs/concepts/tasks/README.md b/docs/concepts/tasks/README.md index 098ae2bc..2306eee9 100644 --- a/docs/concepts/tasks/README.md +++ b/docs/concepts/tasks/README.md @@ -161,13 +161,27 @@ task execution, state transitions, and other functionalities. ### `AnyTask._get_checkers` -No documentation available. +Retrieves the checkers set for the task. + +This internal method returns an iterable of all the checkers that have been added to +the task. It's mainly used for internal logic and debugging to understand the +validations or conditions applied to the task. +__Returns:__ + +`Iterable[TAnyTask]`: An iterable of checkers associated with the task. ### `AnyTask._get_combined_inputs` -No documentation available. +Combines and retrieves all inputs for the task. +This internal method aggregates inputs from various sources (static definition, +`inject_inputs`, etc.) and provides a unified view of all inputs that the task +will process. This is crucial for preparing the task's runtime environment. + +__Returns:__ + +`Iterable[AnyInput]`: An iterable of all combined inputs for the task. ### `AnyTask._get_env_files` @@ -204,13 +218,27 @@ __Returns:__ ### `AnyTask._get_inputs` -No documentation available. +Retrieves the list of inputs associated with the task. + +This internal method is used to obtain all the inputs that have been set for the task, +either through static definition or via the `inject_inputs` method. It's primarily used +for introspection and debugging purposes. +__Returns:__ + +`List[AnyInput]`: A list of `AnyInput` instances representing the inputs for the task. ### `AnyTask._get_upstreams` -No documentation available. +Retrieves the upstream tasks of the current task. + +An internal method to get the list of upstream tasks that have been set for the +task, either statically or through `inject_upstreams`. This is essential for task +scheduling and dependency management. + +__Returns:__ +`Iterable[TAnyTask]`: An iterable of upstream tasks. ### `AnyTask._loop_check` @@ -444,7 +472,19 @@ No documentation available. ### `AnyTask.inject_checkers` -No documentation available. +Injects custom checkers into the task. + +This method allows for the addition of custom validation or condition checkers. These +checkers can be used to verify certain conditions before the task execution proceeds. +Subclasses should implement this method to define task-specific checkers. + +Example: +```python +from zrb import Task +class MyTask(Task): + def inject_checkers(self): + self.add_checker(some_custom_condition_checker) +``` ### `AnyTask.inject_env_files` @@ -475,12 +515,36 @@ class MyTask(Task): ### `AnyTask.inject_inputs` -No documentation available. +Injects custom inputs into the task. + +This method is used to programmatically add input parameters to the task, allowing +dynamic customization of the task's input data. Subclasses should override this method +to define specific inputs that the task should receive. + +Example: +```python +from zrb import Task, Input +class MyTask(Task): + def inject_inputs(self): + self.add_input(Input(name='user_email', type='email')) +``` ### `AnyTask.inject_upstreams` -No documentation available. +Injects upstream tasks into the current task. + +This method is used for programmatically adding upstream dependencies to the task. +Upstream tasks are those that must be completed before the current task starts. +Override this method in subclasses to specify such dependencies. + +Example: +```python +from zrb import Task +class MyTask(Task): + def inject_upstreams(self): + self.add_upstream(another_task) +``` ### `AnyTask.insert_env` diff --git a/docs/concepts/tasks/checkers.md b/docs/concepts/tasks/checkers.md index 3aacbbbe..de29d0df 100644 --- a/docs/concepts/tasks/checkers.md +++ b/docs/concepts/tasks/checkers.md @@ -142,8 +142,15 @@ No documentation available. ### `Checker._get_checkers` -No documentation available. +Retrieves the checkers set for the task. + +This internal method returns an iterable of all the checkers that have been added to +the task. It's mainly used for internal logic and debugging to understand the +validations or conditions applied to the task. +__Returns:__ + +`Iterable[TAnyTask]`: An iterable of checkers associated with the task. ### `Checker._get_combined_env` @@ -195,8 +202,15 @@ __Returns:__ ### `Checker._get_inputs` -No documentation available. +Retrieves the list of inputs associated with the task. +This internal method is used to obtain all the inputs that have been set for the task, +either through static definition or via the `inject_inputs` method. It's primarily used +for introspection and debugging purposes. + +__Returns:__ + +`List[AnyInput]`: A list of `AnyInput` instances representing the inputs for the task. ### `Checker._get_max_attempt` @@ -210,8 +224,15 @@ No documentation available. ### `Checker._get_upstreams` -No documentation available. +Retrieves the upstream tasks of the current task. +An internal method to get the list of upstream tasks that have been set for the +task, either statically or through `inject_upstreams`. This is essential for task +scheduling and dependency management. + +__Returns:__ + +`Iterable[TAnyTask]`: An iterable of upstream tasks. ### `Checker._increase_attempt` @@ -545,7 +566,19 @@ No documentation available. ### `Checker.inject_checkers` -No documentation available. +Injects custom checkers into the task. + +This method allows for the addition of custom validation or condition checkers. These +checkers can be used to verify certain conditions before the task execution proceeds. +Subclasses should implement this method to define task-specific checkers. + +Example: +```python +from zrb import Task +class MyTask(Task): + def inject_checkers(self): + self.add_checker(some_custom_condition_checker) +``` ### `Checker.inject_env_files` @@ -576,12 +609,36 @@ class MyTask(Task): ### `Checker.inject_inputs` -No documentation available. +Injects custom inputs into the task. + +This method is used to programmatically add input parameters to the task, allowing +dynamic customization of the task's input data. Subclasses should override this method +to define specific inputs that the task should receive. + +Example: +```python +from zrb import Task, Input +class MyTask(Task): + def inject_inputs(self): + self.add_input(Input(name='user_email', type='email')) +``` ### `Checker.inject_upstreams` -No documentation available. +Injects upstream tasks into the current task. + +This method is used for programmatically adding upstream dependencies to the task. +Upstream tasks are those that must be completed before the current task starts. +Override this method in subclasses to specify such dependencies. + +Example: +```python +from zrb import Task +class MyTask(Task): + def inject_upstreams(self): + self.add_upstream(another_task) +``` ### `Checker.insert_env` diff --git a/docs/concepts/tasks/cmd-task.md b/docs/concepts/tasks/cmd-task.md index 55c277cd..9f6d7aca 100644 --- a/docs/concepts/tasks/cmd-task.md +++ b/docs/concepts/tasks/cmd-task.md @@ -245,8 +245,15 @@ No documentation available. ### `CmdTask._get_checkers` -No documentation available. +Retrieves the checkers set for the task. + +This internal method returns an iterable of all the checkers that have been added to +the task. It's mainly used for internal logic and debugging to understand the +validations or conditions applied to the task. +__Returns:__ + +`Iterable[TAnyTask]`: An iterable of checkers associated with the task. ### `CmdTask._get_combined_env` @@ -298,8 +305,15 @@ __Returns:__ ### `CmdTask._get_inputs` -No documentation available. +Retrieves the list of inputs associated with the task. +This internal method is used to obtain all the inputs that have been set for the task, +either through static definition or via the `inject_inputs` method. It's primarily used +for introspection and debugging purposes. + +__Returns:__ + +`List[AnyInput]`: A list of `AnyInput` instances representing the inputs for the task. ### `CmdTask._get_max_attempt` @@ -313,8 +327,15 @@ No documentation available. ### `CmdTask._get_upstreams` -No documentation available. +Retrieves the upstream tasks of the current task. +An internal method to get the list of upstream tasks that have been set for the +task, either statically or through `inject_upstreams`. This is essential for task +scheduling and dependency management. + +__Returns:__ + +`Iterable[TAnyTask]`: An iterable of upstream tasks. ### `CmdTask._increase_attempt` @@ -653,7 +674,19 @@ No documentation available. ### `CmdTask.inject_checkers` -No documentation available. +Injects custom checkers into the task. + +This method allows for the addition of custom validation or condition checkers. These +checkers can be used to verify certain conditions before the task execution proceeds. +Subclasses should implement this method to define task-specific checkers. + +Example: +```python +from zrb import Task +class MyTask(Task): + def inject_checkers(self): + self.add_checker(some_custom_condition_checker) +``` ### `CmdTask.inject_env_files` @@ -684,12 +717,36 @@ class MyTask(Task): ### `CmdTask.inject_inputs` -No documentation available. +Injects custom inputs into the task. + +This method is used to programmatically add input parameters to the task, allowing +dynamic customization of the task's input data. Subclasses should override this method +to define specific inputs that the task should receive. + +Example: +```python +from zrb import Task, Input +class MyTask(Task): + def inject_inputs(self): + self.add_input(Input(name='user_email', type='email')) +``` ### `CmdTask.inject_upstreams` -No documentation available. +Injects upstream tasks into the current task. + +This method is used for programmatically adding upstream dependencies to the task. +Upstream tasks are those that must be completed before the current task starts. +Override this method in subclasses to specify such dependencies. + +Example: +```python +from zrb import Task +class MyTask(Task): + def inject_upstreams(self): + self.add_upstream(another_task) +``` ### `CmdTask.insert_env` diff --git a/docs/concepts/tasks/docker-compose-task.md b/docs/concepts/tasks/docker-compose-task.md index 6bccde2c..dd045445 100644 --- a/docs/concepts/tasks/docker-compose-task.md +++ b/docs/concepts/tasks/docker-compose-task.md @@ -261,8 +261,15 @@ No documentation available. ### `DockerComposeTask._get_checkers` -No documentation available. +Retrieves the checkers set for the task. + +This internal method returns an iterable of all the checkers that have been added to +the task. It's mainly used for internal logic and debugging to understand the +validations or conditions applied to the task. +__Returns:__ + +`Iterable[TAnyTask]`: An iterable of checkers associated with the task. ### `DockerComposeTask._get_combined_env` @@ -314,8 +321,15 @@ __Returns:__ ### `DockerComposeTask._get_inputs` -No documentation available. +Retrieves the list of inputs associated with the task. +This internal method is used to obtain all the inputs that have been set for the task, +either through static definition or via the `inject_inputs` method. It's primarily used +for introspection and debugging purposes. + +__Returns:__ + +`List[AnyInput]`: A list of `AnyInput` instances representing the inputs for the task. ### `DockerComposeTask._get_max_attempt` @@ -329,8 +343,15 @@ No documentation available. ### `DockerComposeTask._get_upstreams` -No documentation available. +Retrieves the upstream tasks of the current task. +An internal method to get the list of upstream tasks that have been set for the +task, either statically or through `inject_upstreams`. This is essential for task +scheduling and dependency management. + +__Returns:__ + +`Iterable[TAnyTask]`: An iterable of upstream tasks. ### `DockerComposeTask._increase_attempt` @@ -669,7 +690,19 @@ No documentation available. ### `DockerComposeTask.inject_checkers` -No documentation available. +Injects custom checkers into the task. + +This method allows for the addition of custom validation or condition checkers. These +checkers can be used to verify certain conditions before the task execution proceeds. +Subclasses should implement this method to define task-specific checkers. + +Example: +```python +from zrb import Task +class MyTask(Task): + def inject_checkers(self): + self.add_checker(some_custom_condition_checker) +``` ### `DockerComposeTask.inject_env_files` @@ -700,12 +733,36 @@ class MyTask(Task): ### `DockerComposeTask.inject_inputs` -No documentation available. +Injects custom inputs into the task. + +This method is used to programmatically add input parameters to the task, allowing +dynamic customization of the task's input data. Subclasses should override this method +to define specific inputs that the task should receive. + +Example: +```python +from zrb import Task, Input +class MyTask(Task): + def inject_inputs(self): + self.add_input(Input(name='user_email', type='email')) +``` ### `DockerComposeTask.inject_upstreams` -No documentation available. +Injects upstream tasks into the current task. + +This method is used for programmatically adding upstream dependencies to the task. +Upstream tasks are those that must be completed before the current task starts. +Override this method in subclasses to specify such dependencies. + +Example: +```python +from zrb import Task +class MyTask(Task): + def inject_upstreams(self): + self.add_upstream(another_task) +``` ### `DockerComposeTask.insert_env` diff --git a/docs/concepts/tasks/flow-task.md b/docs/concepts/tasks/flow-task.md index b874f398..7512102d 100644 --- a/docs/concepts/tasks/flow-task.md +++ b/docs/concepts/tasks/flow-task.md @@ -139,8 +139,15 @@ No documentation available. ### `FlowTask._get_checkers` -No documentation available. +Retrieves the checkers set for the task. + +This internal method returns an iterable of all the checkers that have been added to +the task. It's mainly used for internal logic and debugging to understand the +validations or conditions applied to the task. +__Returns:__ + +`Iterable[TAnyTask]`: An iterable of checkers associated with the task. ### `FlowTask._get_combined_env` @@ -197,8 +204,15 @@ __Returns:__ ### `FlowTask._get_inputs` -No documentation available. +Retrieves the list of inputs associated with the task. +This internal method is used to obtain all the inputs that have been set for the task, +either through static definition or via the `inject_inputs` method. It's primarily used +for introspection and debugging purposes. + +__Returns:__ + +`List[AnyInput]`: A list of `AnyInput` instances representing the inputs for the task. ### `FlowTask._get_max_attempt` @@ -212,8 +226,15 @@ No documentation available. ### `FlowTask._get_upstreams` -No documentation available. +Retrieves the upstream tasks of the current task. +An internal method to get the list of upstream tasks that have been set for the +task, either statically or through `inject_upstreams`. This is essential for task +scheduling and dependency management. + +__Returns:__ + +`Iterable[TAnyTask]`: An iterable of upstream tasks. ### `FlowTask._increase_attempt` @@ -552,7 +573,19 @@ No documentation available. ### `FlowTask.inject_checkers` -No documentation available. +Injects custom checkers into the task. + +This method allows for the addition of custom validation or condition checkers. These +checkers can be used to verify certain conditions before the task execution proceeds. +Subclasses should implement this method to define task-specific checkers. + +Example: +```python +from zrb import Task +class MyTask(Task): + def inject_checkers(self): + self.add_checker(some_custom_condition_checker) +``` ### `FlowTask.inject_env_files` @@ -583,12 +616,36 @@ class MyTask(Task): ### `FlowTask.inject_inputs` -No documentation available. +Injects custom inputs into the task. + +This method is used to programmatically add input parameters to the task, allowing +dynamic customization of the task's input data. Subclasses should override this method +to define specific inputs that the task should receive. + +Example: +```python +from zrb import Task, Input +class MyTask(Task): + def inject_inputs(self): + self.add_input(Input(name='user_email', type='email')) +``` ### `FlowTask.inject_upstreams` -No documentation available. +Injects upstream tasks into the current task. + +This method is used for programmatically adding upstream dependencies to the task. +Upstream tasks are those that must be completed before the current task starts. +Override this method in subclasses to specify such dependencies. + +Example: +```python +from zrb import Task +class MyTask(Task): + def inject_upstreams(self): + self.add_upstream(another_task) +``` ### `FlowTask.insert_env` diff --git a/docs/concepts/tasks/remote-cmd-task.md b/docs/concepts/tasks/remote-cmd-task.md index ba6b47ad..01c66280 100644 --- a/docs/concepts/tasks/remote-cmd-task.md +++ b/docs/concepts/tasks/remote-cmd-task.md @@ -124,8 +124,15 @@ No documentation available. ### `RemoteCmdTask._get_checkers` -No documentation available. +Retrieves the checkers set for the task. + +This internal method returns an iterable of all the checkers that have been added to +the task. It's mainly used for internal logic and debugging to understand the +validations or conditions applied to the task. +__Returns:__ + +`Iterable[TAnyTask]`: An iterable of checkers associated with the task. ### `RemoteCmdTask._get_combined_env` @@ -177,8 +184,15 @@ __Returns:__ ### `RemoteCmdTask._get_inputs` -No documentation available. +Retrieves the list of inputs associated with the task. +This internal method is used to obtain all the inputs that have been set for the task, +either through static definition or via the `inject_inputs` method. It's primarily used +for introspection and debugging purposes. + +__Returns:__ + +`List[AnyInput]`: A list of `AnyInput` instances representing the inputs for the task. ### `RemoteCmdTask._get_max_attempt` @@ -192,8 +206,15 @@ No documentation available. ### `RemoteCmdTask._get_upstreams` -No documentation available. +Retrieves the upstream tasks of the current task. +An internal method to get the list of upstream tasks that have been set for the +task, either statically or through `inject_upstreams`. This is essential for task +scheduling and dependency management. + +__Returns:__ + +`Iterable[TAnyTask]`: An iterable of upstream tasks. ### `RemoteCmdTask._increase_attempt` @@ -527,7 +548,19 @@ No documentation available. ### `RemoteCmdTask.inject_checkers` -No documentation available. +Injects custom checkers into the task. + +This method allows for the addition of custom validation or condition checkers. These +checkers can be used to verify certain conditions before the task execution proceeds. +Subclasses should implement this method to define task-specific checkers. + +Example: +```python +from zrb import Task +class MyTask(Task): + def inject_checkers(self): + self.add_checker(some_custom_condition_checker) +``` ### `RemoteCmdTask.inject_env_files` @@ -558,12 +591,36 @@ class MyTask(Task): ### `RemoteCmdTask.inject_inputs` -No documentation available. +Injects custom inputs into the task. + +This method is used to programmatically add input parameters to the task, allowing +dynamic customization of the task's input data. Subclasses should override this method +to define specific inputs that the task should receive. + +Example: +```python +from zrb import Task, Input +class MyTask(Task): + def inject_inputs(self): + self.add_input(Input(name='user_email', type='email')) +``` ### `RemoteCmdTask.inject_upstreams` -No documentation available. +Injects upstream tasks into the current task. + +This method is used for programmatically adding upstream dependencies to the task. +Upstream tasks are those that must be completed before the current task starts. +Override this method in subclasses to specify such dependencies. + +Example: +```python +from zrb import Task +class MyTask(Task): + def inject_upstreams(self): + self.add_upstream(another_task) +``` ### `RemoteCmdTask.insert_env` diff --git a/docs/concepts/tasks/resource-maker.md b/docs/concepts/tasks/resource-maker.md index 34ea1f46..23690f85 100644 --- a/docs/concepts/tasks/resource-maker.md +++ b/docs/concepts/tasks/resource-maker.md @@ -151,8 +151,15 @@ No documentation available. ### `ResourceMaker._get_checkers` -No documentation available. +Retrieves the checkers set for the task. + +This internal method returns an iterable of all the checkers that have been added to +the task. It's mainly used for internal logic and debugging to understand the +validations or conditions applied to the task. +__Returns:__ + +`Iterable[TAnyTask]`: An iterable of checkers associated with the task. ### `ResourceMaker._get_combined_env` @@ -204,8 +211,15 @@ __Returns:__ ### `ResourceMaker._get_inputs` -No documentation available. +Retrieves the list of inputs associated with the task. +This internal method is used to obtain all the inputs that have been set for the task, +either through static definition or via the `inject_inputs` method. It's primarily used +for introspection and debugging purposes. + +__Returns:__ + +`List[AnyInput]`: A list of `AnyInput` instances representing the inputs for the task. ### `ResourceMaker._get_max_attempt` @@ -219,8 +233,15 @@ No documentation available. ### `ResourceMaker._get_upstreams` -No documentation available. +Retrieves the upstream tasks of the current task. +An internal method to get the list of upstream tasks that have been set for the +task, either statically or through `inject_upstreams`. This is essential for task +scheduling and dependency management. + +__Returns:__ + +`Iterable[TAnyTask]`: An iterable of upstream tasks. ### `ResourceMaker._increase_attempt` @@ -559,7 +580,19 @@ No documentation available. ### `ResourceMaker.inject_checkers` -No documentation available. +Injects custom checkers into the task. + +This method allows for the addition of custom validation or condition checkers. These +checkers can be used to verify certain conditions before the task execution proceeds. +Subclasses should implement this method to define task-specific checkers. + +Example: +```python +from zrb import Task +class MyTask(Task): + def inject_checkers(self): + self.add_checker(some_custom_condition_checker) +``` ### `ResourceMaker.inject_env_files` @@ -590,12 +623,36 @@ class MyTask(Task): ### `ResourceMaker.inject_inputs` -No documentation available. +Injects custom inputs into the task. + +This method is used to programmatically add input parameters to the task, allowing +dynamic customization of the task's input data. Subclasses should override this method +to define specific inputs that the task should receive. + +Example: +```python +from zrb import Task, Input +class MyTask(Task): + def inject_inputs(self): + self.add_input(Input(name='user_email', type='email')) +``` ### `ResourceMaker.inject_upstreams` -No documentation available. +Injects upstream tasks into the current task. + +This method is used for programmatically adding upstream dependencies to the task. +Upstream tasks are those that must be completed before the current task starts. +Override this method in subclasses to specify such dependencies. + +Example: +```python +from zrb import Task +class MyTask(Task): + def inject_upstreams(self): + self.add_upstream(another_task) +``` ### `ResourceMaker.insert_env` diff --git a/docs/concepts/tasks/rsync-task.md b/docs/concepts/tasks/rsync-task.md index 66c07646..93031768 100644 --- a/docs/concepts/tasks/rsync-task.md +++ b/docs/concepts/tasks/rsync-task.md @@ -150,8 +150,15 @@ No documentation available. ### `RsyncTask._get_checkers` -No documentation available. +Retrieves the checkers set for the task. + +This internal method returns an iterable of all the checkers that have been added to +the task. It's mainly used for internal logic and debugging to understand the +validations or conditions applied to the task. +__Returns:__ + +`Iterable[TAnyTask]`: An iterable of checkers associated with the task. ### `RsyncTask._get_combined_env` @@ -203,8 +210,15 @@ __Returns:__ ### `RsyncTask._get_inputs` -No documentation available. +Retrieves the list of inputs associated with the task. +This internal method is used to obtain all the inputs that have been set for the task, +either through static definition or via the `inject_inputs` method. It's primarily used +for introspection and debugging purposes. + +__Returns:__ + +`List[AnyInput]`: A list of `AnyInput` instances representing the inputs for the task. ### `RsyncTask._get_max_attempt` @@ -223,8 +237,15 @@ No documentation available. ### `RsyncTask._get_upstreams` -No documentation available. +Retrieves the upstream tasks of the current task. +An internal method to get the list of upstream tasks that have been set for the +task, either statically or through `inject_upstreams`. This is essential for task +scheduling and dependency management. + +__Returns:__ + +`Iterable[TAnyTask]`: An iterable of upstream tasks. ### `RsyncTask._increase_attempt` @@ -558,7 +579,19 @@ No documentation available. ### `RsyncTask.inject_checkers` -No documentation available. +Injects custom checkers into the task. + +This method allows for the addition of custom validation or condition checkers. These +checkers can be used to verify certain conditions before the task execution proceeds. +Subclasses should implement this method to define task-specific checkers. + +Example: +```python +from zrb import Task +class MyTask(Task): + def inject_checkers(self): + self.add_checker(some_custom_condition_checker) +``` ### `RsyncTask.inject_env_files` @@ -589,12 +622,36 @@ class MyTask(Task): ### `RsyncTask.inject_inputs` -No documentation available. +Injects custom inputs into the task. + +This method is used to programmatically add input parameters to the task, allowing +dynamic customization of the task's input data. Subclasses should override this method +to define specific inputs that the task should receive. + +Example: +```python +from zrb import Task, Input +class MyTask(Task): + def inject_inputs(self): + self.add_input(Input(name='user_email', type='email')) +``` ### `RsyncTask.inject_upstreams` -No documentation available. +Injects upstream tasks into the current task. + +This method is used for programmatically adding upstream dependencies to the task. +Upstream tasks are those that must be completed before the current task starts. +Override this method in subclasses to specify such dependencies. + +Example: +```python +from zrb import Task +class MyTask(Task): + def inject_upstreams(self): + self.add_upstream(another_task) +``` ### `RsyncTask.insert_env` diff --git a/src/zrb/task/any_task.py b/src/zrb/task/any_task.py index 5aa81dbf..ec6c57ed 100644 --- a/src/zrb/task/any_task.py +++ b/src/zrb/task/any_task.py @@ -675,30 +675,109 @@ def _get_envs(self) -> List[Env]: @abstractmethod def inject_inputs(self): + ''' + Injects custom inputs into the task. + + This method is used to programmatically add input parameters to the task, allowing + dynamic customization of the task's input data. Subclasses should override this method + to define specific inputs that the task should receive. + + Example: + >>> from zrb import Task, Input + >>> class MyTask(Task): + >>> def inject_inputs(self): + >>> self.add_input(Input(name='user_email', type='email')) + ''' pass @abstractmethod def _get_inputs(self) -> List[AnyInput]: + ''' + Retrieves the list of inputs associated with the task. + + This internal method is used to obtain all the inputs that have been set for the task, + either through static definition or via the `inject_inputs` method. It's primarily used + for introspection and debugging purposes. + + Returns: + List[AnyInput]: A list of `AnyInput` instances representing the inputs for the task. + ''' pass @abstractmethod def inject_checkers(self): + ''' + Injects custom checkers into the task. + + This method allows for the addition of custom validation or condition checkers. These + checkers can be used to verify certain conditions before the task execution proceeds. + Subclasses should implement this method to define task-specific checkers. + + Example: + >>> from zrb import Task + >>> class MyTask(Task): + >>> def inject_checkers(self): + >>> self.add_checker(some_custom_condition_checker) + ''' pass @abstractmethod def _get_checkers(self) -> Iterable[TAnyTask]: + ''' + Retrieves the checkers set for the task. + + This internal method returns an iterable of all the checkers that have been added to + the task. It's mainly used for internal logic and debugging to understand the + validations or conditions applied to the task. + + Returns: + Iterable[TAnyTask]: An iterable of checkers associated with the task. + ''' pass @abstractmethod def inject_upstreams(self): + ''' + Injects upstream tasks into the current task. + + This method is used for programmatically adding upstream dependencies to the task. + Upstream tasks are those that must be completed before the current task starts. + Override this method in subclasses to specify such dependencies. + + Example: + >>> from zrb import Task + >>> class MyTask(Task): + >>> def inject_upstreams(self): + >>> self.add_upstream(another_task) + ''' pass @abstractmethod def _get_upstreams(self) -> Iterable[TAnyTask]: + ''' + Retrieves the upstream tasks of the current task. + + An internal method to get the list of upstream tasks that have been set for the + task, either statically or through `inject_upstreams`. This is essential for task + scheduling and dependency management. + + Returns: + Iterable[TAnyTask]: An iterable of upstream tasks. + ''' pass @abstractmethod def _get_combined_inputs(self) -> Iterable[AnyInput]: + ''' + Combines and retrieves all inputs for the task. + + This internal method aggregates inputs from various sources (static definition, + `inject_inputs`, etc.) and provides a unified view of all inputs that the task + will process. This is crucial for preparing the task's runtime environment. + + Returns: + Iterable[AnyInput]: An iterable of all combined inputs for the task. + ''' pass @abstractmethod From 82252ecc83ad39ded21f234d3940b1c3acb38cb1 Mon Sep 17 00:00:00 2001 From: goFrendiAsgard Date: Sat, 9 Dec 2023 18:01:53 +0700 Subject: [PATCH 06/13] update docs --- docs/concepts/task-group.md | 51 +++++++- helper/doc.py | 124 +------------------ src/zrb/action/runner.py | 7 +- src/zrb/helper/docstring.py | 122 ++++++++++++++++++ src/zrb/task/any_task.py | 12 +- src/zrb/task/base_task/base_task.py | 4 +- src/zrb/task/base_task/component/renderer.py | 68 +++++----- src/zrb/task_env/env.py | 9 +- src/zrb/task_env/env_file.py | 7 +- src/zrb/task_group/group.py | 61 +++++++-- 10 files changed, 282 insertions(+), 183 deletions(-) create mode 100644 src/zrb/helper/docstring.py diff --git a/docs/concepts/task-group.md b/docs/concepts/task-group.md index d963ce4e..c5e9248b 100644 --- a/docs/concepts/task-group.md +++ b/docs/concepts/task-group.md @@ -49,7 +49,7 @@ print(group.get_tasks()) ``` ``` -[, ] +[, ] ``` @@ -98,7 +98,7 @@ print(group.get_children()) ``` ``` -[, ] +[, ] ``` @@ -125,6 +125,51 @@ my-system ``` +### `Group.get_description` + +Retrieves group description. + +__Returns:__ + +`str`: Description of the group. + +__Examples:__ + +```python +from zrb import Group +group = Group(name='group', description='description of the group') +print(group.get_description()) +``` + +``` +description of the group +``` + + +### `Group.get_parent` + +Retrieves parent of the Group. + +__Returns:__ + +`Optional[Group]`: Parent of the group. + +__Examples:__ + +```python +from zrb import Group +system_group = Group(name='my system') +system_log_group = Group(name='log', parent=system_group) +print(system_group.get_parent()) +print(system_log_group.get_parent()) +``` + +``` +None + +``` + + ### `Group.get_tasks` Get direct Tasks under this Task Group. @@ -144,7 +189,7 @@ print(group.get_tasks()) ``` ``` -[, ] +[, ] ``` diff --git a/helper/doc.py b/helper/doc.py index 94a85738..fdb2174f 100644 --- a/helper/doc.py +++ b/helper/doc.py @@ -1,9 +1,9 @@ -import inspect +from zrb.helper.docstring import get_markdown_from_docstring import re def inject_doc(markdown_file_name: str, cls): - docstring_markdown = docstring_to_markdown(cls) + docstring_markdown = get_markdown_from_docstring(cls) with open(markdown_file_name, 'r') as file: original_content = file.read() pattern = r'.*?' @@ -17,123 +17,3 @@ def inject_doc(markdown_file_name: str, cls): ) with open(markdown_file_name, 'w') as file: file.write(new_content) - - -def docstring_to_markdown(cls) -> str: - """ - Convert Google Style docstrings of a class and its methods to Markdown. - - Args: - cls (class): The class whose docstrings are to be converted. - - Returns: - str: The converted Markdown text. - """ - markdown = f"## `{cls.__name__}`\n\n" - cls_doc = get_doc(cls) - markdown += parse_docstring(cls_doc) + '\n' - for method_name, _ in inspect.getmembers(cls, predicate=inspect.isfunction): # noqa - if method_name.startswith('__'): - # Don't parse private or protected function - continue - markdown += f"\n### `{cls.__name__}.{method_name}`\n\n" - method_doc = get_method_doc(cls, method_name) - markdown += parse_docstring(method_doc) + '\n' - return markdown - - -def get_method_doc(cls, method_name: str) -> str: - if not hasattr(cls, method_name): - return None - method = getattr(cls, method_name) - if not method.__doc__ and hasattr(cls, '__bases__'): - for parent in cls.__bases__: - parent_method_doc = get_method_doc(parent, method_name) - if parent_method_doc: - return parent_method_doc - return method.__doc__ - - -def get_doc(cls) -> str: - if not cls.__doc__ and hasattr(cls, '__bases__'): - for parent in cls.__bases__: - parent_doc = get_doc(parent) - if parent_doc: - return parent_doc - return cls.__doc__ - - -def parse_docstring(docstring: str) -> str: - if not docstring: - return 'No documentation available.\n' - # Split the docstring into lines - lines = docstring.strip().split('\n') - line_length = len(lines) - # Process each line - markdown_lines = [] - section = '' - is_previous_code = False - has_unclosed_backtick = False - for line_index, line in enumerate(lines): - line = line.strip() - is_code = line.startswith('>>> ') - is_last_line = line_index == line_length - 1 - is_new_section = False - # Add code backticks - if is_code and not is_previous_code: - markdown_lines.append('```python') - has_unclosed_backtick = True - elif section == 'examples' and is_previous_code and not is_code: - markdown_lines.append('```') - markdown_lines.append('') - markdown_lines.append('```') - has_unclosed_backtick = True - elif is_previous_code and not is_code: - markdown_lines.append('````') - markdown_lines.append('') - has_unclosed_backtick = False - # Handle lines - if is_code: - markdown_lines.append(line[4:]) - elif line.startswith('Attributes:'): - markdown_lines.append('__Attributes:__\n') - section = 'attributes' - is_new_section = True - elif line.startswith('Args:'): - markdown_lines.append('__Arguments:__\n') - section = 'args' - is_new_section = True - elif line.startswith('Returns:'): - markdown_lines.append('__Returns:__\n') - section = 'returns' - is_new_section = True - elif line.startswith('Examples:'): - markdown_lines.append('__Examples:__\n') - section = 'examples' - is_new_section = True - elif line == '```': - markdown_lines.append(line) - elif section == 'args' or section == 'attributes': - named_param_match = re.match(r'^(\w+)\s+\((.+)\):(.+)$', line) - if named_param_match: - param_name, param_type, param_desc = named_param_match.groups() - markdown_lines.append( - f'- `{param_name}` (`{param_type}`): {param_desc.strip()}' - ) - else: - markdown_lines.append(line) - elif section == 'returns': - return_match = re.match(r'^(.+):(.+)$', line) - if return_match: - param_type, param_desc = return_match.groups() - markdown_lines.append(f'`{param_type}`: {param_desc.strip()}') - else: - markdown_lines.append(line) - else: - markdown_lines.append(line) - is_previous_code = is_code - if (is_new_section or is_last_line) and has_unclosed_backtick: - markdown_lines.append('```') - markdown_lines.append('') - has_unclosed_backtick = False - return '\n'.join(markdown_lines) diff --git a/src/zrb/action/runner.py b/src/zrb/action/runner.py index 4fcfe7b5..b01ca527 100644 --- a/src/zrb/action/runner.py +++ b/src/zrb/action/runner.py @@ -59,10 +59,11 @@ def __create_cli_subcommand( task_group = task._group while task_group is not None: group = self.__register_sub_command(task_group, subcommand) - if task_group._parent is None: + parent_group = task_group.get_parent() + if parent_group is None: return group subcommand = group - task_group = task_group._parent + task_group = parent_group return subcommand def __register_sub_command( @@ -82,7 +83,7 @@ def __get_cli_group(self, task_group: TaskGroup) -> click.Group: if task_group_id in self.__registered_groups: return self.__registered_groups[task_group_id] group_cli_name = task_group.get_cli_name() - group_description = task_group._description + group_description = task_group.get_description() group = click.Group(name=group_cli_name, help=group_description) self.__registered_groups[task_group_id] = group return group diff --git a/src/zrb/helper/docstring.py b/src/zrb/helper/docstring.py new file mode 100644 index 00000000..4457060b --- /dev/null +++ b/src/zrb/helper/docstring.py @@ -0,0 +1,122 @@ +import inspect +import re + + +def get_markdown_from_docstring(cls) -> str: + """ + Convert Google Style docstrings of a class and its methods to Markdown. + + Args: + cls (class): The class whose docstrings are to be converted. + + Returns: + str: The converted Markdown text. + """ + markdown = f"## `{cls.__name__}`\n\n" + cls_doc = get_doc(cls) + markdown += parse_docstring(cls_doc) + '\n' + for method_name, _ in inspect.getmembers(cls, predicate=inspect.isfunction): # noqa + if method_name.startswith('__'): + # Don't parse private or protected function + continue + markdown += f"\n### `{cls.__name__}.{method_name}`\n\n" + method_doc = get_method_doc(cls, method_name) + markdown += parse_docstring(method_doc) + '\n' + return markdown + + +def get_method_doc(cls, method_name: str) -> str: + if not hasattr(cls, method_name): + return None + method = getattr(cls, method_name) + if not method.__doc__ and hasattr(cls, '__bases__'): + for parent in cls.__bases__: + parent_method_doc = get_method_doc(parent, method_name) + if parent_method_doc: + return parent_method_doc + return method.__doc__ + + +def get_doc(cls) -> str: + if not cls.__doc__ and hasattr(cls, '__bases__'): + for parent in cls.__bases__: + parent_doc = get_doc(parent) + if parent_doc: + return parent_doc + return cls.__doc__ + + +def parse_docstring(docstring: str) -> str: + if not docstring: + return 'No documentation available.\n' + # Split the docstring into lines + lines = docstring.strip().split('\n') + line_length = len(lines) + # Process each line + markdown_lines = [] + section = '' + is_previous_code = False + has_unclosed_backtick = False + for line_index, line in enumerate(lines): + line = line.strip() + is_code = line.startswith('>>> ') + is_last_line = line_index == line_length - 1 + is_new_section = False + # Add code backticks + if is_code and not is_previous_code: + markdown_lines.append('```python') + has_unclosed_backtick = True + elif section == 'examples' and is_previous_code and not is_code: + markdown_lines.append('```') + markdown_lines.append('') + markdown_lines.append('```') + has_unclosed_backtick = True + elif is_previous_code and not is_code: + markdown_lines.append('````') + markdown_lines.append('') + has_unclosed_backtick = False + # Handle lines + if is_code: + markdown_lines.append(line[4:]) + elif line.startswith('Attributes:'): + markdown_lines.append('__Attributes:__\n') + section = 'attributes' + is_new_section = True + elif line.startswith('Args:'): + markdown_lines.append('__Arguments:__\n') + section = 'args' + is_new_section = True + elif line.startswith('Returns:'): + markdown_lines.append('__Returns:__\n') + section = 'returns' + is_new_section = True + elif line.startswith('Examples:'): + markdown_lines.append('__Examples:__\n') + section = 'examples' + is_new_section = True + elif line == '```': + markdown_lines.append(line) + elif section == 'args' or section == 'attributes': + named_param_match = re.match(r'^(\w+)\s+\((.+)\):(.+)$', line) + if named_param_match: + param_name, param_type, param_desc = named_param_match.groups() + markdown_lines.append( + f'- `{param_name}` (`{param_type}`): {param_desc.strip()}' + ) + else: + markdown_lines.append(line) + elif section == 'returns': + return_match = re.match(r'^(.+):(.+)$', line) + if return_match: + param_type, param_desc = return_match.groups() + markdown_lines.append(f'`{param_type}`: {param_desc.strip()}') + else: + markdown_lines.append(line) + else: + markdown_lines.append(line) + is_previous_code = is_code + if (is_new_section or is_last_line) and has_unclosed_backtick: + markdown_lines.append('```') + markdown_lines.append('') + has_unclosed_backtick = False + return '\n'.join(markdown_lines) diff --git a/src/zrb/task/any_task.py b/src/zrb/task/any_task.py index ec6c57ed..579cafe0 100644 --- a/src/zrb/task/any_task.py +++ b/src/zrb/task/any_task.py @@ -822,14 +822,14 @@ def get_env_map(self) -> Mapping[str, Any]: @abstractmethod def render_any( - self, val: Any, data: Optional[Mapping[str, Any]] = None + self, value: Any, data: Optional[Mapping[str, Any]] = None ) -> Any: pass @abstractmethod def render_float( self, - val: Union[JinjaTemplate, float], + value: Union[JinjaTemplate, float], data: Optional[Mapping[str, Any]] = None ) -> float: pass @@ -837,7 +837,7 @@ def render_float( @abstractmethod def render_int( self, - val: Union[JinjaTemplate, int], + value: Union[JinjaTemplate, int], data: Optional[Mapping[str, Any]] = None ) -> int: pass @@ -845,7 +845,7 @@ def render_int( @abstractmethod def render_bool( self, - val: Union[JinjaTemplate, bool], + value: Union[JinjaTemplate, bool], data: Optional[Mapping[str, Any]] = None ) -> bool: pass @@ -853,7 +853,7 @@ def render_bool( @abstractmethod def render_str( self, - val: JinjaTemplate, + value: JinjaTemplate, data: Optional[Mapping[str, Any]] = None ) -> str: pass @@ -861,7 +861,7 @@ def render_str( @abstractmethod def render_file( self, - location: JinjaTemplate, + path: JinjaTemplate, data: Optional[Mapping[str, Any]] = None ) -> str: pass diff --git a/src/zrb/task/base_task/base_task.py b/src/zrb/task/base_task/base_task.py index f738fc07..f462d8b2 100644 --- a/src/zrb/task/base_task/base_task.py +++ b/src/zrb/task/base_task/base_task.py @@ -21,6 +21,7 @@ from zrb.helper.accessories.name import get_random_name from zrb.helper.advertisement import get_advertisement from zrb.helper.string.conversion import to_variable_name +from zrb.helper.string.modification import double_quote from zrb.helper.map.conversion import to_str as map_to_str from zrb.config.config import show_advertisement @@ -419,4 +420,5 @@ async def _set_local_keyval( def __repr__(self) -> str: cls_name = self.__class__.__name__ - return f'<{cls_name} name={self._name}>' + full_cli_name = double_quote(self._get_full_cli_name()) + return f'<{cls_name} {full_cli_name}>' diff --git a/src/zrb/task/base_task/component/renderer.py b/src/zrb/task/base_task/component/renderer.py index 774a249a..859c951c 100644 --- a/src/zrb/task/base_task/component/renderer.py +++ b/src/zrb/task/base_task/component/renderer.py @@ -1,4 +1,4 @@ -from zrb.helper.typing import Any, Mapping, Optional, Union +from zrb.helper.typing import Any, JinjaTemplate, Mapping, Optional, Union from zrb.helper.typecheck import typechecked from zrb.helper.string.conversion import to_boolean from zrb.helper.string.jinja import is_probably_jinja @@ -43,57 +43,69 @@ def _set_env_map(self, key: str, val: str): self.__env_map[key] = val def render_any( - self, val: Any, data: Optional[Mapping[str, Any]] = None + self, value: Any, data: Optional[Mapping[str, Any]] = None ) -> Any: - if isinstance(val, str): - return self.render_str(val, data) - return val + if isinstance(value, str): + return self.render_str(value, data) + return value def render_float( - self, val: Union[str, float], data: Optional[Mapping[str, Any]] = None + self, + value: Union[JinjaTemplate, float], + data: Optional[Mapping[str, Any]] = None ) -> float: - if isinstance(val, str): - return float(self.render_str(val, data)) - return val + if isinstance(value, str): + return float(self.render_str(value, data)) + return value def render_int( - self, val: Union[str, int], data: Optional[Mapping[str, Any]] = None + self, + value: Union[JinjaTemplate, int], + data: Optional[Mapping[str, Any]] = None ) -> int: - if isinstance(val, str): - return int(self.render_str(val, data)) - return val + if isinstance(value, str): + return int(self.render_str(value, data)) + return value def render_bool( - self, val: Union[str, bool], data: Optional[Mapping[str, Any]] = None + self, + value: Union[JinjaTemplate, bool], + data: Optional[Mapping[str, Any]] = None ) -> bool: - if isinstance(val, str): - return to_boolean(self.render_str(val, data)) - return val + if isinstance(value, str): + return to_boolean(self.render_str(value, data)) + return value def render_str( - self, val: str, data: Optional[Mapping[str, Any]] = None + self, + value: JinjaTemplate, + data: Optional[Mapping[str, Any]] = None ) -> str: - if val in self.__rendered_str: - return self.__rendered_str[val] - if not is_probably_jinja(val): - return val - template = jinja2.Template(val) + if value in self.__rendered_str: + return self.__rendered_str[value] + if not is_probably_jinja(value): + return value + template = jinja2.Template(value) render_data = self.__get_render_data(additional_data=data) try: rendered_text = template.render(render_data) except Exception: - raise Exception(f'Fail to render "{val}" with data: {render_data}') - self.__rendered_str[val] = rendered_text + raise Exception( + f'Fail to render "{value}" with data: {render_data}' + ) + self.__rendered_str[value] = rendered_text return rendered_text def render_file( - self, location: str, data: Optional[Mapping[str, Any]] = None + self, + path: JinjaTemplate, + data: Optional[Mapping[str, Any]] = None ) -> str: - location_dir = os.path.dirname(location) + location_dir = os.path.dirname(path) env = jinja2.Environment( loader=AnyExtensionFileSystemLoader([location_dir]) ) - template = env.get_template(location) + template = env.get_template(path) render_data = self.__get_render_data(additional_data=data) render_data['TEMPLATE_DIR'] = location_dir rendered_text = template.render(render_data) diff --git a/src/zrb/task_env/env.py b/src/zrb/task_env/env.py index 8bf4ea71..bc20b225 100644 --- a/src/zrb/task_env/env.py +++ b/src/zrb/task_env/env.py @@ -1,6 +1,7 @@ from zrb.helper.typing import Optional, JinjaTemplate from zrb.helper.typecheck import typechecked from zrb.task_env.constant import RESERVED_ENV_NAMES +from zrb.helper.string.modification import double_quote import os # flake8: noqa E501 @@ -124,8 +125,8 @@ def __get_prefixed_name(self, name: str, prefix: str): return prefix + '_' + name def __repr__(self) -> str: - name = self.__name - os_name = self.__os_name - default = self.__default cls_name = self.__class__.__name__ - return f'<{cls_name} name={name} os_name={os_name} default={default}>' + name = double_quote(self.__name) + os_name = 'None' if self.__os_name is None else double_quote(self.__os_name) + default = double_quote(self.__default) + return f'<{cls_name} {name} os_name={os_name} default={default}>' diff --git a/src/zrb/task_env/env_file.py b/src/zrb/task_env/env_file.py index a46cdf42..1e8f0390 100644 --- a/src/zrb/task_env/env_file.py +++ b/src/zrb/task_env/env_file.py @@ -2,6 +2,7 @@ from zrb.helper.typecheck import typechecked from dotenv import dotenv_values from zrb.task_env.constant import RESERVED_ENV_NAMES +from zrb.helper.string.modification import double_quote from zrb.task_env.env import Env # flake8: noqa E501 @@ -75,7 +76,7 @@ def get_envs(self) -> List[Env]: return env_list def __repr__(self) -> str: - env_file = self.__path - prefix = self.__prefix cls_name = self.__class__.__name__ - return f'<{cls_name} file={env_file} prefix={prefix}>' + path = double_quote(self.__path) + prefix = double_quote(self.__prefix) + return f'<{cls_name} path={path} prefix={prefix}>' diff --git a/src/zrb/task_group/group.py b/src/zrb/task_group/group.py index 96b792d3..2a3c593b 100644 --- a/src/zrb/task_group/group.py +++ b/src/zrb/task_group/group.py @@ -2,6 +2,7 @@ from zrb.helper.typecheck import typechecked from zrb.task.any_task import AnyTask from zrb.helper.string.conversion import to_cli_name +from zrb.helper.string.modification import double_quote # flake8: noqa E501 TGroup = TypeVar('TGroup', bound='Group') @@ -33,13 +34,46 @@ def __init__( description: Optional[str] = None, parent: Optional[TGroup] = None ): - self._name = name - self._description = description + self.__name = name + self.__description = description self._parent = parent if parent is not None: - parent._children.append(self) - self._children: List[TGroup] = [] - self._tasks: List[AnyTask] = [] + parent.__children.append(self) + self.__children: List[TGroup] = [] + self.__tasks: List[AnyTask] = [] + + def get_parent(self) -> Optional[TGroup]: + ''' + Retrieves parent of the Group. + + Returns: + Optional[Group]: Parent of the group. + + Examples: + >>> from zrb import Group + >>> system_group = Group(name='my system') + >>> system_log_group = Group(name='log', parent=system_group) + >>> print(system_group.get_parent()) + >>> print(system_log_group.get_parent()) + None + + ''' + return self._parent + + def get_description(self) -> str: + ''' + Retrieves group description. + + Returns: + str: Description of the group. + + Examples: + >>> from zrb import Group + >>> group = Group(name='group', description='description of the group') + >>> print(group.get_description()) + description of the group + ''' + return self.__description def get_cli_name(self) -> str: ''' @@ -56,7 +90,7 @@ def get_cli_name(self) -> str: >>> print(system_group.get_cli_name()) my-system ''' - return to_cli_name(self._name) + return to_cli_name(self.__name) def _get_full_cli_name(self) -> str: ''' @@ -97,9 +131,9 @@ def _add_task(self, task: AnyTask): >>> group._add_task(first_task) >>> group._add_task(second_task) >>> print(group.get_tasks()) - [, ] + [, ] ''' - self._tasks.append(task) + self.__tasks.append(task) def get_tasks(self) -> List[AnyTask]: ''' @@ -114,9 +148,9 @@ def get_tasks(self) -> List[AnyTask]: >>> first_task = Task(name='first-task', group=group) >>> second_task = Task(name='second-task', group=group) >>> print(group.get_tasks()) - [, ] + [, ] ''' - return self._tasks + return self.__tasks def get_children(self) -> List[TGroup]: ''' @@ -133,10 +167,11 @@ def get_children(self) -> List[TGroup]: >>> sub_group_1 = TaskGroup(name='sub-group-1', parent=group) >>> sub_group_2 = TaskGroup(name='sub-group-2', parent=group) >>> print(group.get_children()) - [, ] + [, ] ''' - return self._children + return self.__children def __repr__(self) -> str: cls_name = self.__class__.__name__ - return f'<{cls_name} name={self._name}>' + full_cli_name = double_quote(self._get_full_cli_name()) + return f'<{cls_name} {full_cli_name}>' From 6e4eb134f4b1720ba5be24075e061e8a5b611479 Mon Sep 17 00:00:00 2001 From: goFrendiAsgard Date: Sat, 9 Dec 2023 19:32:00 +0700 Subject: [PATCH 07/13] add unit-test --- test/helper/test_fetch_external_env.py | 2 +- .../test_get_markdown_from_docstring.py | 47 +++++++++++++++++++ zrb_init.py | 2 +- 3 files changed, 49 insertions(+), 2 deletions(-) create mode 100644 test/helper/test_get_markdown_from_docstring.py diff --git a/test/helper/test_fetch_external_env.py b/test/helper/test_fetch_external_env.py index 95098043..bb44893d 100644 --- a/test/helper/test_fetch_external_env.py +++ b/test/helper/test_fetch_external_env.py @@ -36,4 +36,4 @@ def test_fetch_external_env(): assert external_env.get('HOST_B1') == '' assert external_env.get('HOST_B2') == '' assert external_env.get('HOST_B3') == 'localhost' - assert external_env.get('URL_B') == '' \ No newline at end of file + assert external_env.get('URL_B') == '' diff --git a/test/helper/test_get_markdown_from_docstring.py b/test/helper/test_get_markdown_from_docstring.py new file mode 100644 index 00000000..353a66f3 --- /dev/null +++ b/test/helper/test_get_markdown_from_docstring.py @@ -0,0 +1,47 @@ +from zrb.helper.docstring import get_markdown_from_docstring + + +class SampleClass: + """ + This is a sample class for testing. + + Attributes: + attribute1 (int): An example attribute. + """ + + def method1(self, param1: str) -> bool: + """ + An example method. + + Args: + param1 (str): A sample parameter. + + Returns: + bool: The return value. + + Examples: + >>> sc = SampleClass() + >>> sc.method1("test") + """ + return True + + +def test_get_markdown_from_docstring(): + expected_output = ( + "## `SampleClass`\n\n" + "This is a sample class for testing.\n\n" + "__Attributes:__\n\n" + "- `attribute1` (`int`): An example attribute.\n" + "\n### `SampleClass.method1`\n\n" + "An example method.\n\n" + "__Arguments:__\n\n" + "- `param1` (`str`): A sample parameter.\n\n" + "__Returns:__\n\n" + "`bool`: The return value.\n\n" + "__Examples:__\n\n" + "```python\n" + "sc = SampleClass()\n" + "sc.method1(\"test\")\n" + "```\n\n" + ) + assert get_markdown_from_docstring(SampleClass) == expected_output diff --git a/zrb_init.py b/zrb_init.py index 6e6b15f7..296ae35a 100644 --- a/zrb_init.py +++ b/zrb_init.py @@ -343,7 +343,7 @@ def make_docs(*args: Any, **kwargs: Any): 'set -e', f'cd {CURRENT_DIR}', 'echo "🤖 Perform test"', - 'pytest --ignore-glob="**/template/**/test" --ignore-glob="**/generator/**/app" --ignore=playground --cov=zrb --cov-config=".coveragerc" --cov-report=html --cov-report=term --cov-report=term-missing {{input.test}}' # noqa + 'pytest -vv --ignore-glob="**/template/**/test" --ignore-glob="**/generator/**/app" --ignore=playground --cov=zrb --cov-config=".coveragerc" --cov-report=html --cov-report=term --cov-report=term-missing {{input.test}}' # noqa ], retry=0, checking_interval=1 From 7b05aa0763f9658662efda502d919bf6d3443ef7 Mon Sep 17 00:00:00 2001 From: goFrendiAsgard Date: Sat, 9 Dec 2023 20:34:51 +0700 Subject: [PATCH 08/13] add docs --- docs/concepts/README.md | 4 +- docs/concepts/task-input/README.md | 86 +++++++++++++++ docs/concepts/task-input/bool-input.md | 100 ++++++++++++++++++ docs/concepts/task-input/choice-input.md | 100 ++++++++++++++++++ docs/concepts/task-input/float-input.md | 100 ++++++++++++++++++ docs/concepts/task-input/input.md | 10 ++ .../int-input.md} | 22 ++-- docs/concepts/task-input/password-input.md | 100 ++++++++++++++++++ docs/concepts/task-input/str-input.md | 100 ++++++++++++++++++ docs/concepts/{tasks => task}/README.md | 0 docs/concepts/{tasks => task}/checkers.md | 0 docs/concepts/{tasks => task}/cmd-task.md | 0 .../{tasks => task}/docker-compose-task.md | 0 docs/concepts/{tasks => task}/flow-task.md | 0 docs/concepts/{tasks => task}/python-task.md | 0 .../{tasks => task}/remote-cmd-task.md | 0 .../{tasks => task}/resource-maker.md | 0 docs/concepts/{tasks => task}/rsync-task.md | 0 zrb_init.py | 14 ++- 19 files changed, 621 insertions(+), 15 deletions(-) create mode 100644 docs/concepts/task-input/README.md create mode 100644 docs/concepts/task-input/bool-input.md create mode 100644 docs/concepts/task-input/choice-input.md create mode 100644 docs/concepts/task-input/float-input.md create mode 100644 docs/concepts/task-input/input.md rename docs/concepts/{task-input.md => task-input/int-input.md} (87%) create mode 100644 docs/concepts/task-input/password-input.md create mode 100644 docs/concepts/task-input/str-input.md rename docs/concepts/{tasks => task}/README.md (100%) rename docs/concepts/{tasks => task}/checkers.md (100%) rename docs/concepts/{tasks => task}/cmd-task.md (100%) rename docs/concepts/{tasks => task}/docker-compose-task.md (100%) rename docs/concepts/{tasks => task}/flow-task.md (100%) rename docs/concepts/{tasks => task}/python-task.md (100%) rename docs/concepts/{tasks => task}/remote-cmd-task.md (100%) rename docs/concepts/{tasks => task}/resource-maker.md (100%) rename docs/concepts/{tasks => task}/rsync-task.md (100%) diff --git a/docs/concepts/README.md b/docs/concepts/README.md index c9823b83..d20349ad 100644 --- a/docs/concepts/README.md +++ b/docs/concepts/README.md @@ -2,9 +2,9 @@ # Concepts -- [Tasks](tasks/README.md) +- [Tasks](task/README.md) - [Task Group](task-group.md) -- [Task Input](task-input.md) +- [Task Inputs](task-input/README.md) - [Task Env](task-env.md) - [Task EnvFile](task-env-file.md) - [Template](template.md) diff --git a/docs/concepts/task-input/README.md b/docs/concepts/task-input/README.md new file mode 100644 index 00000000..ee2e8958 --- /dev/null +++ b/docs/concepts/task-input/README.md @@ -0,0 +1,86 @@ +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) + +# Task Input + +Sometimes, you need some user inputs to run your Tasks. + +Zrb allows you to set `inputs` for your Task; either by: + +- Using `inputs` parameter. +- Using `add_input` method. +- Using `insert_input` method. + +All Task Input should comply with `AnyInput` interface. + +Currently, there are some built-in inputs you can use: + +- [Input](./input.md) +- [BoolInput](./bool-input.md) +- [ChoiceInput](./choice-input.md) +- [FloatInput](./float-input.md) +- [IntInput](./int-input.md) +- [PasswordInput](./password-input.md) +- [StrInput](./str-input.md) + +Here, you will see the technical specification of `AnyInput` + +# Technical Specification + + +## `AnyInput` + +Abstract base class representing a generalized input specification. +This class serves as a template for creating various input types, +providing a standardized interface for input handling and processing. + +### `AnyInput.get_default` + +Obtains the default value of the input. + +__Returns:__ + +`Any`: The default value of the input. The type can be any, depending on the input specification. + +### `AnyInput.get_name` + +Retrieves the name of the input. + +__Returns:__ + +`str`: The name of the input. + +### `AnyInput.get_options` + +Provides a mapping (dictionary) representing the input. + +__Returns:__ + +`Mapping[str, Any]`: A dictionary where keys are option names and values are the corresponding details. + +### `AnyInput.get_param_decl` + +Fetches a list of parameter option associated with the input (i.e., `-f` or `--file`). + +__Returns:__ + +`List[str]`: A list containing strings of parameter options. + +### `AnyInput.is_hidden` + +Checks whether the input value is meant to be hidden from view or output. + +__Returns:__ + +`bool`: True if the input is hidden, False otherwise. + +### `AnyInput.should_render` + +Determines whether or not the input should be rendered. + +__Returns:__ + +`bool`: True if the input should be rendered, False otherwise. + + + +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) diff --git a/docs/concepts/task-input/bool-input.md b/docs/concepts/task-input/bool-input.md new file mode 100644 index 00000000..87373f7c --- /dev/null +++ b/docs/concepts/task-input/bool-input.md @@ -0,0 +1,100 @@ +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task Input](README.md) + +# BoolInput + +# Technical Specification + + +## `BoolInput` + +A concrete implementation of the AnyInput abstract base class, representing a specific type of task input. +This class allows for the creation of interactive and configurable inputs for tasks, with various attributes +to customize its behavior and appearance. + +__Attributes:__ + +- `name` (`str`): The name of the input, used as a unique identifier. +- `shortcut` (`Optional[str]`): An optional single-character shortcut for the input. +- `default` (`Optional[Any]`): The default value of the input. +- `description` (`Optional[str]`): A brief description of what the input is for. +- `show_default` (`Union[bool, JinjaTemplate, None]`): Determines whether the default value should be displayed. +- `prompt` (`Union[bool, str]`): The prompt text to be displayed when asking for the input. +- `confirmation_prompt` (`Union[bool, str]`): A prompt for confirmation if required. +- `prompt_required` (`bool`): Indicates whether a prompt is required. +- `hide_input` (`bool`): If True, the input value will be hidden (e.g., for passwords). +- `is_flag` (`Optional[bool]`): Specifies whether the input is a flag. +- `flag_value` (`Optional[Any]`): The value to be used if the input is a flag. +- `multiple` (`bool`): Allows multiple values for this input if True. +- `count` (`bool`): If True, counts the occurrences of the input. +- `allow_from_autoenv` (`bool`): If True, allows values to be automatically sourced from the environment. +- `type` (`Optional[Any]`): The expected type of the input value. +- `hidden` (`bool`): If True, the input is hidden and not rendered. +- `show_choices` (`bool`): Indicates whether to show available choices for the input. +- `show_envvar` (`bool`): If True, shows the corresponding environment variable. +- `nargs` (`int`): Number of arguments expected for this input. +- `should_render` (`bool`): Determines whether the input should be rendered. + +__Examples:__ + +```python +from zrb import Input, Task +task = Task( + name='task', + inputs=[ + Input(name='delay', default=10, description='Delay') + ] +) +``` + + +### `BoolInput.get_default` + +Obtains the default value of the input. + +__Returns:__ + +`Any`: The default value of the input. The type can be any, depending on the input specification. + +### `BoolInput.get_name` + +Retrieves the name of the input. + +__Returns:__ + +`str`: The name of the input. + +### `BoolInput.get_options` + +Provides a mapping (dictionary) representing the input. + +__Returns:__ + +`Mapping[str, Any]`: A dictionary where keys are option names and values are the corresponding details. + +### `BoolInput.get_param_decl` + +Fetches a list of parameter option associated with the input (i.e., `-f` or `--file`). + +__Returns:__ + +`List[str]`: A list containing strings of parameter options. + +### `BoolInput.is_hidden` + +Checks whether the input value is meant to be hidden from view or output. + +__Returns:__ + +`bool`: True if the input is hidden, False otherwise. + +### `BoolInput.should_render` + +Determines whether or not the input should be rendered. + +__Returns:__ + +`bool`: True if the input should be rendered, False otherwise. + + + +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task Input](README.md) diff --git a/docs/concepts/task-input/choice-input.md b/docs/concepts/task-input/choice-input.md new file mode 100644 index 00000000..6267e69b --- /dev/null +++ b/docs/concepts/task-input/choice-input.md @@ -0,0 +1,100 @@ +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task Input](README.md) + +# ChoiceInput + +# Technical Specification + + +## `ChoiceInput` + +A concrete implementation of the AnyInput abstract base class, representing a specific type of task input. +This class allows for the creation of interactive and configurable inputs for tasks, with various attributes +to customize its behavior and appearance. + +__Attributes:__ + +- `name` (`str`): The name of the input, used as a unique identifier. +- `shortcut` (`Optional[str]`): An optional single-character shortcut for the input. +- `default` (`Optional[Any]`): The default value of the input. +- `description` (`Optional[str]`): A brief description of what the input is for. +- `show_default` (`Union[bool, JinjaTemplate, None]`): Determines whether the default value should be displayed. +- `prompt` (`Union[bool, str]`): The prompt text to be displayed when asking for the input. +- `confirmation_prompt` (`Union[bool, str]`): A prompt for confirmation if required. +- `prompt_required` (`bool`): Indicates whether a prompt is required. +- `hide_input` (`bool`): If True, the input value will be hidden (e.g., for passwords). +- `is_flag` (`Optional[bool]`): Specifies whether the input is a flag. +- `flag_value` (`Optional[Any]`): The value to be used if the input is a flag. +- `multiple` (`bool`): Allows multiple values for this input if True. +- `count` (`bool`): If True, counts the occurrences of the input. +- `allow_from_autoenv` (`bool`): If True, allows values to be automatically sourced from the environment. +- `type` (`Optional[Any]`): The expected type of the input value. +- `hidden` (`bool`): If True, the input is hidden and not rendered. +- `show_choices` (`bool`): Indicates whether to show available choices for the input. +- `show_envvar` (`bool`): If True, shows the corresponding environment variable. +- `nargs` (`int`): Number of arguments expected for this input. +- `should_render` (`bool`): Determines whether the input should be rendered. + +__Examples:__ + +```python +from zrb import Input, Task +task = Task( + name='task', + inputs=[ + Input(name='delay', default=10, description='Delay') + ] +) +``` + + +### `ChoiceInput.get_default` + +Obtains the default value of the input. + +__Returns:__ + +`Any`: The default value of the input. The type can be any, depending on the input specification. + +### `ChoiceInput.get_name` + +Retrieves the name of the input. + +__Returns:__ + +`str`: The name of the input. + +### `ChoiceInput.get_options` + +Provides a mapping (dictionary) representing the input. + +__Returns:__ + +`Mapping[str, Any]`: A dictionary where keys are option names and values are the corresponding details. + +### `ChoiceInput.get_param_decl` + +Fetches a list of parameter option associated with the input (i.e., `-f` or `--file`). + +__Returns:__ + +`List[str]`: A list containing strings of parameter options. + +### `ChoiceInput.is_hidden` + +Checks whether the input value is meant to be hidden from view or output. + +__Returns:__ + +`bool`: True if the input is hidden, False otherwise. + +### `ChoiceInput.should_render` + +Determines whether or not the input should be rendered. + +__Returns:__ + +`bool`: True if the input should be rendered, False otherwise. + + + +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task Input](README.md) diff --git a/docs/concepts/task-input/float-input.md b/docs/concepts/task-input/float-input.md new file mode 100644 index 00000000..86f17321 --- /dev/null +++ b/docs/concepts/task-input/float-input.md @@ -0,0 +1,100 @@ +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task Input](README.md) + +# FloatInput + +# Technical Specification + + +## `FloatInput` + +A concrete implementation of the AnyInput abstract base class, representing a specific type of task input. +This class allows for the creation of interactive and configurable inputs for tasks, with various attributes +to customize its behavior and appearance. + +__Attributes:__ + +- `name` (`str`): The name of the input, used as a unique identifier. +- `shortcut` (`Optional[str]`): An optional single-character shortcut for the input. +- `default` (`Optional[Any]`): The default value of the input. +- `description` (`Optional[str]`): A brief description of what the input is for. +- `show_default` (`Union[bool, JinjaTemplate, None]`): Determines whether the default value should be displayed. +- `prompt` (`Union[bool, str]`): The prompt text to be displayed when asking for the input. +- `confirmation_prompt` (`Union[bool, str]`): A prompt for confirmation if required. +- `prompt_required` (`bool`): Indicates whether a prompt is required. +- `hide_input` (`bool`): If True, the input value will be hidden (e.g., for passwords). +- `is_flag` (`Optional[bool]`): Specifies whether the input is a flag. +- `flag_value` (`Optional[Any]`): The value to be used if the input is a flag. +- `multiple` (`bool`): Allows multiple values for this input if True. +- `count` (`bool`): If True, counts the occurrences of the input. +- `allow_from_autoenv` (`bool`): If True, allows values to be automatically sourced from the environment. +- `type` (`Optional[Any]`): The expected type of the input value. +- `hidden` (`bool`): If True, the input is hidden and not rendered. +- `show_choices` (`bool`): Indicates whether to show available choices for the input. +- `show_envvar` (`bool`): If True, shows the corresponding environment variable. +- `nargs` (`int`): Number of arguments expected for this input. +- `should_render` (`bool`): Determines whether the input should be rendered. + +__Examples:__ + +```python +from zrb import Input, Task +task = Task( + name='task', + inputs=[ + Input(name='delay', default=10, description='Delay') + ] +) +``` + + +### `FloatInput.get_default` + +Obtains the default value of the input. + +__Returns:__ + +`Any`: The default value of the input. The type can be any, depending on the input specification. + +### `FloatInput.get_name` + +Retrieves the name of the input. + +__Returns:__ + +`str`: The name of the input. + +### `FloatInput.get_options` + +Provides a mapping (dictionary) representing the input. + +__Returns:__ + +`Mapping[str, Any]`: A dictionary where keys are option names and values are the corresponding details. + +### `FloatInput.get_param_decl` + +Fetches a list of parameter option associated with the input (i.e., `-f` or `--file`). + +__Returns:__ + +`List[str]`: A list containing strings of parameter options. + +### `FloatInput.is_hidden` + +Checks whether the input value is meant to be hidden from view or output. + +__Returns:__ + +`bool`: True if the input is hidden, False otherwise. + +### `FloatInput.should_render` + +Determines whether or not the input should be rendered. + +__Returns:__ + +`bool`: True if the input should be rendered, False otherwise. + + + +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task Input](README.md) diff --git a/docs/concepts/task-input/input.md b/docs/concepts/task-input/input.md new file mode 100644 index 00000000..33c77705 --- /dev/null +++ b/docs/concepts/task-input/input.md @@ -0,0 +1,10 @@ +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task Input](README.md) + +# Input + +# Technical Specification + + + + +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task Input](README.md) diff --git a/docs/concepts/task-input.md b/docs/concepts/task-input/int-input.md similarity index 87% rename from docs/concepts/task-input.md rename to docs/concepts/task-input/int-input.md index 1c10169e..f2f8863e 100644 --- a/docs/concepts/task-input.md +++ b/docs/concepts/task-input/int-input.md @@ -1,9 +1,11 @@ -🔖 [Table of Contents](../README.md) +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task Input](README.md) -# Task Input +# IntInput + +# Technical Specification -## `Input` +## `IntInput` A concrete implementation of the AnyInput abstract base class, representing a specific type of task input. This class allows for the creation of interactive and configurable inputs for tasks, with various attributes @@ -45,7 +47,7 @@ task = Task( ``` -### `Input.get_default` +### `IntInput.get_default` Obtains the default value of the input. @@ -53,7 +55,7 @@ __Returns:__ `Any`: The default value of the input. The type can be any, depending on the input specification. -### `Input.get_name` +### `IntInput.get_name` Retrieves the name of the input. @@ -61,7 +63,7 @@ __Returns:__ `str`: The name of the input. -### `Input.get_options` +### `IntInput.get_options` Provides a mapping (dictionary) representing the input. @@ -69,7 +71,7 @@ __Returns:__ `Mapping[str, Any]`: A dictionary where keys are option names and values are the corresponding details. -### `Input.get_param_decl` +### `IntInput.get_param_decl` Fetches a list of parameter option associated with the input (i.e., `-f` or `--file`). @@ -77,7 +79,7 @@ __Returns:__ `List[str]`: A list containing strings of parameter options. -### `Input.is_hidden` +### `IntInput.is_hidden` Checks whether the input value is meant to be hidden from view or output. @@ -85,7 +87,7 @@ __Returns:__ `bool`: True if the input is hidden, False otherwise. -### `Input.should_render` +### `IntInput.should_render` Determines whether or not the input should be rendered. @@ -95,4 +97,4 @@ __Returns:__ -🔖 [Table of Contents](../README.md) +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task Input](README.md) diff --git a/docs/concepts/task-input/password-input.md b/docs/concepts/task-input/password-input.md new file mode 100644 index 00000000..5c384eef --- /dev/null +++ b/docs/concepts/task-input/password-input.md @@ -0,0 +1,100 @@ +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task Input](README.md) + +# PasswordInput + +# Technical Specification + + +## `PasswordInput` + +A concrete implementation of the AnyInput abstract base class, representing a specific type of task input. +This class allows for the creation of interactive and configurable inputs for tasks, with various attributes +to customize its behavior and appearance. + +__Attributes:__ + +- `name` (`str`): The name of the input, used as a unique identifier. +- `shortcut` (`Optional[str]`): An optional single-character shortcut for the input. +- `default` (`Optional[Any]`): The default value of the input. +- `description` (`Optional[str]`): A brief description of what the input is for. +- `show_default` (`Union[bool, JinjaTemplate, None]`): Determines whether the default value should be displayed. +- `prompt` (`Union[bool, str]`): The prompt text to be displayed when asking for the input. +- `confirmation_prompt` (`Union[bool, str]`): A prompt for confirmation if required. +- `prompt_required` (`bool`): Indicates whether a prompt is required. +- `hide_input` (`bool`): If True, the input value will be hidden (e.g., for passwords). +- `is_flag` (`Optional[bool]`): Specifies whether the input is a flag. +- `flag_value` (`Optional[Any]`): The value to be used if the input is a flag. +- `multiple` (`bool`): Allows multiple values for this input if True. +- `count` (`bool`): If True, counts the occurrences of the input. +- `allow_from_autoenv` (`bool`): If True, allows values to be automatically sourced from the environment. +- `type` (`Optional[Any]`): The expected type of the input value. +- `hidden` (`bool`): If True, the input is hidden and not rendered. +- `show_choices` (`bool`): Indicates whether to show available choices for the input. +- `show_envvar` (`bool`): If True, shows the corresponding environment variable. +- `nargs` (`int`): Number of arguments expected for this input. +- `should_render` (`bool`): Determines whether the input should be rendered. + +__Examples:__ + +```python +from zrb import Input, Task +task = Task( + name='task', + inputs=[ + Input(name='delay', default=10, description='Delay') + ] +) +``` + + +### `PasswordInput.get_default` + +Obtains the default value of the input. + +__Returns:__ + +`Any`: The default value of the input. The type can be any, depending on the input specification. + +### `PasswordInput.get_name` + +Retrieves the name of the input. + +__Returns:__ + +`str`: The name of the input. + +### `PasswordInput.get_options` + +Provides a mapping (dictionary) representing the input. + +__Returns:__ + +`Mapping[str, Any]`: A dictionary where keys are option names and values are the corresponding details. + +### `PasswordInput.get_param_decl` + +Fetches a list of parameter option associated with the input (i.e., `-f` or `--file`). + +__Returns:__ + +`List[str]`: A list containing strings of parameter options. + +### `PasswordInput.is_hidden` + +Checks whether the input value is meant to be hidden from view or output. + +__Returns:__ + +`bool`: True if the input is hidden, False otherwise. + +### `PasswordInput.should_render` + +Determines whether or not the input should be rendered. + +__Returns:__ + +`bool`: True if the input should be rendered, False otherwise. + + + +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task Input](README.md) diff --git a/docs/concepts/task-input/str-input.md b/docs/concepts/task-input/str-input.md new file mode 100644 index 00000000..9d40c86d --- /dev/null +++ b/docs/concepts/task-input/str-input.md @@ -0,0 +1,100 @@ +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task Input](README.md) + +# StrInput + +# Technical Specification + + +## `StrInput` + +A concrete implementation of the AnyInput abstract base class, representing a specific type of task input. +This class allows for the creation of interactive and configurable inputs for tasks, with various attributes +to customize its behavior and appearance. + +__Attributes:__ + +- `name` (`str`): The name of the input, used as a unique identifier. +- `shortcut` (`Optional[str]`): An optional single-character shortcut for the input. +- `default` (`Optional[Any]`): The default value of the input. +- `description` (`Optional[str]`): A brief description of what the input is for. +- `show_default` (`Union[bool, JinjaTemplate, None]`): Determines whether the default value should be displayed. +- `prompt` (`Union[bool, str]`): The prompt text to be displayed when asking for the input. +- `confirmation_prompt` (`Union[bool, str]`): A prompt for confirmation if required. +- `prompt_required` (`bool`): Indicates whether a prompt is required. +- `hide_input` (`bool`): If True, the input value will be hidden (e.g., for passwords). +- `is_flag` (`Optional[bool]`): Specifies whether the input is a flag. +- `flag_value` (`Optional[Any]`): The value to be used if the input is a flag. +- `multiple` (`bool`): Allows multiple values for this input if True. +- `count` (`bool`): If True, counts the occurrences of the input. +- `allow_from_autoenv` (`bool`): If True, allows values to be automatically sourced from the environment. +- `type` (`Optional[Any]`): The expected type of the input value. +- `hidden` (`bool`): If True, the input is hidden and not rendered. +- `show_choices` (`bool`): Indicates whether to show available choices for the input. +- `show_envvar` (`bool`): If True, shows the corresponding environment variable. +- `nargs` (`int`): Number of arguments expected for this input. +- `should_render` (`bool`): Determines whether the input should be rendered. + +__Examples:__ + +```python +from zrb import Input, Task +task = Task( + name='task', + inputs=[ + Input(name='delay', default=10, description='Delay') + ] +) +``` + + +### `StrInput.get_default` + +Obtains the default value of the input. + +__Returns:__ + +`Any`: The default value of the input. The type can be any, depending on the input specification. + +### `StrInput.get_name` + +Retrieves the name of the input. + +__Returns:__ + +`str`: The name of the input. + +### `StrInput.get_options` + +Provides a mapping (dictionary) representing the input. + +__Returns:__ + +`Mapping[str, Any]`: A dictionary where keys are option names and values are the corresponding details. + +### `StrInput.get_param_decl` + +Fetches a list of parameter option associated with the input (i.e., `-f` or `--file`). + +__Returns:__ + +`List[str]`: A list containing strings of parameter options. + +### `StrInput.is_hidden` + +Checks whether the input value is meant to be hidden from view or output. + +__Returns:__ + +`bool`: True if the input is hidden, False otherwise. + +### `StrInput.should_render` + +Determines whether or not the input should be rendered. + +__Returns:__ + +`bool`: True if the input should be rendered, False otherwise. + + + +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task Input](README.md) diff --git a/docs/concepts/tasks/README.md b/docs/concepts/task/README.md similarity index 100% rename from docs/concepts/tasks/README.md rename to docs/concepts/task/README.md diff --git a/docs/concepts/tasks/checkers.md b/docs/concepts/task/checkers.md similarity index 100% rename from docs/concepts/tasks/checkers.md rename to docs/concepts/task/checkers.md diff --git a/docs/concepts/tasks/cmd-task.md b/docs/concepts/task/cmd-task.md similarity index 100% rename from docs/concepts/tasks/cmd-task.md rename to docs/concepts/task/cmd-task.md diff --git a/docs/concepts/tasks/docker-compose-task.md b/docs/concepts/task/docker-compose-task.md similarity index 100% rename from docs/concepts/tasks/docker-compose-task.md rename to docs/concepts/task/docker-compose-task.md diff --git a/docs/concepts/tasks/flow-task.md b/docs/concepts/task/flow-task.md similarity index 100% rename from docs/concepts/tasks/flow-task.md rename to docs/concepts/task/flow-task.md diff --git a/docs/concepts/tasks/python-task.md b/docs/concepts/task/python-task.md similarity index 100% rename from docs/concepts/tasks/python-task.md rename to docs/concepts/task/python-task.md diff --git a/docs/concepts/tasks/remote-cmd-task.md b/docs/concepts/task/remote-cmd-task.md similarity index 100% rename from docs/concepts/tasks/remote-cmd-task.md rename to docs/concepts/task/remote-cmd-task.md diff --git a/docs/concepts/tasks/resource-maker.md b/docs/concepts/task/resource-maker.md similarity index 100% rename from docs/concepts/tasks/resource-maker.md rename to docs/concepts/task/resource-maker.md diff --git a/docs/concepts/tasks/rsync-task.md b/docs/concepts/task/rsync-task.md similarity index 100% rename from docs/concepts/tasks/rsync-task.md rename to docs/concepts/task/rsync-task.md diff --git a/zrb_init.py b/zrb_init.py index 296ae35a..4a2a6469 100644 --- a/zrb_init.py +++ b/zrb_init.py @@ -2,7 +2,8 @@ from zrb import ( runner, python_task, AnyTask, Task, CmdTask, DockerComposeTask, FlowTask, Checker, ResourceMaker, RsyncTask, RemoteCmdTask, PathWatcher, - RecurringTask, HTTPChecker, Env, EnvFile, Group, Input, BoolInput, StrInput + RecurringTask, HTTPChecker, Env, EnvFile, Group, AnyInput, Input, + BoolInput, ChoiceInput, FloatInput, IntInput, PasswordInput, StrInput ) from helper.doc import inject_doc import os @@ -99,12 +100,12 @@ def make_docs(*args: Any, **kwargs: Any): task: Task = kwargs.get('_task') doc_dir = os.path.join(CURRENT_DIR, 'docs') doc_concept_dir = os.path.join(doc_dir, 'concepts') - doc_concept_task_dir = os.path.join(doc_concept_dir, 'tasks') + doc_concept_task_dir = os.path.join(doc_concept_dir, 'task') + doc_concept_task_input_dir = os.path.join(doc_concept_dir, 'task-input') configs: Mapping[str, Any] = { os.path.join(doc_concept_dir, 'task-group.md'): Group, os.path.join(doc_concept_dir, 'task-env.md'): Env, os.path.join(doc_concept_dir, 'task-env-file.md'): EnvFile, - os.path.join(doc_concept_dir, 'task-input.md'): Input, os.path.join(doc_concept_task_dir, 'README.md'): AnyTask, os.path.join(doc_concept_task_dir, 'checkers.md'): Checker, os.path.join(doc_concept_task_dir, 'cmd-task.md'): CmdTask, @@ -114,6 +115,13 @@ def make_docs(*args: Any, **kwargs: Any): os.path.join(doc_concept_task_dir, 'remote-cmd-task.md'): RemoteCmdTask, # noqa os.path.join(doc_concept_task_dir, 'resource-maker.md'): ResourceMaker, os.path.join(doc_concept_task_dir, 'rsync-task.md'): RsyncTask, + os.path.join(doc_concept_task_input_dir, 'README.md'): AnyInput, + os.path.join(doc_concept_task_input_dir, 'bool-input.md'): BoolInput, + os.path.join(doc_concept_task_input_dir, 'choice-input.md'): ChoiceInput, # noqa + os.path.join(doc_concept_task_input_dir, 'float-input.md'): FloatInput, + os.path.join(doc_concept_task_input_dir, 'int-input.md'): IntInput, + os.path.join(doc_concept_task_input_dir, 'password-input.md'): PasswordInput, # noqa + os.path.join(doc_concept_task_input_dir, 'str-input.md'): StrInput, } for file_name, cls in configs.items(): task.print_out(f'Injecting doc for `{cls.__name__}` on {file_name}') From 1e9415ba4f28638fba15091945905cf2a30d561c Mon Sep 17 00:00:00 2001 From: goFrendiAsgard Date: Sun, 10 Dec 2023 12:17:43 +0700 Subject: [PATCH 09/13] add separators --- docs/concepts/task/README.md | 78 ++++++--- docs/concepts/task/checkers.md | 78 ++++++--- docs/concepts/task/cmd-task.md | 78 ++++++--- docs/concepts/task/docker-compose-task.md | 78 ++++++--- docs/concepts/task/flow-task.md | 78 ++++++--- docs/concepts/task/remote-cmd-task.md | 78 ++++++--- docs/concepts/task/resource-maker.md | 78 ++++++--- docs/concepts/task/rsync-task.md | 78 ++++++--- src/zrb/builtin/base64.py | 2 +- src/zrb/builtin/devtool/devtool_install.py | 2 +- .../{checker.py => _checker.py} | 0 .../_automate/snake_zrb_app_name/_common.py | 4 +- .../_automate/snake_zrb_app_name/container.py | 20 ++- .../snake_zrb_app_name/deployment.py | 12 +- .../_automate/snake_zrb_app_name/image.py | 2 +- .../_automate/snake_zrb_app_name/local.py | 2 +- .../_automate/snake_zrb_app_name/_common.py | 4 +- .../_automate/snake_zrb_app_name/container.py | 18 ++- .../snake_zrb_app_name/deployment.py | 12 +- .../_automate/snake_zrb_app_name/image.py | 10 +- .../_automate/snake_zrb_app_name/local.py | 6 +- .../_automate/snake_zrb_app_name/local.py | 4 +- .../{checker.py => _checker.py} | 0 .../template/_automate/snake_zrb_task_name.py | 2 +- .../template/_automate/snake_zrb_task_name.py | 4 +- .../_automate/snake_zrb_app_name/_checker.py | 64 ++++++++ .../_automate/snake_zrb_app_name/_common.py | 153 ------------------ .../_automate/snake_zrb_app_name/_config.py | 56 +++++++ .../_automate/snake_zrb_app_name/_env.py | 44 +++++ .../_automate/snake_zrb_app_name/_env_file.py | 24 +++ ...ervices.py => _get_start_microservices.py} | 9 +- .../_automate/snake_zrb_app_name/_helper.py | 71 ++++++++ .../_automate/snake_zrb_app_name/_input.py | 60 +++++++ .../_automate/snake_zrb_app_name/container.py | 135 +++++----------- .../snake_zrb_app_name/deployment.py | 95 ++--------- .../_automate/snake_zrb_app_name/frontend.py | 8 +- .../_automate/snake_zrb_app_name/image.py | 33 ++-- .../_automate/snake_zrb_app_name/load_test.py | 107 +++++------- .../_automate/snake_zrb_app_name/local.py | 102 ++++++------ .../_automate/snake_zrb_app_name/test.py | 22 +-- .../_automate/snake_zrb_package_name/local.py | 14 +- .../template/_automate/snake_zrb_task_name.py | 2 +- .../_automate/snake_zrb_app_name/_common.py | 4 +- .../_automate/snake_zrb_app_name/container.py | 18 ++- .../snake_zrb_app_name/deployment.py | 12 +- .../_automate/snake_zrb_app_name/image.py | 10 +- .../_automate/snake_zrb_app_name/local.py | 12 +- src/zrb/task/any_task.py | 50 +++--- zrb_init.py | 4 +- 49 files changed, 1056 insertions(+), 781 deletions(-) rename src/zrb/builtin/generator/app_generator/template/base/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/{checker.py => _checker.py} (100%) rename src/zrb/builtin/generator/app_generator/template/http-port/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/{checker.py => _checker.py} (100%) create mode 100644 src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/_checker.py delete mode 100644 src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/_common.py create mode 100644 src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/_config.py create mode 100644 src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/_env.py create mode 100644 src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/_env_file.py rename src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/{local_microservices.py => _get_start_microservices.py} (94%) create mode 100644 src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/_helper.py create mode 100644 src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/_input.py diff --git a/docs/concepts/task/README.md b/docs/concepts/task/README.md index 2306eee9..872e9785 100644 --- a/docs/concepts/task/README.md +++ b/docs/concepts/task/README.md @@ -287,7 +287,8 @@ __Arguments:__ - `envs` (`Env`): One or more environment variable instances to be added. -Example: +__Examples:__ + ```python from zrb import Task, Env task = Task(name='task') @@ -308,7 +309,8 @@ __Arguments:__ - `env_files` (`EnvFile`): One or more environment file instances to be added. -Example: +__Examples:__ + ```python from zrb import Task, EnvFile task = Task() @@ -328,7 +330,8 @@ __Arguments:__ - `inputs` (`AnyInput`): One or more input instances to be added to the input list. -Example: +__Examples:__ + ```python from zrb import Task, Input task = Task(name='task') @@ -348,7 +351,8 @@ __Arguments:__ - `upstreams` (`TAnyTask`): One or more task instances to be added to the upstream list. -Example: +__Examples:__ + ```python from zrb import Task task = Task(name='task') @@ -371,7 +375,8 @@ __Returns:__ `bool`: True if the task is completed, False otherwise. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -395,7 +400,8 @@ __Returns:__ `TAnyTask`: A copy of the current task. -Example: +__Examples:__ + ```python from zrb import Task task = Task(name='my-task', cmd='echo hello') @@ -478,7 +484,8 @@ This method allows for the addition of custom validation or condition checkers. checkers can be used to verify certain conditions before the task execution proceeds. Subclasses should implement this method to define task-specific checkers. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -491,7 +498,8 @@ class MyTask(Task): Injects additional `EnvFile` into the task. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -504,7 +512,8 @@ class MyTask(Task): Injects environment variables into the task. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -521,7 +530,8 @@ This method is used to programmatically add input parameters to the task, allowi dynamic customization of the task's input data. Subclasses should override this method to define specific inputs that the task should receive. -Example: +__Examples:__ + ```python from zrb import Task, Input class MyTask(Task): @@ -538,7 +548,8 @@ This method is used for programmatically adding upstream dependencies to the tas Upstream tasks are those that must be completed before the current task starts. Override this method in subclasses to specify such dependencies. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -558,7 +569,8 @@ __Arguments:__ - `envs` (`Env`): One or more environment variable instances to be added. -Example: +__Examples:__ + ```python from zrb import Task, Env task = Task(name='task') @@ -579,7 +591,8 @@ __Arguments:__ - `env_files` (`EnvFile`): One or more environment file instances to be added. -Example: +__Examples:__ + ```python from zrb import Task, EnvFile task = Task() @@ -599,7 +612,8 @@ __Arguments:__ - `inputs` (`AnyInput`): One or more input instances to be added to the input list. -Example: +__Examples:__ + ```python from zrb import Task, Input task = Task(name='task') @@ -620,7 +634,8 @@ __Arguments:__ - `upstreams` (`TAnyTask`): One or more task instances to be added to the upstream list. -Example: +__Examples:__ + ```python from zrb import Task task = Task(name='task') @@ -667,7 +682,8 @@ __Arguments:__ - `is_last_attempt` (`bool`): Indicates if this is the final retry attempt. - `exception` (`Exception`): The exception that caused the task to fail. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -687,7 +703,8 @@ This asynchronous method should be implemented in subclasses to specify actions that occur when the task reaches the `ready` state. This can include any cleanup, notification, or follow-up actions specific to the task. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -704,7 +721,8 @@ Implement this method to specify behavior when the task is retried after a failu This could include resetting states, logging the retry attempt, or other necessary steps before re-execution. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -720,7 +738,8 @@ Defines actions to perform when the task status is set to `skipped`. Implement this method to specify behavior when the task is skipped. This could include logging information, cleaning up resources, or any other necessary steps. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -736,7 +755,8 @@ Defines actions to perform when the task status is set to 'started'. Implement this method to specify behavior when the task starts its execution. This could involve initializing resources, logging, or other startup procedures. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -753,7 +773,8 @@ Implement this method to specify behavior when the task transitions to the `triggered` state. This could involve setting up prerequisites or sending notifications. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -770,7 +791,8 @@ Implement this method to specify behavior when the task transitions to the `waiting` state. This state usually indicates the task is waiting for some condition or prerequisite to be met. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -806,7 +828,8 @@ __Arguments:__ - `result` (`Any`): The result of the task to be printed. -Example: +__Examples:__ + >> from zrb import Task >> # Example of overriding in a subclass >> class MyTask(Task): @@ -861,7 +884,8 @@ __Returns:__ `Any`: The result of the task execution, the type of which is determined by the specific task implementation. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -979,15 +1003,17 @@ __Returns:__ `Callable[..., Any]`: A callable representation of the task. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): async def run(self, *args: Any, **kwargs: Any) -> int: self.print_out('Doing some calculation') return 42 -```` +``` +``` >>> ```python task = MyTask() diff --git a/docs/concepts/task/checkers.md b/docs/concepts/task/checkers.md index de29d0df..2a47a127 100644 --- a/docs/concepts/task/checkers.md +++ b/docs/concepts/task/checkers.md @@ -381,7 +381,8 @@ __Arguments:__ - `envs` (`Env`): One or more environment variable instances to be added. -Example: +__Examples:__ + ```python from zrb import Task, Env task = Task(name='task') @@ -402,7 +403,8 @@ __Arguments:__ - `env_files` (`EnvFile`): One or more environment file instances to be added. -Example: +__Examples:__ + ```python from zrb import Task, EnvFile task = Task() @@ -422,7 +424,8 @@ __Arguments:__ - `inputs` (`AnyInput`): One or more input instances to be added to the input list. -Example: +__Examples:__ + ```python from zrb import Task, Input task = Task(name='task') @@ -442,7 +445,8 @@ __Arguments:__ - `upstreams` (`TAnyTask`): One or more task instances to be added to the upstream list. -Example: +__Examples:__ + ```python from zrb import Task task = Task(name='task') @@ -465,7 +469,8 @@ __Returns:__ `bool`: True if the task is completed, False otherwise. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -489,7 +494,8 @@ __Returns:__ `TAnyTask`: A copy of the current task. -Example: +__Examples:__ + ```python from zrb import Task task = Task(name='my-task', cmd='echo hello') @@ -572,7 +578,8 @@ This method allows for the addition of custom validation or condition checkers. checkers can be used to verify certain conditions before the task execution proceeds. Subclasses should implement this method to define task-specific checkers. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -585,7 +592,8 @@ class MyTask(Task): Injects additional `EnvFile` into the task. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -598,7 +606,8 @@ class MyTask(Task): Injects environment variables into the task. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -615,7 +624,8 @@ This method is used to programmatically add input parameters to the task, allowi dynamic customization of the task's input data. Subclasses should override this method to define specific inputs that the task should receive. -Example: +__Examples:__ + ```python from zrb import Task, Input class MyTask(Task): @@ -632,7 +642,8 @@ This method is used for programmatically adding upstream dependencies to the tas Upstream tasks are those that must be completed before the current task starts. Override this method in subclasses to specify such dependencies. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -652,7 +663,8 @@ __Arguments:__ - `envs` (`Env`): One or more environment variable instances to be added. -Example: +__Examples:__ + ```python from zrb import Task, Env task = Task(name='task') @@ -673,7 +685,8 @@ __Arguments:__ - `env_files` (`EnvFile`): One or more environment file instances to be added. -Example: +__Examples:__ + ```python from zrb import Task, EnvFile task = Task() @@ -693,7 +706,8 @@ __Arguments:__ - `inputs` (`AnyInput`): One or more input instances to be added to the input list. -Example: +__Examples:__ + ```python from zrb import Task, Input task = Task(name='task') @@ -714,7 +728,8 @@ __Arguments:__ - `upstreams` (`TAnyTask`): One or more task instances to be added to the upstream list. -Example: +__Examples:__ + ```python from zrb import Task task = Task(name='task') @@ -766,7 +781,8 @@ __Arguments:__ - `is_last_attempt` (`bool`): Indicates if this is the final retry attempt. - `exception` (`Exception`): The exception that caused the task to fail. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -786,7 +802,8 @@ This asynchronous method should be implemented in subclasses to specify actions that occur when the task reaches the `ready` state. This can include any cleanup, notification, or follow-up actions specific to the task. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -803,7 +820,8 @@ Implement this method to specify behavior when the task is retried after a failu This could include resetting states, logging the retry attempt, or other necessary steps before re-execution. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -819,7 +837,8 @@ Defines actions to perform when the task status is set to `skipped`. Implement this method to specify behavior when the task is skipped. This could include logging information, cleaning up resources, or any other necessary steps. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -835,7 +854,8 @@ Defines actions to perform when the task status is set to 'started'. Implement this method to specify behavior when the task starts its execution. This could involve initializing resources, logging, or other startup procedures. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -852,7 +872,8 @@ Implement this method to specify behavior when the task transitions to the `triggered` state. This could involve setting up prerequisites or sending notifications. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -869,7 +890,8 @@ Implement this method to specify behavior when the task transitions to the `waiting` state. This state usually indicates the task is waiting for some condition or prerequisite to be met. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -905,7 +927,8 @@ __Arguments:__ - `result` (`Any`): The result of the task to be printed. -Example: +__Examples:__ + >> from zrb import Task >> # Example of overriding in a subclass >> class MyTask(Task): @@ -960,7 +983,8 @@ __Returns:__ `Any`: The result of the task execution, the type of which is determined by the specific task implementation. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -1083,15 +1107,17 @@ __Returns:__ `Callable[..., Any]`: A callable representation of the task. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): async def run(self, *args: Any, **kwargs: Any) -> int: self.print_out('Doing some calculation') return 42 -```` +``` +``` >>> ```python task = MyTask() diff --git a/docs/concepts/task/cmd-task.md b/docs/concepts/task/cmd-task.md index 9f6d7aca..87f53c11 100644 --- a/docs/concepts/task/cmd-task.md +++ b/docs/concepts/task/cmd-task.md @@ -484,7 +484,8 @@ __Arguments:__ - `envs` (`Env`): One or more environment variable instances to be added. -Example: +__Examples:__ + ```python from zrb import Task, Env task = Task(name='task') @@ -505,7 +506,8 @@ __Arguments:__ - `env_files` (`EnvFile`): One or more environment file instances to be added. -Example: +__Examples:__ + ```python from zrb import Task, EnvFile task = Task() @@ -525,7 +527,8 @@ __Arguments:__ - `inputs` (`AnyInput`): One or more input instances to be added to the input list. -Example: +__Examples:__ + ```python from zrb import Task, Input task = Task(name='task') @@ -545,7 +548,8 @@ __Arguments:__ - `upstreams` (`TAnyTask`): One or more task instances to be added to the upstream list. -Example: +__Examples:__ + ```python from zrb import Task task = Task(name='task') @@ -568,7 +572,8 @@ __Returns:__ `bool`: True if the task is completed, False otherwise. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -592,7 +597,8 @@ __Returns:__ `TAnyTask`: A copy of the current task. -Example: +__Examples:__ + ```python from zrb import Task task = Task(name='my-task', cmd='echo hello') @@ -680,7 +686,8 @@ This method allows for the addition of custom validation or condition checkers. checkers can be used to verify certain conditions before the task execution proceeds. Subclasses should implement this method to define task-specific checkers. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -693,7 +700,8 @@ class MyTask(Task): Injects additional `EnvFile` into the task. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -706,7 +714,8 @@ class MyTask(Task): Injects environment variables into the task. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -723,7 +732,8 @@ This method is used to programmatically add input parameters to the task, allowi dynamic customization of the task's input data. Subclasses should override this method to define specific inputs that the task should receive. -Example: +__Examples:__ + ```python from zrb import Task, Input class MyTask(Task): @@ -740,7 +750,8 @@ This method is used for programmatically adding upstream dependencies to the tas Upstream tasks are those that must be completed before the current task starts. Override this method in subclasses to specify such dependencies. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -760,7 +771,8 @@ __Arguments:__ - `envs` (`Env`): One or more environment variable instances to be added. -Example: +__Examples:__ + ```python from zrb import Task, Env task = Task(name='task') @@ -781,7 +793,8 @@ __Arguments:__ - `env_files` (`EnvFile`): One or more environment file instances to be added. -Example: +__Examples:__ + ```python from zrb import Task, EnvFile task = Task() @@ -801,7 +814,8 @@ __Arguments:__ - `inputs` (`AnyInput`): One or more input instances to be added to the input list. -Example: +__Examples:__ + ```python from zrb import Task, Input task = Task(name='task') @@ -822,7 +836,8 @@ __Arguments:__ - `upstreams` (`TAnyTask`): One or more task instances to be added to the upstream list. -Example: +__Examples:__ + ```python from zrb import Task task = Task(name='task') @@ -869,7 +884,8 @@ __Arguments:__ - `is_last_attempt` (`bool`): Indicates if this is the final retry attempt. - `exception` (`Exception`): The exception that caused the task to fail. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -889,7 +905,8 @@ This asynchronous method should be implemented in subclasses to specify actions that occur when the task reaches the `ready` state. This can include any cleanup, notification, or follow-up actions specific to the task. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -906,7 +923,8 @@ Implement this method to specify behavior when the task is retried after a failu This could include resetting states, logging the retry attempt, or other necessary steps before re-execution. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -922,7 +940,8 @@ Defines actions to perform when the task status is set to `skipped`. Implement this method to specify behavior when the task is skipped. This could include logging information, cleaning up resources, or any other necessary steps. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -938,7 +957,8 @@ Defines actions to perform when the task status is set to 'started'. Implement this method to specify behavior when the task starts its execution. This could involve initializing resources, logging, or other startup procedures. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -955,7 +975,8 @@ Implement this method to specify behavior when the task transitions to the `triggered` state. This could involve setting up prerequisites or sending notifications. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -972,7 +993,8 @@ Implement this method to specify behavior when the task transitions to the `waiting` state. This state usually indicates the task is waiting for some condition or prerequisite to be met. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -1008,7 +1030,8 @@ __Arguments:__ - `result` (`Any`): The result of the task to be printed. -Example: +__Examples:__ + >> from zrb import Task >> # Example of overriding in a subclass >> class MyTask(Task): @@ -1063,7 +1086,8 @@ __Returns:__ `Any`: The result of the task execution, the type of which is determined by the specific task implementation. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -1186,15 +1210,17 @@ __Returns:__ `Callable[..., Any]`: A callable representation of the task. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): async def run(self, *args: Any, **kwargs: Any) -> int: self.print_out('Doing some calculation') return 42 -```` +``` +``` >>> ```python task = MyTask() diff --git a/docs/concepts/task/docker-compose-task.md b/docs/concepts/task/docker-compose-task.md index dd045445..7354ee78 100644 --- a/docs/concepts/task/docker-compose-task.md +++ b/docs/concepts/task/docker-compose-task.md @@ -500,7 +500,8 @@ __Arguments:__ - `envs` (`Env`): One or more environment variable instances to be added. -Example: +__Examples:__ + ```python from zrb import Task, Env task = Task(name='task') @@ -521,7 +522,8 @@ __Arguments:__ - `env_files` (`EnvFile`): One or more environment file instances to be added. -Example: +__Examples:__ + ```python from zrb import Task, EnvFile task = Task() @@ -541,7 +543,8 @@ __Arguments:__ - `inputs` (`AnyInput`): One or more input instances to be added to the input list. -Example: +__Examples:__ + ```python from zrb import Task, Input task = Task(name='task') @@ -561,7 +564,8 @@ __Arguments:__ - `upstreams` (`TAnyTask`): One or more task instances to be added to the upstream list. -Example: +__Examples:__ + ```python from zrb import Task task = Task(name='task') @@ -584,7 +588,8 @@ __Returns:__ `bool`: True if the task is completed, False otherwise. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -608,7 +613,8 @@ __Returns:__ `TAnyTask`: A copy of the current task. -Example: +__Examples:__ + ```python from zrb import Task task = Task(name='my-task', cmd='echo hello') @@ -696,7 +702,8 @@ This method allows for the addition of custom validation or condition checkers. checkers can be used to verify certain conditions before the task execution proceeds. Subclasses should implement this method to define task-specific checkers. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -709,7 +716,8 @@ class MyTask(Task): Injects additional `EnvFile` into the task. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -722,7 +730,8 @@ class MyTask(Task): Injects environment variables into the task. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -739,7 +748,8 @@ This method is used to programmatically add input parameters to the task, allowi dynamic customization of the task's input data. Subclasses should override this method to define specific inputs that the task should receive. -Example: +__Examples:__ + ```python from zrb import Task, Input class MyTask(Task): @@ -756,7 +766,8 @@ This method is used for programmatically adding upstream dependencies to the tas Upstream tasks are those that must be completed before the current task starts. Override this method in subclasses to specify such dependencies. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -776,7 +787,8 @@ __Arguments:__ - `envs` (`Env`): One or more environment variable instances to be added. -Example: +__Examples:__ + ```python from zrb import Task, Env task = Task(name='task') @@ -797,7 +809,8 @@ __Arguments:__ - `env_files` (`EnvFile`): One or more environment file instances to be added. -Example: +__Examples:__ + ```python from zrb import Task, EnvFile task = Task() @@ -817,7 +830,8 @@ __Arguments:__ - `inputs` (`AnyInput`): One or more input instances to be added to the input list. -Example: +__Examples:__ + ```python from zrb import Task, Input task = Task(name='task') @@ -838,7 +852,8 @@ __Arguments:__ - `upstreams` (`TAnyTask`): One or more task instances to be added to the upstream list. -Example: +__Examples:__ + ```python from zrb import Task task = Task(name='task') @@ -885,7 +900,8 @@ __Arguments:__ - `is_last_attempt` (`bool`): Indicates if this is the final retry attempt. - `exception` (`Exception`): The exception that caused the task to fail. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -905,7 +921,8 @@ This asynchronous method should be implemented in subclasses to specify actions that occur when the task reaches the `ready` state. This can include any cleanup, notification, or follow-up actions specific to the task. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -922,7 +939,8 @@ Implement this method to specify behavior when the task is retried after a failu This could include resetting states, logging the retry attempt, or other necessary steps before re-execution. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -938,7 +956,8 @@ Defines actions to perform when the task status is set to `skipped`. Implement this method to specify behavior when the task is skipped. This could include logging information, cleaning up resources, or any other necessary steps. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -954,7 +973,8 @@ Defines actions to perform when the task status is set to 'started'. Implement this method to specify behavior when the task starts its execution. This could involve initializing resources, logging, or other startup procedures. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -971,7 +991,8 @@ Implement this method to specify behavior when the task transitions to the `triggered` state. This could involve setting up prerequisites or sending notifications. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -988,7 +1009,8 @@ Implement this method to specify behavior when the task transitions to the `waiting` state. This state usually indicates the task is waiting for some condition or prerequisite to be met. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -1024,7 +1046,8 @@ __Arguments:__ - `result` (`Any`): The result of the task to be printed. -Example: +__Examples:__ + >> from zrb import Task >> # Example of overriding in a subclass >> class MyTask(Task): @@ -1079,7 +1102,8 @@ __Returns:__ `Any`: The result of the task execution, the type of which is determined by the specific task implementation. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -1202,15 +1226,17 @@ __Returns:__ `Callable[..., Any]`: A callable representation of the task. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): async def run(self, *args: Any, **kwargs: Any) -> int: self.print_out('Doing some calculation') return 42 -```` +``` +``` >>> ```python task = MyTask() diff --git a/docs/concepts/task/flow-task.md b/docs/concepts/task/flow-task.md index 7512102d..01d76b7a 100644 --- a/docs/concepts/task/flow-task.md +++ b/docs/concepts/task/flow-task.md @@ -388,7 +388,8 @@ __Arguments:__ - `envs` (`Env`): One or more environment variable instances to be added. -Example: +__Examples:__ + ```python from zrb import Task, Env task = Task(name='task') @@ -409,7 +410,8 @@ __Arguments:__ - `env_files` (`EnvFile`): One or more environment file instances to be added. -Example: +__Examples:__ + ```python from zrb import Task, EnvFile task = Task() @@ -429,7 +431,8 @@ __Arguments:__ - `inputs` (`AnyInput`): One or more input instances to be added to the input list. -Example: +__Examples:__ + ```python from zrb import Task, Input task = Task(name='task') @@ -449,7 +452,8 @@ __Arguments:__ - `upstreams` (`TAnyTask`): One or more task instances to be added to the upstream list. -Example: +__Examples:__ + ```python from zrb import Task task = Task(name='task') @@ -472,7 +476,8 @@ __Returns:__ `bool`: True if the task is completed, False otherwise. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -496,7 +501,8 @@ __Returns:__ `TAnyTask`: A copy of the current task. -Example: +__Examples:__ + ```python from zrb import Task task = Task(name='my-task', cmd='echo hello') @@ -579,7 +585,8 @@ This method allows for the addition of custom validation or condition checkers. checkers can be used to verify certain conditions before the task execution proceeds. Subclasses should implement this method to define task-specific checkers. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -592,7 +599,8 @@ class MyTask(Task): Injects additional `EnvFile` into the task. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -605,7 +613,8 @@ class MyTask(Task): Injects environment variables into the task. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -622,7 +631,8 @@ This method is used to programmatically add input parameters to the task, allowi dynamic customization of the task's input data. Subclasses should override this method to define specific inputs that the task should receive. -Example: +__Examples:__ + ```python from zrb import Task, Input class MyTask(Task): @@ -639,7 +649,8 @@ This method is used for programmatically adding upstream dependencies to the tas Upstream tasks are those that must be completed before the current task starts. Override this method in subclasses to specify such dependencies. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -659,7 +670,8 @@ __Arguments:__ - `envs` (`Env`): One or more environment variable instances to be added. -Example: +__Examples:__ + ```python from zrb import Task, Env task = Task(name='task') @@ -680,7 +692,8 @@ __Arguments:__ - `env_files` (`EnvFile`): One or more environment file instances to be added. -Example: +__Examples:__ + ```python from zrb import Task, EnvFile task = Task() @@ -700,7 +713,8 @@ __Arguments:__ - `inputs` (`AnyInput`): One or more input instances to be added to the input list. -Example: +__Examples:__ + ```python from zrb import Task, Input task = Task(name='task') @@ -721,7 +735,8 @@ __Arguments:__ - `upstreams` (`TAnyTask`): One or more task instances to be added to the upstream list. -Example: +__Examples:__ + ```python from zrb import Task task = Task(name='task') @@ -768,7 +783,8 @@ __Arguments:__ - `is_last_attempt` (`bool`): Indicates if this is the final retry attempt. - `exception` (`Exception`): The exception that caused the task to fail. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -788,7 +804,8 @@ This asynchronous method should be implemented in subclasses to specify actions that occur when the task reaches the `ready` state. This can include any cleanup, notification, or follow-up actions specific to the task. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -805,7 +822,8 @@ Implement this method to specify behavior when the task is retried after a failu This could include resetting states, logging the retry attempt, or other necessary steps before re-execution. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -821,7 +839,8 @@ Defines actions to perform when the task status is set to `skipped`. Implement this method to specify behavior when the task is skipped. This could include logging information, cleaning up resources, or any other necessary steps. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -837,7 +856,8 @@ Defines actions to perform when the task status is set to 'started'. Implement this method to specify behavior when the task starts its execution. This could involve initializing resources, logging, or other startup procedures. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -854,7 +874,8 @@ Implement this method to specify behavior when the task transitions to the `triggered` state. This could involve setting up prerequisites or sending notifications. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -871,7 +892,8 @@ Implement this method to specify behavior when the task transitions to the `waiting` state. This state usually indicates the task is waiting for some condition or prerequisite to be met. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -907,7 +929,8 @@ __Arguments:__ - `result` (`Any`): The result of the task to be printed. -Example: +__Examples:__ + >> from zrb import Task >> # Example of overriding in a subclass >> class MyTask(Task): @@ -962,7 +985,8 @@ __Returns:__ `Any`: The result of the task execution, the type of which is determined by the specific task implementation. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -1080,15 +1104,17 @@ __Returns:__ `Callable[..., Any]`: A callable representation of the task. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): async def run(self, *args: Any, **kwargs: Any) -> int: self.print_out('Doing some calculation') return 42 -```` +``` +``` >>> ```python task = MyTask() diff --git a/docs/concepts/task/remote-cmd-task.md b/docs/concepts/task/remote-cmd-task.md index 01c66280..ac5b3b86 100644 --- a/docs/concepts/task/remote-cmd-task.md +++ b/docs/concepts/task/remote-cmd-task.md @@ -363,7 +363,8 @@ __Arguments:__ - `envs` (`Env`): One or more environment variable instances to be added. -Example: +__Examples:__ + ```python from zrb import Task, Env task = Task(name='task') @@ -384,7 +385,8 @@ __Arguments:__ - `env_files` (`EnvFile`): One or more environment file instances to be added. -Example: +__Examples:__ + ```python from zrb import Task, EnvFile task = Task() @@ -404,7 +406,8 @@ __Arguments:__ - `inputs` (`AnyInput`): One or more input instances to be added to the input list. -Example: +__Examples:__ + ```python from zrb import Task, Input task = Task(name='task') @@ -424,7 +427,8 @@ __Arguments:__ - `upstreams` (`TAnyTask`): One or more task instances to be added to the upstream list. -Example: +__Examples:__ + ```python from zrb import Task task = Task(name='task') @@ -447,7 +451,8 @@ __Returns:__ `bool`: True if the task is completed, False otherwise. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -471,7 +476,8 @@ __Returns:__ `TAnyTask`: A copy of the current task. -Example: +__Examples:__ + ```python from zrb import Task task = Task(name='my-task', cmd='echo hello') @@ -554,7 +560,8 @@ This method allows for the addition of custom validation or condition checkers. checkers can be used to verify certain conditions before the task execution proceeds. Subclasses should implement this method to define task-specific checkers. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -567,7 +574,8 @@ class MyTask(Task): Injects additional `EnvFile` into the task. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -580,7 +588,8 @@ class MyTask(Task): Injects environment variables into the task. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -597,7 +606,8 @@ This method is used to programmatically add input parameters to the task, allowi dynamic customization of the task's input data. Subclasses should override this method to define specific inputs that the task should receive. -Example: +__Examples:__ + ```python from zrb import Task, Input class MyTask(Task): @@ -614,7 +624,8 @@ This method is used for programmatically adding upstream dependencies to the tas Upstream tasks are those that must be completed before the current task starts. Override this method in subclasses to specify such dependencies. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -634,7 +645,8 @@ __Arguments:__ - `envs` (`Env`): One or more environment variable instances to be added. -Example: +__Examples:__ + ```python from zrb import Task, Env task = Task(name='task') @@ -655,7 +667,8 @@ __Arguments:__ - `env_files` (`EnvFile`): One or more environment file instances to be added. -Example: +__Examples:__ + ```python from zrb import Task, EnvFile task = Task() @@ -675,7 +688,8 @@ __Arguments:__ - `inputs` (`AnyInput`): One or more input instances to be added to the input list. -Example: +__Examples:__ + ```python from zrb import Task, Input task = Task(name='task') @@ -696,7 +710,8 @@ __Arguments:__ - `upstreams` (`TAnyTask`): One or more task instances to be added to the upstream list. -Example: +__Examples:__ + ```python from zrb import Task task = Task(name='task') @@ -743,7 +758,8 @@ __Arguments:__ - `is_last_attempt` (`bool`): Indicates if this is the final retry attempt. - `exception` (`Exception`): The exception that caused the task to fail. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -763,7 +779,8 @@ This asynchronous method should be implemented in subclasses to specify actions that occur when the task reaches the `ready` state. This can include any cleanup, notification, or follow-up actions specific to the task. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -780,7 +797,8 @@ Implement this method to specify behavior when the task is retried after a failu This could include resetting states, logging the retry attempt, or other necessary steps before re-execution. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -796,7 +814,8 @@ Defines actions to perform when the task status is set to `skipped`. Implement this method to specify behavior when the task is skipped. This could include logging information, cleaning up resources, or any other necessary steps. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -812,7 +831,8 @@ Defines actions to perform when the task status is set to 'started'. Implement this method to specify behavior when the task starts its execution. This could involve initializing resources, logging, or other startup procedures. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -829,7 +849,8 @@ Implement this method to specify behavior when the task transitions to the `triggered` state. This could involve setting up prerequisites or sending notifications. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -846,7 +867,8 @@ Implement this method to specify behavior when the task transitions to the `waiting` state. This state usually indicates the task is waiting for some condition or prerequisite to be met. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -882,7 +904,8 @@ __Arguments:__ - `result` (`Any`): The result of the task to be printed. -Example: +__Examples:__ + >> from zrb import Task >> # Example of overriding in a subclass >> class MyTask(Task): @@ -937,7 +960,8 @@ __Returns:__ `Any`: The result of the task execution, the type of which is determined by the specific task implementation. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -1055,15 +1079,17 @@ __Returns:__ `Callable[..., Any]`: A callable representation of the task. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): async def run(self, *args: Any, **kwargs: Any) -> int: self.print_out('Doing some calculation') return 42 -```` +``` +``` >>> ```python task = MyTask() diff --git a/docs/concepts/task/resource-maker.md b/docs/concepts/task/resource-maker.md index 23690f85..79846077 100644 --- a/docs/concepts/task/resource-maker.md +++ b/docs/concepts/task/resource-maker.md @@ -395,7 +395,8 @@ __Arguments:__ - `envs` (`Env`): One or more environment variable instances to be added. -Example: +__Examples:__ + ```python from zrb import Task, Env task = Task(name='task') @@ -416,7 +417,8 @@ __Arguments:__ - `env_files` (`EnvFile`): One or more environment file instances to be added. -Example: +__Examples:__ + ```python from zrb import Task, EnvFile task = Task() @@ -436,7 +438,8 @@ __Arguments:__ - `inputs` (`AnyInput`): One or more input instances to be added to the input list. -Example: +__Examples:__ + ```python from zrb import Task, Input task = Task(name='task') @@ -456,7 +459,8 @@ __Arguments:__ - `upstreams` (`TAnyTask`): One or more task instances to be added to the upstream list. -Example: +__Examples:__ + ```python from zrb import Task task = Task(name='task') @@ -479,7 +483,8 @@ __Returns:__ `bool`: True if the task is completed, False otherwise. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -503,7 +508,8 @@ __Returns:__ `TAnyTask`: A copy of the current task. -Example: +__Examples:__ + ```python from zrb import Task task = Task(name='my-task', cmd='echo hello') @@ -586,7 +592,8 @@ This method allows for the addition of custom validation or condition checkers. checkers can be used to verify certain conditions before the task execution proceeds. Subclasses should implement this method to define task-specific checkers. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -599,7 +606,8 @@ class MyTask(Task): Injects additional `EnvFile` into the task. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -612,7 +620,8 @@ class MyTask(Task): Injects environment variables into the task. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -629,7 +638,8 @@ This method is used to programmatically add input parameters to the task, allowi dynamic customization of the task's input data. Subclasses should override this method to define specific inputs that the task should receive. -Example: +__Examples:__ + ```python from zrb import Task, Input class MyTask(Task): @@ -646,7 +656,8 @@ This method is used for programmatically adding upstream dependencies to the tas Upstream tasks are those that must be completed before the current task starts. Override this method in subclasses to specify such dependencies. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -666,7 +677,8 @@ __Arguments:__ - `envs` (`Env`): One or more environment variable instances to be added. -Example: +__Examples:__ + ```python from zrb import Task, Env task = Task(name='task') @@ -687,7 +699,8 @@ __Arguments:__ - `env_files` (`EnvFile`): One or more environment file instances to be added. -Example: +__Examples:__ + ```python from zrb import Task, EnvFile task = Task() @@ -707,7 +720,8 @@ __Arguments:__ - `inputs` (`AnyInput`): One or more input instances to be added to the input list. -Example: +__Examples:__ + ```python from zrb import Task, Input task = Task(name='task') @@ -728,7 +742,8 @@ __Arguments:__ - `upstreams` (`TAnyTask`): One or more task instances to be added to the upstream list. -Example: +__Examples:__ + ```python from zrb import Task task = Task(name='task') @@ -775,7 +790,8 @@ __Arguments:__ - `is_last_attempt` (`bool`): Indicates if this is the final retry attempt. - `exception` (`Exception`): The exception that caused the task to fail. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -795,7 +811,8 @@ This asynchronous method should be implemented in subclasses to specify actions that occur when the task reaches the `ready` state. This can include any cleanup, notification, or follow-up actions specific to the task. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -812,7 +829,8 @@ Implement this method to specify behavior when the task is retried after a failu This could include resetting states, logging the retry attempt, or other necessary steps before re-execution. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -828,7 +846,8 @@ Defines actions to perform when the task status is set to `skipped`. Implement this method to specify behavior when the task is skipped. This could include logging information, cleaning up resources, or any other necessary steps. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -844,7 +863,8 @@ Defines actions to perform when the task status is set to 'started'. Implement this method to specify behavior when the task starts its execution. This could involve initializing resources, logging, or other startup procedures. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -861,7 +881,8 @@ Implement this method to specify behavior when the task transitions to the `triggered` state. This could involve setting up prerequisites or sending notifications. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -878,7 +899,8 @@ Implement this method to specify behavior when the task transitions to the `waiting` state. This state usually indicates the task is waiting for some condition or prerequisite to be met. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -914,7 +936,8 @@ __Arguments:__ - `result` (`Any`): The result of the task to be printed. -Example: +__Examples:__ + >> from zrb import Task >> # Example of overriding in a subclass >> class MyTask(Task): @@ -969,7 +992,8 @@ __Returns:__ `Any`: The result of the task execution, the type of which is determined by the specific task implementation. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -1087,15 +1111,17 @@ __Returns:__ `Callable[..., Any]`: A callable representation of the task. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): async def run(self, *args: Any, **kwargs: Any) -> int: self.print_out('Doing some calculation') return 42 -```` +``` +``` >>> ```python task = MyTask() diff --git a/docs/concepts/task/rsync-task.md b/docs/concepts/task/rsync-task.md index 93031768..e7d30e79 100644 --- a/docs/concepts/task/rsync-task.md +++ b/docs/concepts/task/rsync-task.md @@ -394,7 +394,8 @@ __Arguments:__ - `envs` (`Env`): One or more environment variable instances to be added. -Example: +__Examples:__ + ```python from zrb import Task, Env task = Task(name='task') @@ -415,7 +416,8 @@ __Arguments:__ - `env_files` (`EnvFile`): One or more environment file instances to be added. -Example: +__Examples:__ + ```python from zrb import Task, EnvFile task = Task() @@ -435,7 +437,8 @@ __Arguments:__ - `inputs` (`AnyInput`): One or more input instances to be added to the input list. -Example: +__Examples:__ + ```python from zrb import Task, Input task = Task(name='task') @@ -455,7 +458,8 @@ __Arguments:__ - `upstreams` (`TAnyTask`): One or more task instances to be added to the upstream list. -Example: +__Examples:__ + ```python from zrb import Task task = Task(name='task') @@ -478,7 +482,8 @@ __Returns:__ `bool`: True if the task is completed, False otherwise. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -502,7 +507,8 @@ __Returns:__ `TAnyTask`: A copy of the current task. -Example: +__Examples:__ + ```python from zrb import Task task = Task(name='my-task', cmd='echo hello') @@ -585,7 +591,8 @@ This method allows for the addition of custom validation or condition checkers. checkers can be used to verify certain conditions before the task execution proceeds. Subclasses should implement this method to define task-specific checkers. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -598,7 +605,8 @@ class MyTask(Task): Injects additional `EnvFile` into the task. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -611,7 +619,8 @@ class MyTask(Task): Injects environment variables into the task. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -628,7 +637,8 @@ This method is used to programmatically add input parameters to the task, allowi dynamic customization of the task's input data. Subclasses should override this method to define specific inputs that the task should receive. -Example: +__Examples:__ + ```python from zrb import Task, Input class MyTask(Task): @@ -645,7 +655,8 @@ This method is used for programmatically adding upstream dependencies to the tas Upstream tasks are those that must be completed before the current task starts. Override this method in subclasses to specify such dependencies. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -665,7 +676,8 @@ __Arguments:__ - `envs` (`Env`): One or more environment variable instances to be added. -Example: +__Examples:__ + ```python from zrb import Task, Env task = Task(name='task') @@ -686,7 +698,8 @@ __Arguments:__ - `env_files` (`EnvFile`): One or more environment file instances to be added. -Example: +__Examples:__ + ```python from zrb import Task, EnvFile task = Task() @@ -706,7 +719,8 @@ __Arguments:__ - `inputs` (`AnyInput`): One or more input instances to be added to the input list. -Example: +__Examples:__ + ```python from zrb import Task, Input task = Task(name='task') @@ -727,7 +741,8 @@ __Arguments:__ - `upstreams` (`TAnyTask`): One or more task instances to be added to the upstream list. -Example: +__Examples:__ + ```python from zrb import Task task = Task(name='task') @@ -774,7 +789,8 @@ __Arguments:__ - `is_last_attempt` (`bool`): Indicates if this is the final retry attempt. - `exception` (`Exception`): The exception that caused the task to fail. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -794,7 +810,8 @@ This asynchronous method should be implemented in subclasses to specify actions that occur when the task reaches the `ready` state. This can include any cleanup, notification, or follow-up actions specific to the task. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -811,7 +828,8 @@ Implement this method to specify behavior when the task is retried after a failu This could include resetting states, logging the retry attempt, or other necessary steps before re-execution. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -827,7 +845,8 @@ Defines actions to perform when the task status is set to `skipped`. Implement this method to specify behavior when the task is skipped. This could include logging information, cleaning up resources, or any other necessary steps. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -843,7 +862,8 @@ Defines actions to perform when the task status is set to 'started'. Implement this method to specify behavior when the task starts its execution. This could involve initializing resources, logging, or other startup procedures. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -860,7 +880,8 @@ Implement this method to specify behavior when the task transitions to the `triggered` state. This could involve setting up prerequisites or sending notifications. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -877,7 +898,8 @@ Implement this method to specify behavior when the task transitions to the `waiting` state. This state usually indicates the task is waiting for some condition or prerequisite to be met. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -913,7 +935,8 @@ __Arguments:__ - `result` (`Any`): The result of the task to be printed. -Example: +__Examples:__ + >> from zrb import Task >> # Example of overriding in a subclass >> class MyTask(Task): @@ -968,7 +991,8 @@ __Returns:__ `Any`: The result of the task execution, the type of which is determined by the specific task implementation. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): @@ -1086,15 +1110,17 @@ __Returns:__ `Callable[..., Any]`: A callable representation of the task. -Example: +__Examples:__ + ```python from zrb import Task class MyTask(Task): async def run(self, *args: Any, **kwargs: Any) -> int: self.print_out('Doing some calculation') return 42 -```` +``` +``` >>> ```python task = MyTask() diff --git a/src/zrb/builtin/base64.py b/src/zrb/builtin/base64.py index 7b38ef42..bbd5161c 100644 --- a/src/zrb/builtin/base64.py +++ b/src/zrb/builtin/base64.py @@ -7,7 +7,7 @@ import base64 ############################################################################### -# Input Definitions +# 🔤 Input Definitions ############################################################################### text_input = StrInput( diff --git a/src/zrb/builtin/devtool/devtool_install.py b/src/zrb/builtin/devtool/devtool_install.py index 933f414a..b323dad7 100644 --- a/src/zrb/builtin/devtool/devtool_install.py +++ b/src/zrb/builtin/devtool/devtool_install.py @@ -15,7 +15,7 @@ current_shell = get_current_shell() ############################################################################### -# Input Definitions +# 🔤 Input Definitions ############################################################################### terminal_config_file_input = StrInput( diff --git a/src/zrb/builtin/generator/app_generator/template/base/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/checker.py b/src/zrb/builtin/generator/app_generator/template/base/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/_checker.py similarity index 100% rename from src/zrb/builtin/generator/app_generator/template/base/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/checker.py rename to src/zrb/builtin/generator/app_generator/template/base/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/_checker.py diff --git a/src/zrb/builtin/generator/app_generator/template/base/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/_common.py b/src/zrb/builtin/generator/app_generator/template/base/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/_common.py index 41c8b1ec..d0ef02b2 100644 --- a/src/zrb/builtin/generator/app_generator/template/base/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/_common.py +++ b/src/zrb/builtin/generator/app_generator/template/base/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/_common.py @@ -2,7 +2,7 @@ import os ############################################################################### -# Constants +# 🏔️ Constants ############################################################################### CURRENT_DIR = os.path.dirname(__file__) @@ -16,7 +16,7 @@ APP_TEMPLATE_ENV_FILE_NAME = os.path.join(APP_DIR, 'template.env') ############################################################################### -# Input Definitions +# 🔤 Input Definitions ############################################################################### local_input = BoolInput( diff --git a/src/zrb/builtin/generator/app_generator/template/base/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/container.py b/src/zrb/builtin/generator/app_generator/template/base/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/container.py index b9bc7632..91f5cbc7 100644 --- a/src/zrb/builtin/generator/app_generator/template/base/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/container.py +++ b/src/zrb/builtin/generator/app_generator/template/base/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/container.py @@ -2,11 +2,11 @@ from zrb.builtin.group import project_group from .image import image_env from ._common import RESOURCE_DIR, local_input, host_input -from .checker import snake_zrb_app_name_container_checker +from ._checker import snake_zrb_app_name_container_checker import os ############################################################################### -# Env File Definitions +# 🌳 Env File Definitions ############################################################################### compose_env_file = EnvFile( @@ -15,7 +15,7 @@ ) ############################################################################### -# Env Definitions +# 🌱 Env Definitions ############################################################################### host_port_env = Env( @@ -25,7 +25,7 @@ ) ############################################################################### -# Task Definitions +# ⚙️ remove-kebab-zrb-task-name-container ############################################################################### remove_snake_zrb_app_name_container = DockerComposeTask( @@ -44,6 +44,10 @@ ) runner.register(remove_snake_zrb_app_name_container) +############################################################################### +# ⚙️ stop-kebab-zrb-task-name-container +############################################################################### + stop_snake_zrb_app_name_container = DockerComposeTask( icon='⛔', name='stop-kebab-zrb-app-name-container', @@ -60,6 +64,10 @@ ) runner.register(stop_snake_zrb_app_name_container) +############################################################################### +# ⚙️ init-kebab-zrb-task-name-container +############################################################################### + init_snake_zrb_app_name_container = DockerComposeTask( icon='🔥', name='init-kebab-zrb-app-name-container', @@ -82,6 +90,10 @@ ], ) +############################################################################### +# ⚙️ start-kebab-zrb-task-name-container +############################################################################### + start_snake_zrb_app_name_container = DockerComposeTask( icon='🐳', name='start-kebab-zrb-app-name-container', diff --git a/src/zrb/builtin/generator/app_generator/template/base/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/deployment.py b/src/zrb/builtin/generator/app_generator/template/base/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/deployment.py index eadb5ae6..e101ed9c 100644 --- a/src/zrb/builtin/generator/app_generator/template/base/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/deployment.py +++ b/src/zrb/builtin/generator/app_generator/template/base/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/deployment.py @@ -7,7 +7,7 @@ import os ############################################################################### -# Input Definitions +# 🔤 Input Definitions ############################################################################### replica_input = IntInput( @@ -25,7 +25,7 @@ ) ############################################################################### -# Env File Definitions +# 🌳 Env File Definitions ############################################################################### deployment_config_env_file = EnvFile( @@ -34,7 +34,7 @@ ) ############################################################################### -# Env Definitions +# 🌱 Env Definitions ############################################################################### pulumi_backend_url_env = Env( @@ -56,7 +56,7 @@ ) ############################################################################### -# Task Definitions +# ⚙️ deploy-kebab-zrb-task-name ############################################################################### deploy_snake_zrb_app_name = CmdTask( @@ -85,6 +85,10 @@ ) runner.register(deploy_snake_zrb_app_name) +############################################################################### +# ⚙️ destroy-kebab-zrb-task-name +############################################################################### + destroy_snake_zrb_app_name = CmdTask( icon='💨', name='destroy-kebab-zrb-app-name', diff --git a/src/zrb/builtin/generator/app_generator/template/base/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/image.py b/src/zrb/builtin/generator/app_generator/template/base/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/image.py index 0d253213..b9e98d9d 100644 --- a/src/zrb/builtin/generator/app_generator/template/base/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/image.py +++ b/src/zrb/builtin/generator/app_generator/template/base/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/image.py @@ -1,7 +1,7 @@ from zrb import Env ############################################################################### -# Env Definitions +# 🌱 Env Definitions ############################################################################### image_env = Env( diff --git a/src/zrb/builtin/generator/app_generator/template/base/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/local.py b/src/zrb/builtin/generator/app_generator/template/base/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/local.py index 21b605e5..7fcd1582 100644 --- a/src/zrb/builtin/generator/app_generator/template/base/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/local.py +++ b/src/zrb/builtin/generator/app_generator/template/base/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/local.py @@ -3,7 +3,7 @@ from .container import start_snake_zrb_app_name_container ############################################################################### -# Task Definitions +# ⚙️ start-kebab-zrb-task-name ############################################################################### start_snake_zrb_app_name = CmdTask( diff --git a/src/zrb/builtin/generator/app_generator/template/build-custom-image/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/_common.py b/src/zrb/builtin/generator/app_generator/template/build-custom-image/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/_common.py index 41c8b1ec..d0ef02b2 100644 --- a/src/zrb/builtin/generator/app_generator/template/build-custom-image/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/_common.py +++ b/src/zrb/builtin/generator/app_generator/template/build-custom-image/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/_common.py @@ -2,7 +2,7 @@ import os ############################################################################### -# Constants +# 🏔️ Constants ############################################################################### CURRENT_DIR = os.path.dirname(__file__) @@ -16,7 +16,7 @@ APP_TEMPLATE_ENV_FILE_NAME = os.path.join(APP_DIR, 'template.env') ############################################################################### -# Input Definitions +# 🔤 Input Definitions ############################################################################### local_input = BoolInput( diff --git a/src/zrb/builtin/generator/app_generator/template/build-custom-image/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/container.py b/src/zrb/builtin/generator/app_generator/template/build-custom-image/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/container.py index 36ed7aae..6d51421b 100644 --- a/src/zrb/builtin/generator/app_generator/template/build-custom-image/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/container.py +++ b/src/zrb/builtin/generator/app_generator/template/build-custom-image/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/container.py @@ -9,7 +9,7 @@ import os ############################################################################### -# Env File Definitions +# 🌳 Env File Definitions ############################################################################### compose_env_file = EnvFile( @@ -18,7 +18,7 @@ ) ############################################################################### -# Env Definitions +# 🌱 Env Definitions ############################################################################### host_port_env = Env( @@ -41,7 +41,7 @@ ) ############################################################################### -# Task Definitions +# ⚙️ remove-zrb-task-name-container ############################################################################### remove_snake_zrb_app_name_container = DockerComposeTask( @@ -63,6 +63,10 @@ ) runner.register(remove_snake_zrb_app_name_container) +############################################################################### +# ⚙️ stop-zrb-task-name-container +############################################################################### + stop_snake_zrb_app_name_container = DockerComposeTask( icon='⛔', name='stop-kebab-zrb-app-name-container', @@ -82,6 +86,10 @@ ) runner.register(stop_snake_zrb_app_name_container) +############################################################################### +# ⚙️ init-zrb-task-name-container +############################################################################### + init_snake_zrb_app_name_container = DockerComposeTask( icon='🔥', name='init-kebab-zrb-app-name-container', @@ -109,6 +117,10 @@ ], ) +############################################################################### +# ⚙️ start-zrb-task-name-container +############################################################################### + start_snake_zrb_app_name_container = DockerComposeTask( icon='🐳', name='start-kebab-zrb-app-name-container', diff --git a/src/zrb/builtin/generator/app_generator/template/build-custom-image/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/deployment.py b/src/zrb/builtin/generator/app_generator/template/build-custom-image/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/deployment.py index e186a7e2..1a5b7a17 100644 --- a/src/zrb/builtin/generator/app_generator/template/build-custom-image/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/deployment.py +++ b/src/zrb/builtin/generator/app_generator/template/build-custom-image/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/deployment.py @@ -8,7 +8,7 @@ import os ############################################################################### -# Input Definitions +# 🔤 Input Definitions ############################################################################### replica_input = IntInput( @@ -26,7 +26,7 @@ ) ############################################################################### -# Env File Definitions +# 🌳 Env File Definitions ############################################################################### deployment_app_env_file = EnvFile( @@ -40,7 +40,7 @@ ) ############################################################################### -# Env Definitions +# 🌱 Env Definitions ############################################################################### pulumi_backend_url_env = Env( @@ -62,7 +62,7 @@ ) ############################################################################### -# Task Definitions +# ⚙️ deploy-zrb-task-name ############################################################################### deploy_snake_zrb_app_name = CmdTask( @@ -94,6 +94,10 @@ ) runner.register(deploy_snake_zrb_app_name) +############################################################################### +# ⚙️ destroy-zrb-task-name +############################################################################### + destroy_snake_zrb_app_name = CmdTask( icon='💨', name='destroy-kebab-zrb-app-name', diff --git a/src/zrb/builtin/generator/app_generator/template/build-custom-image/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/image.py b/src/zrb/builtin/generator/app_generator/template/build-custom-image/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/image.py index 5e13d373..d7fc3149 100644 --- a/src/zrb/builtin/generator/app_generator/template/build-custom-image/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/image.py +++ b/src/zrb/builtin/generator/app_generator/template/build-custom-image/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/image.py @@ -5,7 +5,7 @@ ) ############################################################################### -# Input Definitions +# 🔤 Input Definitions ############################################################################### image_input = StrInput( @@ -17,7 +17,7 @@ ############################################################################### -# Env Definitions +# 🌱 Env Definitions ############################################################################### image_env = Env( @@ -27,7 +27,7 @@ ) ############################################################################### -# Task Definitions +# ⚙️ build-zrb-task-name-image ############################################################################### build_snake_zrb_app_name_image = DockerComposeTask( @@ -50,6 +50,10 @@ ) runner.register(build_snake_zrb_app_name_image) +############################################################################### +# ⚙️ push-zrb-task-name-image +############################################################################### + push_snake_zrb_app_name_image = DockerComposeTask( icon='📰', name='push-kebab-zrb-app-name-image', diff --git a/src/zrb/builtin/generator/app_generator/template/build-custom-image/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/local.py b/src/zrb/builtin/generator/app_generator/template/build-custom-image/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/local.py index 5279a5ba..7a4a8a29 100644 --- a/src/zrb/builtin/generator/app_generator/template/build-custom-image/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/local.py +++ b/src/zrb/builtin/generator/app_generator/template/build-custom-image/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/local.py @@ -3,11 +3,11 @@ from ._common import ( CURRENT_DIR, APP_DIR, APP_TEMPLATE_ENV_FILE_NAME, local_input, host_input ) -from .checker import snake_zrb_app_name_checker +from ._checker import snake_zrb_app_name_checker import os ############################################################################### -# Env File Definitions +# 🌳 Env File Definitions ############################################################################### app_env_file = EnvFile( @@ -15,7 +15,7 @@ ) ############################################################################### -# Task Definitions +# ⚙️ start_kebab-zrb-task-name ############################################################################### start_snake_zrb_app_name = CmdTask( diff --git a/src/zrb/builtin/generator/app_generator/template/http-port-build-custom-image/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/local.py b/src/zrb/builtin/generator/app_generator/template/http-port-build-custom-image/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/local.py index 834c38c2..a40b9a55 100644 --- a/src/zrb/builtin/generator/app_generator/template/http-port-build-custom-image/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/local.py +++ b/src/zrb/builtin/generator/app_generator/template/http-port-build-custom-image/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/local.py @@ -4,11 +4,11 @@ CURRENT_DIR, APP_DIR, APP_TEMPLATE_ENV_FILE_NAME, local_input, host_input, https_input ) -from .checker import snake_zrb_app_name_checker +from ._checker import snake_zrb_app_name_checker import os ############################################################################### -# Env File Definitions +# 🌳 Env File Definitions ############################################################################### app_env_file = EnvFile( diff --git a/src/zrb/builtin/generator/app_generator/template/http-port/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/checker.py b/src/zrb/builtin/generator/app_generator/template/http-port/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/_checker.py similarity index 100% rename from src/zrb/builtin/generator/app_generator/template/http-port/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/checker.py rename to src/zrb/builtin/generator/app_generator/template/http-port/_automate/generate_snake_zrb_meta_template_name/template/_automate/snake_zrb_app_name/_checker.py diff --git a/src/zrb/builtin/generator/cmd_task/template/_automate/snake_zrb_task_name.py b/src/zrb/builtin/generator/cmd_task/template/_automate/snake_zrb_task_name.py index 85abcb22..a9bb26d1 100644 --- a/src/zrb/builtin/generator/cmd_task/template/_automate/snake_zrb_task_name.py +++ b/src/zrb/builtin/generator/cmd_task/template/_automate/snake_zrb_task_name.py @@ -2,7 +2,7 @@ from zrb.builtin.group import project_group ############################################################################### -# Task Definitions +# ⚙️ kebab-zrb-task-name ############################################################################### snake_zrb_task_name = CmdTask( diff --git a/src/zrb/builtin/generator/docker_compose_task/template/_automate/snake_zrb_task_name.py b/src/zrb/builtin/generator/docker_compose_task/template/_automate/snake_zrb_task_name.py index 3e1e0668..0296804b 100644 --- a/src/zrb/builtin/generator/docker_compose_task/template/_automate/snake_zrb_task_name.py +++ b/src/zrb/builtin/generator/docker_compose_task/template/_automate/snake_zrb_task_name.py @@ -3,7 +3,7 @@ import os ############################################################################### -# Constants +# 🏔️ Constants ############################################################################### CURRENT_DIR = os.path.dirname(__file__) @@ -11,7 +11,7 @@ RESOURCE_DIR = os.path.join(PROJECT_DIR, 'src', 'kebab-zrb-task-name') ############################################################################### -# Task Definitions +# ⚙️ kebab-zrb-task-name ############################################################################### snake_zrb_task_name = DockerComposeTask( diff --git a/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/_checker.py b/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/_checker.py new file mode 100644 index 00000000..d436697e --- /dev/null +++ b/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/_checker.py @@ -0,0 +1,64 @@ +from zrb import HTTPChecker, PortChecker +from ._helper import should_start_local_microservices + +rabbitmq_management_checker = HTTPChecker( + name='check-rabbitmq-management', + port='{{env.get("RABBITMQ_MANAGEMENT_HOST_PORT", "15672")}}', + is_https='{{input.snake_zrb_app_name_https}}', + should_execute='{{env.get("APP_BROKER_TYPE", "rabbitmq") == "rabbitmq"}}' +) + +rabbitmq_checker = PortChecker( + name='check-rabbitmq', + port='{{env.get("RABBITMQ_HOST_PORT", "5672")}}', + should_execute='{{env.get("APP_BROKER_TYPE", "rabbitmq") == "rabbitmq"}}' +) + +redpanda_console_checker = HTTPChecker( + name='check-redpanda-console', + method='GET', + port='{{env.get("REDPANDA_CONSOLE_HOST_PORT", "9000")}}', + is_https='{{input.snake_zrb_app_name_https}}', + should_execute='{{env.get("APP_BROKER_TYPE", "rabbitmq") == "kafka"}}' +) + +kafka_plaintext_checker = PortChecker( + name='check-kafka-plaintext', + port='{{env.get("KAFKA_INTERNAL_HOST_PORT", "29092")}}', + should_execute='{{env.get("APP_BROKER_TYPE", "rabbitmq") == "kafka"}}' +) + +kafka_outside_checker = PortChecker( + name='check-kafka-outside', + port='{{env.get("KAFKA_EXTERNAL_HOST_PORT", "9092")}}', + should_execute='{{env.get("APP_BROKER_TYPE", "rabbitmq") == "kafka"}}' +) + +pandaproxy_plaintext_checker = PortChecker( + name='check-pandaproxy-plaintext', + port='{{env.get("PANDAPROXY_INTERNAL_HOST_PORT", "29092")}}', + should_execute='{{env.get("APP_BROKER_TYPE", "rabbitmq") == "kafka"}}' +) + +pandaproxy_outside_checker = PortChecker( + name='check-pandaproxy-outside', + port='{{env.get("PANDAPROXY_EXTERNAL_HOST_PORT", "9092")}}', + should_execute='{{env.get("APP_BROKER_TYPE", "rabbitmq") == "kafka"}}' +) + +app_container_checker = HTTPChecker( + name='check-kebab-zrb-app-name-container', + host='{{input.snake_zrb_app_name_host}}', + url='/readiness', + port='{{env.get("HOST_PORT", "zrbAppHttpPort")}}', + is_https='{{input.snake_zrb_app_name_https}}' +) + +app_local_checker = HTTPChecker( + name='check-kebab-zrb-app-name', + host='{{input.snake_zrb_app_name_host}}', + url='/readiness', + port='{{env.APP_PORT}}', + is_https='{{input.snake_zrb_app_name_https}}', + should_execute=should_start_local_microservices +) diff --git a/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/_common.py b/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/_common.py deleted file mode 100644 index 5129d73f..00000000 --- a/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/_common.py +++ /dev/null @@ -1,153 +0,0 @@ -from typing import Any -from zrb import ( - BoolInput, ChoiceInput, StrInput, Env, HTTPChecker, PortChecker -) -import jsons -import os - -############################################################################### -# Constants -############################################################################### - -CURRENT_DIR = os.path.dirname(__file__) -PROJECT_DIR = os.path.abspath(os.path.join(CURRENT_DIR, '..', '..')) -RESOURCE_DIR = os.path.join(PROJECT_DIR, 'src', 'kebab-zrb-app-name') -DEPLOYMENT_DIR = os.path.join(RESOURCE_DIR, 'deployment') -DEPLOYMENT_TEMPLATE_ENV_FILE_NAME = os.path.join( - DEPLOYMENT_DIR, 'template.env' -) -APP_DIR = os.path.join(RESOURCE_DIR, 'src') -APP_FRONTEND_DIR = os.path.join(APP_DIR, 'frontend') -APP_FRONTEND_BUILD_DIR = os.path.join(APP_FRONTEND_DIR, 'build') -APP_TEMPLATE_ENV_FILE_NAME = os.path.join(APP_DIR, 'template.env') -MODULE_CONFIG_PATH = os.path.join(CURRENT_DIR, 'config', 'modules.json') -with open(MODULE_CONFIG_PATH) as file: - MODULE_JSON_STR = file.read() -MODULES = jsons.loads(MODULE_JSON_STR) - -############################################################################### -# Functions -############################################################################### - - -def should_start_local_microservices(*args: Any, **kwargs: Any) -> bool: - if not kwargs.get('local_snake_zrb_app_name', True): - return False - run_mode = kwargs.get('snake_zrb_app_name_run_mode', 'monolith') - return run_mode == 'microservices' - - -############################################################################### -# Checker Task Definitions -############################################################################### - -rabbitmq_management_checker = HTTPChecker( - name='check-rabbitmq-management', - port='{{env.get("RABBITMQ_MANAGEMENT_HOST_PORT", "15672")}}', - is_https='{{input.snake_zrb_app_name_https}}', - should_execute='{{env.get("APP_BROKER_TYPE", "rabbitmq") == "rabbitmq"}}' -) - -rabbitmq_checker = PortChecker( - name='check-rabbitmq', - port='{{env.get("RABBITMQ_HOST_PORT", "5672")}}', - should_execute='{{env.get("APP_BROKER_TYPE", "rabbitmq") == "rabbitmq"}}' -) - -redpanda_console_checker = HTTPChecker( - name='check-redpanda-console', - method='GET', - port='{{env.get("REDPANDA_CONSOLE_HOST_PORT", "9000")}}', - is_https='{{input.snake_zrb_app_name_https}}', - should_execute='{{env.get("APP_BROKER_TYPE", "rabbitmq") == "kafka"}}' -) - -kafka_plaintext_checker = PortChecker( - name='check-kafka-plaintext', - port='{{env.get("KAFKA_INTERNAL_HOST_PORT", "29092")}}', - should_execute='{{env.get("APP_BROKER_TYPE", "rabbitmq") == "kafka"}}' -) - -kafka_outside_checker = PortChecker( - name='check-kafka-outside', - port='{{env.get("KAFKA_EXTERNAL_HOST_PORT", "9092")}}', - should_execute='{{env.get("APP_BROKER_TYPE", "rabbitmq") == "kafka"}}' -) - -pandaproxy_plaintext_checker = PortChecker( - name='check-pandaproxy-plaintext', - port='{{env.get("PANDAPROXY_INTERNAL_HOST_PORT", "29092")}}', - should_execute='{{env.get("APP_BROKER_TYPE", "rabbitmq") == "kafka"}}' -) - -pandaproxy_outside_checker = PortChecker( - name='check-pandaproxy-outside', - port='{{env.get("PANDAPROXY_EXTERNAL_HOST_PORT", "9092")}}', - should_execute='{{env.get("APP_BROKER_TYPE", "rabbitmq") == "kafka"}}' -) - -app_container_checker = HTTPChecker( - name='check-kebab-zrb-app-name-container', - host='{{input.snake_zrb_app_name_host}}', - url='/readiness', - port='{{env.get("HOST_PORT", "zrbAppHttpPort")}}', - is_https='{{input.snake_zrb_app_name_https}}' -) - -app_local_checker = HTTPChecker( - name='check-kebab-zrb-app-name', - host='{{input.snake_zrb_app_name_host}}', - url='/readiness', - port='{{env.APP_PORT}}', - is_https='{{input.snake_zrb_app_name_https}}', - should_execute=should_start_local_microservices -) - -############################################################################### -# Input Definitions -############################################################################### - -enable_monitoring_input = BoolInput( - name='enable-kebab-zrb-app-name-monitoring', - description='Enable "kebab-zrb-app-name" monitoring', - prompt='Enable "kebab-zrb-app-name" monitoring?', - default=False -) - -local_input = BoolInput( - name='local-kebab-zrb-app-name', - description='Use "kebab-zrb-app-name" on local machine', - prompt='Use "kebab-zrb-app-name" on local machine?', - default=True -) - -run_mode_input = ChoiceInput( - name='kebab-zrb-app-name-run-mode', - description='"kebab-zrb-app-name" run mode (monolith/microservices)', - prompt='Run "kebab-zrb-app-name" as a monolith or microservices?', - choices=['monolith', 'microservices'], - default='monolith' -) - -https_input = BoolInput( - name='kebab-zrb-app-name-https', - description='Whether "kebab-zrb-app-name" run on HTTPS', - prompt='Is "kebab-zrb-app-name" run on HTTPS?', - default=False -) - -host_input = StrInput( - name='kebab-zrb-app-name-host', - description='Hostname of "kebab-zrb-app-name"', - prompt='Hostname of "kebab-zrb-app-name"', - default='localhost' -) - -############################################################################### -# Env fDefinitions -############################################################################### - -app_enable_otel_env = Env( - name='APP_ENABLE_OTEL', - default='{{ "1" if input.enable_snake_zrb_app_name_monitoring else "0" }}' -) diff --git a/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/_config.py b/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/_config.py new file mode 100644 index 00000000..b08a1ec0 --- /dev/null +++ b/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/_config.py @@ -0,0 +1,56 @@ +from typing import Mapping +from zrb import Env, ServiceConfig, EnvFile +from zrb.helper.util import to_kebab_case + +import jsons +import os + +CURRENT_DIR = os.path.dirname(__file__) +PROJECT_DIR = os.path.abspath(os.path.join(CURRENT_DIR, '..', '..')) +RESOURCE_DIR = os.path.join(PROJECT_DIR, 'src', 'kebab-zrb-app-name') +DEPLOYMENT_DIR = os.path.join(RESOURCE_DIR, 'deployment') +DEPLOYMENT_TEMPLATE_ENV_FILE_NAME = os.path.join( + DEPLOYMENT_DIR, 'template.env' +) +APP_DIR = os.path.join(RESOURCE_DIR, 'src') +APP_FRONTEND_DIR = os.path.join(APP_DIR, 'frontend') +APP_FRONTEND_BUILD_DIR = os.path.join(APP_FRONTEND_DIR, 'build') +APP_TEMPLATE_ENV_FILE_NAME = os.path.join(APP_DIR, 'template.env') + +LOAD_TEST_DIR = os.path.join(RESOURCE_DIR, 'loadtest') +LOAD_TEST_TEMPLATE_ENV_FILE_NAME = os.path.join(RESOURCE_DIR, 'template.env') + +MODULE_CONFIG_PATH = os.path.join(CURRENT_DIR, 'config', 'modules.json') + +with open(MODULE_CONFIG_PATH) as file: + MODULE_JSON_STR = file.read() +MODULES = jsons.loads(MODULE_JSON_STR) + +DOCKER_COMPOSE_APP_ENV_FILE_NAME = os.path.join( + RESOURCE_DIR, 'docker-compose-app.env' +) + +SERVICE_CONFIGS: Mapping[str, ServiceConfig] = {} +service_names = [to_kebab_case(module) + '-service' for module in MODULES] +for suffix in ['', 'gateway'] + service_names: + service_suffix = '-' + suffix if suffix != '' else '' + service_name = f'kebab-zrb-app-name{service_suffix}' + SERVICE_CONFIGS[service_name] = ServiceConfig( + env_files=[ + EnvFile( + path=APP_TEMPLATE_ENV_FILE_NAME, + prefix='CONTAINER_ZRB_ENV_PREFIX' + ), + EnvFile( + path=DOCKER_COMPOSE_APP_ENV_FILE_NAME, + prefix='CONTAINER_ZRB_ENV_PREFIX' + ) + ], + envs=[ + Env( + name='APP_OTEL_EXPORTER_OTLP_ENDPOINT', + os_name='', + default='http://otel-collector:4317' + ) + ] + ) diff --git a/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/_env.py b/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/_env.py new file mode 100644 index 00000000..872c307c --- /dev/null +++ b/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/_env.py @@ -0,0 +1,44 @@ +from zrb import Env +from ._config import DEPLOYMENT_DIR, MODULES +import jsons + +app_enable_otel_env = Env( + name='APP_ENABLE_OTEL', + default='{{ "1" if input.enable_snake_zrb_app_name_monitoring else "0" }}' +) + +image_env = Env( + name='IMAGE', + os_name='CONTAINER_ZRB_ENV_PREFIX_IMAGE', + default='{{input.snake_zrb_app_name_image}}' +) + +pulumi_backend_url_env = Env( + name='PULUMI_BACKEND_URL', + os_name='PULUMI_ZRB_ENV_PREFIX_BACKEND_URL', + default=f'file://{DEPLOYMENT_DIR}/state' +) + +pulumi_config_passphrase_env = Env( + name='PULUMI_CONFIG_PASSPHRASE', + os_name='PULUMI_ZRB_ENV_PREFIX_CONFIG_PASSPHRASE', + default='secret' +) + +deployment_modules_env = Env( + name='MODULES', + os_name='DEPLOYMENT_CONFIG_ZRB_ENV_PREFIX_MODULES', + default=jsons.dumps(MODULES) +) + +deployment_mode_env = Env( + name='MODE', + os_name='DEPLOYMENT_CONFIG_ZRB_ENV_PREFIX_MODE', + default='{{input.snake_zrb_app_name_deploy_mode}}' +) + +deployment_enable_monitoring_env = Env( + name='ENABLE_MONITORING', + os_name='DEPLOYMENT_CONFIG_ZRB_ENV_PREFIX_ENABLE_MONITORING', + default='{{ 1 if input.enable_snake_zrb_app_name_monitoring else 0 }}' +) \ No newline at end of file diff --git a/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/_env_file.py b/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/_env_file.py new file mode 100644 index 00000000..55fab972 --- /dev/null +++ b/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/_env_file.py @@ -0,0 +1,24 @@ +from zrb import EnvFile +from ._config import ( + RESOURCE_DIR, APP_TEMPLATE_ENV_FILE_NAME, DEPLOYMENT_TEMPLATE_ENV_FILE_NAME +) +import os + +app_env_file = EnvFile( + path=APP_TEMPLATE_ENV_FILE_NAME, prefix='ZRB_ENV_PREFIX' +) + +compose_env_file = EnvFile( + path=os.path.join(RESOURCE_DIR, 'docker-compose.env'), + prefix='CONTAINER_ZRB_ENV_PREFIX' +) + +deployment_app_env_file = EnvFile( + path=APP_TEMPLATE_ENV_FILE_NAME, + prefix='DEPLOYMENT_APP_ZRB_ENV_PREFIX' +) + +deployment_config_env_file = EnvFile( + path=DEPLOYMENT_TEMPLATE_ENV_FILE_NAME, + prefix='DEPLOYMENT_CONFIG_ZRB_ENV_PREFIX' +) \ No newline at end of file diff --git a/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/local_microservices.py b/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/_get_start_microservices.py similarity index 94% rename from src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/local_microservices.py rename to src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/_get_start_microservices.py index 25e3674e..2d80adc6 100644 --- a/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/local_microservices.py +++ b/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/_get_start_microservices.py @@ -1,12 +1,13 @@ from typing import List from zrb import CmdTask, Env, HTTPChecker, Task, EnvFile from zrb.helper.util import to_snake_case, to_kebab_case -from ._common import ( - CURRENT_DIR, APP_DIR, should_start_local_microservices, - APP_TEMPLATE_ENV_FILE_NAME, MODULES, +from ._helper import should_start_local_microservices +from ._input import ( local_input, run_mode_input, host_input, https_input, - enable_monitoring_input, app_enable_otel_env + enable_monitoring_input ) +from ._env import app_enable_otel_env +from ._config import CURRENT_DIR, APP_DIR, APP_TEMPLATE_ENV_FILE_NAME, MODULES import os diff --git a/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/_helper.py b/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/_helper.py new file mode 100644 index 00000000..55871d60 --- /dev/null +++ b/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/_helper.py @@ -0,0 +1,71 @@ +from typing import Any, List +from zrb import Task + +############################################################################### +# Functions +############################################################################### + + +def should_start_local_microservices(*args: Any, **kwargs: Any) -> bool: + if not kwargs.get('local_snake_zrb_app_name', True): + return False + run_mode = kwargs.get('snake_zrb_app_name_run_mode', 'monolith') + return run_mode == 'microservices' + + +def get_support_container_compose_profiles( + *args: Any, **kwargs: Any +) -> List[str]: + task: Task = kwargs.get('_task') + env_map = task.get_env_map() + compose_profiles: List[str] = [] + broker_type = env_map.get('APP_BROKER_TYPE', 'rabbitmq') + if broker_type in ['rabbitmq', 'kafka']: + compose_profiles.append(broker_type) + if kwargs.get('enable_snake_zrb_app_name_monitoring', False): + compose_profiles.append('monitoring') + return compose_profiles + + +def get_container_compose_profiles(*args: Any, **kwargs: Any) -> str: + compose_profiles = get_support_container_compose_profiles(*args, **kwargs) + compose_profiles.append( + kwargs.get('snake_zrb_app_name_run_mode', 'monolith'), + ) + return compose_profiles + + +def activate_support_compose_profile(*args: Any, **kwargs: Any) -> str: + compose_profiles = get_support_container_compose_profiles(*args, **kwargs) + compose_profile_str = ','.join(compose_profiles) + return f'export COMPOSE_PROFILES={compose_profile_str}' + + +def should_start_support_container(*args: Any, **kwargs: Any) -> bool: + if not kwargs.get('local_snake_zrb_app_name', True): + return False + compose_profiles = get_support_container_compose_profiles(*args, **kwargs) + return len(compose_profiles) > 0 + + +def should_start_local_monolith(*args: Any, **kwargs: Any) -> bool: + if not kwargs.get('local_snake_zrb_app_name', True): + return False + return kwargs.get('snake_zrb_app_name_run_mode', 'monolith') == 'monolith' + + +def activate_selected_compose_profile(*args: Any, **kwargs: Any) -> str: + compose_profiles = get_container_compose_profiles(*args, **kwargs) + compose_profile_str = ','.join(compose_profiles) + return f'export COMPOSE_PROFILES={compose_profile_str}' + + +def activate_all_compose_profile(*args: Any, **kwargs: Any) -> str: + compose_profile_str = ','.join([ + 'monitoring', 'monolith', 'microservices', 'kafka', 'rabbitmq' + ]) + return f'export COMPOSE_PROFILES={compose_profile_str}' + + +def should_start_container(*args: Any, **kwargs: Any) -> bool: + return kwargs.get('local_snake_zrb_app_name', True) diff --git a/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/_input.py b/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/_input.py new file mode 100644 index 00000000..d651a59d --- /dev/null +++ b/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/_input.py @@ -0,0 +1,60 @@ +from zrb import BoolInput, ChoiceInput, StrInput +import os + +enable_monitoring_input = BoolInput( + name='enable-kebab-zrb-app-name-monitoring', + description='Enable "kebab-zrb-app-name" monitoring', + prompt='Enable "kebab-zrb-app-name" monitoring?', + default=False +) + +local_input = BoolInput( + name='local-kebab-zrb-app-name', + description='Use "kebab-zrb-app-name" on local machine', + prompt='Use "kebab-zrb-app-name" on local machine?', + default=True +) + +run_mode_input = ChoiceInput( + name='kebab-zrb-app-name-run-mode', + description='"kebab-zrb-app-name" run mode (monolith/microservices)', + prompt='Run "kebab-zrb-app-name" as a monolith or microservices?', + choices=['monolith', 'microservices'], + default='monolith' +) + +https_input = BoolInput( + name='kebab-zrb-app-name-https', + description='Whether "kebab-zrb-app-name" run on HTTPS', + prompt='Is "kebab-zrb-app-name" run on HTTPS?', + default=False +) + +host_input = StrInput( + name='kebab-zrb-app-name-host', + description='Hostname of "kebab-zrb-app-name"', + prompt='Hostname of "kebab-zrb-app-name"', + default='localhost' +) + +image_input = StrInput( + name='kebab-zrb-app-name-image', + description='Image name of "kebab-zrb-app-name"', + prompt='Image name of "kebab-zrb-app-name"', + default='zrb-app-image-name:latest' +) + +deploy_mode_input = ChoiceInput( + name='kebab-zrb-app-name-deploy-mode', + description='"kebab-zrb-app-name" deploy mode (monolith/microservices)', + prompt='Deploy "kebab-zrb-app-name" as a monolith or microservices?', + choices=['monolith', 'microservices'], + default='monolith' +) + +pulumi_stack_input = StrInput( + name='kebab-zrb-app-name-pulumi-stack', + description='Pulumi stack name for "kebab-zrb-app-name"', + prompt='Pulumi stack name for "kebab-zrb-app-name"', + default=os.getenv('ZRB_ENV', 'dev') +) \ No newline at end of file diff --git a/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/container.py b/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/container.py index 12f17788..d62eb507 100644 --- a/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/container.py +++ b/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/container.py @@ -1,97 +1,26 @@ -from typing import Mapping, Any, List -from zrb import DockerComposeTask, Env, ServiceConfig, EnvFile, runner, Task -from zrb.helper.util import to_kebab_case +from zrb import DockerComposeTask, runner from zrb.builtin.group import project_group -from ._common import ( - APP_TEMPLATE_ENV_FILE_NAME, RESOURCE_DIR, MODULES, app_container_checker, - rabbitmq_checker, rabbitmq_management_checker, redpanda_console_checker, - kafka_outside_checker, kafka_plaintext_checker, pandaproxy_outside_checker, - pandaproxy_plaintext_checker, local_input, run_mode_input, - enable_monitoring_input, host_input, https_input, app_enable_otel_env +from ._checker import ( + app_container_checker, rabbitmq_checker, rabbitmq_management_checker, + redpanda_console_checker, kafka_outside_checker, kafka_plaintext_checker, + pandaproxy_outside_checker, pandaproxy_plaintext_checker ) -from .image import build_snake_zrb_app_name_image, image_input, image_env -import os - -DOCKER_COMPOSE_APP_ENV_FILE_NAME = os.path.join( - RESOURCE_DIR, 'docker-compose-app.env' +from ._input import ( + local_input, run_mode_input, enable_monitoring_input, host_input, + https_input, image_input ) - -############################################################################### -# Functions -############################################################################### - - -def setup_runtime_compose_profile(*args: Any, **kwargs: Any) -> str: - task: Task = kwargs.get('_task') - env_map = task.get_env_map() - compose_profiles: List[str] = [ - kwargs.get('snake_zrb_app_name_run_mode', 'monolith'), - ] - broker_type = env_map.get('APP_BROKER_TYPE', 'rabbitmq') - if broker_type in ['rabbitmq', 'kafka']: - compose_profiles.append(broker_type) - if kwargs.get('enable_snake_zrb_app_name_monitoring', False): - compose_profiles.append('monitoring') - compose_profile_str = ','.join(compose_profiles) - return f'export COMPOSE_PROFILES={compose_profile_str}' - - -def setup_all_compose_profile(*args: Any, **kwargs: Any) -> str: - compose_profiles = [ - 'monitoring', - 'monolith', - 'microservices', - 'kafka', - 'rabbitmq' - ] - compose_profile_str = ','.join(compose_profiles) - return f'export COMPOSE_PROFILES={compose_profile_str}' - - -def should_execute(*args: Any, **kwargs: Any) -> bool: - return kwargs.get('local_snake_zrb_app_name', True) - - -############################################################################### -# Env File Definitions -############################################################################### - -compose_env_file = EnvFile( - path=os.path.join(RESOURCE_DIR, 'docker-compose.env'), - prefix='CONTAINER_ZRB_ENV_PREFIX' +from ._env import app_enable_otel_env, image_env +from ._env_file import compose_env_file +from ._helper import ( + activate_selected_compose_profile, activate_all_compose_profile, + should_start_container ) +from ._config import RESOURCE_DIR, SERVICE_CONFIGS +from .image import build_snake_zrb_app_name_image -############################################################################### -# Compose Service Config Definitions -############################################################################### - -service_configs: Mapping[str, ServiceConfig] = {} -service_names = [to_kebab_case(module) + '-service' for module in MODULES] -for suffix in ['', 'gateway'] + service_names: - service_suffix = '-' + suffix if suffix != '' else '' - service_name = f'kebab-zrb-app-name{service_suffix}' - service_configs[service_name] = ServiceConfig( - env_files=[ - EnvFile( - path=APP_TEMPLATE_ENV_FILE_NAME, - prefix='CONTAINER_ZRB_ENV_PREFIX' - ), - EnvFile( - path=DOCKER_COMPOSE_APP_ENV_FILE_NAME, - prefix='CONTAINER_ZRB_ENV_PREFIX' - ) - ], - envs=[ - Env( - name='APP_OTEL_EXPORTER_OTLP_ENDPOINT', - os_name='', - default='http://otel-collector:4317' - ) - ] - ) ############################################################################### -# Task Definitions +# ⚙️ remove-kebab-zrb-task-name-container ############################################################################### remove_snake_zrb_app_name_container = DockerComposeTask( @@ -100,15 +29,19 @@ def should_execute(*args: Any, **kwargs: Any) -> bool: description='Remove human readable zrb app name container', group=project_group, cwd=RESOURCE_DIR, - setup_cmd=setup_all_compose_profile, + setup_cmd=activate_all_compose_profile, compose_cmd='down', compose_env_prefix='CONTAINER_ZRB_ENV_PREFIX', - compose_service_configs=service_configs, + compose_service_configs=SERVICE_CONFIGS, envs=[image_env], env_files=[compose_env_file] ) runner.register(remove_snake_zrb_app_name_container) +############################################################################### +# ⚙️ init-kebab-zrb-task-name-container +############################################################################### + init_snake_zrb_app_name_container = DockerComposeTask( icon='🔥', name='init-kebab-zrb-app-name-container', @@ -120,17 +53,17 @@ def should_execute(*args: Any, **kwargs: Any) -> bool: host_input, image_input, ], - should_execute=should_execute, + should_execute=should_start_container, upstreams=[ build_snake_zrb_app_name_image, remove_snake_zrb_app_name_container ], cwd=RESOURCE_DIR, - setup_cmd=setup_runtime_compose_profile, + setup_cmd=activate_selected_compose_profile, compose_cmd='up', compose_flags=['-d'], compose_env_prefix='CONTAINER_ZRB_ENV_PREFIX', - compose_service_configs=service_configs, + compose_service_configs=SERVICE_CONFIGS, envs=[ image_env, app_enable_otel_env, @@ -138,6 +71,10 @@ def should_execute(*args: Any, **kwargs: Any) -> bool: env_files=[compose_env_file], ) +############################################################################### +# ⚙️ start-kebab-zrb-task-name-container +############################################################################### + start_snake_zrb_app_name_container = DockerComposeTask( icon='🐳', name='start-kebab-zrb-app-name-container', @@ -150,14 +87,14 @@ def should_execute(*args: Any, **kwargs: Any) -> bool: https_input, image_input, ], - should_execute=should_execute, + should_execute=should_start_container, upstreams=[init_snake_zrb_app_name_container], cwd=RESOURCE_DIR, - setup_cmd=setup_runtime_compose_profile, + setup_cmd=activate_selected_compose_profile, compose_cmd='logs', compose_flags=['-f'], compose_env_prefix='CONTAINER_ZRB_ENV_PREFIX', - compose_service_configs=service_configs, + compose_service_configs=SERVICE_CONFIGS, envs=[image_env], env_files=[compose_env_file], checkers=[ @@ -173,16 +110,20 @@ def should_execute(*args: Any, **kwargs: Any) -> bool: ) runner.register(start_snake_zrb_app_name_container) +############################################################################### +# ⚙️ stop-kebab-zrb-task-name-container +############################################################################### + stop_snake_zrb_app_name_container = DockerComposeTask( icon='⛔', name='stop-kebab-zrb-app-name-container', description='Stop human readable zrb app name container', group=project_group, cwd=RESOURCE_DIR, - setup_cmd=setup_all_compose_profile, + setup_cmd=activate_all_compose_profile, compose_cmd='stop', compose_env_prefix='CONTAINER_ZRB_ENV_PREFIX', - compose_service_configs=service_configs, + compose_service_configs=SERVICE_CONFIGS, envs=[image_env], env_files=[compose_env_file] ) diff --git a/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/deployment.py b/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/deployment.py index 6f589c7a..742ed77d 100644 --- a/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/deployment.py +++ b/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/deployment.py @@ -1,89 +1,20 @@ -from zrb import CmdTask, Env, EnvFile, StrInput, ChoiceInput, runner +from zrb import CmdTask, runner from zrb.builtin.group import project_group from .image import push_snake_zrb_app_name_image -from ._common import ( - CURRENT_DIR, DEPLOYMENT_DIR, APP_TEMPLATE_ENV_FILE_NAME, - DEPLOYMENT_TEMPLATE_ENV_FILE_NAME, MODULES, - enable_monitoring_input +from ._config import CURRENT_DIR, DEPLOYMENT_DIR +from ._input import ( + enable_monitoring_input, image_input, deploy_mode_input, pulumi_stack_input ) -from .image import image_input, image_env -import os -import jsons - - -############################################################################### -# Input Definitions -############################################################################### - -deploy_mode_input = ChoiceInput( - name='kebab-zrb-app-name-deploy-mode', - description='"kebab-zrb-app-name" deploy mode (monolith/microservices)', - prompt='Deploy "kebab-zrb-app-name" as a monolith or microservices?', - choices=['monolith', 'microservices'], - default='monolith' -) - -pulumi_stack_input = StrInput( - name='kebab-zrb-app-name-pulumi-stack', - description='Pulumi stack name for "kebab-zrb-app-name"', - prompt='Pulumi stack name for "kebab-zrb-app-name"', - default=os.getenv('ZRB_ENV', 'dev') -) - -############################################################################### -# Env Definitions -############################################################################### - -pulumi_backend_url_env = Env( - name='PULUMI_BACKEND_URL', - os_name='PULUMI_ZRB_ENV_PREFIX_BACKEND_URL', - default=f'file://{DEPLOYMENT_DIR}/state' -) - -pulumi_config_passphrase_env = Env( - name='PULUMI_CONFIG_PASSPHRASE', - os_name='PULUMI_ZRB_ENV_PREFIX_CONFIG_PASSPHRASE', - default='secret' -) - -############################################################################### -# Env File Definitions -############################################################################### - -deployment_app_env_file = EnvFile( - path=APP_TEMPLATE_ENV_FILE_NAME, - prefix='DEPLOYMENT_APP_ZRB_ENV_PREFIX' -) - -deployment_config_env_file = EnvFile( - path=DEPLOYMENT_TEMPLATE_ENV_FILE_NAME, - prefix='DEPLOYMENT_CONFIG_ZRB_ENV_PREFIX' -) - -############################################################################### -# Env Definitions -############################################################################### - -deployment_modules_env = Env( - name='MODULES', - os_name='DEPLOYMENT_CONFIG_ZRB_ENV_PREFIX_MODULES', - default=jsons.dumps(MODULES) -) - -deployment_mode_env = Env( - name='MODE', - os_name='DEPLOYMENT_CONFIG_ZRB_ENV_PREFIX_MODE', - default='{{input.snake_zrb_app_name_deploy_mode}}' -) - -deployment_enable_monitoring_env = Env( - name='ENABLE_MONITORING', - os_name='DEPLOYMENT_CONFIG_ZRB_ENV_PREFIX_ENABLE_MONITORING', - default='{{ 1 if input.enable_snake_zrb_app_name_monitoring else 0 }}' +from ._env import ( + image_env, pulumi_backend_url_env, pulumi_config_passphrase_env, + deployment_modules_env, deployment_mode_env, + deployment_enable_monitoring_env ) +from ._env_file import deployment_app_env_file, deployment_config_env_file +import os ############################################################################### -# Task Definitions +# ⚙️ deploy-kebab-zrb-task-name ############################################################################### deploy_snake_zrb_app_name = CmdTask( @@ -118,6 +49,10 @@ ) runner.register(deploy_snake_zrb_app_name) +############################################################################### +# ⚙️ destroy-kebab-zrb-task-name +############################################################################### + destroy_snake_zrb_app_name = CmdTask( icon='💨', name='destroy-kebab-zrb-app-name', diff --git a/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/frontend.py b/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/frontend.py index a3b527e1..f9945db7 100644 --- a/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/frontend.py +++ b/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/frontend.py @@ -1,13 +1,13 @@ from zrb import CmdTask, Env, EnvFile, PathChecker, runner from zrb.builtin.group import project_group -from ._common import ( +from ._config import ( APP_FRONTEND_DIR, APP_FRONTEND_BUILD_DIR, CURRENT_DIR, APP_TEMPLATE_ENV_FILE_NAME ) import os ############################################################################### -# Task Definitions +# ⚙️ build-kebab-zrb-task-name-frontend ############################################################################### build_snake_zrb_app_name_frontend = CmdTask( @@ -34,6 +34,10 @@ ) runner.register(build_snake_zrb_app_name_frontend) +############################################################################### +# ⚙️ build-kebab-zrb-task-name-frontend-once +############################################################################### + build_snake_zrb_app_name_frontend_once = CmdTask( icon='🚤', name='build-kebab-zrb-app-name-frontend_once', diff --git a/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/image.py b/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/image.py index 8d35eea3..78319b69 100644 --- a/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/image.py +++ b/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/image.py @@ -1,30 +1,11 @@ -from zrb import DockerComposeTask, Env, StrInput, runner +from zrb import DockerComposeTask, runner from zrb.builtin.group import project_group -from ._common import RESOURCE_DIR, local_input +from ._config import RESOURCE_DIR +from ._input import local_input, image_input +from ._env import image_env ############################################################################### -# Input Definitions -############################################################################### - -image_input = StrInput( - name='kebab-zrb-app-name-image', - description='Image name of "kebab-zrb-app-name"', - prompt='Image name of "kebab-zrb-app-name"', - default='zrb-app-image-name:latest' -) - -############################################################################### -# Env fDefinitions -############################################################################### - -image_env = Env( - name='IMAGE', - os_name='CONTAINER_ZRB_ENV_PREFIX_IMAGE', - default='{{input.snake_zrb_app_name_image}}' -) - -############################################################################### -# Task Definitions +# ⚙️ build-kebab-zrb-task-name-image ############################################################################### build_snake_zrb_app_name_image = DockerComposeTask( @@ -47,6 +28,10 @@ ) runner.register(build_snake_zrb_app_name_image) +############################################################################### +# ⚙️ push-kebab-zrb-task-name-image +############################################################################### + push_snake_zrb_app_name_image = DockerComposeTask( icon='📰', name='push-kebab-zrb-app-name-image', diff --git a/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/load_test.py b/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/load_test.py index a91d88ca..719cb83e 100644 --- a/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/load_test.py +++ b/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/load_test.py @@ -1,65 +1,12 @@ from zrb import CmdTask, EnvFile, BoolInput, StrInput, IntInput, runner from zrb.builtin.group import project_group -from ._common import CURRENT_DIR, RESOURCE_DIR -import os - -############################################################################### -# Constants -############################################################################### - -LOAD_TEST_DIR = os.path.join(RESOURCE_DIR, 'loadtest') -LOAD_TEST_TEMPLATE_ENV_FILE_NAME = os.path.join(RESOURCE_DIR, 'template.env') - -############################################################################### -# Input Definitions -############################################################################### - -headless_input = BoolInput( - name='kebab-zrb-app-name-load-test-headless', - default=True, - description='Load test UI headless', - prompt='Load test UI headless (if True, there will be no UI)', -) - -web_port_input = IntInput( - name='kebab-zrb-app-name-load-test-port', - default=8089, - description='Load test UI web port', - prompt='Load test UI web port (Only works if headless is False)', -) - -users_input = IntInput( - name='kebab-zrb-app-name-load-test-users', - default=200, - description='Load test users', - prompt='Load test users', -) - -spawn_rate_input = IntInput( - name='kebab-zrb-app-name-load-test-spawn-rate', - default=10, - description='Load test spawn rate', - prompt='Load test spawn rate', -) - -url_input = StrInput( - name='kebab-zrb-app-name-load-test-url', - default='http://localhost:zrbAppHttpPort', - description='Load test url', - prompt='Load test url', -) - -############################################################################### -# Env file Definitions -############################################################################### - -load_test_env_file = EnvFile( - path=LOAD_TEST_TEMPLATE_ENV_FILE_NAME, - prefix='LOAD_TEST_ZRB_ENV_PREFIX' +from ._config import ( + CURRENT_DIR, LOAD_TEST_DIR, LOAD_TEST_TEMPLATE_ENV_FILE_NAME ) +import os ############################################################################### -# Task Definitions +# ⚙️ prepare-kebab-zrb-task-name-load-test ############################################################################### prepare_snake_zrb_app_name_load_test = CmdTask( @@ -75,6 +22,10 @@ ) runner.register(prepare_snake_zrb_app_name_load_test) +############################################################################### +# ⚙️ load-test-kebab-zrb-task-name +############################################################################### + load_test_snake_zrb_app_name_load_test = CmdTask( icon='🧪', name='load-test-kebab-zrb-app-name', @@ -82,14 +33,44 @@ group=project_group, upstreams=[prepare_snake_zrb_app_name_load_test], inputs=[ - headless_input, - web_port_input, - users_input, - spawn_rate_input, - url_input, + BoolInput( + name='kebab-zrb-app-name-load-test-headless', + default=True, + description='Load test UI headless', + prompt='Load test UI headless (if True, there will be no UI)', + ), + IntInput( + name='kebab-zrb-app-name-load-test-port', + default=8089, + description='Load test UI web port', + prompt='Load test UI web port (Only works if headless is False)', + ), + IntInput( + name='kebab-zrb-app-name-load-test-users', + default=200, + description='Load test users', + prompt='Load test users', + ), + IntInput( + name='kebab-zrb-app-name-load-test-spawn-rate', + default=10, + description='Load test spawn rate', + prompt='Load test spawn rate', + ), + StrInput( + name='kebab-zrb-app-name-load-test-url', + default='http://localhost:zrbAppHttpPort', + description='Load test url', + prompt='Load test url', + ) ], cwd=LOAD_TEST_DIR, - env_files=[load_test_env_file], + env_files=[ + EnvFile( + path=LOAD_TEST_TEMPLATE_ENV_FILE_NAME, + prefix='LOAD_TEST_ZRB_ENV_PREFIX' + ) + ], cmd_path=[ os.path.join(CURRENT_DIR, 'cmd', 'activate-venv.sh'), os.path.join(CURRENT_DIR, 'cmd', 'app-load-test.sh'), diff --git a/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/local.py b/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/local.py index e284a234..8507fd05 100644 --- a/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/local.py +++ b/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/local.py @@ -1,58 +1,29 @@ -from typing import Any, List -from zrb import CmdTask, DockerComposeTask, Task, Env, EnvFile, runner +from zrb import CmdTask, DockerComposeTask, Task, Env, runner from zrb.builtin.group import project_group -from ._common import ( - CURRENT_DIR, APP_DIR, APP_TEMPLATE_ENV_FILE_NAME, RESOURCE_DIR, - should_start_local_microservices, rabbitmq_checker, - rabbitmq_management_checker, redpanda_console_checker, +from ._config import CURRENT_DIR, APP_DIR, RESOURCE_DIR +from ._helper import ( + activate_support_compose_profile, should_start_support_container, + should_start_local_microservices, should_start_local_monolith +) +from ._checker import ( + rabbitmq_checker, rabbitmq_management_checker, redpanda_console_checker, kafka_outside_checker, kafka_plaintext_checker, pandaproxy_outside_checker, - pandaproxy_plaintext_checker, app_local_checker, local_input, https_input, - run_mode_input, enable_monitoring_input, host_input, app_enable_otel_env + pandaproxy_plaintext_checker, app_local_checker +) +from ._input import ( + local_input, https_input, run_mode_input, enable_monitoring_input, + host_input, image_input ) -from .image import image_input +from ._env import app_enable_otel_env +from ._env_file import app_env_file +from ._get_start_microservices import get_start_microservices from .frontend import build_snake_zrb_app_name_frontend from .container import remove_snake_zrb_app_name_container, compose_env_file -from .local_microservices import get_start_microservices import os -############################################################################### -# Functions -############################################################################### - - -def setup_support_compose_profile(*args: Any, **kwargs: Any) -> str: - task: Task = kwargs.get('_task') - env_map = task.get_env_map() - compose_profiles: List[str] = [] - broker_type = env_map.get('APP_BROKER_TYPE', 'rabbitmq') - if broker_type in ['rabbitmq', 'kafka']: - compose_profiles.append(broker_type) - if kwargs.get('enable_snake_zrb_app_name_monitoring', False): - compose_profiles.append('monitoring') - compose_profile_str = ','.join(compose_profiles) - return f'export COMPOSE_PROFILES={compose_profile_str}' - - -def should_start_support_container(*args: Any, **kwargs: Any) -> bool: - return kwargs.get('local_snake_zrb_app_name', True) - - -def should_start_local_monolith(*args: Any, **kwargs: Any) -> bool: - if not kwargs.get('local_snake_zrb_app_name', True): - return False - return kwargs.get('snake_zrb_app_name_run_mode', 'monolith') == 'monolith' - ############################################################################### -# Env file Definitions -############################################################################### - -app_env_file = EnvFile( - path=APP_TEMPLATE_ENV_FILE_NAME, prefix='ZRB_ENV_PREFIX' -) - -############################################################################### -# Task Definitions +# ⚙️ init-kebab-zrb-task-name-support-container ############################################################################### init_snake_zrb_app_name_support_container = DockerComposeTask( @@ -68,13 +39,17 @@ def should_start_local_monolith(*args: Any, **kwargs: Any) -> bool: remove_snake_zrb_app_name_container ], cwd=RESOURCE_DIR, - setup_cmd=setup_support_compose_profile, + setup_cmd=activate_support_compose_profile, compose_cmd='up', compose_flags=['-d'], compose_env_prefix='CONTAINER_ZRB_ENV_PREFIX', env_files=[compose_env_file] ) +############################################################################### +# ⚙️ start-kebab-zrb-task-name-support-container +############################################################################### + start_snake_zrb_app_name_support_container = DockerComposeTask( icon='🐳', name='start-kebab-zrb-app-name-support-container', @@ -89,7 +64,7 @@ def should_start_local_monolith(*args: Any, **kwargs: Any) -> bool: should_execute=should_start_support_container, upstreams=[init_snake_zrb_app_name_support_container], cwd=RESOURCE_DIR, - setup_cmd=setup_support_compose_profile, + setup_cmd=activate_support_compose_profile, compose_cmd='logs', compose_flags=['-f'], compose_env_prefix='CONTAINER_ZRB_ENV_PREFIX', @@ -105,6 +80,10 @@ def should_start_local_monolith(*args: Any, **kwargs: Any) -> bool: ] ) +############################################################################### +# ⚙️ prepare-kebab-zrb-task-name-backend +############################################################################### + prepare_snake_zrb_app_name_backend = CmdTask( icon='🚤', name='prepare-kebab-zrb-app-name-backend', @@ -118,6 +97,10 @@ def should_start_local_monolith(*args: Any, **kwargs: Any) -> bool: ) runner.register(prepare_snake_zrb_app_name_backend) +############################################################################### +# ⚙️ start-monolith-kebab-zrb-task-name +############################################################################### + start_monolith_snake_zrb_app_name = CmdTask( icon='🚤', name='start-monolith-kebab-zrb-app-name', @@ -146,6 +129,10 @@ def should_start_local_monolith(*args: Any, **kwargs: Any) -> bool: ] ) +############################################################################### +# ⚙️ start-kebab-zrb-task-name-gateway +############################################################################### + start_snake_zrb_app_name_gateway = CmdTask( icon='🚪', name='start-kebab-zrb-app-name-gateway', @@ -181,13 +168,9 @@ def should_start_local_monolith(*args: Any, **kwargs: Any) -> bool: ] ) -start_microservices = get_start_microservices( - upstreams=[ - start_snake_zrb_app_name_support_container, - build_snake_zrb_app_name_frontend, - prepare_snake_zrb_app_name_backend, - ] -) +############################################################################### +# ⚙️ start-kebab-zrb-task-name +############################################################################### start_snake_zrb_app_name = Task( icon='🚤', @@ -197,7 +180,14 @@ def should_start_local_monolith(*args: Any, **kwargs: Any) -> bool: upstreams=[ start_monolith_snake_zrb_app_name, start_snake_zrb_app_name_gateway, - ] + start_microservices, + *get_start_microservices( + upstreams=[ + start_snake_zrb_app_name_support_container, + build_snake_zrb_app_name_frontend, + prepare_snake_zrb_app_name_backend, + ] + ) + ], run=lambda *args, **kwargs: kwargs.get('_task').print_out('🆗') ) runner.register(start_snake_zrb_app_name) diff --git a/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/test.py b/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/test.py index 11011d56..d9936536 100644 --- a/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/test.py +++ b/src/zrb/builtin/generator/fastapp/template/_automate/snake_zrb_app_name/test.py @@ -1,20 +1,12 @@ from zrb import CmdTask, StrInput, Env, EnvFile, runner, python_task from zrb.builtin.group import project_group -from ._common import CURRENT_DIR, RESOURCE_DIR, APP_TEMPLATE_ENV_FILE_NAME +from ._config import CURRENT_DIR, RESOURCE_DIR, APP_TEMPLATE_ENV_FILE_NAME from .frontend import build_snake_zrb_app_name_frontend_once from .local import prepare_snake_zrb_app_name_backend import os ############################################################################### -# Env file Definitions -############################################################################### - -app_env_file = EnvFile( - path=APP_TEMPLATE_ENV_FILE_NAME, prefix='TEST_ZRB_ENV_PREFIX' -) - -############################################################################### -# Task Definitions +# ⚙️ remove-kebab-zrb-task-name-test-db ############################################################################### @@ -30,6 +22,10 @@ def remove_snake_zrb_app_name_test_db(*args, **kwargs): os.remove(test_db_file_path) +############################################################################### +# ⚙️ test-kebab-zrb-task-name +############################################################################### + test_snake_zrb_app_name = CmdTask( icon='🚤', name='test-kebab-zrb-app-name', @@ -48,7 +44,11 @@ def remove_snake_zrb_app_name_test_db(*args, **kwargs): remove_snake_zrb_app_name_test_db, ], cwd=RESOURCE_DIR, - env_files=[app_env_file], + env_files=[ + EnvFile( + path=APP_TEMPLATE_ENV_FILE_NAME, prefix='TEST_ZRB_ENV_PREFIX' + ) + ], envs=[ Env( name='APP_BROKER_TYPE', diff --git a/src/zrb/builtin/generator/pip_package/template/_automate/snake_zrb_package_name/local.py b/src/zrb/builtin/generator/pip_package/template/_automate/snake_zrb_package_name/local.py index e277f09c..3575c40d 100644 --- a/src/zrb/builtin/generator/pip_package/template/_automate/snake_zrb_package_name/local.py +++ b/src/zrb/builtin/generator/pip_package/template/_automate/snake_zrb_package_name/local.py @@ -9,7 +9,7 @@ PACKAGE_DIR = os.path.join(RESOURCE_DIR, 'src') ############################################################################### -# Task Definitions +# ⚙️ prepare-kebab-zrb-task-name ############################################################################### prepare_snake_zrb_package_name = CmdTask( @@ -24,6 +24,10 @@ ) runner.register(prepare_snake_zrb_package_name) +############################################################################### +# ⚙️ build-kebab-zrb-task-name +############################################################################### + build_snake_zrb_package_name = CmdTask( name='build-kebab-zrb-package-name', description='Build human readable zrb package name', @@ -37,6 +41,10 @@ ) runner.register(build_snake_zrb_package_name) +############################################################################### +# ⚙️ publish-kebab-zrb-task-name +############################################################################### + publish_snake_zrb_package_name = CmdTask( name='publish-kebab-zrb-package-name', description='Publish human readable zrb package name', @@ -58,6 +66,10 @@ ) runner.register(publish_snake_zrb_package_name) +############################################################################### +# ⚙️ install-kebab-zrb-task-name-symlink +############################################################################### + install_snake_zrb_package_name_symlink = CmdTask( name='install-kebab-zrb-package-name-symlink', description='Install human readable zrb package name as symlink', diff --git a/src/zrb/builtin/generator/python_task/template/_automate/snake_zrb_task_name.py b/src/zrb/builtin/generator/python_task/template/_automate/snake_zrb_task_name.py index 0828d89e..77494639 100644 --- a/src/zrb/builtin/generator/python_task/template/_automate/snake_zrb_task_name.py +++ b/src/zrb/builtin/generator/python_task/template/_automate/snake_zrb_task_name.py @@ -3,7 +3,7 @@ from zrb.builtin.group import project_group ############################################################################### -# Task Definitions +# ⚙️ kebab-zrb-task-name ############################################################################### diff --git a/src/zrb/builtin/generator/simple_python_app/template/_automate/snake_zrb_app_name/_common.py b/src/zrb/builtin/generator/simple_python_app/template/_automate/snake_zrb_app_name/_common.py index 41c8b1ec..d0ef02b2 100644 --- a/src/zrb/builtin/generator/simple_python_app/template/_automate/snake_zrb_app_name/_common.py +++ b/src/zrb/builtin/generator/simple_python_app/template/_automate/snake_zrb_app_name/_common.py @@ -2,7 +2,7 @@ import os ############################################################################### -# Constants +# 🏔️ Constants ############################################################################### CURRENT_DIR = os.path.dirname(__file__) @@ -16,7 +16,7 @@ APP_TEMPLATE_ENV_FILE_NAME = os.path.join(APP_DIR, 'template.env') ############################################################################### -# Input Definitions +# 🔤 Input Definitions ############################################################################### local_input = BoolInput( diff --git a/src/zrb/builtin/generator/simple_python_app/template/_automate/snake_zrb_app_name/container.py b/src/zrb/builtin/generator/simple_python_app/template/_automate/snake_zrb_app_name/container.py index 255918e7..67947faf 100644 --- a/src/zrb/builtin/generator/simple_python_app/template/_automate/snake_zrb_app_name/container.py +++ b/src/zrb/builtin/generator/simple_python_app/template/_automate/snake_zrb_app_name/container.py @@ -11,7 +11,7 @@ import os ############################################################################### -# Env File Definitions +# 🌳 Env File Definitions ############################################################################### compose_env_file = EnvFile( @@ -20,7 +20,7 @@ ) ############################################################################### -# Env Definitions +# 🌱 Env Definitions ############################################################################### host_port_env = Env( @@ -43,7 +43,7 @@ ) ############################################################################### -# Task Definitions +# ⚙️ kebab-zrb-task-name ############################################################################### remove_snake_zrb_app_name_container = DockerComposeTask( @@ -65,6 +65,10 @@ ) runner.register(remove_snake_zrb_app_name_container) +############################################################################### +# ⚙️ kebab-zrb-task-name +############################################################################### + stop_snake_zrb_app_name_container = DockerComposeTask( icon='⛔', name='stop-kebab-zrb-app-name-container', @@ -84,6 +88,10 @@ ) runner.register(stop_snake_zrb_app_name_container) +############################################################################### +# ⚙️ kebab-zrb-task-name +############################################################################### + init_snake_zrb_app_name_container = DockerComposeTask( icon='🔥', name='init-kebab-zrb-app-name-container', @@ -111,6 +119,10 @@ ], ) +############################################################################### +# ⚙️ kebab-zrb-task-name +############################################################################### + start_snake_zrb_app_name_container = DockerComposeTask( icon='🐳', name='start-kebab-zrb-app-name-container', diff --git a/src/zrb/builtin/generator/simple_python_app/template/_automate/snake_zrb_app_name/deployment.py b/src/zrb/builtin/generator/simple_python_app/template/_automate/snake_zrb_app_name/deployment.py index e186a7e2..e2b24e75 100644 --- a/src/zrb/builtin/generator/simple_python_app/template/_automate/snake_zrb_app_name/deployment.py +++ b/src/zrb/builtin/generator/simple_python_app/template/_automate/snake_zrb_app_name/deployment.py @@ -8,7 +8,7 @@ import os ############################################################################### -# Input Definitions +# 🔤 Input Definitions ############################################################################### replica_input = IntInput( @@ -26,7 +26,7 @@ ) ############################################################################### -# Env File Definitions +# 🌳 Env File Definitions ############################################################################### deployment_app_env_file = EnvFile( @@ -40,7 +40,7 @@ ) ############################################################################### -# Env Definitions +# 🌱 Env Definitions ############################################################################### pulumi_backend_url_env = Env( @@ -62,7 +62,7 @@ ) ############################################################################### -# Task Definitions +# ⚙️ deploy-kebab-zrb-task-name ############################################################################### deploy_snake_zrb_app_name = CmdTask( @@ -94,6 +94,10 @@ ) runner.register(deploy_snake_zrb_app_name) +############################################################################### +# ⚙️ destroy-kebab-zrb-task-name +############################################################################### + destroy_snake_zrb_app_name = CmdTask( icon='💨', name='destroy-kebab-zrb-app-name', diff --git a/src/zrb/builtin/generator/simple_python_app/template/_automate/snake_zrb_app_name/image.py b/src/zrb/builtin/generator/simple_python_app/template/_automate/snake_zrb_app_name/image.py index d22a7f77..8f3d7e84 100644 --- a/src/zrb/builtin/generator/simple_python_app/template/_automate/snake_zrb_app_name/image.py +++ b/src/zrb/builtin/generator/simple_python_app/template/_automate/snake_zrb_app_name/image.py @@ -5,7 +5,7 @@ ) ############################################################################### -# Input Definitions +# 🔤 Input Definitions ############################################################################### image_input = StrInput( @@ -17,7 +17,7 @@ ############################################################################### -# Env Definitions +# 🌱 Env Definitions ############################################################################### image_env = Env( @@ -27,7 +27,7 @@ ) ############################################################################### -# Task Definitions +# ⚙️ kebab-zrb-task-name ############################################################################### build_snake_zrb_app_name_image = DockerComposeTask( @@ -50,6 +50,10 @@ ) runner.register(build_snake_zrb_app_name_image) +############################################################################### +# ⚙️ kebab-zrb-task-name +############################################################################### + push_snake_zrb_app_name_image = DockerComposeTask( icon='📰', name='push-kebab-zrb-app-name-image', diff --git a/src/zrb/builtin/generator/simple_python_app/template/_automate/snake_zrb_app_name/local.py b/src/zrb/builtin/generator/simple_python_app/template/_automate/snake_zrb_app_name/local.py index 526118f6..80c55a34 100644 --- a/src/zrb/builtin/generator/simple_python_app/template/_automate/snake_zrb_app_name/local.py +++ b/src/zrb/builtin/generator/simple_python_app/template/_automate/snake_zrb_app_name/local.py @@ -7,13 +7,7 @@ import os ############################################################################### -# Env File Definitions -############################################################################### - -app_env_file = EnvFile(path=APP_TEMPLATE_ENV_FILE_NAME, prefix='ZRB_ENV_PREFIX') - -############################################################################### -# Task Definitions +# ⚙️ kebab-zrb-task-name ############################################################################### start_snake_zrb_app_name = CmdTask( @@ -28,7 +22,9 @@ ], should_execute='{{ input.local_snake_zrb_app_name}}', cwd=APP_DIR, - env_files=[app_env_file], + env_files=[ + EnvFile(path=APP_TEMPLATE_ENV_FILE_NAME, prefix='ZRB_ENV_PREFIX') + ], envs=[ Env( name='APP_PORT', diff --git a/src/zrb/task/any_task.py b/src/zrb/task/any_task.py index 579cafe0..33f5df09 100644 --- a/src/zrb/task/any_task.py +++ b/src/zrb/task/any_task.py @@ -34,7 +34,7 @@ def copy(self) -> TAnyTask: Returns: TAnyTask: A copy of the current task. - Example: + Examples: >>> from zrb import Task >>> task = Task(name='my-task', cmd='echo hello') >>> copied_task = task.copy() @@ -59,7 +59,7 @@ async def run(self, *args: Any, **kwargs: Any) -> Any: Any: The result of the task execution, the type of which is determined by the specific task implementation. - Example: + Examples: >>> from zrb import Task >>> class MyTask(Task): >>> async def run(self, *args: Any, **kwargs: Any) -> int: @@ -82,7 +82,7 @@ async def check(self) -> bool: Returns: bool: True if the task is completed, False otherwise. - Example: + Examples: >>> from zrb import Task >>> class MyTask(Task): >>> async def run(self, *args: Any, **kwargs: Any) -> int: @@ -103,7 +103,7 @@ async def on_triggered(self): `triggered` state. This could involve setting up prerequisites or sending notifications. - Example: + Examples: >>> from zrb import Task >>> class MyTask(Task): >>> async def on_triggered(self): @@ -120,7 +120,7 @@ async def on_waiting(self): `waiting` state. This state usually indicates the task is waiting for some condition or prerequisite to be met. - Example: + Examples: >>> from zrb import Task >>> class MyTask(Task): >>> async def on_waiting(self): @@ -136,7 +136,7 @@ async def on_skipped(self): Implement this method to specify behavior when the task is skipped. This could include logging information, cleaning up resources, or any other necessary steps. - Example: + Examples: >>> from zrb import Task >>> class MyTask(Task): >>> async def on_skipped(self): @@ -152,7 +152,7 @@ async def on_started(self): Implement this method to specify behavior when the task starts its execution. This could involve initializing resources, logging, or other startup procedures. - Example: + Examples: >>> from zrb import Task >>> class MyTask(Task): >>> async def on_started(self): @@ -169,7 +169,7 @@ async def on_ready(self): actions that occur when the task reaches the `ready` state. This can include any cleanup, notification, or follow-up actions specific to the task. - Example: + Examples: >>> from zrb import Task >>> class MyTask(Task): >>> async def on_ready(self): @@ -190,7 +190,7 @@ async def on_failed(self, is_last_attempt: bool, exception: Exception): is_last_attempt (bool): Indicates if this is the final retry attempt. exception (Exception): The exception that caused the task to fail. - Example: + Examples: >>> from zrb import Task >>> class MyTask(Task): >>> async def on_failed(self, is_last_attempt: bool, exception: Exception): @@ -210,7 +210,7 @@ async def on_retry(self): This could include resetting states, logging the retry attempt, or other necessary steps before re-execution. - Example: + Examples: >>> from zrb import Task >>> class MyTask(Task): >>> async def on_retry(self): @@ -242,7 +242,7 @@ def to_function( Returns: Callable[..., Any]: A callable representation of the task. - Example: + Examples: >>> from zrb import Task >>> class MyTask(Task): >>> async def run(self, *args: Any, **kwargs: Any) -> int: @@ -267,7 +267,7 @@ def insert_upstream(self, *upstreams: TAnyTask): Args: upstreams (TAnyTask): One or more task instances to be added to the upstream list. - Example: + Examples: >>> from zrb import Task >>> task = Task(name='task') >>> upstream_task = Task(name='upstream-task') @@ -286,7 +286,7 @@ def add_upstream(self, *upstreams: TAnyTask): Args: upstreams (TAnyTask): One or more task instances to be added to the upstream list. - Example: + Examples: >>> from zrb import Task >>> task = Task(name='task') >>> upstream_task = Task(name='upstream-task') @@ -305,7 +305,7 @@ def insert_input(self, *inputs: AnyInput): Args: inputs (AnyInput): One or more input instances to be added to the input list. - Example: + Examples: >>> from zrb import Task, Input >>> task = Task(name='task') >>> email_input = Input(name='email-address') @@ -324,7 +324,7 @@ def add_input(self, *inputs: AnyInput): Args: inputs (AnyInput): One or more input instances to be added to the input list. - Example: + Examples: >>> from zrb import Task, Input >>> task = Task(name='task') >>> email_input = Input(name='email-address') @@ -343,7 +343,7 @@ def insert_env(self, *envs: Env): Args: envs (Env): One or more environment variable instances to be added. - Example: + Examples: >>> from zrb import Task, Env >>> task = Task(name='task') >>> db_url_env = Env(name='DATABASE_URL', value='postgresql://...') @@ -362,7 +362,7 @@ def add_env(self, *envs: Env): Args: envs (Env): One or more environment variable instances to be added. - Example: + Examples: >>> from zrb import Task, Env >>> task = Task(name='task') >>> db_url_env = Env(name='DATABASE_URL', value='postgresql://...') @@ -382,7 +382,7 @@ def insert_env_file(self, *env_files: EnvFile): Args: env_files (EnvFile): One or more environment file instances to be added. - Example: + Examples: >>> from zrb import Task, EnvFile >>> task = Task() >>> env_file = EnvFile(path='config.env') @@ -402,7 +402,7 @@ def add_env_file(self, *env_files: EnvFile): Args: env_files (EnvFile): One or more environment file instances to be added. - Example: + Examples: >>> from zrb import Task, EnvFile >>> task = Task() >>> env_file = EnvFile(path='config.env') @@ -626,7 +626,7 @@ def inject_env_files(self): ''' Injects additional `EnvFile` into the task. - Example: + Examples: >>> from zrb import Task >>> class MyTask(Task): >>> def inject_env_files(self): @@ -652,7 +652,7 @@ def inject_envs(self): ''' Injects environment variables into the task. - Example: + Examples: >>> from zrb import Task >>> class MyTask(Task): >>> def inject_envs(self): @@ -682,7 +682,7 @@ def inject_inputs(self): dynamic customization of the task's input data. Subclasses should override this method to define specific inputs that the task should receive. - Example: + Examples: >>> from zrb import Task, Input >>> class MyTask(Task): >>> def inject_inputs(self): @@ -713,7 +713,7 @@ def inject_checkers(self): checkers can be used to verify certain conditions before the task execution proceeds. Subclasses should implement this method to define task-specific checkers. - Example: + Examples: >>> from zrb import Task >>> class MyTask(Task): >>> def inject_checkers(self): @@ -744,7 +744,7 @@ def inject_upstreams(self): Upstream tasks are those that must be completed before the current task starts. Override this method in subclasses to specify such dependencies. - Example: + Examples: >>> from zrb import Task >>> class MyTask(Task): >>> def inject_upstreams(self): @@ -906,7 +906,7 @@ def print_result(self, result: Any): Args: result (Any): The result of the task to be printed. - Example: + Examples: >> from zrb import Task >> # Example of overriding in a subclass >> class MyTask(Task): diff --git a/zrb_init.py b/zrb_init.py index 4a2a6469..ac2d2d9b 100644 --- a/zrb_init.py +++ b/zrb_init.py @@ -34,7 +34,7 @@ ) ############################################################################### -# Input Definitions +# 🔤 Input Definitions ############################################################################### zrb_version_input = StrInput( @@ -65,7 +65,7 @@ ) ############################################################################### -# Env Definitions +# 🌱 Env Definitions ############################################################################### zrb_version_env = Env( From 97da5af18c889ca742d917f6b6127992480b81d7 Mon Sep 17 00:00:00 2001 From: goFrendiAsgard Date: Sun, 10 Dec 2023 14:03:15 +0700 Subject: [PATCH 10/13] update docs --- docs/concepts/task-input/README.md | 58 +- docs/concepts/task-input/bool-input.md | 65 +- docs/concepts/task-input/choice-input.md | 67 +- docs/concepts/task-input/float-input.md | 65 +- docs/concepts/task-input/int-input.md | 66 +- docs/concepts/task-input/password-input.md | 66 +- docs/concepts/task-input/str-input.md | 66 +- docs/concepts/task/README.md | 564 ++++++--- docs/concepts/task/base-remote-cmd-task.md | 1102 ++++++++++++++++ .../concepts/task/{checkers.md => checker.md} | 159 ++- docs/concepts/task/cmd-task.md | 171 +-- docs/concepts/task/docker-compose-task.md | 152 +-- docs/concepts/task/flow-task.md | 154 +-- docs/concepts/task/http-checker.md | 1112 ++++++++++++++++ docs/concepts/task/path-checker.md | 1112 ++++++++++++++++ docs/concepts/task/path-watcher.md | 1117 +++++++++++++++++ docs/concepts/task/port-checker.md | 1112 ++++++++++++++++ docs/concepts/task/python-task.md | 82 +- docs/concepts/task/recurring-task.md | 1107 ++++++++++++++++ docs/concepts/task/remote-cmd-task.md | 139 +- docs/concepts/task/resource-maker.md | 161 +-- docs/concepts/task/rsync-task.md | 167 ++- docs/concepts/task/time-watcher.md | 1112 ++++++++++++++++ src/zrb/helper/docstring.py | 19 +- src/zrb/task/any_task.py | 101 +- src/zrb/task_input/bool_input.py | 35 +- src/zrb/task_input/choice_input.py | 35 + src/zrb/task_input/float_input.py | 33 + src/zrb/task_input/int_input.py | 34 + src/zrb/task_input/password_input.py | 34 + src/zrb/task_input/str_input.py | 34 + src/zrb/task_input/task_input.py | 35 + zrb_init.py | 22 +- 33 files changed, 9227 insertions(+), 1131 deletions(-) create mode 100644 docs/concepts/task/base-remote-cmd-task.md rename docs/concepts/task/{checkers.md => checker.md} (91%) create mode 100644 docs/concepts/task/http-checker.md create mode 100644 docs/concepts/task/path-checker.md create mode 100644 docs/concepts/task/path-watcher.md create mode 100644 docs/concepts/task/port-checker.md create mode 100644 docs/concepts/task/recurring-task.md create mode 100644 docs/concepts/task/time-watcher.md diff --git a/docs/concepts/task-input/README.md b/docs/concepts/task-input/README.md index ee2e8958..e927040c 100644 --- a/docs/concepts/task-input/README.md +++ b/docs/concepts/task-input/README.md @@ -27,13 +27,47 @@ Here, you will see the technical specification of `AnyInput` # Technical Specification -## `AnyInput` - -Abstract base class representing a generalized input specification. -This class serves as a template for creating various input types, -providing a standardized interface for input handling and processing. - -### `AnyInput.get_default` +## `Input` + +Alias for BaseInput + +__Attributes:__ + +- `name` (`str`): The name of the input, used as a unique identifier. +- `shortcut` (`Optional[str]`): An optional single-character shortcut for the input. +- `default` (`Optional[Any]`): The default value of the input. +- `description` (`Optional[str]`): A brief description of what the input is for. +- `show_default` (`Union[bool, JinjaTemplate, None]`): Determines whether the default value should be displayed. +- `prompt` (`Union[bool, str]`): The prompt text to be displayed when asking for the input. +- `confirmation_prompt` (`Union[bool, str]`): A prompt for confirmation if required. +- `prompt_required` (`bool`): Indicates whether a prompt is required. +- `hide_input` (`bool`): If True, the input value will be hidden (e.g., for passwords). +- `is_flag` (`Optional[bool]`): Specifies whether the input is a flag. +- `flag_value` (`Optional[Any]`): The value to be used if the input is a flag. +- `multiple` (`bool`): Allows multiple values for this input if True. +- `count` (`bool`): If True, counts the occurrences of the input. +- `allow_from_autoenv` (`bool`): If True, allows values to be automatically sourced from the environment. +- `type` (`Optional[Any]`): The expected type of the input value. +- `hidden` (`bool`): If True, the input is hidden and not rendered. +- `show_choices` (`bool`): Indicates whether to show available choices for the input. +- `show_envvar` (`bool`): If True, shows the corresponding environment variable. +- `nargs` (`int`): Number of arguments expected for this input. +- `should_render` (`bool`): Determines whether the input should be rendered. + +__Examples:__ + +```python +from zrb import Input, Task +task = Task( + name='task', + inputs=[ + Input(name='delay', default=10, description='Delay') + ] +) +``` + + +### `Input.get_default` Obtains the default value of the input. @@ -41,7 +75,7 @@ __Returns:__ `Any`: The default value of the input. The type can be any, depending on the input specification. -### `AnyInput.get_name` +### `Input.get_name` Retrieves the name of the input. @@ -49,7 +83,7 @@ __Returns:__ `str`: The name of the input. -### `AnyInput.get_options` +### `Input.get_options` Provides a mapping (dictionary) representing the input. @@ -57,7 +91,7 @@ __Returns:__ `Mapping[str, Any]`: A dictionary where keys are option names and values are the corresponding details. -### `AnyInput.get_param_decl` +### `Input.get_param_decl` Fetches a list of parameter option associated with the input (i.e., `-f` or `--file`). @@ -65,7 +99,7 @@ __Returns:__ `List[str]`: A list containing strings of parameter options. -### `AnyInput.is_hidden` +### `Input.is_hidden` Checks whether the input value is meant to be hidden from view or output. @@ -73,7 +107,7 @@ __Returns:__ `bool`: True if the input is hidden, False otherwise. -### `AnyInput.should_render` +### `Input.should_render` Determines whether or not the input should be rendered. diff --git a/docs/concepts/task-input/bool-input.md b/docs/concepts/task-input/bool-input.md index 87373f7c..141229db 100644 --- a/docs/concepts/task-input/bool-input.md +++ b/docs/concepts/task-input/bool-input.md @@ -7,43 +7,42 @@ ## `BoolInput` -A concrete implementation of the AnyInput abstract base class, representing a specific type of task input. -This class allows for the creation of interactive and configurable inputs for tasks, with various attributes -to customize its behavior and appearance. - -__Attributes:__ - -- `name` (`str`): The name of the input, used as a unique identifier. -- `shortcut` (`Optional[str]`): An optional single-character shortcut for the input. -- `default` (`Optional[Any]`): The default value of the input. -- `description` (`Optional[str]`): A brief description of what the input is for. -- `show_default` (`Union[bool, JinjaTemplate, None]`): Determines whether the default value should be displayed. -- `prompt` (`Union[bool, str]`): The prompt text to be displayed when asking for the input. -- `confirmation_prompt` (`Union[bool, str]`): A prompt for confirmation if required. -- `prompt_required` (`bool`): Indicates whether a prompt is required. -- `hide_input` (`bool`): If True, the input value will be hidden (e.g., for passwords). -- `is_flag` (`Optional[bool]`): Specifies whether the input is a flag. -- `flag_value` (`Optional[Any]`): The value to be used if the input is a flag. -- `multiple` (`bool`): Allows multiple values for this input if True. -- `count` (`bool`): If True, counts the occurrences of the input. -- `allow_from_autoenv` (`bool`): If True, allows values to be automatically sourced from the environment. -- `type` (`Optional[Any]`): The expected type of the input value. -- `hidden` (`bool`): If True, the input is hidden and not rendered. -- `show_choices` (`bool`): Indicates whether to show available choices for the input. -- `show_envvar` (`bool`): If True, shows the corresponding environment variable. -- `nargs` (`int`): Number of arguments expected for this input. -- `should_render` (`bool`): Determines whether the input should be rendered. +A specialized input class for handling boolean values in a task input context. + +This class extends `BaseInput` and provides specific functionality for boolean type inputs, +including support for default values, prompts, flags, and various customization options. + +__Arguments:__ + +- `name` (`str`): The name of the input. +- `shortcut` (`Optional[str]`): A shortcut string for the input. +- `default` (`Optional[Any]`): The default value for the input. Should be a boolean if set. +- `description` (`Optional[str]`): A brief description of the input. +- `show_default` (`Union[bool, str, None]`): Option to display the default value. Can be a boolean or string representation. +- `prompt` (`Union[bool, str]`): A boolean or string to prompt the user for input. If `True`, uses the default prompt. +- `confirmation_prompt` (`Union[bool, str]`): If set to `True`, the user is asked to confirm the input. +- `prompt_required` (`bool`): If `True`, the prompt for input is mandatory. +- `hide_input` (`bool`): If `True`, the input is hidden (useful for sensitive information). +- `is_flag` (`Optional[bool]`): Indicates if the input is a flag. If `True`, the input accepts boolean flag values. +- `flag_value` (`Optional[Any]`): The value associated with the flag if `is_flag` is `True`. +- `multiple` (`bool`): If `True`, allows multiple values for the input. +- `count` (`bool`): If `True`, counts the occurrences of the input. +- `allow_from_autoenv` (`bool`): If `True`, allows the input to be automatically populated from the environment. +- `hidden` (`bool`): If `True`, the input is not shown in help messages or documentation. +- `show_choices` (`bool`): If `True`, displays the choices available for the input. +- `show_envvar` (`bool`): Indicates whether to display the environment variable associated with this input. +- `nargs` (`int`): The number of arguments that the input can accept. +- `should_render` (`bool`): If `True`, the input is rendered in the UI or command-line interface. __Examples:__ ```python -from zrb import Input, Task -task = Task( - name='task', - inputs=[ - Input(name='delay', default=10, description='Delay') - ] -) +bool_input = BoolInput(name='confirm', prompt='Do you agree?', default=False) +bool_input.get_default() +``` + +``` +False ``` diff --git a/docs/concepts/task-input/choice-input.md b/docs/concepts/task-input/choice-input.md index 6267e69b..bd30cb4c 100644 --- a/docs/concepts/task-input/choice-input.md +++ b/docs/concepts/task-input/choice-input.md @@ -7,43 +7,44 @@ ## `ChoiceInput` -A concrete implementation of the AnyInput abstract base class, representing a specific type of task input. -This class allows for the creation of interactive and configurable inputs for tasks, with various attributes -to customize its behavior and appearance. - -__Attributes:__ - -- `name` (`str`): The name of the input, used as a unique identifier. -- `shortcut` (`Optional[str]`): An optional single-character shortcut for the input. -- `default` (`Optional[Any]`): The default value of the input. -- `description` (`Optional[str]`): A brief description of what the input is for. -- `show_default` (`Union[bool, JinjaTemplate, None]`): Determines whether the default value should be displayed. -- `prompt` (`Union[bool, str]`): The prompt text to be displayed when asking for the input. -- `confirmation_prompt` (`Union[bool, str]`): A prompt for confirmation if required. -- `prompt_required` (`bool`): Indicates whether a prompt is required. -- `hide_input` (`bool`): If True, the input value will be hidden (e.g., for passwords). -- `is_flag` (`Optional[bool]`): Specifies whether the input is a flag. -- `flag_value` (`Optional[Any]`): The value to be used if the input is a flag. -- `multiple` (`bool`): Allows multiple values for this input if True. -- `count` (`bool`): If True, counts the occurrences of the input. -- `allow_from_autoenv` (`bool`): If True, allows values to be automatically sourced from the environment. -- `type` (`Optional[Any]`): The expected type of the input value. -- `hidden` (`bool`): If True, the input is hidden and not rendered. -- `show_choices` (`bool`): Indicates whether to show available choices for the input. -- `show_envvar` (`bool`): If True, shows the corresponding environment variable. -- `nargs` (`int`): Number of arguments expected for this input. -- `should_render` (`bool`): Determines whether the input should be rendered. +A specialized input class for handling choice-based inputs in a task input context. + +This class extends `BaseInput` and provides functionality for inputs where the user +must select from a predefined set of choices. It includes support for default values, +prompts, flags, and various customization options. + +__Arguments:__ + +- `name` (`str`): The name of the input. +- `shortcut` (`Optional[str]`): An optional shortcut string for the input. +- `choices` (`Iterable[Any]`): An iterable of choices from which the user can select. +- `default` (`Optional[Any]`): The default value for the input. Should be one of the choices if set. +- `description` (`Optional[str]`): A brief description of the input. +- `show_default` (`Union[bool, str, None]`): Option to display the default value. Can be a boolean or string representation. +- `prompt` (`Union[bool, str]`): A boolean or string to prompt the user for input. If `True`, uses the default prompt. +- `confirmation_prompt` (`Union[bool, str]`): If set to `True`, the user is asked to confirm the input. +- `prompt_required` (`bool`): If `True`, the prompt for input is mandatory. +- `hide_input` (`bool`): If `True`, the input is hidden (useful for sensitive information). +- `is_flag` (`Optional[bool]`): Indicates if the input is a flag. If `True`, the input accepts boolean flag values. +- `flag_value` (`Optional[Any]`): The value associated with the flag if `is_flag` is `True`. +- `multiple` (`bool`): If `True`, allows multiple values for the input. +- `count` (`bool`): If `True`, counts the occurrences of the input. +- `allow_from_autoenv` (`bool`): If `True`, allows the input to be automatically populated from the environment. +- `hidden` (`bool`): If `True`, the input is not shown in help messages or documentation. +- `show_choices` (`bool`): If `True`, displays the available choices to the user. +- `show_envvar` (`bool`): Indicates whether to display the environment variable associated with this input. +- `nargs` (`int`): The number of arguments that the input can accept. +- `should_render` (`bool`): If `True`, the input is rendered in the UI or command-line interface. __Examples:__ ```python -from zrb import Input, Task -task = Task( - name='task', - inputs=[ - Input(name='delay', default=10, description='Delay') - ] -) +choice_input = ChoiceInput(name='color', choices=['red', 'green', 'blue'], default='red') +choice_input.get_default() +``` + +``` +'red' ``` diff --git a/docs/concepts/task-input/float-input.md b/docs/concepts/task-input/float-input.md index 86f17321..dc896a06 100644 --- a/docs/concepts/task-input/float-input.md +++ b/docs/concepts/task-input/float-input.md @@ -7,43 +7,42 @@ ## `FloatInput` -A concrete implementation of the AnyInput abstract base class, representing a specific type of task input. -This class allows for the creation of interactive and configurable inputs for tasks, with various attributes -to customize its behavior and appearance. - -__Attributes:__ - -- `name` (`str`): The name of the input, used as a unique identifier. -- `shortcut` (`Optional[str]`): An optional single-character shortcut for the input. -- `default` (`Optional[Any]`): The default value of the input. -- `description` (`Optional[str]`): A brief description of what the input is for. -- `show_default` (`Union[bool, JinjaTemplate, None]`): Determines whether the default value should be displayed. -- `prompt` (`Union[bool, str]`): The prompt text to be displayed when asking for the input. -- `confirmation_prompt` (`Union[bool, str]`): A prompt for confirmation if required. -- `prompt_required` (`bool`): Indicates whether a prompt is required. -- `hide_input` (`bool`): If True, the input value will be hidden (e.g., for passwords). -- `is_flag` (`Optional[bool]`): Specifies whether the input is a flag. -- `flag_value` (`Optional[Any]`): The value to be used if the input is a flag. -- `multiple` (`bool`): Allows multiple values for this input if True. -- `count` (`bool`): If True, counts the occurrences of the input. -- `allow_from_autoenv` (`bool`): If True, allows values to be automatically sourced from the environment. -- `type` (`Optional[Any]`): The expected type of the input value. -- `hidden` (`bool`): If True, the input is hidden and not rendered. -- `show_choices` (`bool`): Indicates whether to show available choices for the input. -- `show_envvar` (`bool`): If True, shows the corresponding environment variable. -- `nargs` (`int`): Number of arguments expected for this input. -- `should_render` (`bool`): Determines whether the input should be rendered. +A specialized input class designed to handle floating-point numbers in a task input context. + +Extending `BaseInput`, this class facilitates the handling of float-type inputs, accommodating +various features like default values, prompts, flags, and customization options. + +__Arguments:__ + +- `name` (`str`): The name of the input. +- `shortcut` (`Optional[str]`): An optional shortcut string for the input. +- `default` (`Optional[Any]`): The default value for the input, expected to be a float if set. +- `description` (`Optional[str]`): A brief description of the input's purpose. +- `show_default` (`Union[bool, str, None]`): Option to display the default value. Can be a boolean or string. +- `prompt` (`Union[bool, str]`): A boolean or string to prompt the user for input. If `True`, uses the default prompt. +- `confirmation_prompt` (`Union[bool, str]`): If `True`, the user is asked to confirm the input. +- `prompt_required` (`bool`): If `True`, the prompt for input is mandatory. +- `hide_input` (`bool`): If `True`, the input is hidden, useful for sensitive information. +- `is_flag` (`Optional[bool]`): Indicates if the input is a flag. If `True`, the input accepts boolean flag values. +- `flag_value` (`Optional[Any]`): The value associated with the flag if `is_flag` is `True`. +- `multiple` (`bool`): If `True`, allows multiple float values for the input. +- `count` (`bool`): If `True`, counts the occurrences of the input. +- `allow_from_autoenv` (`bool`): If `True`, allows the input to be automatically populated from the environment. +- `hidden` (`bool`): If `True`, the input is not shown in help messages or documentation. +- `show_choices` (`bool`): If `True`, displays the available choices to the user (relevant if there are restricted float choices). +- `show_envvar` (`bool`): Indicates whether to display the environment variable associated with this input. +- `nargs` (`int`): The number of arguments that the input can accept. +- `should_render` (`bool`): If `True`, the input is rendered in the UI or command-line interface. __Examples:__ ```python -from zrb import Input, Task -task = Task( - name='task', - inputs=[ - Input(name='delay', default=10, description='Delay') - ] -) +float_input = FloatInput(name='threshold', default=0.5, description='Set the threshold value') +float_input.get_default() +``` + +``` +0.5 ``` diff --git a/docs/concepts/task-input/int-input.md b/docs/concepts/task-input/int-input.md index f2f8863e..10ed0228 100644 --- a/docs/concepts/task-input/int-input.md +++ b/docs/concepts/task-input/int-input.md @@ -7,43 +7,43 @@ ## `IntInput` -A concrete implementation of the AnyInput abstract base class, representing a specific type of task input. -This class allows for the creation of interactive and configurable inputs for tasks, with various attributes -to customize its behavior and appearance. - -__Attributes:__ - -- `name` (`str`): The name of the input, used as a unique identifier. -- `shortcut` (`Optional[str]`): An optional single-character shortcut for the input. -- `default` (`Optional[Any]`): The default value of the input. -- `description` (`Optional[str]`): A brief description of what the input is for. -- `show_default` (`Union[bool, JinjaTemplate, None]`): Determines whether the default value should be displayed. -- `prompt` (`Union[bool, str]`): The prompt text to be displayed when asking for the input. -- `confirmation_prompt` (`Union[bool, str]`): A prompt for confirmation if required. -- `prompt_required` (`bool`): Indicates whether a prompt is required. -- `hide_input` (`bool`): If True, the input value will be hidden (e.g., for passwords). -- `is_flag` (`Optional[bool]`): Specifies whether the input is a flag. -- `flag_value` (`Optional[Any]`): The value to be used if the input is a flag. -- `multiple` (`bool`): Allows multiple values for this input if True. -- `count` (`bool`): If True, counts the occurrences of the input. -- `allow_from_autoenv` (`bool`): If True, allows values to be automatically sourced from the environment. -- `type` (`Optional[Any]`): The expected type of the input value. -- `hidden` (`bool`): If True, the input is hidden and not rendered. -- `show_choices` (`bool`): Indicates whether to show available choices for the input. -- `show_envvar` (`bool`): If True, shows the corresponding environment variable. -- `nargs` (`int`): Number of arguments expected for this input. -- `should_render` (`bool`): Determines whether the input should be rendered. +A specialized input class for handling integer values in task inputs. + +`IntInput` extends `BaseInput` to specifically handle inputs where integer values are required. +It supports various features like default values, prompts, flags, and other customization options, +making it suitable for tasks that require numerical input in the form of integers. + +__Arguments:__ + +- `name` (`str`): The name of the input, serving as an identifier. +- `shortcut` (`Optional[str]`): An optional shortcut for easier reference to the input. +- `default` (`Optional[Any]`): The default value for the input, should be an integer if provided. +- `description` (`Optional[str]`): A brief description of what the input represents or its intended use. +- `show_default` (`Union[bool, str, None]`): Option to show the default value in prompts or documentation. +- `prompt` (`Union[bool, str]`): A boolean or string to determine the prompt for user input. If `True`, uses a default prompt. +- `confirmation_prompt` (`Union[bool, str]`): If `True`, the user will be asked to confirm their input. +- `prompt_required` (`bool`): If `True`, makes the input prompt mandatory. +- `hide_input` (`bool`): If `True`, hides the input value, typically used for sensitive information. +- `is_flag` (`Optional[bool]`): Indicates if the input functions as a flag, taking boolean values. +- `flag_value` (`Optional[Any]`): The value associated with the input when used as a flag. +- `multiple` (`bool`): If `True`, allows entering multiple integer values. +- `count` (`bool`): If `True`, counts the occurrences of the input. +- `allow_from_autoenv` (`bool`): If `True`, enables automatic population of the input from environment variables. +- `hidden` (`bool`): If `True`, keeps the input hidden in help messages or documentation. +- `show_choices` (`bool`): If `True`, shows any restricted choices for the input value. +- `show_envvar` (`bool`): If `True`, displays the associated environment variable, if applicable. +- `nargs` (`int`): The number of arguments that the input can accept. +- `should_render` (`bool`): If `True`, renders the input in the user interface or command-line interface. __Examples:__ ```python -from zrb import Input, Task -task = Task( - name='task', - inputs=[ - Input(name='delay', default=10, description='Delay') - ] -) +int_input = IntInput(name='age', default=30, description='Enter your age') +int_input.get_default() +``` + +``` +30 ``` diff --git a/docs/concepts/task-input/password-input.md b/docs/concepts/task-input/password-input.md index 5c384eef..1ddfb62e 100644 --- a/docs/concepts/task-input/password-input.md +++ b/docs/concepts/task-input/password-input.md @@ -7,43 +7,43 @@ ## `PasswordInput` -A concrete implementation of the AnyInput abstract base class, representing a specific type of task input. -This class allows for the creation of interactive and configurable inputs for tasks, with various attributes -to customize its behavior and appearance. - -__Attributes:__ - -- `name` (`str`): The name of the input, used as a unique identifier. -- `shortcut` (`Optional[str]`): An optional single-character shortcut for the input. -- `default` (`Optional[Any]`): The default value of the input. -- `description` (`Optional[str]`): A brief description of what the input is for. -- `show_default` (`Union[bool, JinjaTemplate, None]`): Determines whether the default value should be displayed. -- `prompt` (`Union[bool, str]`): The prompt text to be displayed when asking for the input. -- `confirmation_prompt` (`Union[bool, str]`): A prompt for confirmation if required. -- `prompt_required` (`bool`): Indicates whether a prompt is required. -- `hide_input` (`bool`): If True, the input value will be hidden (e.g., for passwords). -- `is_flag` (`Optional[bool]`): Specifies whether the input is a flag. -- `flag_value` (`Optional[Any]`): The value to be used if the input is a flag. -- `multiple` (`bool`): Allows multiple values for this input if True. -- `count` (`bool`): If True, counts the occurrences of the input. -- `allow_from_autoenv` (`bool`): If True, allows values to be automatically sourced from the environment. -- `type` (`Optional[Any]`): The expected type of the input value. -- `hidden` (`bool`): If True, the input is hidden and not rendered. -- `show_choices` (`bool`): Indicates whether to show available choices for the input. -- `show_envvar` (`bool`): If True, shows the corresponding environment variable. -- `nargs` (`int`): Number of arguments expected for this input. -- `should_render` (`bool`): Determines whether the input should be rendered. +A specialized input class for handling password or sensitive data inputs in tasks. + +`PasswordInput` extends `BaseInput` to manage inputs that should be treated as sensitive, +such as passwords. It ensures that the input is hidden when entered, providing an added +layer of security and privacy. This class supports various features like default values, +prompts, and flags, tailored for the safe handling of sensitive information. + +__Arguments:__ + +- `name` (`str`): The name of the input, serving as an identifier. +- `shortcut` (`Optional[str]`): An optional shortcut string for the input. +- `default` (`Optional[Any]`): The default value for the input, expected to be a string if set. +- `description` (`Optional[str]`): A brief description of the input's purpose. +- `show_default` (`Union[bool, str, None]`): Option to display the default value. Can be a boolean or string. +- `prompt` (`Union[bool, str]`): A boolean or string to prompt the user for input. If `True`, uses the default prompt. +- `confirmation_prompt` (`Union[bool, str]`): If `True`, the user is asked to confirm the input. +- `prompt_required` (`bool`): If `True`, the prompt for input is mandatory. +- `is_flag` (`Optional[bool]`): Indicates if the input is a flag. If `True`, the input accepts boolean flag values. +- `flag_value` (`Optional[Any]`): The value associated with the flag if `is_flag` is `True`. +- `multiple` (`bool`): If `True`, allows multiple values for the input. +- `count` (`bool`): If `True`, counts the occurrences of the input. +- `allow_from_autoenv` (`bool`): If `True`, allows the input to be automatically populated from the environment. +- `hidden` (`bool`): If `True`, the input is not shown in help messages or documentation. +- `show_choices` (`bool`): If `True`, displays the available choices to the user (if applicable). +- `show_envvar` (`bool`): Indicates whether to display the environment variable associated with this input. +- `nargs` (`int`): The number of arguments that the input can accept. +- `should_render` (`bool`): If `True’, the input is rendered in the UI or command-line interface. __Examples:__ ```python -from zrb import Input, Task -task = Task( - name='task', - inputs=[ - Input(name='delay', default=10, description='Delay') - ] -) +password_input = PasswordInput(name='password', description='Enter your password') +password_input.is_hidden() +``` + +``` +True ``` diff --git a/docs/concepts/task-input/str-input.md b/docs/concepts/task-input/str-input.md index 9d40c86d..96053d97 100644 --- a/docs/concepts/task-input/str-input.md +++ b/docs/concepts/task-input/str-input.md @@ -7,43 +7,43 @@ ## `StrInput` -A concrete implementation of the AnyInput abstract base class, representing a specific type of task input. -This class allows for the creation of interactive and configurable inputs for tasks, with various attributes -to customize its behavior and appearance. - -__Attributes:__ - -- `name` (`str`): The name of the input, used as a unique identifier. -- `shortcut` (`Optional[str]`): An optional single-character shortcut for the input. -- `default` (`Optional[Any]`): The default value of the input. -- `description` (`Optional[str]`): A brief description of what the input is for. -- `show_default` (`Union[bool, JinjaTemplate, None]`): Determines whether the default value should be displayed. -- `prompt` (`Union[bool, str]`): The prompt text to be displayed when asking for the input. -- `confirmation_prompt` (`Union[bool, str]`): A prompt for confirmation if required. -- `prompt_required` (`bool`): Indicates whether a prompt is required. -- `hide_input` (`bool`): If True, the input value will be hidden (e.g., for passwords). -- `is_flag` (`Optional[bool]`): Specifies whether the input is a flag. -- `flag_value` (`Optional[Any]`): The value to be used if the input is a flag. -- `multiple` (`bool`): Allows multiple values for this input if True. -- `count` (`bool`): If True, counts the occurrences of the input. -- `allow_from_autoenv` (`bool`): If True, allows values to be automatically sourced from the environment. -- `type` (`Optional[Any]`): The expected type of the input value. -- `hidden` (`bool`): If True, the input is hidden and not rendered. -- `show_choices` (`bool`): Indicates whether to show available choices for the input. -- `show_envvar` (`bool`): If True, shows the corresponding environment variable. -- `nargs` (`int`): Number of arguments expected for this input. -- `should_render` (`bool`): Determines whether the input should be rendered. +A specialized input class for handling string-based inputs in various tasks. + +`StrInput` extends `BaseInput` to manage string-type inputs, supporting features like +default values, prompts, flags, and other customization options. This class is useful +for tasks requiring textual input, such as names, descriptions, or any other string parameters. + +__Arguments:__ + +- `name` (`str`): The name of the input, used as an identifier. +- `shortcut` (`Optional[str]`): An optional shortcut string for the input. +- `default` (`Optional[Any]`): The default value for the input, expected to be a string if set. +- `description` (`Optional[str]`): A brief description of the input's purpose. +- `show_default` (`Union[bool, str, None]`): Option to display the default value. Can be a boolean or string. +- `prompt` (`Union[bool, str]`): A boolean or string to prompt the user for input. If `True`, uses the default prompt. +- `confirmation_prompt` (`Union[bool, str]`): If `True`, the user is asked to confirm the input. +- `prompt_required` (`bool`): If `True’, the prompt for input is mandatory. +- `hide_input` (`bool`): If `True’, hides the input value, typically used for sensitive data. +- `is_flag` (`Optional[bool]`): Indicates if the input is a flag. If `True’, the input accepts boolean flag values. +- `flag_value` (`Optional[Any]`): The value associated with the flag if `is_flag` is `True`. +- `multiple` (`bool`): If `True’, allows multiple string values for the input. +- `count` (`bool`): If `True’, counts the occurrences of the input. +- `allow_from_autoenv` (`bool`): If `True’, enables automatic population of the input from environment variables. +- `hidden` (`bool`): If `True’, keeps the input hidden in help messages or documentation. +- `show_choices` (`bool`): If `True’, shows any restricted choices for the input value. +- `show_envvar` (`bool`): If `True’, displays the associated environment variable, if applicable. +- `nargs` (`int`): The number of arguments that the input can accept. +- `should_render` (`bool`): If `True’, renders the input in the user interface or command-line interface. __Examples:__ ```python -from zrb import Input, Task -task = Task( - name='task', - inputs=[ - Input(name='delay', default=10, description='Delay') - ] -) +str_input = StrInput(name='username', default='user123', description='Enter your username') +str_input.get_default() +``` + +``` +'user123' ``` diff --git a/docs/concepts/task/README.md b/docs/concepts/task/README.md index 872e9785..e6aa1121 100644 --- a/docs/concepts/task/README.md +++ b/docs/concepts/task/README.md @@ -6,117 +6,54 @@ There are many task types in Zrb. Every task has its own specific use cases: +- [python_task](python-task.md): Run a Python function - [CmdTask](cmd-task.md): Run a CLI command -- [Task (python task)](python-task.md): Run a Python function - [DockerComposeTask](docker-compose-task.md): Run a Docker compose Command - [ResourceMaker](resource-maker.md): Generate artifacts/resources based on templates -- [FlowTask](flow-task.md): Put `CmdTask` and `python task` into single flow. +- [FlowTask](flow-task.md): Put multiple tasks into a single flow. +- [BaseRemoteCmdTask](base-remote-cmd-task.md) - [RemoteCmdTask](remote-cmd-task.md) -- [RsyncTask](rsync-task.md) -- [Checkers (HttpChecker, PortChecker, and PathChecker)](checkers.md): Check parent task's readiness. +- [RSyncTask](rsync-task.md) +- [Checker](checker.md): Check readiness of other task. +- [HTTPChecker](http-checker.md) +- [PortChecker](port-checker.md) +- [PathChecker](path-checker.md) +- [PathWatcher](path-watcher.md) +- [TimeWatcher](time-watcher.md) +- [RecurringTask](recurring-task.md) -As every task are extended from `BaseTask`, you will see that most of them share some common parameters. ``` + AnyTask + │ + │ + ▼ BaseTask │ │ - ┌──────┬───────────┬───────────┬─────────────┼─────────────────┬─────────────┬───────────┬──────────┐ - │ │ │ │ │ │ │ │ │ - │ │ │ │ │ │ │ │ │ - ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ -Task CmdTask ResourceMaker FlowTask BaseRemoteCmdTask ReccuringTask HttpChecker PortChecker PathChecker - │ │ - │ │ - ▼ ┌─────┴──────┐ - DockerComposeTask │ │ - ▼ ▼ - RemoteCmdTask RsyncTask + ┌──────┬───────────┬───────────┬─────────────┼─────────────────┬────────────┐ + │ │ │ │ │ │ │ + │ │ │ │ │ │ │ + ▼ ▼ ▼ ▼ ▼ ▼ ▼ +Task CmdTask ResourceMaker FlowTask BaseRemoteCmdTask Checker ReccuringTask + │ │ │ + │ │ │ + ▼ ┌─────┴──────┐ │ + DockerComposeTask │ │ │ + ▼ ▼ │ + RemoteCmdTask RsyncTask │ + │ + ┌───────────┬───────────┬──────────┼─────────────┐ + │ │ │ │ │ + ▼ ▼ ▼ ▼ ▼ + HttpChecker PortChecker PathChecker PathWatcher TimeWatcher ``` Aside from the documentation, you can always dive down into [the source code](https://github.com/state-alchemists/zrb/tree/main/src/zrb/task) to see the detail implementation. > __📝 NOTE:__ Never initiate `BaseTask` directly, use `Task` instead. -# Task Overview - -Tasks are building blocks of your automation. - -Let's see how you can define tasks and connect them to each others: - -```python -from zrb import CmdTask, IntInput, Env, Group, runner, PortChecker - -# defining two groups: arasaka, and jupyterlab -# jupyterlab is located under arasaka -arasaka = Group(name='arasaka', description='Arasaka automation') -jupyterlab = Group(name='jupyterlab', parent=arasaka, description='Jupyterlab related tasks') - -# defining show banner under `arasaka` group -show_banner = CmdTask( - name='show-banner', - icon='🎉', - color='yellow', - description='Show banner', - group=arasaka, - envs=[ - # EMPLOYEE enviornment variable will be accessible from inside the task as USER. - # The default value this variable will be `employee`. - Env(name='USER', os_name='EMPLOYEE', default='employee') - ], - cmd=[ - 'figlet Arasaka', - 'echo "Welcome $USER"' - ] -) - -# registering `show_banner` to zrb runner -runner.register(show_banner) - -# defining show banner under `arasaka jupyterlab` group -start_jupyterlab = CmdTask( - name='start', - icon='🧪', - color='green', - description='Start Jupyterlab', - group=jupyterlab, - inputs=[ - # Port where jupyterlab should be started - IntInput(name='jupyterlab-port', default=8080) - ], - # start_jupyterlab depends on show_banner - upstreams=[show_banner], - cmd='jupyter lab --no-browser --port={{input.jupyterlab_port}}', - checkers=[ - PortChecker(port='{{input.jupyterlab_port}}') - ], - retry=2, - retry_interval=3 -) - -# registering `show_banner` to zrb runner -runner.register(start_jupyterlab) -``` - - -You can try to run `start_jupyterlab` task as follow: - -```bash -export EMPLOYEE="Yorinobu Arasaka" - -# The following command will -# - Show Arasaka Banner -# - Start jupyterlab on the port you choose (by default it is 8080) -zrb arasaka jupyterlab start -``` - -As `start_jupyterlab` has `show_banner` as it's upstream, you can expect the `show_banner` to be executed prior to `start_jupyterlab`. - -A task might also have multiple upstreams. In that case, the upstreams will be executed concurrently. - -> __📝 NOTE:__ Only tasks registered to `runner` are directly accessible from the CLI. - # Task Lifecycle Every task has its own lifecycle. @@ -148,18 +85,88 @@ Triggered ┌─────────► Ready ◄──┐ # Technical Documentation -## `AnyTask` +## `Task` + +Alias for BaseTask + +### `Task._BaseTaskModel__get_colored` + +No documentation available. + + +### `Task._BaseTaskModel__get_colored_print_prefix` + +No documentation available. + + +### `Task._BaseTaskModel__get_common_prefix` + +No documentation available. + + +### `Task._BaseTaskModel__get_executable_name` + +No documentation available. + + +### `Task._BaseTaskModel__get_log_prefix` + +No documentation available. + + +### `Task._BaseTaskModel__get_print_prefix` + +No documentation available. + + +### `Task._BaseTaskModel__get_rjust_full_cli_name` + +No documentation available. + + +### `Task._Renderer__ensure_cached_render_data` + +No documentation available. + + +### `Task._Renderer__get_render_data` + +No documentation available. -Abstract base class for defining tasks in a task management system. -This class acts as a template for creating new task types. To define a new task, -extend this class and implement all its abstract methods. The `AnyTask` class is -considered atomic and is not broken into multiple interfaces. +### `Task._cached_check` -Subclasses should implement the abstract methods to define custom behavior for -task execution, state transitions, and other functionalities. +No documentation available. + + +### `Task._cached_run` + +No documentation available. + + +### `Task._check` + +Check current task readiness. +- If self.checkers is defined, +this will return True once every self.checkers is completed +- Otherwise, this will return check method's return value. + +### `Task._check_should_execute` + +No documentation available. + + +### `Task._end_timer` -### `AnyTask._get_checkers` +No documentation available. + + +### `Task._get_attempt` + +No documentation available. + + +### `Task._get_checkers` Retrieves the checkers set for the task. @@ -171,19 +178,22 @@ __Returns:__ `Iterable[TAnyTask]`: An iterable of checkers associated with the task. -### `AnyTask._get_combined_inputs` +### `Task._get_combined_env` -Combines and retrieves all inputs for the task. +No documentation available. -This internal method aggregates inputs from various sources (static definition, -`inject_inputs`, etc.) and provides a unified view of all inputs that the task -will process. This is crucial for preparing the task's runtime environment. -__Returns:__ +### `Task._get_combined_inputs` + +' +Getting all inputs of this task and all its upstream, non-duplicated. + +### `Task._get_elapsed_time` + +No documentation available. -`Iterable[AnyInput]`: An iterable of all combined inputs for the task. -### `AnyTask._get_env_files` +### `Task._get_env_files` Retrieves the list of environment variable files associated with the task. @@ -194,7 +204,7 @@ __Returns:__ `List[EnvFile]`: A list of `EnvFile` instances associated with the task. -### `AnyTask._get_envs` +### `Task._get_envs` Retrieves the list of environment variables set for the task. @@ -205,7 +215,7 @@ __Returns:__ `List[Env]`: A list of `Env` instances representing the environment variables of the task. -### `AnyTask._get_full_cli_name` +### `Task._get_full_cli_name` Retrieves the full command-line interface (CLI) name of the task. @@ -216,7 +226,7 @@ __Returns:__ `str`: The full CLI name of the task. -### `AnyTask._get_inputs` +### `Task._get_inputs` Retrieves the list of inputs associated with the task. @@ -228,7 +238,17 @@ __Returns:__ `List[AnyInput]`: A list of `AnyInput` instances representing the inputs for the task. -### `AnyTask._get_upstreams` +### `Task._get_max_attempt` + +No documentation available. + + +### `Task._get_task_pid` + +No documentation available. + + +### `Task._get_upstreams` Retrieves the upstream tasks of the current task. @@ -240,19 +260,80 @@ __Returns:__ `Iterable[TAnyTask]`: An iterable of upstream tasks. -### `AnyTask._loop_check` +### `Task._increase_attempt` + +No documentation available. + + +### `Task._is_done` + +No documentation available. + + +### `Task._is_last_attempt` + +No documentation available. + + +### `Task._lock_upstreams` + +No documentation available. + + +### `Task._loop_check` + +For internal use. + +Regularly check whether the task is ready or not. -For internal use +### `Task._mark_awaited` + +No documentation available. + + +### `Task._mark_done` + +No documentation available. + + +### `Task._play_bell` + +No documentation available. + + +### `Task._print_result` + +For internal use. + +Directly call `print_result` + +### `Task._propagate_execution_id` + +No documentation available. + + +### `Task._run_all` + +For internal use. + +Run this task and all its upstreams. + +### `Task._run_and_check_all` + +No documentation available. + + +### `Task._set_args` + +No documentation available. -### `AnyTask._print_result` -For internal use +### `Task._set_env_map` -### `AnyTask._run_all` +No documentation available. -For internal use -### `AnyTask._set_execution_id` +### `Task._set_execution_id` Sets the execution ID for the current task. @@ -265,18 +346,65 @@ __Arguments:__ - `execution_id` (`str`): A string representing the unique execution ID. -### `AnyTask._set_has_cli_interface` +### `Task._set_has_cli_interface` Marks the task as having a CLI interface. This internal method is used to indicate that the task is accessible and executable through a CLI, enabling the task system to appropriately handle its CLI interactions. -### `AnyTask._set_keyval` +### `Task._set_input_map` + +No documentation available. + + +### `Task._set_keyval` + +For internal use. + +Set current task's key values. + +### `Task._set_kwargs` + +No documentation available. + + +### `Task._set_local_keyval` + +No documentation available. + + +### `Task._set_task_pid` + +No documentation available. + + +### `Task._should_attempt` + +No documentation available. + + +### `Task._show_done_info` -For internal use +No documentation available. + + +### `Task._show_env_prefix` + +No documentation available. + + +### `Task._show_run_command` + +No documentation available. + + +### `Task._start_timer` + +No documentation available. -### `AnyTask.add_env` + +### `Task.add_env` Adds one or more `Env` instances to the end of the current task's environment variable list. @@ -297,7 +425,7 @@ task.add_env(env_var) ``` -### `AnyTask.add_env_file` +### `Task.add_env_file` Adds one or more `EnvFile` instances to the end of the current task's environment file list. @@ -319,7 +447,7 @@ task.add_env_file(env_file) ``` -### `AnyTask.add_input` +### `Task.add_input` Adds one or more `AnyInput` instances to the end of the current task's input list. @@ -340,7 +468,7 @@ task.add_input(email_input) ``` -### `AnyTask.add_upstream` +### `Task.add_upstream` Adds one or more `AnyTask` instances to the end of the current task's upstream list. @@ -361,7 +489,7 @@ task.add_upstream(upstream_task) ``` -### `AnyTask.check` +### `Task.check` Checks if the current task is `ready`. @@ -389,7 +517,7 @@ class MyTask(Task): ``` -### `AnyTask.copy` +### `Task.copy` Creates and returns a copy of the current task. @@ -410,7 +538,7 @@ copied_task.set_name('new_name') ``` -### `AnyTask.get_cli_name` +### `Task.get_cli_name` Gets the command-line interface (CLI) name of the task. @@ -421,7 +549,7 @@ __Returns:__ `str`: The CLI name of the task. -### `AnyTask.get_color` +### `Task.get_color` Retrieves the color associated with the current task. @@ -432,7 +560,7 @@ __Returns:__ `str`: A string representing the color assigned to the task. -### `AnyTask.get_description` +### `Task.get_description` Fetches the current description of the task. @@ -443,12 +571,25 @@ __Returns:__ `str`: The description of the task. -### `AnyTask.get_env_map` +### `Task.get_env_map` -No documentation available. +Get a map representing task's Envs and EnvFiles +Typically used inside `run`, `check`, or in `@python_task` decorator + +__Examples:__ + +```python +from zrb import python_task, Task, Env +@python_task(name='task', envs=[Env(name='DB_URL')]) +def task(*args, **kwargs): + task: Task = kwargs.get('_task') + for key, value in task.get_env_map(): + task.print_out(f'{key}: {value}') +``` -### `AnyTask.get_execution_id` + +### `Task.get_execution_id` Retrieves the execution ID of the task. @@ -460,7 +601,7 @@ __Returns:__ `str`: The unique execution ID of the task. -### `AnyTask.get_icon` +### `Task.get_icon` Retrieves the icon identifier of the current task. @@ -471,12 +612,25 @@ __Returns:__ `str`: A string representing the icon identifier for the task -### `AnyTask.get_input_map` +### `Task.get_input_map` -No documentation available. +Get a map representing task's Inputs. + +Typically used inside `run`, `check`, or in `@python_task` decorator + +__Examples:__ + +```python +from zrb import python_task, Task, Input +@python_task(name='task', inputs=[Input(name='name')]) +def task(*args, **kwargs): + task: Task = kwargs.get('_task') + for key, value in task.get_input_map(): + task.print_out(f'{key}: {value}') +``` -### `AnyTask.inject_checkers` +### `Task.inject_checkers` Injects custom checkers into the task. @@ -494,7 +648,7 @@ class MyTask(Task): ``` -### `AnyTask.inject_env_files` +### `Task.inject_env_files` Injects additional `EnvFile` into the task. @@ -508,7 +662,7 @@ class MyTask(Task): ``` -### `AnyTask.inject_envs` +### `Task.inject_envs` Injects environment variables into the task. @@ -522,7 +676,7 @@ class MyTask(Task): ``` -### `AnyTask.inject_inputs` +### `Task.inject_inputs` Injects custom inputs into the task. @@ -540,7 +694,7 @@ class MyTask(Task): ``` -### `AnyTask.inject_upstreams` +### `Task.inject_upstreams` Injects upstream tasks into the current task. @@ -558,7 +712,7 @@ class MyTask(Task): ``` -### `AnyTask.insert_env` +### `Task.insert_env` Inserts one or more `Env` instances at the beginning of the current task's environment variable list. @@ -579,7 +733,7 @@ task.insert_env(env_var) ``` -### `AnyTask.insert_env_file` +### `Task.insert_env_file` Inserts one or more `EnvFile` instances at the beginning of the current task's environment file list. @@ -601,7 +755,7 @@ task.insert_env_file(env_file) ``` -### `AnyTask.insert_input` +### `Task.insert_input` Inserts one or more `AnyInput` instances at the beginning of the current task's input list. @@ -622,7 +776,7 @@ task.insert_input(email_input) ``` -### `AnyTask.insert_upstream` +### `Task.insert_upstream` Inserts one or more `AnyTask` instances at the beginning of the current task's upstream list. @@ -644,32 +798,37 @@ task.insert_upstream(upstream_task) ``` -### `AnyTask.log_critical` +### `Task.log_critical` -No documentation available. +Log message with log level "CRITICAL" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment -### `AnyTask.log_debug` +### `Task.log_debug` -No documentation available. +Log message with log level "DEBUG" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment -### `AnyTask.log_error` +### `Task.log_error` -No documentation available. +Log message with log level "ERROR" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment -### `AnyTask.log_info` +### `Task.log_info` -No documentation available. +Log message with log level "INFO" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment -### `AnyTask.log_warn` +### `Task.log_warn` -No documentation available. +Log message with log level "WARNING" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment -### `AnyTask.on_failed` +### `Task.on_failed` Specifies the behavior when the task execution fails. @@ -695,7 +854,7 @@ class MyTask(Task): ``` -### `AnyTask.on_ready` +### `Task.on_ready` Defines actions to be performed when the task status is `ready`. @@ -713,7 +872,7 @@ class MyTask(Task): ``` -### `AnyTask.on_retry` +### `Task.on_retry` Defines actions to perform when the task is retried. @@ -731,7 +890,7 @@ class MyTask(Task): ``` -### `AnyTask.on_skipped` +### `Task.on_skipped` Defines actions to perform when the task status is set to `skipped`. @@ -748,7 +907,7 @@ class MyTask(Task): ``` -### `AnyTask.on_started` +### `Task.on_started` Defines actions to perform when the task status is set to 'started'. @@ -765,7 +924,7 @@ class MyTask(Task): ``` -### `AnyTask.on_triggered` +### `Task.on_triggered` Defines actions to perform when the task status is set to `triggered`. @@ -783,7 +942,7 @@ class MyTask(Task): ``` -### `AnyTask.on_waiting` +### `Task.on_waiting` Defines actions to perform when the task status is set to `waiting`. @@ -801,22 +960,19 @@ class MyTask(Task): ``` -### `AnyTask.print_err` +### `Task.print_err` -No documentation available. - - -### `AnyTask.print_out` - -No documentation available. +Print message to stderr and style it as error. +### `Task.print_out` -### `AnyTask.print_out_dark` +Print message to stderr as normal text. -No documentation available. +### `Task.print_out_dark` +Print message to stdout and style it as faint. -### `AnyTask.print_result` +### `Task.print_result` Outputs the task result to stdout for further processing. @@ -830,43 +986,41 @@ __Arguments:__ __Examples:__ ->> from zrb import Task ->> # Example of overriding in a subclass ->> class MyTask(Task): ->> def print_result(self, result: Any): ->> print(f'Result: {result}') - -### `AnyTask.render_any` - -No documentation available. - +```python +from zrb import Task +# Example of overriding in a subclass +class MyTask(Task): + def print_result(self, result: Any): + print(f'Result: {result}') +``` -### `AnyTask.render_bool` -No documentation available. +### `Task.render_any` +Render any value. -### `AnyTask.render_file` +### `Task.render_bool` -No documentation available. +Render int value. +### `Task.render_file` -### `AnyTask.render_float` +Render file content. -No documentation available. +### `Task.render_float` +Render float value. -### `AnyTask.render_int` +### `Task.render_int` No documentation available. -### `AnyTask.render_str` - -No documentation available. +### `Task.render_str` +Render str value. -### `AnyTask.run` +### `Task.run` Executes the main logic of the task. @@ -895,7 +1049,7 @@ class MyTask(Task): ``` -### `AnyTask.set_checking_interval` +### `Task.set_checking_interval` Sets the interval for checking the task's readiness or completion status. @@ -906,7 +1060,7 @@ __Arguments:__ - `new_checking_interval` (`Union[float, int]`): The time interval (in seconds) for readiness or checks. -### `AnyTask.set_color` +### `Task.set_color` Defines a new color for the current task. @@ -917,7 +1071,7 @@ __Arguments:__ - `new_color` (`str`): A string representing the color to be assigned to the task. -### `AnyTask.set_description` +### `Task.set_description` Sets a new description for the current task. @@ -928,7 +1082,7 @@ __Arguments:__ - `new_description` (`str`): A string representing the new description of the task. -### `AnyTask.set_icon` +### `Task.set_icon` Assigns a new icon to the current task. @@ -939,7 +1093,7 @@ __Arguments:__ - `new_icon` (`str`): A string representing the icon identifier for the task. -### `AnyTask.set_name` +### `Task.set_name` Sets a new name for the current task. @@ -950,7 +1104,7 @@ __Arguments:__ - `new_name` (`str`): A string representing the new name to be assigned to the task. -### `AnyTask.set_retry` +### `Task.set_retry` Sets the number of retry attempts for the task. @@ -961,7 +1115,7 @@ __Arguments:__ - `new_retry` (`int`): An integer representing the number of retry attempts. -### `AnyTask.set_retry_interval` +### `Task.set_retry_interval` Specifies the interval between retry attempts for the task. @@ -972,7 +1126,7 @@ __Arguments:__ - `new_retry_interval` (`Union[float, int]`): The time interval (in seconds) to wait before a retry attempt. -### `AnyTask.set_should_execute` +### `Task.set_should_execute` Determines whether the task should execute. @@ -984,7 +1138,7 @@ __Arguments:__ - `should_execute` (`Union[bool, str, Callable[..., bool]]`): The condition to determine if the task should execute. -### `AnyTask.to_function` +### `Task.to_function` Converts the current task into a callable function. diff --git a/docs/concepts/task/base-remote-cmd-task.md b/docs/concepts/task/base-remote-cmd-task.md new file mode 100644 index 00000000..3893d9e7 --- /dev/null +++ b/docs/concepts/task/base-remote-cmd-task.md @@ -0,0 +1,1102 @@ +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task](./README.md) + +# BaseRemoteCmdTask + +# Technical Specification + + +## `BaseRemoteCmdTask` + +Base class for all tasks. +Every task definition should be extended from this class. + +### `BaseRemoteCmdTask._BaseTaskModel__get_colored` + +No documentation available. + + +### `BaseRemoteCmdTask._BaseTaskModel__get_colored_print_prefix` + +No documentation available. + + +### `BaseRemoteCmdTask._BaseTaskModel__get_common_prefix` + +No documentation available. + + +### `BaseRemoteCmdTask._BaseTaskModel__get_executable_name` + +No documentation available. + + +### `BaseRemoteCmdTask._BaseTaskModel__get_log_prefix` + +No documentation available. + + +### `BaseRemoteCmdTask._BaseTaskModel__get_print_prefix` + +No documentation available. + + +### `BaseRemoteCmdTask._BaseTaskModel__get_rjust_full_cli_name` + +No documentation available. + + +### `BaseRemoteCmdTask._Renderer__ensure_cached_render_data` + +No documentation available. + + +### `BaseRemoteCmdTask._Renderer__get_render_data` + +No documentation available. + + +### `BaseRemoteCmdTask._cached_check` + +No documentation available. + + +### `BaseRemoteCmdTask._cached_run` + +No documentation available. + + +### `BaseRemoteCmdTask._check` + +Check current task readiness. +- If self.checkers is defined, +this will return True once every self.checkers is completed +- Otherwise, this will return check method's return value. + +### `BaseRemoteCmdTask._check_should_execute` + +No documentation available. + + +### `BaseRemoteCmdTask._end_timer` + +No documentation available. + + +### `BaseRemoteCmdTask._get_attempt` + +No documentation available. + + +### `BaseRemoteCmdTask._get_checkers` + +Retrieves the checkers set for the task. + +This internal method returns an iterable of all the checkers that have been added to +the task. It's mainly used for internal logic and debugging to understand the +validations or conditions applied to the task. + +__Returns:__ + +`Iterable[TAnyTask]`: An iterable of checkers associated with the task. + +### `BaseRemoteCmdTask._get_combined_env` + +No documentation available. + + +### `BaseRemoteCmdTask._get_combined_inputs` + +' +Getting all inputs of this task and all its upstream, non-duplicated. + +### `BaseRemoteCmdTask._get_elapsed_time` + +No documentation available. + + +### `BaseRemoteCmdTask._get_env_files` + +Retrieves the list of environment variable files associated with the task. + +Intended for internal use, this method returns a list of `EnvFile` instances that the task +uses to load environment variables, primarily for setup and configuration purposes. + +__Returns:__ + +`List[EnvFile]`: A list of `EnvFile` instances associated with the task. + +### `BaseRemoteCmdTask._get_envs` + +Retrieves the list of environment variables set for the task. + +For internal use, this method returns a list of `Env` instances representing the environment variables +configured for the task, essential for understanding and debugging the task's environment setup. + +__Returns:__ + +`List[Env]`: A list of `Env` instances representing the environment variables of the task. + +### `BaseRemoteCmdTask._get_full_cli_name` + +Retrieves the full command-line interface (CLI) name of the task. + +Intended for internal use, this method provides the complete CLI name, including any +prefixes or namespaces, used primarily for logging or debugging purposes. + +__Returns:__ + +`str`: The full CLI name of the task. + +### `BaseRemoteCmdTask._get_inputs` + +Retrieves the list of inputs associated with the task. + +This internal method is used to obtain all the inputs that have been set for the task, +either through static definition or via the `inject_inputs` method. It's primarily used +for introspection and debugging purposes. + +__Returns:__ + +`List[AnyInput]`: A list of `AnyInput` instances representing the inputs for the task. + +### `BaseRemoteCmdTask._get_max_attempt` + +No documentation available. + + +### `BaseRemoteCmdTask._get_task_pid` + +No documentation available. + + +### `BaseRemoteCmdTask._get_upstreams` + +Retrieves the upstream tasks of the current task. + +An internal method to get the list of upstream tasks that have been set for the +task, either statically or through `inject_upstreams`. This is essential for task +scheduling and dependency management. + +__Returns:__ + +`Iterable[TAnyTask]`: An iterable of upstream tasks. + +### `BaseRemoteCmdTask._increase_attempt` + +No documentation available. + + +### `BaseRemoteCmdTask._is_done` + +No documentation available. + + +### `BaseRemoteCmdTask._is_last_attempt` + +No documentation available. + + +### `BaseRemoteCmdTask._lock_upstreams` + +No documentation available. + + +### `BaseRemoteCmdTask._loop_check` + +For internal use. + +Regularly check whether the task is ready or not. + +### `BaseRemoteCmdTask._mark_awaited` + +No documentation available. + + +### `BaseRemoteCmdTask._mark_done` + +No documentation available. + + +### `BaseRemoteCmdTask._play_bell` + +No documentation available. + + +### `BaseRemoteCmdTask._print_result` + +For internal use. + +Directly call `print_result` + +### `BaseRemoteCmdTask._propagate_execution_id` + +No documentation available. + + +### `BaseRemoteCmdTask._run_all` + +For internal use. + +Run this task and all its upstreams. + +### `BaseRemoteCmdTask._run_and_check_all` + +No documentation available. + + +### `BaseRemoteCmdTask._set_args` + +No documentation available. + + +### `BaseRemoteCmdTask._set_env_map` + +No documentation available. + + +### `BaseRemoteCmdTask._set_execution_id` + +Sets the execution ID for the current task. + +This method is intended for internal use to assign a unique identifier to the task's execution. +This ID can be used for tracking, logging, and inter-task communication. + +This method should not be used externally, as it is meant to be managed within the task system. + +__Arguments:__ + +- `execution_id` (`str`): A string representing the unique execution ID. + +### `BaseRemoteCmdTask._set_has_cli_interface` + +Marks the task as having a CLI interface. + +This internal method is used to indicate that the task is accessible and executable through a CLI, +enabling the task system to appropriately handle its CLI interactions. + +### `BaseRemoteCmdTask._set_input_map` + +No documentation available. + + +### `BaseRemoteCmdTask._set_keyval` + +For internal use. + +Set current task's key values. + +### `BaseRemoteCmdTask._set_kwargs` + +No documentation available. + + +### `BaseRemoteCmdTask._set_local_keyval` + +No documentation available. + + +### `BaseRemoteCmdTask._set_task_pid` + +No documentation available. + + +### `BaseRemoteCmdTask._should_attempt` + +No documentation available. + + +### `BaseRemoteCmdTask._show_done_info` + +No documentation available. + + +### `BaseRemoteCmdTask._show_env_prefix` + +No documentation available. + + +### `BaseRemoteCmdTask._show_run_command` + +No documentation available. + + +### `BaseRemoteCmdTask._start_timer` + +No documentation available. + + +### `BaseRemoteCmdTask.add_env` + +Adds one or more `Env` instances to the end of the current task's environment variable list. + +Use this method to append environment variables for the task, which will be used after +any variables already set. + +__Arguments:__ + +- `envs` (`Env`): One or more environment variable instances to be added. + +__Examples:__ + +```python +from zrb import Task, Env +task = Task(name='task') +db_url_env = Env(name='DATABASE_URL', value='postgresql://...') +task.add_env(env_var) +``` + + +### `BaseRemoteCmdTask.add_env_file` + +Adds one or more `EnvFile` instances to the end of the current task's environment file list. + +Use this method to append environment file references, which will be processed after +any files already specified. This allows for supplementing the existing environment +configuration. + +__Arguments:__ + +- `env_files` (`EnvFile`): One or more environment file instances to be added. + +__Examples:__ + +```python +from zrb import Task, EnvFile +task = Task() +env_file = EnvFile(path='config.env') +task.add_env_file(env_file) +``` + + +### `BaseRemoteCmdTask.add_input` + +Adds one or more `AnyInput` instances to the end of the current task's input list. + +This method is used to append inputs for the task to process, placing them after any inputs +already specified. + +__Arguments:__ + +- `inputs` (`AnyInput`): One or more input instances to be added to the input list. + +__Examples:__ + +```python +from zrb import Task, Input +task = Task(name='task') +email_input = Input(name='email-address') +task.add_input(email_input) +``` + + +### `BaseRemoteCmdTask.add_upstream` + +Adds one or more `AnyTask` instances to the end of the current task's upstream list. + +This method appends tasks to the upstream list, indicating that these tasks should be executed +before the current task, but after any tasks already in the upstream list. + +__Arguments:__ + +- `upstreams` (`TAnyTask`): One or more task instances to be added to the upstream list. + +__Examples:__ + +```python +from zrb import Task +task = Task(name='task') +upstream_task = Task(name='upstream-task') +task.add_upstream(upstream_task) +``` + + +### `BaseRemoteCmdTask.check` + +Checks if the current task is `ready`. + +Any other tasks depends on the current task, will be `started` once the current task is `ready`. + +This method should be implemented to define the criteria for considering the task +`ready`. The specifics of this completion depend on the task's +nature and the subclass implementation. + +__Returns:__ + +`bool`: True if the task is completed, False otherwise. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def run(self, *args: Any, **kwargs: Any) -> int: + self.print_out('Doing some calculation') + self._completed = True + return 42 + async def check(self) -> bool: + return self._completed +``` + + +### `BaseRemoteCmdTask.copy` + +Creates and returns a copy of the current task. + +The copied task can be modified using various setter methods like `set_name`, +`set_description`, and others, depending on the subclass implementation. + +__Returns:__ + +`TAnyTask`: A copy of the current task. + +__Examples:__ + +```python +from zrb import Task +task = Task(name='my-task', cmd='echo hello') +copied_task = task.copy() +copied_task.set_name('new_name') +``` + + +### `BaseRemoteCmdTask.get_cli_name` + +Gets the command-line interface (CLI) name of the task. + +This method returns the name used to invoke the task via a CLI, facilitating integration with command-line tools +or scripts. + +__Returns:__ + +`str`: The CLI name of the task. + +### `BaseRemoteCmdTask.get_color` + +Retrieves the color associated with the current task. + +This method returns the color of the task, useful for visual differentiation, priority indication, +or categorization in user interfaces or documentation. + +__Returns:__ + +`str`: A string representing the color assigned to the task. + +### `BaseRemoteCmdTask.get_description` + +Fetches the current description of the task. + +This method is used to obtain the detailed description of the task, providing insights into its purpose, +functionality, and usage within the task management system. + +__Returns:__ + +`str`: The description of the task. + +### `BaseRemoteCmdTask.get_env_map` + +Get a map representing task's Envs and EnvFiles + +Typically used inside `run`, `check`, or in `@python_task` decorator + +__Examples:__ + +```python +from zrb import python_task, Task, Env +@python_task(name='task', envs=[Env(name='DB_URL')]) +def task(*args, **kwargs): + task: Task = kwargs.get('_task') + for key, value in task.get_env_map(): + task.print_out(f'{key}: {value}') +``` + + +### `BaseRemoteCmdTask.get_execution_id` + +Retrieves the execution ID of the task. + +This method returns the unique identifier associated with the task's execution. +The execution ID is crucial for tracking, logging, and differentiating between +multiple instances or runs of the same task. + +__Returns:__ + +`str`: The unique execution ID of the task. + +### `BaseRemoteCmdTask.get_icon` + +Retrieves the icon identifier of the current task. + +This method is used to get the icon associated with the task, which can be utilized for +visual representation in user interfaces or documentation. + +__Returns:__ + +`str`: A string representing the icon identifier for the task + +### `BaseRemoteCmdTask.get_input_map` + +Get a map representing task's Inputs. + +Typically used inside `run`, `check`, or in `@python_task` decorator + +__Examples:__ + +```python +from zrb import python_task, Task, Input +@python_task(name='task', inputs=[Input(name='name')]) +def task(*args, **kwargs): + task: Task = kwargs.get('_task') + for key, value in task.get_input_map(): + task.print_out(f'{key}: {value}') +``` + + +### `BaseRemoteCmdTask.inject_checkers` + +Injects custom checkers into the task. + +This method allows for the addition of custom validation or condition checkers. These +checkers can be used to verify certain conditions before the task execution proceeds. +Subclasses should implement this method to define task-specific checkers. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + def inject_checkers(self): + self.add_checker(some_custom_condition_checker) +``` + + +### `BaseRemoteCmdTask.inject_env_files` + +Injects additional `EnvFile` into the task. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + def inject_env_files(self): + self.add_env_files(EnvFile(path='config.env')) +``` + + +### `BaseRemoteCmdTask.inject_envs` + +Injects environment variables into the task. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + def inject_envs(self): + self.add_envs(Env(name='DATABASE_URL')) +``` + + +### `BaseRemoteCmdTask.inject_inputs` + +Injects custom inputs into the task. + +This method is used to programmatically add input parameters to the task, allowing +dynamic customization of the task's input data. Subclasses should override this method +to define specific inputs that the task should receive. + +__Examples:__ + +```python +from zrb import Task, Input +class MyTask(Task): + def inject_inputs(self): + self.add_input(Input(name='user_email', type='email')) +``` + + +### `BaseRemoteCmdTask.inject_upstreams` + +Injects upstream tasks into the current task. + +This method is used for programmatically adding upstream dependencies to the task. +Upstream tasks are those that must be completed before the current task starts. +Override this method in subclasses to specify such dependencies. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + def inject_upstreams(self): + self.add_upstream(another_task) +``` + + +### `BaseRemoteCmdTask.insert_env` + +Inserts one or more `Env` instances at the beginning of the current task's environment variable list. + +This method allows for setting or overriding environment variables for the task, with earlier entries +having precedence over later ones. + +__Arguments:__ + +- `envs` (`Env`): One or more environment variable instances to be added. + +__Examples:__ + +```python +from zrb import Task, Env +task = Task(name='task') +db_url_env = Env(name='DATABASE_URL', value='postgresql://...') +task.insert_env(env_var) +``` + + +### `BaseRemoteCmdTask.insert_env_file` + +Inserts one or more `EnvFile` instances at the beginning of the current task's environment file list. + +This method is used to specify environment variable files whose contents should be loaded +before those of any files already in the list. This is useful for overriding or setting +additional environment configurations. + +__Arguments:__ + +- `env_files` (`EnvFile`): One or more environment file instances to be added. + +__Examples:__ + +```python +from zrb import Task, EnvFile +task = Task() +env_file = EnvFile(path='config.env') +task.insert_env_file(env_file) +``` + + +### `BaseRemoteCmdTask.insert_input` + +Inserts one or more `AnyInput` instances at the beginning of the current task's input list. + +This method is used to add inputs that the task will process. Inserting an input at the beginning +of the list gives it precedence over those already present. + +__Arguments:__ + +- `inputs` (`AnyInput`): One or more input instances to be added to the input list. + +__Examples:__ + +```python +from zrb import Task, Input +task = Task(name='task') +email_input = Input(name='email-address') +task.insert_input(email_input) +``` + + +### `BaseRemoteCmdTask.insert_upstream` + +Inserts one or more `AnyTask` instances at the beginning of the current task's upstream list. + +This method is used to define dependencies for the current task. Tasks in the upstream list are +executed before the current task. Adding a task to the beginning of the list means it will be +executed earlier than those already in the list. + +__Arguments:__ + +- `upstreams` (`TAnyTask`): One or more task instances to be added to the upstream list. + +__Examples:__ + +```python +from zrb import Task +task = Task(name='task') +upstream_task = Task(name='upstream-task') +task.insert_upstream(upstream_task) +``` + + +### `BaseRemoteCmdTask.log_critical` + +Log message with log level "CRITICAL" + +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + +### `BaseRemoteCmdTask.log_debug` + +Log message with log level "DEBUG" + +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + +### `BaseRemoteCmdTask.log_error` + +Log message with log level "ERROR" + +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + +### `BaseRemoteCmdTask.log_info` + +Log message with log level "INFO" + +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + +### `BaseRemoteCmdTask.log_warn` + +Log message with log level "WARNING" + +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + +### `BaseRemoteCmdTask.on_failed` + +Specifies the behavior when the task execution fails. + +This asynchronous method should be implemented in subclasses to handle task +failure scenarios. It can include logging the error, performing retries, or +any other failure handling mechanisms. + +__Arguments:__ + +- `is_last_attempt` (`bool`): Indicates if this is the final retry attempt. +- `exception` (`Exception`): The exception that caused the task to fail. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_failed(self, is_last_attempt: bool, exception: Exception): + if is_last_attempt: + self.print_out('The task has failed with no remaining retries') + else: + self.print_out('The task failed, retrying...') +``` + + +### `BaseRemoteCmdTask.on_ready` + +Defines actions to be performed when the task status is `ready`. + +This asynchronous method should be implemented in subclasses to specify +actions that occur when the task reaches the `ready` state. This can include +any cleanup, notification, or follow-up actions specific to the task. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_ready(self): + self.print_out('The task is ready') +``` + + +### `BaseRemoteCmdTask.on_retry` + +Defines actions to perform when the task is retried. + +Implement this method to specify behavior when the task is retried after a failure. +This could include resetting states, logging the retry attempt, or other necessary +steps before re-execution. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_retry(self): + self.log_info('Retrying task') +``` + + +### `BaseRemoteCmdTask.on_skipped` + +Defines actions to perform when the task status is set to `skipped`. + +Implement this method to specify behavior when the task is skipped. This could +include logging information, cleaning up resources, or any other necessary steps. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_skipped(self): + self.log_info('Task was skipped') +``` + + +### `BaseRemoteCmdTask.on_started` + +Defines actions to perform when the task status is set to 'started'. + +Implement this method to specify behavior when the task starts its execution. This +could involve initializing resources, logging, or other startup procedures. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_started(self): + self.log_info('Task has started') +``` + + +### `BaseRemoteCmdTask.on_triggered` + +Defines actions to perform when the task status is set to `triggered`. + +Implement this method to specify behavior when the task transitions to the +`triggered` state. This could involve setting up prerequisites or sending +notifications. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_triggered(self): + self.log_info('Task has been triggered') +``` + + +### `BaseRemoteCmdTask.on_waiting` + +Defines actions to perform when the task status is set to `waiting`. + +Implement this method to specify behavior when the task transitions to the +`waiting` state. This state usually indicates the task is waiting for some +condition or prerequisite to be met. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_waiting(self): + self.log_info('Task is waiting to be started') +``` + + +### `BaseRemoteCmdTask.print_err` + +Print message to stderr and style it as error. + +### `BaseRemoteCmdTask.print_out` + +Print message to stderr as normal text. + +### `BaseRemoteCmdTask.print_out_dark` + +Print message to stdout and style it as faint. + +### `BaseRemoteCmdTask.print_result` + +Outputs the task result to stdout for further processing. + +Override this method in subclasses to customize how the task result is displayed +or processed. Useful for integrating the task output with other systems or +command-line tools. + +__Arguments:__ + +- `result` (`Any`): The result of the task to be printed. + +__Examples:__ + +```python +from zrb import Task +# Example of overriding in a subclass +class MyTask(Task): + def print_result(self, result: Any): + print(f'Result: {result}') +``` + + +### `BaseRemoteCmdTask.render_any` + +Render any value. + +### `BaseRemoteCmdTask.render_bool` + +Render int value. + +### `BaseRemoteCmdTask.render_file` + +Render file content. + +### `BaseRemoteCmdTask.render_float` + +Render float value. + +### `BaseRemoteCmdTask.render_int` + +No documentation available. + + +### `BaseRemoteCmdTask.render_str` + +Render str value. + +### `BaseRemoteCmdTask.run` + +Executes the main logic of the task. + +This asynchronous method should be implemented in subclasses to define the +task's primary functionality. The specific behavior and the return value +depend on the task's nature and purpose. + +__Arguments:__ + +- `args` (`Any`): Variable length argument list. +- `kwargs` (`Any`): Arbitrary keyword arguments. + +__Returns:__ + +`Any`: The result of the task execution, the type of which is determined by +the specific task implementation. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def run(self, *args: Any, **kwargs: Any) -> int: + self.print_out('Doing some calculation') + return 42 +``` + + +### `BaseRemoteCmdTask.set_checking_interval` + +Sets the interval for checking the task's readiness or completion status. + +This method defines how frequently the system should check if the task is ready or completed. +It's useful for tasks that have an indeterminate completion time. + +__Arguments:__ + +- `new_checking_interval` (`Union[float, int]`): The time interval (in seconds) for readiness or checks. + +### `BaseRemoteCmdTask.set_color` + +Defines a new color for the current task. + +This method updates the color associated with the task. This can be useful for categorization, +priority indication, or visual differentiation in a UI. + +__Arguments:__ + +- `new_color` (`str`): A string representing the color to be assigned to the task. + +### `BaseRemoteCmdTask.set_description` + +Sets a new description for the current task. + +This method allows updating the task's description to provide more context or details about its purpose and behavior. +Useful for enhancing clarity and maintainability in the task management system. + +__Arguments:__ + +- `new_description` (`str`): A string representing the new description of the task. + +### `BaseRemoteCmdTask.set_icon` + +Assigns a new icon to the current task. + +This method is used for setting or updating the task's icon, which can be utilized for visual representation +in a user interface. The icon should ideally be a string identifier that maps to an actual graphical resource. + +__Arguments:__ + +- `new_icon` (`str`): A string representing the icon identifier for the task. + +### `BaseRemoteCmdTask.set_name` + +Sets a new name for the current task. + +This method is used to update the task's name, typically after creating a copy of an existing task. +The new name helps in differentiating the task in the task management system. + +__Arguments:__ + +- `new_name` (`str`): A string representing the new name to be assigned to the task. + +### `BaseRemoteCmdTask.set_retry` + +Sets the number of retry attempts for the task. + +This method configures how many times the task should be retried in case of failure. +It's essential for tasks that may fail transiently and need multiple attempts for successful execution. + +__Arguments:__ + +- `new_retry` (`int`): An integer representing the number of retry attempts. + +### `BaseRemoteCmdTask.set_retry_interval` + +Specifies the interval between retry attempts for the task. + +This method sets the duration to wait before retrying the task after a failure. +This can help in scenarios where immediate retry is not desirable or effective. + +__Arguments:__ + +- `new_retry_interval` (`Union[float, int]`): The time interval (in seconds) to wait before a retry attempt. + +### `BaseRemoteCmdTask.set_should_execute` + +Determines whether the task should execute. + +This method configures the execution criteria for the task. It can be set as a boolean value, +a string representing a condition, or a callable that returns a boolean. This is useful for +conditional task execution based on dynamic criteria. + +__Arguments:__ + +- `should_execute` (`Union[bool, str, Callable[..., bool]]`): The condition to determine if the task should execute. + +### `BaseRemoteCmdTask.to_function` + +Converts the current task into a callable function. + +This method should be implemented to allow the task to be executed as a function. +Parameters can be used to modify the behavior of the generated function, such as +raising errors, asynchronous execution, and logging. + +__Arguments:__ + +- `env_prefix` (`str`): A prefix for environment variables. +- `raise_error` (`bool`): Whether to raise an error if the task execution fails. +- `is_async` (`bool`): Whether the resulting function should be asynchronous. +- `show_done_info` (`bool`): Whether to show information upon task completion. + +__Returns:__ + +`Callable[..., Any]`: A callable representation of the task. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def run(self, *args: Any, **kwargs: Any) -> int: + self.print_out('Doing some calculation') + return 42 +``` + +``` +>>> +```python +task = MyTask() +fn = task.to_function() +fn() +``` + + + + +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task](./README.md) diff --git a/docs/concepts/task/checkers.md b/docs/concepts/task/checker.md similarity index 91% rename from docs/concepts/task/checkers.md rename to docs/concepts/task/checker.md index 2a47a127..092d3386 100644 --- a/docs/concepts/task/checkers.md +++ b/docs/concepts/task/checker.md @@ -1,61 +1,8 @@ -🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Tasks](README.md) +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task](./README.md) -# Checkers +# Checker -Checkers are special type of tasks. You can use checkers to check for other task's readiness. - -Currently there are three types of checkers: -- PathChecker -- PortChecker -- HttpChecker - - -Let's say you invoke `npm run build:watch`. This command will build your Node.js App into `dist` directory, as well as watch the changes and rebuild your app as soon as there are some changes. - -- A web server is considered ready if it's HTTP Port is accessible. You can use `HTTPChecker` to check for web server readiness. -- But, before running the web server to start, you need to build the frontend and make sure that the `src/frontend/dist` has been created. You can use `PathChecker` to check for frontend readiness. - -Let's see how we can do this: - -```python -from zrb import CmdTask, PathChecker, Env, EnvFile, runner - -build_frontend = CmdTask( - name='build-frontend', - cmd='npm run build', - cwd='src/frontend', - checkers=[ - PathChecker(path='src/frontend/dist') - ] -) - -run_server = CmdTask( - name='run-server', - envs=[ - Env(name='PORT', os_name='WEB_PORT', default='3000') - ], - env_files=[ - EnvFile(path='src/template.env', prefix='WEB') - ] - cmd='python main.py', - cwd='src', - upstreams=[ - build_frontend - ], - checkers=[HTTPChecker(port='{{env.PORT}}')], -) -runner.register(run_server) -``` - -> Aside from `PathChecker` and `HTTPChecker`, you can also use `PortChecker` to check for TCP port readiness. - -You can then run the server by invoking: - -```bash -zrb run-server -``` - -# Technical Documentation +# Technical Specification ## `Checker` @@ -256,7 +203,9 @@ No documentation available. ### `Checker._loop_check` -For internal use +For internal use. + +Regularly check whether the task is ready or not. ### `Checker._mark_awaited` @@ -275,7 +224,9 @@ No documentation available. ### `Checker._print_result` -For internal use +For internal use. + +Directly call `print_result` ### `Checker._propagate_execution_id` @@ -284,7 +235,9 @@ No documentation available. ### `Checker._run_all` -For internal use +For internal use. + +Run this task and all its upstreams. ### `Checker._run_and_check_all` @@ -328,7 +281,9 @@ No documentation available. ### `Checker._set_keyval` -For internal use +For internal use. + +Set current task's key values. ### `Checker._set_kwargs` @@ -539,7 +494,20 @@ __Returns:__ ### `Checker.get_env_map` -No documentation available. +Get a map representing task's Envs and EnvFiles + +Typically used inside `run`, `check`, or in `@python_task` decorator + +__Examples:__ + +```python +from zrb import python_task, Task, Env +@python_task(name='task', envs=[Env(name='DB_URL')]) +def task(*args, **kwargs): + task: Task = kwargs.get('_task') + for key, value in task.get_env_map(): + task.print_out(f'{key}: {value}') +``` ### `Checker.get_execution_id` @@ -567,7 +535,20 @@ __Returns:__ ### `Checker.get_input_map` -No documentation available. +Get a map representing task's Inputs. + +Typically used inside `run`, `check`, or in `@python_task` decorator + +__Examples:__ + +```python +from zrb import python_task, Task, Input +@python_task(name='task', inputs=[Input(name='name')]) +def task(*args, **kwargs): + task: Task = kwargs.get('_task') + for key, value in task.get_input_map(): + task.print_out(f'{key}: {value}') +``` ### `Checker.inject_checkers` @@ -745,28 +726,33 @@ No documentation available. ### `Checker.log_critical` -No documentation available. +Log message with log level "CRITICAL" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment ### `Checker.log_debug` -No documentation available. +Log message with log level "DEBUG" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment ### `Checker.log_error` -No documentation available. +Log message with log level "ERROR" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment ### `Checker.log_info` -No documentation available. +Log message with log level "INFO" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment ### `Checker.log_warn` -No documentation available. +Log message with log level "WARNING" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment ### `Checker.on_failed` @@ -902,18 +888,15 @@ class MyTask(Task): ### `Checker.print_err` -No documentation available. - +Print message to stderr and style it as error. ### `Checker.print_out` -No documentation available. - +Print message to stderr as normal text. ### `Checker.print_out_dark` -No documentation available. - +Print message to stdout and style it as faint. ### `Checker.print_result` @@ -929,31 +912,30 @@ __Arguments:__ __Examples:__ ->> from zrb import Task ->> # Example of overriding in a subclass ->> class MyTask(Task): ->> def print_result(self, result: Any): ->> print(f'Result: {result}') +```python +from zrb import Task +# Example of overriding in a subclass +class MyTask(Task): + def print_result(self, result: Any): + print(f'Result: {result}') +``` + ### `Checker.render_any` -No documentation available. - +Render any value. ### `Checker.render_bool` -No documentation available. - +Render int value. ### `Checker.render_file` -No documentation available. - +Render file content. ### `Checker.render_float` -No documentation available. - +Render float value. ### `Checker.render_int` @@ -962,8 +944,7 @@ No documentation available. ### `Checker.render_str` -No documentation available. - +Render str value. ### `Checker.run` @@ -1128,4 +1109,4 @@ fn() -🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Tasks](README.md) \ No newline at end of file +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task](./README.md) diff --git a/docs/concepts/task/cmd-task.md b/docs/concepts/task/cmd-task.md index 87f53c11..1cfbe378 100644 --- a/docs/concepts/task/cmd-task.md +++ b/docs/concepts/task/cmd-task.md @@ -1,75 +1,8 @@ -🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Tasks](README.md) +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task](./README.md) # CmdTask -You can use CmdTask to run CLI commands. - -Let's see the following example: - -```python -from zrb import CmdTask, StrInput, Env, runner - -say_hello = CmdTask( - name='say-hello', - inputs=[ - StrInput(name='name') - ], - envs=[ - Env(name='SOME_ENV') - ], - cmd='echo {{input.name}}' -) -runner.register(say_hello) -``` - -If you need a multi-line command, you can also define the command as a list: - -```python -from zrb import CmdTask, StrInput, Env, runner - -say_hello = CmdTask( - name='say-hello', - inputs=[ - StrInput(name='name') - ], - envs=[ - Env(name='SOME_ENV') - ], - cmd=[ - 'echo {{input.name}}', - 'echo $_INPUT_NAME', # This will also works - 'echo Yeay!!!' - ] -) -runner.register(say_hello) -``` - -However, if your command is too long, you can also load it from another file: - - -```python -from zrb import CmdTask, StrInput, Env, runner - -say_hello = CmdTask( - name='say-hello', - inputs=[ - StrInput(name='name') - ], - envs=[ - Env(name='SOME_ENV') - ], - cmd_path='hello_script.sh' -) -runner.register(say_hello) -``` - -You can then run the task by invoking: - -```bash -zrb say-hello --name=John -``` - -# Technical Documentation +# Technical Specification ## `CmdTask` @@ -359,7 +292,9 @@ No documentation available. ### `CmdTask._loop_check` -For internal use +For internal use. + +Regularly check whether the task is ready or not. ### `CmdTask._mark_awaited` @@ -378,7 +313,9 @@ No documentation available. ### `CmdTask._print_result` -For internal use +For internal use. + +Directly call `print_result` ### `CmdTask._propagate_execution_id` @@ -387,7 +324,9 @@ No documentation available. ### `CmdTask._run_all` -For internal use +For internal use. + +Run this task and all its upstreams. ### `CmdTask._run_and_check_all` @@ -431,7 +370,9 @@ No documentation available. ### `CmdTask._set_keyval` -For internal use +For internal use. + +Set current task's key values. ### `CmdTask._set_kwargs` @@ -647,7 +588,20 @@ __Returns:__ ### `CmdTask.get_env_map` -No documentation available. +Get a map representing task's Envs and EnvFiles + +Typically used inside `run`, `check`, or in `@python_task` decorator + +__Examples:__ + +```python +from zrb import python_task, Task, Env +@python_task(name='task', envs=[Env(name='DB_URL')]) +def task(*args, **kwargs): + task: Task = kwargs.get('_task') + for key, value in task.get_env_map(): + task.print_out(f'{key}: {value}') +``` ### `CmdTask.get_execution_id` @@ -675,7 +629,20 @@ __Returns:__ ### `CmdTask.get_input_map` -No documentation available. +Get a map representing task's Inputs. + +Typically used inside `run`, `check`, or in `@python_task` decorator + +__Examples:__ + +```python +from zrb import python_task, Task, Input +@python_task(name='task', inputs=[Input(name='name')]) +def task(*args, **kwargs): + task: Task = kwargs.get('_task') + for key, value in task.get_input_map(): + task.print_out(f'{key}: {value}') +``` ### `CmdTask.inject_checkers` @@ -848,28 +815,33 @@ task.insert_upstream(upstream_task) ### `CmdTask.log_critical` -No documentation available. +Log message with log level "CRITICAL" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment ### `CmdTask.log_debug` -No documentation available. +Log message with log level "DEBUG" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment ### `CmdTask.log_error` -No documentation available. +Log message with log level "ERROR" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment ### `CmdTask.log_info` -No documentation available. +Log message with log level "INFO" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment ### `CmdTask.log_warn` -No documentation available. +Log message with log level "WARNING" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment ### `CmdTask.on_failed` @@ -1005,18 +977,15 @@ class MyTask(Task): ### `CmdTask.print_err` -No documentation available. - +Print message to stderr and style it as error. ### `CmdTask.print_out` -No documentation available. - +Print message to stderr as normal text. ### `CmdTask.print_out_dark` -No documentation available. - +Print message to stdout and style it as faint. ### `CmdTask.print_result` @@ -1032,31 +1001,30 @@ __Arguments:__ __Examples:__ ->> from zrb import Task ->> # Example of overriding in a subclass ->> class MyTask(Task): ->> def print_result(self, result: Any): ->> print(f'Result: {result}') +```python +from zrb import Task +# Example of overriding in a subclass +class MyTask(Task): + def print_result(self, result: Any): + print(f'Result: {result}') +``` + ### `CmdTask.render_any` -No documentation available. - +Render any value. ### `CmdTask.render_bool` -No documentation available. - +Render int value. ### `CmdTask.render_file` -No documentation available. - +Render file content. ### `CmdTask.render_float` -No documentation available. - +Render float value. ### `CmdTask.render_int` @@ -1065,8 +1033,7 @@ No documentation available. ### `CmdTask.render_str` -No documentation available. - +Render str value. ### `CmdTask.run` @@ -1231,4 +1198,4 @@ fn() -🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Tasks](README.md) +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task](./README.md) diff --git a/docs/concepts/task/docker-compose-task.md b/docs/concepts/task/docker-compose-task.md index 7354ee78..da445de8 100644 --- a/docs/concepts/task/docker-compose-task.md +++ b/docs/concepts/task/docker-compose-task.md @@ -1,56 +1,8 @@ -🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Tasks](README.md) +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task](./README.md) # DockerComposeTask -Docker Compose is a convenient way to run containers on your local computer. - -Suppose you have the following Docker Compose file: - -```yaml -# docker-compose.yml file -version: '3' - -services: - # The load balancer - nginx: - image: nginx:1.16.0-alpine - volumes: - - ./nginx.conf:/etc/nginx/nginx.conf:ro - ports: - - "${HOST_PORT:-8080}:80" -``` - -You can define a task to run your Docker Compose file (i.e., `docker compose up`) like this: - -```python -from zrb import DockerComposeTask, HTTPChecker, Env, runner - -run_container = DockerComposeTask( - name='run-container', - compose_cmd='up', - compose_file='docker-compose.yml', - envs=[ - Env(name='HOST_PORT', default='3000') - ], - checkers=[ - HTTPChecker( - name='check-readiness', port='{{env.HOST_PORT}}' - ) - ] -) -runner.register(run_container) -``` - -You can then run the task by invoking: - -```bash -zrb run-container -``` - -Under the hood, Zrb will read your `compose_file` populate it with some additional configuration, and create a runtime compose file `._-.runtime.yml`. Zrb will use the run the runtime compose file to run your `compose_cmd` (i.e., `docker compose -f -.runtime.yml `) - - -# Technical Documentation +# Technical Specification ## `DockerComposeTask` @@ -375,7 +327,9 @@ No documentation available. ### `DockerComposeTask._loop_check` -For internal use +For internal use. + +Regularly check whether the task is ready or not. ### `DockerComposeTask._mark_awaited` @@ -394,7 +348,9 @@ No documentation available. ### `DockerComposeTask._print_result` -For internal use +For internal use. + +Directly call `print_result` ### `DockerComposeTask._propagate_execution_id` @@ -403,7 +359,9 @@ No documentation available. ### `DockerComposeTask._run_all` -For internal use +For internal use. + +Run this task and all its upstreams. ### `DockerComposeTask._run_and_check_all` @@ -447,7 +405,9 @@ No documentation available. ### `DockerComposeTask._set_keyval` -For internal use +For internal use. + +Set current task's key values. ### `DockerComposeTask._set_kwargs` @@ -663,7 +623,20 @@ __Returns:__ ### `DockerComposeTask.get_env_map` -No documentation available. +Get a map representing task's Envs and EnvFiles + +Typically used inside `run`, `check`, or in `@python_task` decorator + +__Examples:__ + +```python +from zrb import python_task, Task, Env +@python_task(name='task', envs=[Env(name='DB_URL')]) +def task(*args, **kwargs): + task: Task = kwargs.get('_task') + for key, value in task.get_env_map(): + task.print_out(f'{key}: {value}') +``` ### `DockerComposeTask.get_execution_id` @@ -691,7 +664,20 @@ __Returns:__ ### `DockerComposeTask.get_input_map` -No documentation available. +Get a map representing task's Inputs. + +Typically used inside `run`, `check`, or in `@python_task` decorator + +__Examples:__ + +```python +from zrb import python_task, Task, Input +@python_task(name='task', inputs=[Input(name='name')]) +def task(*args, **kwargs): + task: Task = kwargs.get('_task') + for key, value in task.get_input_map(): + task.print_out(f'{key}: {value}') +``` ### `DockerComposeTask.inject_checkers` @@ -864,28 +850,33 @@ task.insert_upstream(upstream_task) ### `DockerComposeTask.log_critical` -No documentation available. +Log message with log level "CRITICAL" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment ### `DockerComposeTask.log_debug` -No documentation available. +Log message with log level "DEBUG" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment ### `DockerComposeTask.log_error` -No documentation available. +Log message with log level "ERROR" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment ### `DockerComposeTask.log_info` -No documentation available. +Log message with log level "INFO" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment ### `DockerComposeTask.log_warn` -No documentation available. +Log message with log level "WARNING" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment ### `DockerComposeTask.on_failed` @@ -1021,18 +1012,15 @@ class MyTask(Task): ### `DockerComposeTask.print_err` -No documentation available. - +Print message to stderr and style it as error. ### `DockerComposeTask.print_out` -No documentation available. - +Print message to stderr as normal text. ### `DockerComposeTask.print_out_dark` -No documentation available. - +Print message to stdout and style it as faint. ### `DockerComposeTask.print_result` @@ -1048,31 +1036,30 @@ __Arguments:__ __Examples:__ ->> from zrb import Task ->> # Example of overriding in a subclass ->> class MyTask(Task): ->> def print_result(self, result: Any): ->> print(f'Result: {result}') +```python +from zrb import Task +# Example of overriding in a subclass +class MyTask(Task): + def print_result(self, result: Any): + print(f'Result: {result}') +``` -### `DockerComposeTask.render_any` -No documentation available. +### `DockerComposeTask.render_any` +Render any value. ### `DockerComposeTask.render_bool` -No documentation available. - +Render int value. ### `DockerComposeTask.render_file` -No documentation available. - +Render file content. ### `DockerComposeTask.render_float` -No documentation available. - +Render float value. ### `DockerComposeTask.render_int` @@ -1081,8 +1068,7 @@ No documentation available. ### `DockerComposeTask.render_str` -No documentation available. - +Render str value. ### `DockerComposeTask.run` @@ -1247,4 +1233,4 @@ fn() -🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Tasks](README.md) \ No newline at end of file +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task](./README.md) diff --git a/docs/concepts/task/flow-task.md b/docs/concepts/task/flow-task.md index 01d76b7a..3b689cb3 100644 --- a/docs/concepts/task/flow-task.md +++ b/docs/concepts/task/flow-task.md @@ -1,58 +1,8 @@ - -🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Tasks](README.md) +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task](./README.md) # FlowTask -FlowTask allows you to compose several unrelated tasks/actions into a single tasks. - -```python -from zrb import FlowTask, CmdTask, HttpChecker, runner -import os - -CURRENT_DIR = os.dirname(__file__) - -prepare_backend = CmdTask( - name='prepare-backend', - cwd=os.path.join(CURRENT_DIR, 'app', 'backend'), - cmd='pip install -r requirements.txt' -) - -prepare_frontend = CmdTask( - name='prepare-backend', - cwd=os.path.join(CURRENT_DIR, 'app', 'frontend'), - cmd='npm install && npm run build' -) - -start_app = CmdTask( - name='start-app', - cwd=os.path.join(CURRENT_DIR, 'app', 'backend'), - cmd='uvicorn main:app --port 8080', - checkers=[ - HttpChecker(port=8080) - ] -) - -prepare_and_start_app = FlowTask( - name='prepare-and-start-app', - steps=[ - # Prepare backend and frontend concurrently - [ - prepare_backend, - prepare_frontend - ], - # Then start app - start_app, - # And finally show instruction - CmdTask( - name='show-instruction', - cmd='echo "App is ready, Check your browser"' - ) - ] -) -runner.register(prepare_app) -``` - -# Technical Documentation +# Technical Specification ## `FlowTask` @@ -258,7 +208,9 @@ No documentation available. ### `FlowTask._loop_check` -For internal use +For internal use. + +Regularly check whether the task is ready or not. ### `FlowTask._mark_awaited` @@ -277,7 +229,9 @@ No documentation available. ### `FlowTask._print_result` -For internal use +For internal use. + +Directly call `print_result` ### `FlowTask._propagate_execution_id` @@ -286,7 +240,9 @@ No documentation available. ### `FlowTask._run_all` -For internal use +For internal use. + +Run this task and all its upstreams. ### `FlowTask._run_and_check_all` @@ -330,7 +286,9 @@ No documentation available. ### `FlowTask._set_keyval` -For internal use +For internal use. + +Set current task's key values. ### `FlowTask._set_kwargs` @@ -546,7 +504,20 @@ __Returns:__ ### `FlowTask.get_env_map` -No documentation available. +Get a map representing task's Envs and EnvFiles + +Typically used inside `run`, `check`, or in `@python_task` decorator + +__Examples:__ + +```python +from zrb import python_task, Task, Env +@python_task(name='task', envs=[Env(name='DB_URL')]) +def task(*args, **kwargs): + task: Task = kwargs.get('_task') + for key, value in task.get_env_map(): + task.print_out(f'{key}: {value}') +``` ### `FlowTask.get_execution_id` @@ -574,7 +545,20 @@ __Returns:__ ### `FlowTask.get_input_map` -No documentation available. +Get a map representing task's Inputs. + +Typically used inside `run`, `check`, or in `@python_task` decorator + +__Examples:__ + +```python +from zrb import python_task, Task, Input +@python_task(name='task', inputs=[Input(name='name')]) +def task(*args, **kwargs): + task: Task = kwargs.get('_task') + for key, value in task.get_input_map(): + task.print_out(f'{key}: {value}') +``` ### `FlowTask.inject_checkers` @@ -747,28 +731,33 @@ task.insert_upstream(upstream_task) ### `FlowTask.log_critical` -No documentation available. +Log message with log level "CRITICAL" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment ### `FlowTask.log_debug` -No documentation available. +Log message with log level "DEBUG" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment ### `FlowTask.log_error` -No documentation available. +Log message with log level "ERROR" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment ### `FlowTask.log_info` -No documentation available. +Log message with log level "INFO" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment ### `FlowTask.log_warn` -No documentation available. +Log message with log level "WARNING" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment ### `FlowTask.on_failed` @@ -904,18 +893,15 @@ class MyTask(Task): ### `FlowTask.print_err` -No documentation available. - +Print message to stderr and style it as error. ### `FlowTask.print_out` -No documentation available. - +Print message to stderr as normal text. ### `FlowTask.print_out_dark` -No documentation available. - +Print message to stdout and style it as faint. ### `FlowTask.print_result` @@ -931,31 +917,30 @@ __Arguments:__ __Examples:__ ->> from zrb import Task ->> # Example of overriding in a subclass ->> class MyTask(Task): ->> def print_result(self, result: Any): ->> print(f'Result: {result}') +```python +from zrb import Task +# Example of overriding in a subclass +class MyTask(Task): + def print_result(self, result: Any): + print(f'Result: {result}') +``` + ### `FlowTask.render_any` -No documentation available. - +Render any value. ### `FlowTask.render_bool` -No documentation available. - +Render int value. ### `FlowTask.render_file` -No documentation available. - +Render file content. ### `FlowTask.render_float` -No documentation available. - +Render float value. ### `FlowTask.render_int` @@ -964,8 +949,7 @@ No documentation available. ### `FlowTask.render_str` -No documentation available. - +Render str value. ### `FlowTask.run` @@ -1125,4 +1109,4 @@ fn() -🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Tasks](README.md) \ No newline at end of file +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task](./README.md) diff --git a/docs/concepts/task/http-checker.md b/docs/concepts/task/http-checker.md new file mode 100644 index 00000000..c3f29220 --- /dev/null +++ b/docs/concepts/task/http-checker.md @@ -0,0 +1,1112 @@ +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task](./README.md) + +# HTTPChecker + +# Technical Specification + + +## `HTTPChecker` + +Base class for all tasks. +Every task definition should be extended from this class. + +### `HTTPChecker._BaseTaskModel__get_colored` + +No documentation available. + + +### `HTTPChecker._BaseTaskModel__get_colored_print_prefix` + +No documentation available. + + +### `HTTPChecker._BaseTaskModel__get_common_prefix` + +No documentation available. + + +### `HTTPChecker._BaseTaskModel__get_executable_name` + +No documentation available. + + +### `HTTPChecker._BaseTaskModel__get_log_prefix` + +No documentation available. + + +### `HTTPChecker._BaseTaskModel__get_print_prefix` + +No documentation available. + + +### `HTTPChecker._BaseTaskModel__get_rjust_full_cli_name` + +No documentation available. + + +### `HTTPChecker._Renderer__ensure_cached_render_data` + +No documentation available. + + +### `HTTPChecker._Renderer__get_render_data` + +No documentation available. + + +### `HTTPChecker._cached_check` + +No documentation available. + + +### `HTTPChecker._cached_run` + +No documentation available. + + +### `HTTPChecker._check` + +Check current task readiness. +- If self.checkers is defined, +this will return True once every self.checkers is completed +- Otherwise, this will return check method's return value. + +### `HTTPChecker._check_should_execute` + +No documentation available. + + +### `HTTPChecker._end_timer` + +No documentation available. + + +### `HTTPChecker._get_attempt` + +No documentation available. + + +### `HTTPChecker._get_checkers` + +Retrieves the checkers set for the task. + +This internal method returns an iterable of all the checkers that have been added to +the task. It's mainly used for internal logic and debugging to understand the +validations or conditions applied to the task. + +__Returns:__ + +`Iterable[TAnyTask]`: An iterable of checkers associated with the task. + +### `HTTPChecker._get_combined_env` + +No documentation available. + + +### `HTTPChecker._get_combined_inputs` + +' +Getting all inputs of this task and all its upstream, non-duplicated. + +### `HTTPChecker._get_elapsed_time` + +No documentation available. + + +### `HTTPChecker._get_env_files` + +Retrieves the list of environment variable files associated with the task. + +Intended for internal use, this method returns a list of `EnvFile` instances that the task +uses to load environment variables, primarily for setup and configuration purposes. + +__Returns:__ + +`List[EnvFile]`: A list of `EnvFile` instances associated with the task. + +### `HTTPChecker._get_envs` + +Retrieves the list of environment variables set for the task. + +For internal use, this method returns a list of `Env` instances representing the environment variables +configured for the task, essential for understanding and debugging the task's environment setup. + +__Returns:__ + +`List[Env]`: A list of `Env` instances representing the environment variables of the task. + +### `HTTPChecker._get_full_cli_name` + +Retrieves the full command-line interface (CLI) name of the task. + +Intended for internal use, this method provides the complete CLI name, including any +prefixes or namespaces, used primarily for logging or debugging purposes. + +__Returns:__ + +`str`: The full CLI name of the task. + +### `HTTPChecker._get_inputs` + +Retrieves the list of inputs associated with the task. + +This internal method is used to obtain all the inputs that have been set for the task, +either through static definition or via the `inject_inputs` method. It's primarily used +for introspection and debugging purposes. + +__Returns:__ + +`List[AnyInput]`: A list of `AnyInput` instances representing the inputs for the task. + +### `HTTPChecker._get_max_attempt` + +No documentation available. + + +### `HTTPChecker._get_task_pid` + +No documentation available. + + +### `HTTPChecker._get_upstreams` + +Retrieves the upstream tasks of the current task. + +An internal method to get the list of upstream tasks that have been set for the +task, either statically or through `inject_upstreams`. This is essential for task +scheduling and dependency management. + +__Returns:__ + +`Iterable[TAnyTask]`: An iterable of upstream tasks. + +### `HTTPChecker._increase_attempt` + +No documentation available. + + +### `HTTPChecker._is_done` + +No documentation available. + + +### `HTTPChecker._is_last_attempt` + +No documentation available. + + +### `HTTPChecker._lock_upstreams` + +No documentation available. + + +### `HTTPChecker._loop_check` + +For internal use. + +Regularly check whether the task is ready or not. + +### `HTTPChecker._mark_awaited` + +No documentation available. + + +### `HTTPChecker._mark_done` + +No documentation available. + + +### `HTTPChecker._play_bell` + +No documentation available. + + +### `HTTPChecker._print_result` + +For internal use. + +Directly call `print_result` + +### `HTTPChecker._propagate_execution_id` + +No documentation available. + + +### `HTTPChecker._run_all` + +For internal use. + +Run this task and all its upstreams. + +### `HTTPChecker._run_and_check_all` + +No documentation available. + + +### `HTTPChecker._set_args` + +No documentation available. + + +### `HTTPChecker._set_env_map` + +No documentation available. + + +### `HTTPChecker._set_execution_id` + +Sets the execution ID for the current task. + +This method is intended for internal use to assign a unique identifier to the task's execution. +This ID can be used for tracking, logging, and inter-task communication. + +This method should not be used externally, as it is meant to be managed within the task system. + +__Arguments:__ + +- `execution_id` (`str`): A string representing the unique execution ID. + +### `HTTPChecker._set_has_cli_interface` + +Marks the task as having a CLI interface. + +This internal method is used to indicate that the task is accessible and executable through a CLI, +enabling the task system to appropriately handle its CLI interactions. + +### `HTTPChecker._set_input_map` + +No documentation available. + + +### `HTTPChecker._set_keyval` + +For internal use. + +Set current task's key values. + +### `HTTPChecker._set_kwargs` + +No documentation available. + + +### `HTTPChecker._set_local_keyval` + +No documentation available. + + +### `HTTPChecker._set_task_pid` + +No documentation available. + + +### `HTTPChecker._should_attempt` + +No documentation available. + + +### `HTTPChecker._show_done_info` + +No documentation available. + + +### `HTTPChecker._show_env_prefix` + +No documentation available. + + +### `HTTPChecker._show_run_command` + +No documentation available. + + +### `HTTPChecker._start_timer` + +No documentation available. + + +### `HTTPChecker.add_env` + +Adds one or more `Env` instances to the end of the current task's environment variable list. + +Use this method to append environment variables for the task, which will be used after +any variables already set. + +__Arguments:__ + +- `envs` (`Env`): One or more environment variable instances to be added. + +__Examples:__ + +```python +from zrb import Task, Env +task = Task(name='task') +db_url_env = Env(name='DATABASE_URL', value='postgresql://...') +task.add_env(env_var) +``` + + +### `HTTPChecker.add_env_file` + +Adds one or more `EnvFile` instances to the end of the current task's environment file list. + +Use this method to append environment file references, which will be processed after +any files already specified. This allows for supplementing the existing environment +configuration. + +__Arguments:__ + +- `env_files` (`EnvFile`): One or more environment file instances to be added. + +__Examples:__ + +```python +from zrb import Task, EnvFile +task = Task() +env_file = EnvFile(path='config.env') +task.add_env_file(env_file) +``` + + +### `HTTPChecker.add_input` + +Adds one or more `AnyInput` instances to the end of the current task's input list. + +This method is used to append inputs for the task to process, placing them after any inputs +already specified. + +__Arguments:__ + +- `inputs` (`AnyInput`): One or more input instances to be added to the input list. + +__Examples:__ + +```python +from zrb import Task, Input +task = Task(name='task') +email_input = Input(name='email-address') +task.add_input(email_input) +``` + + +### `HTTPChecker.add_upstream` + +Adds one or more `AnyTask` instances to the end of the current task's upstream list. + +This method appends tasks to the upstream list, indicating that these tasks should be executed +before the current task, but after any tasks already in the upstream list. + +__Arguments:__ + +- `upstreams` (`TAnyTask`): One or more task instances to be added to the upstream list. + +__Examples:__ + +```python +from zrb import Task +task = Task(name='task') +upstream_task = Task(name='upstream-task') +task.add_upstream(upstream_task) +``` + + +### `HTTPChecker.check` + +Checks if the current task is `ready`. + +Any other tasks depends on the current task, will be `started` once the current task is `ready`. + +This method should be implemented to define the criteria for considering the task +`ready`. The specifics of this completion depend on the task's +nature and the subclass implementation. + +__Returns:__ + +`bool`: True if the task is completed, False otherwise. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def run(self, *args: Any, **kwargs: Any) -> int: + self.print_out('Doing some calculation') + self._completed = True + return 42 + async def check(self) -> bool: + return self._completed +``` + + +### `HTTPChecker.copy` + +Creates and returns a copy of the current task. + +The copied task can be modified using various setter methods like `set_name`, +`set_description`, and others, depending on the subclass implementation. + +__Returns:__ + +`TAnyTask`: A copy of the current task. + +__Examples:__ + +```python +from zrb import Task +task = Task(name='my-task', cmd='echo hello') +copied_task = task.copy() +copied_task.set_name('new_name') +``` + + +### `HTTPChecker.get_cli_name` + +Gets the command-line interface (CLI) name of the task. + +This method returns the name used to invoke the task via a CLI, facilitating integration with command-line tools +or scripts. + +__Returns:__ + +`str`: The CLI name of the task. + +### `HTTPChecker.get_color` + +Retrieves the color associated with the current task. + +This method returns the color of the task, useful for visual differentiation, priority indication, +or categorization in user interfaces or documentation. + +__Returns:__ + +`str`: A string representing the color assigned to the task. + +### `HTTPChecker.get_description` + +Fetches the current description of the task. + +This method is used to obtain the detailed description of the task, providing insights into its purpose, +functionality, and usage within the task management system. + +__Returns:__ + +`str`: The description of the task. + +### `HTTPChecker.get_env_map` + +Get a map representing task's Envs and EnvFiles + +Typically used inside `run`, `check`, or in `@python_task` decorator + +__Examples:__ + +```python +from zrb import python_task, Task, Env +@python_task(name='task', envs=[Env(name='DB_URL')]) +def task(*args, **kwargs): + task: Task = kwargs.get('_task') + for key, value in task.get_env_map(): + task.print_out(f'{key}: {value}') +``` + + +### `HTTPChecker.get_execution_id` + +Retrieves the execution ID of the task. + +This method returns the unique identifier associated with the task's execution. +The execution ID is crucial for tracking, logging, and differentiating between +multiple instances or runs of the same task. + +__Returns:__ + +`str`: The unique execution ID of the task. + +### `HTTPChecker.get_icon` + +Retrieves the icon identifier of the current task. + +This method is used to get the icon associated with the task, which can be utilized for +visual representation in user interfaces or documentation. + +__Returns:__ + +`str`: A string representing the icon identifier for the task + +### `HTTPChecker.get_input_map` + +Get a map representing task's Inputs. + +Typically used inside `run`, `check`, or in `@python_task` decorator + +__Examples:__ + +```python +from zrb import python_task, Task, Input +@python_task(name='task', inputs=[Input(name='name')]) +def task(*args, **kwargs): + task: Task = kwargs.get('_task') + for key, value in task.get_input_map(): + task.print_out(f'{key}: {value}') +``` + + +### `HTTPChecker.inject_checkers` + +Injects custom checkers into the task. + +This method allows for the addition of custom validation or condition checkers. These +checkers can be used to verify certain conditions before the task execution proceeds. +Subclasses should implement this method to define task-specific checkers. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + def inject_checkers(self): + self.add_checker(some_custom_condition_checker) +``` + + +### `HTTPChecker.inject_env_files` + +Injects additional `EnvFile` into the task. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + def inject_env_files(self): + self.add_env_files(EnvFile(path='config.env')) +``` + + +### `HTTPChecker.inject_envs` + +Injects environment variables into the task. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + def inject_envs(self): + self.add_envs(Env(name='DATABASE_URL')) +``` + + +### `HTTPChecker.inject_inputs` + +Injects custom inputs into the task. + +This method is used to programmatically add input parameters to the task, allowing +dynamic customization of the task's input data. Subclasses should override this method +to define specific inputs that the task should receive. + +__Examples:__ + +```python +from zrb import Task, Input +class MyTask(Task): + def inject_inputs(self): + self.add_input(Input(name='user_email', type='email')) +``` + + +### `HTTPChecker.inject_upstreams` + +Injects upstream tasks into the current task. + +This method is used for programmatically adding upstream dependencies to the task. +Upstream tasks are those that must be completed before the current task starts. +Override this method in subclasses to specify such dependencies. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + def inject_upstreams(self): + self.add_upstream(another_task) +``` + + +### `HTTPChecker.insert_env` + +Inserts one or more `Env` instances at the beginning of the current task's environment variable list. + +This method allows for setting or overriding environment variables for the task, with earlier entries +having precedence over later ones. + +__Arguments:__ + +- `envs` (`Env`): One or more environment variable instances to be added. + +__Examples:__ + +```python +from zrb import Task, Env +task = Task(name='task') +db_url_env = Env(name='DATABASE_URL', value='postgresql://...') +task.insert_env(env_var) +``` + + +### `HTTPChecker.insert_env_file` + +Inserts one or more `EnvFile` instances at the beginning of the current task's environment file list. + +This method is used to specify environment variable files whose contents should be loaded +before those of any files already in the list. This is useful for overriding or setting +additional environment configurations. + +__Arguments:__ + +- `env_files` (`EnvFile`): One or more environment file instances to be added. + +__Examples:__ + +```python +from zrb import Task, EnvFile +task = Task() +env_file = EnvFile(path='config.env') +task.insert_env_file(env_file) +``` + + +### `HTTPChecker.insert_input` + +Inserts one or more `AnyInput` instances at the beginning of the current task's input list. + +This method is used to add inputs that the task will process. Inserting an input at the beginning +of the list gives it precedence over those already present. + +__Arguments:__ + +- `inputs` (`AnyInput`): One or more input instances to be added to the input list. + +__Examples:__ + +```python +from zrb import Task, Input +task = Task(name='task') +email_input = Input(name='email-address') +task.insert_input(email_input) +``` + + +### `HTTPChecker.insert_upstream` + +Inserts one or more `AnyTask` instances at the beginning of the current task's upstream list. + +This method is used to define dependencies for the current task. Tasks in the upstream list are +executed before the current task. Adding a task to the beginning of the list means it will be +executed earlier than those already in the list. + +__Arguments:__ + +- `upstreams` (`TAnyTask`): One or more task instances to be added to the upstream list. + +__Examples:__ + +```python +from zrb import Task +task = Task(name='task') +upstream_task = Task(name='upstream-task') +task.insert_upstream(upstream_task) +``` + + +### `HTTPChecker.inspect` + +No documentation available. + + +### `HTTPChecker.log_critical` + +Log message with log level "CRITICAL" + +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + +### `HTTPChecker.log_debug` + +Log message with log level "DEBUG" + +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + +### `HTTPChecker.log_error` + +Log message with log level "ERROR" + +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + +### `HTTPChecker.log_info` + +Log message with log level "INFO" + +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + +### `HTTPChecker.log_warn` + +Log message with log level "WARNING" + +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + +### `HTTPChecker.on_failed` + +Specifies the behavior when the task execution fails. + +This asynchronous method should be implemented in subclasses to handle task +failure scenarios. It can include logging the error, performing retries, or +any other failure handling mechanisms. + +__Arguments:__ + +- `is_last_attempt` (`bool`): Indicates if this is the final retry attempt. +- `exception` (`Exception`): The exception that caused the task to fail. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_failed(self, is_last_attempt: bool, exception: Exception): + if is_last_attempt: + self.print_out('The task has failed with no remaining retries') + else: + self.print_out('The task failed, retrying...') +``` + + +### `HTTPChecker.on_ready` + +Defines actions to be performed when the task status is `ready`. + +This asynchronous method should be implemented in subclasses to specify +actions that occur when the task reaches the `ready` state. This can include +any cleanup, notification, or follow-up actions specific to the task. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_ready(self): + self.print_out('The task is ready') +``` + + +### `HTTPChecker.on_retry` + +Defines actions to perform when the task is retried. + +Implement this method to specify behavior when the task is retried after a failure. +This could include resetting states, logging the retry attempt, or other necessary +steps before re-execution. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_retry(self): + self.log_info('Retrying task') +``` + + +### `HTTPChecker.on_skipped` + +Defines actions to perform when the task status is set to `skipped`. + +Implement this method to specify behavior when the task is skipped. This could +include logging information, cleaning up resources, or any other necessary steps. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_skipped(self): + self.log_info('Task was skipped') +``` + + +### `HTTPChecker.on_started` + +Defines actions to perform when the task status is set to 'started'. + +Implement this method to specify behavior when the task starts its execution. This +could involve initializing resources, logging, or other startup procedures. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_started(self): + self.log_info('Task has started') +``` + + +### `HTTPChecker.on_triggered` + +Defines actions to perform when the task status is set to `triggered`. + +Implement this method to specify behavior when the task transitions to the +`triggered` state. This could involve setting up prerequisites or sending +notifications. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_triggered(self): + self.log_info('Task has been triggered') +``` + + +### `HTTPChecker.on_waiting` + +Defines actions to perform when the task status is set to `waiting`. + +Implement this method to specify behavior when the task transitions to the +`waiting` state. This state usually indicates the task is waiting for some +condition or prerequisite to be met. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_waiting(self): + self.log_info('Task is waiting to be started') +``` + + +### `HTTPChecker.print_err` + +Print message to stderr and style it as error. + +### `HTTPChecker.print_out` + +Print message to stderr as normal text. + +### `HTTPChecker.print_out_dark` + +Print message to stdout and style it as faint. + +### `HTTPChecker.print_result` + +Outputs the task result to stdout for further processing. + +Override this method in subclasses to customize how the task result is displayed +or processed. Useful for integrating the task output with other systems or +command-line tools. + +__Arguments:__ + +- `result` (`Any`): The result of the task to be printed. + +__Examples:__ + +```python +from zrb import Task +# Example of overriding in a subclass +class MyTask(Task): + def print_result(self, result: Any): + print(f'Result: {result}') +``` + + +### `HTTPChecker.render_any` + +Render any value. + +### `HTTPChecker.render_bool` + +Render int value. + +### `HTTPChecker.render_file` + +Render file content. + +### `HTTPChecker.render_float` + +Render float value. + +### `HTTPChecker.render_int` + +No documentation available. + + +### `HTTPChecker.render_str` + +Render str value. + +### `HTTPChecker.run` + +Executes the main logic of the task. + +This asynchronous method should be implemented in subclasses to define the +task's primary functionality. The specific behavior and the return value +depend on the task's nature and purpose. + +__Arguments:__ + +- `args` (`Any`): Variable length argument list. +- `kwargs` (`Any`): Arbitrary keyword arguments. + +__Returns:__ + +`Any`: The result of the task execution, the type of which is determined by +the specific task implementation. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def run(self, *args: Any, **kwargs: Any) -> int: + self.print_out('Doing some calculation') + return 42 +``` + + +### `HTTPChecker.set_checking_interval` + +Sets the interval for checking the task's readiness or completion status. + +This method defines how frequently the system should check if the task is ready or completed. +It's useful for tasks that have an indeterminate completion time. + +__Arguments:__ + +- `new_checking_interval` (`Union[float, int]`): The time interval (in seconds) for readiness or checks. + +### `HTTPChecker.set_color` + +Defines a new color for the current task. + +This method updates the color associated with the task. This can be useful for categorization, +priority indication, or visual differentiation in a UI. + +__Arguments:__ + +- `new_color` (`str`): A string representing the color to be assigned to the task. + +### `HTTPChecker.set_description` + +Sets a new description for the current task. + +This method allows updating the task's description to provide more context or details about its purpose and behavior. +Useful for enhancing clarity and maintainability in the task management system. + +__Arguments:__ + +- `new_description` (`str`): A string representing the new description of the task. + +### `HTTPChecker.set_icon` + +Assigns a new icon to the current task. + +This method is used for setting or updating the task's icon, which can be utilized for visual representation +in a user interface. The icon should ideally be a string identifier that maps to an actual graphical resource. + +__Arguments:__ + +- `new_icon` (`str`): A string representing the icon identifier for the task. + +### `HTTPChecker.set_name` + +Sets a new name for the current task. + +This method is used to update the task's name, typically after creating a copy of an existing task. +The new name helps in differentiating the task in the task management system. + +__Arguments:__ + +- `new_name` (`str`): A string representing the new name to be assigned to the task. + +### `HTTPChecker.set_retry` + +Sets the number of retry attempts for the task. + +This method configures how many times the task should be retried in case of failure. +It's essential for tasks that may fail transiently and need multiple attempts for successful execution. + +__Arguments:__ + +- `new_retry` (`int`): An integer representing the number of retry attempts. + +### `HTTPChecker.set_retry_interval` + +Specifies the interval between retry attempts for the task. + +This method sets the duration to wait before retrying the task after a failure. +This can help in scenarios where immediate retry is not desirable or effective. + +__Arguments:__ + +- `new_retry_interval` (`Union[float, int]`): The time interval (in seconds) to wait before a retry attempt. + +### `HTTPChecker.set_should_execute` + +Determines whether the task should execute. + +This method configures the execution criteria for the task. It can be set as a boolean value, +a string representing a condition, or a callable that returns a boolean. This is useful for +conditional task execution based on dynamic criteria. + +__Arguments:__ + +- `should_execute` (`Union[bool, str, Callable[..., bool]]`): The condition to determine if the task should execute. + +### `HTTPChecker.show_progress` + +No documentation available. + + +### `HTTPChecker.to_function` + +Converts the current task into a callable function. + +This method should be implemented to allow the task to be executed as a function. +Parameters can be used to modify the behavior of the generated function, such as +raising errors, asynchronous execution, and logging. + +__Arguments:__ + +- `env_prefix` (`str`): A prefix for environment variables. +- `raise_error` (`bool`): Whether to raise an error if the task execution fails. +- `is_async` (`bool`): Whether the resulting function should be asynchronous. +- `show_done_info` (`bool`): Whether to show information upon task completion. + +__Returns:__ + +`Callable[..., Any]`: A callable representation of the task. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def run(self, *args: Any, **kwargs: Any) -> int: + self.print_out('Doing some calculation') + return 42 +``` + +``` +>>> +```python +task = MyTask() +fn = task.to_function() +fn() +``` + + + + +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task](./README.md) diff --git a/docs/concepts/task/path-checker.md b/docs/concepts/task/path-checker.md new file mode 100644 index 00000000..aa0e8164 --- /dev/null +++ b/docs/concepts/task/path-checker.md @@ -0,0 +1,1112 @@ +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task](./README.md) + +# PortChecker + +# Technical Specification + + +## `PathChecker` + +Base class for all tasks. +Every task definition should be extended from this class. + +### `PathChecker._BaseTaskModel__get_colored` + +No documentation available. + + +### `PathChecker._BaseTaskModel__get_colored_print_prefix` + +No documentation available. + + +### `PathChecker._BaseTaskModel__get_common_prefix` + +No documentation available. + + +### `PathChecker._BaseTaskModel__get_executable_name` + +No documentation available. + + +### `PathChecker._BaseTaskModel__get_log_prefix` + +No documentation available. + + +### `PathChecker._BaseTaskModel__get_print_prefix` + +No documentation available. + + +### `PathChecker._BaseTaskModel__get_rjust_full_cli_name` + +No documentation available. + + +### `PathChecker._Renderer__ensure_cached_render_data` + +No documentation available. + + +### `PathChecker._Renderer__get_render_data` + +No documentation available. + + +### `PathChecker._cached_check` + +No documentation available. + + +### `PathChecker._cached_run` + +No documentation available. + + +### `PathChecker._check` + +Check current task readiness. +- If self.checkers is defined, +this will return True once every self.checkers is completed +- Otherwise, this will return check method's return value. + +### `PathChecker._check_should_execute` + +No documentation available. + + +### `PathChecker._end_timer` + +No documentation available. + + +### `PathChecker._get_attempt` + +No documentation available. + + +### `PathChecker._get_checkers` + +Retrieves the checkers set for the task. + +This internal method returns an iterable of all the checkers that have been added to +the task. It's mainly used for internal logic and debugging to understand the +validations or conditions applied to the task. + +__Returns:__ + +`Iterable[TAnyTask]`: An iterable of checkers associated with the task. + +### `PathChecker._get_combined_env` + +No documentation available. + + +### `PathChecker._get_combined_inputs` + +' +Getting all inputs of this task and all its upstream, non-duplicated. + +### `PathChecker._get_elapsed_time` + +No documentation available. + + +### `PathChecker._get_env_files` + +Retrieves the list of environment variable files associated with the task. + +Intended for internal use, this method returns a list of `EnvFile` instances that the task +uses to load environment variables, primarily for setup and configuration purposes. + +__Returns:__ + +`List[EnvFile]`: A list of `EnvFile` instances associated with the task. + +### `PathChecker._get_envs` + +Retrieves the list of environment variables set for the task. + +For internal use, this method returns a list of `Env` instances representing the environment variables +configured for the task, essential for understanding and debugging the task's environment setup. + +__Returns:__ + +`List[Env]`: A list of `Env` instances representing the environment variables of the task. + +### `PathChecker._get_full_cli_name` + +Retrieves the full command-line interface (CLI) name of the task. + +Intended for internal use, this method provides the complete CLI name, including any +prefixes or namespaces, used primarily for logging or debugging purposes. + +__Returns:__ + +`str`: The full CLI name of the task. + +### `PathChecker._get_inputs` + +Retrieves the list of inputs associated with the task. + +This internal method is used to obtain all the inputs that have been set for the task, +either through static definition or via the `inject_inputs` method. It's primarily used +for introspection and debugging purposes. + +__Returns:__ + +`List[AnyInput]`: A list of `AnyInput` instances representing the inputs for the task. + +### `PathChecker._get_max_attempt` + +No documentation available. + + +### `PathChecker._get_task_pid` + +No documentation available. + + +### `PathChecker._get_upstreams` + +Retrieves the upstream tasks of the current task. + +An internal method to get the list of upstream tasks that have been set for the +task, either statically or through `inject_upstreams`. This is essential for task +scheduling and dependency management. + +__Returns:__ + +`Iterable[TAnyTask]`: An iterable of upstream tasks. + +### `PathChecker._increase_attempt` + +No documentation available. + + +### `PathChecker._is_done` + +No documentation available. + + +### `PathChecker._is_last_attempt` + +No documentation available. + + +### `PathChecker._lock_upstreams` + +No documentation available. + + +### `PathChecker._loop_check` + +For internal use. + +Regularly check whether the task is ready or not. + +### `PathChecker._mark_awaited` + +No documentation available. + + +### `PathChecker._mark_done` + +No documentation available. + + +### `PathChecker._play_bell` + +No documentation available. + + +### `PathChecker._print_result` + +For internal use. + +Directly call `print_result` + +### `PathChecker._propagate_execution_id` + +No documentation available. + + +### `PathChecker._run_all` + +For internal use. + +Run this task and all its upstreams. + +### `PathChecker._run_and_check_all` + +No documentation available. + + +### `PathChecker._set_args` + +No documentation available. + + +### `PathChecker._set_env_map` + +No documentation available. + + +### `PathChecker._set_execution_id` + +Sets the execution ID for the current task. + +This method is intended for internal use to assign a unique identifier to the task's execution. +This ID can be used for tracking, logging, and inter-task communication. + +This method should not be used externally, as it is meant to be managed within the task system. + +__Arguments:__ + +- `execution_id` (`str`): A string representing the unique execution ID. + +### `PathChecker._set_has_cli_interface` + +Marks the task as having a CLI interface. + +This internal method is used to indicate that the task is accessible and executable through a CLI, +enabling the task system to appropriately handle its CLI interactions. + +### `PathChecker._set_input_map` + +No documentation available. + + +### `PathChecker._set_keyval` + +For internal use. + +Set current task's key values. + +### `PathChecker._set_kwargs` + +No documentation available. + + +### `PathChecker._set_local_keyval` + +No documentation available. + + +### `PathChecker._set_task_pid` + +No documentation available. + + +### `PathChecker._should_attempt` + +No documentation available. + + +### `PathChecker._show_done_info` + +No documentation available. + + +### `PathChecker._show_env_prefix` + +No documentation available. + + +### `PathChecker._show_run_command` + +No documentation available. + + +### `PathChecker._start_timer` + +No documentation available. + + +### `PathChecker.add_env` + +Adds one or more `Env` instances to the end of the current task's environment variable list. + +Use this method to append environment variables for the task, which will be used after +any variables already set. + +__Arguments:__ + +- `envs` (`Env`): One or more environment variable instances to be added. + +__Examples:__ + +```python +from zrb import Task, Env +task = Task(name='task') +db_url_env = Env(name='DATABASE_URL', value='postgresql://...') +task.add_env(env_var) +``` + + +### `PathChecker.add_env_file` + +Adds one or more `EnvFile` instances to the end of the current task's environment file list. + +Use this method to append environment file references, which will be processed after +any files already specified. This allows for supplementing the existing environment +configuration. + +__Arguments:__ + +- `env_files` (`EnvFile`): One or more environment file instances to be added. + +__Examples:__ + +```python +from zrb import Task, EnvFile +task = Task() +env_file = EnvFile(path='config.env') +task.add_env_file(env_file) +``` + + +### `PathChecker.add_input` + +Adds one or more `AnyInput` instances to the end of the current task's input list. + +This method is used to append inputs for the task to process, placing them after any inputs +already specified. + +__Arguments:__ + +- `inputs` (`AnyInput`): One or more input instances to be added to the input list. + +__Examples:__ + +```python +from zrb import Task, Input +task = Task(name='task') +email_input = Input(name='email-address') +task.add_input(email_input) +``` + + +### `PathChecker.add_upstream` + +Adds one or more `AnyTask` instances to the end of the current task's upstream list. + +This method appends tasks to the upstream list, indicating that these tasks should be executed +before the current task, but after any tasks already in the upstream list. + +__Arguments:__ + +- `upstreams` (`TAnyTask`): One or more task instances to be added to the upstream list. + +__Examples:__ + +```python +from zrb import Task +task = Task(name='task') +upstream_task = Task(name='upstream-task') +task.add_upstream(upstream_task) +``` + + +### `PathChecker.check` + +Checks if the current task is `ready`. + +Any other tasks depends on the current task, will be `started` once the current task is `ready`. + +This method should be implemented to define the criteria for considering the task +`ready`. The specifics of this completion depend on the task's +nature and the subclass implementation. + +__Returns:__ + +`bool`: True if the task is completed, False otherwise. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def run(self, *args: Any, **kwargs: Any) -> int: + self.print_out('Doing some calculation') + self._completed = True + return 42 + async def check(self) -> bool: + return self._completed +``` + + +### `PathChecker.copy` + +Creates and returns a copy of the current task. + +The copied task can be modified using various setter methods like `set_name`, +`set_description`, and others, depending on the subclass implementation. + +__Returns:__ + +`TAnyTask`: A copy of the current task. + +__Examples:__ + +```python +from zrb import Task +task = Task(name='my-task', cmd='echo hello') +copied_task = task.copy() +copied_task.set_name('new_name') +``` + + +### `PathChecker.get_cli_name` + +Gets the command-line interface (CLI) name of the task. + +This method returns the name used to invoke the task via a CLI, facilitating integration with command-line tools +or scripts. + +__Returns:__ + +`str`: The CLI name of the task. + +### `PathChecker.get_color` + +Retrieves the color associated with the current task. + +This method returns the color of the task, useful for visual differentiation, priority indication, +or categorization in user interfaces or documentation. + +__Returns:__ + +`str`: A string representing the color assigned to the task. + +### `PathChecker.get_description` + +Fetches the current description of the task. + +This method is used to obtain the detailed description of the task, providing insights into its purpose, +functionality, and usage within the task management system. + +__Returns:__ + +`str`: The description of the task. + +### `PathChecker.get_env_map` + +Get a map representing task's Envs and EnvFiles + +Typically used inside `run`, `check`, or in `@python_task` decorator + +__Examples:__ + +```python +from zrb import python_task, Task, Env +@python_task(name='task', envs=[Env(name='DB_URL')]) +def task(*args, **kwargs): + task: Task = kwargs.get('_task') + for key, value in task.get_env_map(): + task.print_out(f'{key}: {value}') +``` + + +### `PathChecker.get_execution_id` + +Retrieves the execution ID of the task. + +This method returns the unique identifier associated with the task's execution. +The execution ID is crucial for tracking, logging, and differentiating between +multiple instances or runs of the same task. + +__Returns:__ + +`str`: The unique execution ID of the task. + +### `PathChecker.get_icon` + +Retrieves the icon identifier of the current task. + +This method is used to get the icon associated with the task, which can be utilized for +visual representation in user interfaces or documentation. + +__Returns:__ + +`str`: A string representing the icon identifier for the task + +### `PathChecker.get_input_map` + +Get a map representing task's Inputs. + +Typically used inside `run`, `check`, or in `@python_task` decorator + +__Examples:__ + +```python +from zrb import python_task, Task, Input +@python_task(name='task', inputs=[Input(name='name')]) +def task(*args, **kwargs): + task: Task = kwargs.get('_task') + for key, value in task.get_input_map(): + task.print_out(f'{key}: {value}') +``` + + +### `PathChecker.inject_checkers` + +Injects custom checkers into the task. + +This method allows for the addition of custom validation or condition checkers. These +checkers can be used to verify certain conditions before the task execution proceeds. +Subclasses should implement this method to define task-specific checkers. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + def inject_checkers(self): + self.add_checker(some_custom_condition_checker) +``` + + +### `PathChecker.inject_env_files` + +Injects additional `EnvFile` into the task. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + def inject_env_files(self): + self.add_env_files(EnvFile(path='config.env')) +``` + + +### `PathChecker.inject_envs` + +Injects environment variables into the task. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + def inject_envs(self): + self.add_envs(Env(name='DATABASE_URL')) +``` + + +### `PathChecker.inject_inputs` + +Injects custom inputs into the task. + +This method is used to programmatically add input parameters to the task, allowing +dynamic customization of the task's input data. Subclasses should override this method +to define specific inputs that the task should receive. + +__Examples:__ + +```python +from zrb import Task, Input +class MyTask(Task): + def inject_inputs(self): + self.add_input(Input(name='user_email', type='email')) +``` + + +### `PathChecker.inject_upstreams` + +Injects upstream tasks into the current task. + +This method is used for programmatically adding upstream dependencies to the task. +Upstream tasks are those that must be completed before the current task starts. +Override this method in subclasses to specify such dependencies. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + def inject_upstreams(self): + self.add_upstream(another_task) +``` + + +### `PathChecker.insert_env` + +Inserts one or more `Env` instances at the beginning of the current task's environment variable list. + +This method allows for setting or overriding environment variables for the task, with earlier entries +having precedence over later ones. + +__Arguments:__ + +- `envs` (`Env`): One or more environment variable instances to be added. + +__Examples:__ + +```python +from zrb import Task, Env +task = Task(name='task') +db_url_env = Env(name='DATABASE_URL', value='postgresql://...') +task.insert_env(env_var) +``` + + +### `PathChecker.insert_env_file` + +Inserts one or more `EnvFile` instances at the beginning of the current task's environment file list. + +This method is used to specify environment variable files whose contents should be loaded +before those of any files already in the list. This is useful for overriding or setting +additional environment configurations. + +__Arguments:__ + +- `env_files` (`EnvFile`): One or more environment file instances to be added. + +__Examples:__ + +```python +from zrb import Task, EnvFile +task = Task() +env_file = EnvFile(path='config.env') +task.insert_env_file(env_file) +``` + + +### `PathChecker.insert_input` + +Inserts one or more `AnyInput` instances at the beginning of the current task's input list. + +This method is used to add inputs that the task will process. Inserting an input at the beginning +of the list gives it precedence over those already present. + +__Arguments:__ + +- `inputs` (`AnyInput`): One or more input instances to be added to the input list. + +__Examples:__ + +```python +from zrb import Task, Input +task = Task(name='task') +email_input = Input(name='email-address') +task.insert_input(email_input) +``` + + +### `PathChecker.insert_upstream` + +Inserts one or more `AnyTask` instances at the beginning of the current task's upstream list. + +This method is used to define dependencies for the current task. Tasks in the upstream list are +executed before the current task. Adding a task to the beginning of the list means it will be +executed earlier than those already in the list. + +__Arguments:__ + +- `upstreams` (`TAnyTask`): One or more task instances to be added to the upstream list. + +__Examples:__ + +```python +from zrb import Task +task = Task(name='task') +upstream_task = Task(name='upstream-task') +task.insert_upstream(upstream_task) +``` + + +### `PathChecker.inspect` + +No documentation available. + + +### `PathChecker.log_critical` + +Log message with log level "CRITICAL" + +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + +### `PathChecker.log_debug` + +Log message with log level "DEBUG" + +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + +### `PathChecker.log_error` + +Log message with log level "ERROR" + +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + +### `PathChecker.log_info` + +Log message with log level "INFO" + +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + +### `PathChecker.log_warn` + +Log message with log level "WARNING" + +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + +### `PathChecker.on_failed` + +Specifies the behavior when the task execution fails. + +This asynchronous method should be implemented in subclasses to handle task +failure scenarios. It can include logging the error, performing retries, or +any other failure handling mechanisms. + +__Arguments:__ + +- `is_last_attempt` (`bool`): Indicates if this is the final retry attempt. +- `exception` (`Exception`): The exception that caused the task to fail. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_failed(self, is_last_attempt: bool, exception: Exception): + if is_last_attempt: + self.print_out('The task has failed with no remaining retries') + else: + self.print_out('The task failed, retrying...') +``` + + +### `PathChecker.on_ready` + +Defines actions to be performed when the task status is `ready`. + +This asynchronous method should be implemented in subclasses to specify +actions that occur when the task reaches the `ready` state. This can include +any cleanup, notification, or follow-up actions specific to the task. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_ready(self): + self.print_out('The task is ready') +``` + + +### `PathChecker.on_retry` + +Defines actions to perform when the task is retried. + +Implement this method to specify behavior when the task is retried after a failure. +This could include resetting states, logging the retry attempt, or other necessary +steps before re-execution. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_retry(self): + self.log_info('Retrying task') +``` + + +### `PathChecker.on_skipped` + +Defines actions to perform when the task status is set to `skipped`. + +Implement this method to specify behavior when the task is skipped. This could +include logging information, cleaning up resources, or any other necessary steps. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_skipped(self): + self.log_info('Task was skipped') +``` + + +### `PathChecker.on_started` + +Defines actions to perform when the task status is set to 'started'. + +Implement this method to specify behavior when the task starts its execution. This +could involve initializing resources, logging, or other startup procedures. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_started(self): + self.log_info('Task has started') +``` + + +### `PathChecker.on_triggered` + +Defines actions to perform when the task status is set to `triggered`. + +Implement this method to specify behavior when the task transitions to the +`triggered` state. This could involve setting up prerequisites or sending +notifications. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_triggered(self): + self.log_info('Task has been triggered') +``` + + +### `PathChecker.on_waiting` + +Defines actions to perform when the task status is set to `waiting`. + +Implement this method to specify behavior when the task transitions to the +`waiting` state. This state usually indicates the task is waiting for some +condition or prerequisite to be met. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_waiting(self): + self.log_info('Task is waiting to be started') +``` + + +### `PathChecker.print_err` + +Print message to stderr and style it as error. + +### `PathChecker.print_out` + +Print message to stderr as normal text. + +### `PathChecker.print_out_dark` + +Print message to stdout and style it as faint. + +### `PathChecker.print_result` + +Outputs the task result to stdout for further processing. + +Override this method in subclasses to customize how the task result is displayed +or processed. Useful for integrating the task output with other systems or +command-line tools. + +__Arguments:__ + +- `result` (`Any`): The result of the task to be printed. + +__Examples:__ + +```python +from zrb import Task +# Example of overriding in a subclass +class MyTask(Task): + def print_result(self, result: Any): + print(f'Result: {result}') +``` + + +### `PathChecker.render_any` + +Render any value. + +### `PathChecker.render_bool` + +Render int value. + +### `PathChecker.render_file` + +Render file content. + +### `PathChecker.render_float` + +Render float value. + +### `PathChecker.render_int` + +No documentation available. + + +### `PathChecker.render_str` + +Render str value. + +### `PathChecker.run` + +Executes the main logic of the task. + +This asynchronous method should be implemented in subclasses to define the +task's primary functionality. The specific behavior and the return value +depend on the task's nature and purpose. + +__Arguments:__ + +- `args` (`Any`): Variable length argument list. +- `kwargs` (`Any`): Arbitrary keyword arguments. + +__Returns:__ + +`Any`: The result of the task execution, the type of which is determined by +the specific task implementation. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def run(self, *args: Any, **kwargs: Any) -> int: + self.print_out('Doing some calculation') + return 42 +``` + + +### `PathChecker.set_checking_interval` + +Sets the interval for checking the task's readiness or completion status. + +This method defines how frequently the system should check if the task is ready or completed. +It's useful for tasks that have an indeterminate completion time. + +__Arguments:__ + +- `new_checking_interval` (`Union[float, int]`): The time interval (in seconds) for readiness or checks. + +### `PathChecker.set_color` + +Defines a new color for the current task. + +This method updates the color associated with the task. This can be useful for categorization, +priority indication, or visual differentiation in a UI. + +__Arguments:__ + +- `new_color` (`str`): A string representing the color to be assigned to the task. + +### `PathChecker.set_description` + +Sets a new description for the current task. + +This method allows updating the task's description to provide more context or details about its purpose and behavior. +Useful for enhancing clarity and maintainability in the task management system. + +__Arguments:__ + +- `new_description` (`str`): A string representing the new description of the task. + +### `PathChecker.set_icon` + +Assigns a new icon to the current task. + +This method is used for setting or updating the task's icon, which can be utilized for visual representation +in a user interface. The icon should ideally be a string identifier that maps to an actual graphical resource. + +__Arguments:__ + +- `new_icon` (`str`): A string representing the icon identifier for the task. + +### `PathChecker.set_name` + +Sets a new name for the current task. + +This method is used to update the task's name, typically after creating a copy of an existing task. +The new name helps in differentiating the task in the task management system. + +__Arguments:__ + +- `new_name` (`str`): A string representing the new name to be assigned to the task. + +### `PathChecker.set_retry` + +Sets the number of retry attempts for the task. + +This method configures how many times the task should be retried in case of failure. +It's essential for tasks that may fail transiently and need multiple attempts for successful execution. + +__Arguments:__ + +- `new_retry` (`int`): An integer representing the number of retry attempts. + +### `PathChecker.set_retry_interval` + +Specifies the interval between retry attempts for the task. + +This method sets the duration to wait before retrying the task after a failure. +This can help in scenarios where immediate retry is not desirable or effective. + +__Arguments:__ + +- `new_retry_interval` (`Union[float, int]`): The time interval (in seconds) to wait before a retry attempt. + +### `PathChecker.set_should_execute` + +Determines whether the task should execute. + +This method configures the execution criteria for the task. It can be set as a boolean value, +a string representing a condition, or a callable that returns a boolean. This is useful for +conditional task execution based on dynamic criteria. + +__Arguments:__ + +- `should_execute` (`Union[bool, str, Callable[..., bool]]`): The condition to determine if the task should execute. + +### `PathChecker.show_progress` + +No documentation available. + + +### `PathChecker.to_function` + +Converts the current task into a callable function. + +This method should be implemented to allow the task to be executed as a function. +Parameters can be used to modify the behavior of the generated function, such as +raising errors, asynchronous execution, and logging. + +__Arguments:__ + +- `env_prefix` (`str`): A prefix for environment variables. +- `raise_error` (`bool`): Whether to raise an error if the task execution fails. +- `is_async` (`bool`): Whether the resulting function should be asynchronous. +- `show_done_info` (`bool`): Whether to show information upon task completion. + +__Returns:__ + +`Callable[..., Any]`: A callable representation of the task. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def run(self, *args: Any, **kwargs: Any) -> int: + self.print_out('Doing some calculation') + return 42 +``` + +``` +>>> +```python +task = MyTask() +fn = task.to_function() +fn() +``` + + + + +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task](./README.md) diff --git a/docs/concepts/task/path-watcher.md b/docs/concepts/task/path-watcher.md new file mode 100644 index 00000000..172c3a5c --- /dev/null +++ b/docs/concepts/task/path-watcher.md @@ -0,0 +1,1117 @@ +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task](./README.md) + +# PathWatcher + +# Technical Specification + + +## `PathWatcher` + +Base class for all tasks. +Every task definition should be extended from this class. + +### `PathWatcher._BaseTaskModel__get_colored` + +No documentation available. + + +### `PathWatcher._BaseTaskModel__get_colored_print_prefix` + +No documentation available. + + +### `PathWatcher._BaseTaskModel__get_common_prefix` + +No documentation available. + + +### `PathWatcher._BaseTaskModel__get_executable_name` + +No documentation available. + + +### `PathWatcher._BaseTaskModel__get_log_prefix` + +No documentation available. + + +### `PathWatcher._BaseTaskModel__get_print_prefix` + +No documentation available. + + +### `PathWatcher._BaseTaskModel__get_rjust_full_cli_name` + +No documentation available. + + +### `PathWatcher._Renderer__ensure_cached_render_data` + +No documentation available. + + +### `PathWatcher._Renderer__get_render_data` + +No documentation available. + + +### `PathWatcher._cached_check` + +No documentation available. + + +### `PathWatcher._cached_run` + +No documentation available. + + +### `PathWatcher._check` + +Check current task readiness. +- If self.checkers is defined, +this will return True once every self.checkers is completed +- Otherwise, this will return check method's return value. + +### `PathWatcher._check_should_execute` + +No documentation available. + + +### `PathWatcher._end_timer` + +No documentation available. + + +### `PathWatcher._get_attempt` + +No documentation available. + + +### `PathWatcher._get_checkers` + +Retrieves the checkers set for the task. + +This internal method returns an iterable of all the checkers that have been added to +the task. It's mainly used for internal logic and debugging to understand the +validations or conditions applied to the task. + +__Returns:__ + +`Iterable[TAnyTask]`: An iterable of checkers associated with the task. + +### `PathWatcher._get_combined_env` + +No documentation available. + + +### `PathWatcher._get_combined_inputs` + +' +Getting all inputs of this task and all its upstream, non-duplicated. + +### `PathWatcher._get_elapsed_time` + +No documentation available. + + +### `PathWatcher._get_env_files` + +Retrieves the list of environment variable files associated with the task. + +Intended for internal use, this method returns a list of `EnvFile` instances that the task +uses to load environment variables, primarily for setup and configuration purposes. + +__Returns:__ + +`List[EnvFile]`: A list of `EnvFile` instances associated with the task. + +### `PathWatcher._get_envs` + +Retrieves the list of environment variables set for the task. + +For internal use, this method returns a list of `Env` instances representing the environment variables +configured for the task, essential for understanding and debugging the task's environment setup. + +__Returns:__ + +`List[Env]`: A list of `Env` instances representing the environment variables of the task. + +### `PathWatcher._get_full_cli_name` + +Retrieves the full command-line interface (CLI) name of the task. + +Intended for internal use, this method provides the complete CLI name, including any +prefixes or namespaces, used primarily for logging or debugging purposes. + +__Returns:__ + +`str`: The full CLI name of the task. + +### `PathWatcher._get_inputs` + +Retrieves the list of inputs associated with the task. + +This internal method is used to obtain all the inputs that have been set for the task, +either through static definition or via the `inject_inputs` method. It's primarily used +for introspection and debugging purposes. + +__Returns:__ + +`List[AnyInput]`: A list of `AnyInput` instances representing the inputs for the task. + +### `PathWatcher._get_max_attempt` + +No documentation available. + + +### `PathWatcher._get_mod_times` + +No documentation available. + + +### `PathWatcher._get_task_pid` + +No documentation available. + + +### `PathWatcher._get_upstreams` + +Retrieves the upstream tasks of the current task. + +An internal method to get the list of upstream tasks that have been set for the +task, either statically or through `inject_upstreams`. This is essential for task +scheduling and dependency management. + +__Returns:__ + +`Iterable[TAnyTask]`: An iterable of upstream tasks. + +### `PathWatcher._increase_attempt` + +No documentation available. + + +### `PathWatcher._is_done` + +No documentation available. + + +### `PathWatcher._is_last_attempt` + +No documentation available. + + +### `PathWatcher._lock_upstreams` + +No documentation available. + + +### `PathWatcher._loop_check` + +For internal use. + +Regularly check whether the task is ready or not. + +### `PathWatcher._mark_awaited` + +No documentation available. + + +### `PathWatcher._mark_done` + +No documentation available. + + +### `PathWatcher._play_bell` + +No documentation available. + + +### `PathWatcher._print_result` + +For internal use. + +Directly call `print_result` + +### `PathWatcher._propagate_execution_id` + +No documentation available. + + +### `PathWatcher._run_all` + +For internal use. + +Run this task and all its upstreams. + +### `PathWatcher._run_and_check_all` + +No documentation available. + + +### `PathWatcher._set_args` + +No documentation available. + + +### `PathWatcher._set_env_map` + +No documentation available. + + +### `PathWatcher._set_execution_id` + +Sets the execution ID for the current task. + +This method is intended for internal use to assign a unique identifier to the task's execution. +This ID can be used for tracking, logging, and inter-task communication. + +This method should not be used externally, as it is meant to be managed within the task system. + +__Arguments:__ + +- `execution_id` (`str`): A string representing the unique execution ID. + +### `PathWatcher._set_has_cli_interface` + +Marks the task as having a CLI interface. + +This internal method is used to indicate that the task is accessible and executable through a CLI, +enabling the task system to appropriately handle its CLI interactions. + +### `PathWatcher._set_input_map` + +No documentation available. + + +### `PathWatcher._set_keyval` + +For internal use. + +Set current task's key values. + +### `PathWatcher._set_kwargs` + +No documentation available. + + +### `PathWatcher._set_local_keyval` + +No documentation available. + + +### `PathWatcher._set_task_pid` + +No documentation available. + + +### `PathWatcher._should_attempt` + +No documentation available. + + +### `PathWatcher._show_done_info` + +No documentation available. + + +### `PathWatcher._show_env_prefix` + +No documentation available. + + +### `PathWatcher._show_run_command` + +No documentation available. + + +### `PathWatcher._start_timer` + +No documentation available. + + +### `PathWatcher.add_env` + +Adds one or more `Env` instances to the end of the current task's environment variable list. + +Use this method to append environment variables for the task, which will be used after +any variables already set. + +__Arguments:__ + +- `envs` (`Env`): One or more environment variable instances to be added. + +__Examples:__ + +```python +from zrb import Task, Env +task = Task(name='task') +db_url_env = Env(name='DATABASE_URL', value='postgresql://...') +task.add_env(env_var) +``` + + +### `PathWatcher.add_env_file` + +Adds one or more `EnvFile` instances to the end of the current task's environment file list. + +Use this method to append environment file references, which will be processed after +any files already specified. This allows for supplementing the existing environment +configuration. + +__Arguments:__ + +- `env_files` (`EnvFile`): One or more environment file instances to be added. + +__Examples:__ + +```python +from zrb import Task, EnvFile +task = Task() +env_file = EnvFile(path='config.env') +task.add_env_file(env_file) +``` + + +### `PathWatcher.add_input` + +Adds one or more `AnyInput` instances to the end of the current task's input list. + +This method is used to append inputs for the task to process, placing them after any inputs +already specified. + +__Arguments:__ + +- `inputs` (`AnyInput`): One or more input instances to be added to the input list. + +__Examples:__ + +```python +from zrb import Task, Input +task = Task(name='task') +email_input = Input(name='email-address') +task.add_input(email_input) +``` + + +### `PathWatcher.add_upstream` + +Adds one or more `AnyTask` instances to the end of the current task's upstream list. + +This method appends tasks to the upstream list, indicating that these tasks should be executed +before the current task, but after any tasks already in the upstream list. + +__Arguments:__ + +- `upstreams` (`TAnyTask`): One or more task instances to be added to the upstream list. + +__Examples:__ + +```python +from zrb import Task +task = Task(name='task') +upstream_task = Task(name='upstream-task') +task.add_upstream(upstream_task) +``` + + +### `PathWatcher.check` + +Checks if the current task is `ready`. + +Any other tasks depends on the current task, will be `started` once the current task is `ready`. + +This method should be implemented to define the criteria for considering the task +`ready`. The specifics of this completion depend on the task's +nature and the subclass implementation. + +__Returns:__ + +`bool`: True if the task is completed, False otherwise. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def run(self, *args: Any, **kwargs: Any) -> int: + self.print_out('Doing some calculation') + self._completed = True + return 42 + async def check(self) -> bool: + return self._completed +``` + + +### `PathWatcher.copy` + +Creates and returns a copy of the current task. + +The copied task can be modified using various setter methods like `set_name`, +`set_description`, and others, depending on the subclass implementation. + +__Returns:__ + +`TAnyTask`: A copy of the current task. + +__Examples:__ + +```python +from zrb import Task +task = Task(name='my-task', cmd='echo hello') +copied_task = task.copy() +copied_task.set_name('new_name') +``` + + +### `PathWatcher.get_cli_name` + +Gets the command-line interface (CLI) name of the task. + +This method returns the name used to invoke the task via a CLI, facilitating integration with command-line tools +or scripts. + +__Returns:__ + +`str`: The CLI name of the task. + +### `PathWatcher.get_color` + +Retrieves the color associated with the current task. + +This method returns the color of the task, useful for visual differentiation, priority indication, +or categorization in user interfaces or documentation. + +__Returns:__ + +`str`: A string representing the color assigned to the task. + +### `PathWatcher.get_description` + +Fetches the current description of the task. + +This method is used to obtain the detailed description of the task, providing insights into its purpose, +functionality, and usage within the task management system. + +__Returns:__ + +`str`: The description of the task. + +### `PathWatcher.get_env_map` + +Get a map representing task's Envs and EnvFiles + +Typically used inside `run`, `check`, or in `@python_task` decorator + +__Examples:__ + +```python +from zrb import python_task, Task, Env +@python_task(name='task', envs=[Env(name='DB_URL')]) +def task(*args, **kwargs): + task: Task = kwargs.get('_task') + for key, value in task.get_env_map(): + task.print_out(f'{key}: {value}') +``` + + +### `PathWatcher.get_execution_id` + +Retrieves the execution ID of the task. + +This method returns the unique identifier associated with the task's execution. +The execution ID is crucial for tracking, logging, and differentiating between +multiple instances or runs of the same task. + +__Returns:__ + +`str`: The unique execution ID of the task. + +### `PathWatcher.get_icon` + +Retrieves the icon identifier of the current task. + +This method is used to get the icon associated with the task, which can be utilized for +visual representation in user interfaces or documentation. + +__Returns:__ + +`str`: A string representing the icon identifier for the task + +### `PathWatcher.get_input_map` + +Get a map representing task's Inputs. + +Typically used inside `run`, `check`, or in `@python_task` decorator + +__Examples:__ + +```python +from zrb import python_task, Task, Input +@python_task(name='task', inputs=[Input(name='name')]) +def task(*args, **kwargs): + task: Task = kwargs.get('_task') + for key, value in task.get_input_map(): + task.print_out(f'{key}: {value}') +``` + + +### `PathWatcher.inject_checkers` + +Injects custom checkers into the task. + +This method allows for the addition of custom validation or condition checkers. These +checkers can be used to verify certain conditions before the task execution proceeds. +Subclasses should implement this method to define task-specific checkers. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + def inject_checkers(self): + self.add_checker(some_custom_condition_checker) +``` + + +### `PathWatcher.inject_env_files` + +Injects additional `EnvFile` into the task. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + def inject_env_files(self): + self.add_env_files(EnvFile(path='config.env')) +``` + + +### `PathWatcher.inject_envs` + +Injects environment variables into the task. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + def inject_envs(self): + self.add_envs(Env(name='DATABASE_URL')) +``` + + +### `PathWatcher.inject_inputs` + +Injects custom inputs into the task. + +This method is used to programmatically add input parameters to the task, allowing +dynamic customization of the task's input data. Subclasses should override this method +to define specific inputs that the task should receive. + +__Examples:__ + +```python +from zrb import Task, Input +class MyTask(Task): + def inject_inputs(self): + self.add_input(Input(name='user_email', type='email')) +``` + + +### `PathWatcher.inject_upstreams` + +Injects upstream tasks into the current task. + +This method is used for programmatically adding upstream dependencies to the task. +Upstream tasks are those that must be completed before the current task starts. +Override this method in subclasses to specify such dependencies. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + def inject_upstreams(self): + self.add_upstream(another_task) +``` + + +### `PathWatcher.insert_env` + +Inserts one or more `Env` instances at the beginning of the current task's environment variable list. + +This method allows for setting or overriding environment variables for the task, with earlier entries +having precedence over later ones. + +__Arguments:__ + +- `envs` (`Env`): One or more environment variable instances to be added. + +__Examples:__ + +```python +from zrb import Task, Env +task = Task(name='task') +db_url_env = Env(name='DATABASE_URL', value='postgresql://...') +task.insert_env(env_var) +``` + + +### `PathWatcher.insert_env_file` + +Inserts one or more `EnvFile` instances at the beginning of the current task's environment file list. + +This method is used to specify environment variable files whose contents should be loaded +before those of any files already in the list. This is useful for overriding or setting +additional environment configurations. + +__Arguments:__ + +- `env_files` (`EnvFile`): One or more environment file instances to be added. + +__Examples:__ + +```python +from zrb import Task, EnvFile +task = Task() +env_file = EnvFile(path='config.env') +task.insert_env_file(env_file) +``` + + +### `PathWatcher.insert_input` + +Inserts one or more `AnyInput` instances at the beginning of the current task's input list. + +This method is used to add inputs that the task will process. Inserting an input at the beginning +of the list gives it precedence over those already present. + +__Arguments:__ + +- `inputs` (`AnyInput`): One or more input instances to be added to the input list. + +__Examples:__ + +```python +from zrb import Task, Input +task = Task(name='task') +email_input = Input(name='email-address') +task.insert_input(email_input) +``` + + +### `PathWatcher.insert_upstream` + +Inserts one or more `AnyTask` instances at the beginning of the current task's upstream list. + +This method is used to define dependencies for the current task. Tasks in the upstream list are +executed before the current task. Adding a task to the beginning of the list means it will be +executed earlier than those already in the list. + +__Arguments:__ + +- `upstreams` (`TAnyTask`): One or more task instances to be added to the upstream list. + +__Examples:__ + +```python +from zrb import Task +task = Task(name='task') +upstream_task = Task(name='upstream-task') +task.insert_upstream(upstream_task) +``` + + +### `PathWatcher.inspect` + +No documentation available. + + +### `PathWatcher.log_critical` + +Log message with log level "CRITICAL" + +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + +### `PathWatcher.log_debug` + +Log message with log level "DEBUG" + +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + +### `PathWatcher.log_error` + +Log message with log level "ERROR" + +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + +### `PathWatcher.log_info` + +Log message with log level "INFO" + +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + +### `PathWatcher.log_warn` + +Log message with log level "WARNING" + +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + +### `PathWatcher.on_failed` + +Specifies the behavior when the task execution fails. + +This asynchronous method should be implemented in subclasses to handle task +failure scenarios. It can include logging the error, performing retries, or +any other failure handling mechanisms. + +__Arguments:__ + +- `is_last_attempt` (`bool`): Indicates if this is the final retry attempt. +- `exception` (`Exception`): The exception that caused the task to fail. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_failed(self, is_last_attempt: bool, exception: Exception): + if is_last_attempt: + self.print_out('The task has failed with no remaining retries') + else: + self.print_out('The task failed, retrying...') +``` + + +### `PathWatcher.on_ready` + +Defines actions to be performed when the task status is `ready`. + +This asynchronous method should be implemented in subclasses to specify +actions that occur when the task reaches the `ready` state. This can include +any cleanup, notification, or follow-up actions specific to the task. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_ready(self): + self.print_out('The task is ready') +``` + + +### `PathWatcher.on_retry` + +Defines actions to perform when the task is retried. + +Implement this method to specify behavior when the task is retried after a failure. +This could include resetting states, logging the retry attempt, or other necessary +steps before re-execution. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_retry(self): + self.log_info('Retrying task') +``` + + +### `PathWatcher.on_skipped` + +Defines actions to perform when the task status is set to `skipped`. + +Implement this method to specify behavior when the task is skipped. This could +include logging information, cleaning up resources, or any other necessary steps. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_skipped(self): + self.log_info('Task was skipped') +``` + + +### `PathWatcher.on_started` + +Defines actions to perform when the task status is set to 'started'. + +Implement this method to specify behavior when the task starts its execution. This +could involve initializing resources, logging, or other startup procedures. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_started(self): + self.log_info('Task has started') +``` + + +### `PathWatcher.on_triggered` + +Defines actions to perform when the task status is set to `triggered`. + +Implement this method to specify behavior when the task transitions to the +`triggered` state. This could involve setting up prerequisites or sending +notifications. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_triggered(self): + self.log_info('Task has been triggered') +``` + + +### `PathWatcher.on_waiting` + +Defines actions to perform when the task status is set to `waiting`. + +Implement this method to specify behavior when the task transitions to the +`waiting` state. This state usually indicates the task is waiting for some +condition or prerequisite to be met. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_waiting(self): + self.log_info('Task is waiting to be started') +``` + + +### `PathWatcher.print_err` + +Print message to stderr and style it as error. + +### `PathWatcher.print_out` + +Print message to stderr as normal text. + +### `PathWatcher.print_out_dark` + +Print message to stdout and style it as faint. + +### `PathWatcher.print_result` + +Outputs the task result to stdout for further processing. + +Override this method in subclasses to customize how the task result is displayed +or processed. Useful for integrating the task output with other systems or +command-line tools. + +__Arguments:__ + +- `result` (`Any`): The result of the task to be printed. + +__Examples:__ + +```python +from zrb import Task +# Example of overriding in a subclass +class MyTask(Task): + def print_result(self, result: Any): + print(f'Result: {result}') +``` + + +### `PathWatcher.render_any` + +Render any value. + +### `PathWatcher.render_bool` + +Render int value. + +### `PathWatcher.render_file` + +Render file content. + +### `PathWatcher.render_float` + +Render float value. + +### `PathWatcher.render_int` + +No documentation available. + + +### `PathWatcher.render_str` + +Render str value. + +### `PathWatcher.run` + +Executes the main logic of the task. + +This asynchronous method should be implemented in subclasses to define the +task's primary functionality. The specific behavior and the return value +depend on the task's nature and purpose. + +__Arguments:__ + +- `args` (`Any`): Variable length argument list. +- `kwargs` (`Any`): Arbitrary keyword arguments. + +__Returns:__ + +`Any`: The result of the task execution, the type of which is determined by +the specific task implementation. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def run(self, *args: Any, **kwargs: Any) -> int: + self.print_out('Doing some calculation') + return 42 +``` + + +### `PathWatcher.set_checking_interval` + +Sets the interval for checking the task's readiness or completion status. + +This method defines how frequently the system should check if the task is ready or completed. +It's useful for tasks that have an indeterminate completion time. + +__Arguments:__ + +- `new_checking_interval` (`Union[float, int]`): The time interval (in seconds) for readiness or checks. + +### `PathWatcher.set_color` + +Defines a new color for the current task. + +This method updates the color associated with the task. This can be useful for categorization, +priority indication, or visual differentiation in a UI. + +__Arguments:__ + +- `new_color` (`str`): A string representing the color to be assigned to the task. + +### `PathWatcher.set_description` + +Sets a new description for the current task. + +This method allows updating the task's description to provide more context or details about its purpose and behavior. +Useful for enhancing clarity and maintainability in the task management system. + +__Arguments:__ + +- `new_description` (`str`): A string representing the new description of the task. + +### `PathWatcher.set_icon` + +Assigns a new icon to the current task. + +This method is used for setting or updating the task's icon, which can be utilized for visual representation +in a user interface. The icon should ideally be a string identifier that maps to an actual graphical resource. + +__Arguments:__ + +- `new_icon` (`str`): A string representing the icon identifier for the task. + +### `PathWatcher.set_name` + +Sets a new name for the current task. + +This method is used to update the task's name, typically after creating a copy of an existing task. +The new name helps in differentiating the task in the task management system. + +__Arguments:__ + +- `new_name` (`str`): A string representing the new name to be assigned to the task. + +### `PathWatcher.set_retry` + +Sets the number of retry attempts for the task. + +This method configures how many times the task should be retried in case of failure. +It's essential for tasks that may fail transiently and need multiple attempts for successful execution. + +__Arguments:__ + +- `new_retry` (`int`): An integer representing the number of retry attempts. + +### `PathWatcher.set_retry_interval` + +Specifies the interval between retry attempts for the task. + +This method sets the duration to wait before retrying the task after a failure. +This can help in scenarios where immediate retry is not desirable or effective. + +__Arguments:__ + +- `new_retry_interval` (`Union[float, int]`): The time interval (in seconds) to wait before a retry attempt. + +### `PathWatcher.set_should_execute` + +Determines whether the task should execute. + +This method configures the execution criteria for the task. It can be set as a boolean value, +a string representing a condition, or a callable that returns a boolean. This is useful for +conditional task execution based on dynamic criteria. + +__Arguments:__ + +- `should_execute` (`Union[bool, str, Callable[..., bool]]`): The condition to determine if the task should execute. + +### `PathWatcher.show_progress` + +No documentation available. + + +### `PathWatcher.to_function` + +Converts the current task into a callable function. + +This method should be implemented to allow the task to be executed as a function. +Parameters can be used to modify the behavior of the generated function, such as +raising errors, asynchronous execution, and logging. + +__Arguments:__ + +- `env_prefix` (`str`): A prefix for environment variables. +- `raise_error` (`bool`): Whether to raise an error if the task execution fails. +- `is_async` (`bool`): Whether the resulting function should be asynchronous. +- `show_done_info` (`bool`): Whether to show information upon task completion. + +__Returns:__ + +`Callable[..., Any]`: A callable representation of the task. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def run(self, *args: Any, **kwargs: Any) -> int: + self.print_out('Doing some calculation') + return 42 +``` + +``` +>>> +```python +task = MyTask() +fn = task.to_function() +fn() +``` + + + + +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task](./README.md) diff --git a/docs/concepts/task/port-checker.md b/docs/concepts/task/port-checker.md new file mode 100644 index 00000000..a630eb13 --- /dev/null +++ b/docs/concepts/task/port-checker.md @@ -0,0 +1,1112 @@ +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task](./README.md) + +# PortChecker + +# Technical Specification + + +## `PortChecker` + +Base class for all tasks. +Every task definition should be extended from this class. + +### `PortChecker._BaseTaskModel__get_colored` + +No documentation available. + + +### `PortChecker._BaseTaskModel__get_colored_print_prefix` + +No documentation available. + + +### `PortChecker._BaseTaskModel__get_common_prefix` + +No documentation available. + + +### `PortChecker._BaseTaskModel__get_executable_name` + +No documentation available. + + +### `PortChecker._BaseTaskModel__get_log_prefix` + +No documentation available. + + +### `PortChecker._BaseTaskModel__get_print_prefix` + +No documentation available. + + +### `PortChecker._BaseTaskModel__get_rjust_full_cli_name` + +No documentation available. + + +### `PortChecker._Renderer__ensure_cached_render_data` + +No documentation available. + + +### `PortChecker._Renderer__get_render_data` + +No documentation available. + + +### `PortChecker._cached_check` + +No documentation available. + + +### `PortChecker._cached_run` + +No documentation available. + + +### `PortChecker._check` + +Check current task readiness. +- If self.checkers is defined, +this will return True once every self.checkers is completed +- Otherwise, this will return check method's return value. + +### `PortChecker._check_should_execute` + +No documentation available. + + +### `PortChecker._end_timer` + +No documentation available. + + +### `PortChecker._get_attempt` + +No documentation available. + + +### `PortChecker._get_checkers` + +Retrieves the checkers set for the task. + +This internal method returns an iterable of all the checkers that have been added to +the task. It's mainly used for internal logic and debugging to understand the +validations or conditions applied to the task. + +__Returns:__ + +`Iterable[TAnyTask]`: An iterable of checkers associated with the task. + +### `PortChecker._get_combined_env` + +No documentation available. + + +### `PortChecker._get_combined_inputs` + +' +Getting all inputs of this task and all its upstream, non-duplicated. + +### `PortChecker._get_elapsed_time` + +No documentation available. + + +### `PortChecker._get_env_files` + +Retrieves the list of environment variable files associated with the task. + +Intended for internal use, this method returns a list of `EnvFile` instances that the task +uses to load environment variables, primarily for setup and configuration purposes. + +__Returns:__ + +`List[EnvFile]`: A list of `EnvFile` instances associated with the task. + +### `PortChecker._get_envs` + +Retrieves the list of environment variables set for the task. + +For internal use, this method returns a list of `Env` instances representing the environment variables +configured for the task, essential for understanding and debugging the task's environment setup. + +__Returns:__ + +`List[Env]`: A list of `Env` instances representing the environment variables of the task. + +### `PortChecker._get_full_cli_name` + +Retrieves the full command-line interface (CLI) name of the task. + +Intended for internal use, this method provides the complete CLI name, including any +prefixes or namespaces, used primarily for logging or debugging purposes. + +__Returns:__ + +`str`: The full CLI name of the task. + +### `PortChecker._get_inputs` + +Retrieves the list of inputs associated with the task. + +This internal method is used to obtain all the inputs that have been set for the task, +either through static definition or via the `inject_inputs` method. It's primarily used +for introspection and debugging purposes. + +__Returns:__ + +`List[AnyInput]`: A list of `AnyInput` instances representing the inputs for the task. + +### `PortChecker._get_max_attempt` + +No documentation available. + + +### `PortChecker._get_task_pid` + +No documentation available. + + +### `PortChecker._get_upstreams` + +Retrieves the upstream tasks of the current task. + +An internal method to get the list of upstream tasks that have been set for the +task, either statically or through `inject_upstreams`. This is essential for task +scheduling and dependency management. + +__Returns:__ + +`Iterable[TAnyTask]`: An iterable of upstream tasks. + +### `PortChecker._increase_attempt` + +No documentation available. + + +### `PortChecker._is_done` + +No documentation available. + + +### `PortChecker._is_last_attempt` + +No documentation available. + + +### `PortChecker._lock_upstreams` + +No documentation available. + + +### `PortChecker._loop_check` + +For internal use. + +Regularly check whether the task is ready or not. + +### `PortChecker._mark_awaited` + +No documentation available. + + +### `PortChecker._mark_done` + +No documentation available. + + +### `PortChecker._play_bell` + +No documentation available. + + +### `PortChecker._print_result` + +For internal use. + +Directly call `print_result` + +### `PortChecker._propagate_execution_id` + +No documentation available. + + +### `PortChecker._run_all` + +For internal use. + +Run this task and all its upstreams. + +### `PortChecker._run_and_check_all` + +No documentation available. + + +### `PortChecker._set_args` + +No documentation available. + + +### `PortChecker._set_env_map` + +No documentation available. + + +### `PortChecker._set_execution_id` + +Sets the execution ID for the current task. + +This method is intended for internal use to assign a unique identifier to the task's execution. +This ID can be used for tracking, logging, and inter-task communication. + +This method should not be used externally, as it is meant to be managed within the task system. + +__Arguments:__ + +- `execution_id` (`str`): A string representing the unique execution ID. + +### `PortChecker._set_has_cli_interface` + +Marks the task as having a CLI interface. + +This internal method is used to indicate that the task is accessible and executable through a CLI, +enabling the task system to appropriately handle its CLI interactions. + +### `PortChecker._set_input_map` + +No documentation available. + + +### `PortChecker._set_keyval` + +For internal use. + +Set current task's key values. + +### `PortChecker._set_kwargs` + +No documentation available. + + +### `PortChecker._set_local_keyval` + +No documentation available. + + +### `PortChecker._set_task_pid` + +No documentation available. + + +### `PortChecker._should_attempt` + +No documentation available. + + +### `PortChecker._show_done_info` + +No documentation available. + + +### `PortChecker._show_env_prefix` + +No documentation available. + + +### `PortChecker._show_run_command` + +No documentation available. + + +### `PortChecker._start_timer` + +No documentation available. + + +### `PortChecker.add_env` + +Adds one or more `Env` instances to the end of the current task's environment variable list. + +Use this method to append environment variables for the task, which will be used after +any variables already set. + +__Arguments:__ + +- `envs` (`Env`): One or more environment variable instances to be added. + +__Examples:__ + +```python +from zrb import Task, Env +task = Task(name='task') +db_url_env = Env(name='DATABASE_URL', value='postgresql://...') +task.add_env(env_var) +``` + + +### `PortChecker.add_env_file` + +Adds one or more `EnvFile` instances to the end of the current task's environment file list. + +Use this method to append environment file references, which will be processed after +any files already specified. This allows for supplementing the existing environment +configuration. + +__Arguments:__ + +- `env_files` (`EnvFile`): One or more environment file instances to be added. + +__Examples:__ + +```python +from zrb import Task, EnvFile +task = Task() +env_file = EnvFile(path='config.env') +task.add_env_file(env_file) +``` + + +### `PortChecker.add_input` + +Adds one or more `AnyInput` instances to the end of the current task's input list. + +This method is used to append inputs for the task to process, placing them after any inputs +already specified. + +__Arguments:__ + +- `inputs` (`AnyInput`): One or more input instances to be added to the input list. + +__Examples:__ + +```python +from zrb import Task, Input +task = Task(name='task') +email_input = Input(name='email-address') +task.add_input(email_input) +``` + + +### `PortChecker.add_upstream` + +Adds one or more `AnyTask` instances to the end of the current task's upstream list. + +This method appends tasks to the upstream list, indicating that these tasks should be executed +before the current task, but after any tasks already in the upstream list. + +__Arguments:__ + +- `upstreams` (`TAnyTask`): One or more task instances to be added to the upstream list. + +__Examples:__ + +```python +from zrb import Task +task = Task(name='task') +upstream_task = Task(name='upstream-task') +task.add_upstream(upstream_task) +``` + + +### `PortChecker.check` + +Checks if the current task is `ready`. + +Any other tasks depends on the current task, will be `started` once the current task is `ready`. + +This method should be implemented to define the criteria for considering the task +`ready`. The specifics of this completion depend on the task's +nature and the subclass implementation. + +__Returns:__ + +`bool`: True if the task is completed, False otherwise. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def run(self, *args: Any, **kwargs: Any) -> int: + self.print_out('Doing some calculation') + self._completed = True + return 42 + async def check(self) -> bool: + return self._completed +``` + + +### `PortChecker.copy` + +Creates and returns a copy of the current task. + +The copied task can be modified using various setter methods like `set_name`, +`set_description`, and others, depending on the subclass implementation. + +__Returns:__ + +`TAnyTask`: A copy of the current task. + +__Examples:__ + +```python +from zrb import Task +task = Task(name='my-task', cmd='echo hello') +copied_task = task.copy() +copied_task.set_name('new_name') +``` + + +### `PortChecker.get_cli_name` + +Gets the command-line interface (CLI) name of the task. + +This method returns the name used to invoke the task via a CLI, facilitating integration with command-line tools +or scripts. + +__Returns:__ + +`str`: The CLI name of the task. + +### `PortChecker.get_color` + +Retrieves the color associated with the current task. + +This method returns the color of the task, useful for visual differentiation, priority indication, +or categorization in user interfaces or documentation. + +__Returns:__ + +`str`: A string representing the color assigned to the task. + +### `PortChecker.get_description` + +Fetches the current description of the task. + +This method is used to obtain the detailed description of the task, providing insights into its purpose, +functionality, and usage within the task management system. + +__Returns:__ + +`str`: The description of the task. + +### `PortChecker.get_env_map` + +Get a map representing task's Envs and EnvFiles + +Typically used inside `run`, `check`, or in `@python_task` decorator + +__Examples:__ + +```python +from zrb import python_task, Task, Env +@python_task(name='task', envs=[Env(name='DB_URL')]) +def task(*args, **kwargs): + task: Task = kwargs.get('_task') + for key, value in task.get_env_map(): + task.print_out(f'{key}: {value}') +``` + + +### `PortChecker.get_execution_id` + +Retrieves the execution ID of the task. + +This method returns the unique identifier associated with the task's execution. +The execution ID is crucial for tracking, logging, and differentiating between +multiple instances or runs of the same task. + +__Returns:__ + +`str`: The unique execution ID of the task. + +### `PortChecker.get_icon` + +Retrieves the icon identifier of the current task. + +This method is used to get the icon associated with the task, which can be utilized for +visual representation in user interfaces or documentation. + +__Returns:__ + +`str`: A string representing the icon identifier for the task + +### `PortChecker.get_input_map` + +Get a map representing task's Inputs. + +Typically used inside `run`, `check`, or in `@python_task` decorator + +__Examples:__ + +```python +from zrb import python_task, Task, Input +@python_task(name='task', inputs=[Input(name='name')]) +def task(*args, **kwargs): + task: Task = kwargs.get('_task') + for key, value in task.get_input_map(): + task.print_out(f'{key}: {value}') +``` + + +### `PortChecker.inject_checkers` + +Injects custom checkers into the task. + +This method allows for the addition of custom validation or condition checkers. These +checkers can be used to verify certain conditions before the task execution proceeds. +Subclasses should implement this method to define task-specific checkers. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + def inject_checkers(self): + self.add_checker(some_custom_condition_checker) +``` + + +### `PortChecker.inject_env_files` + +Injects additional `EnvFile` into the task. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + def inject_env_files(self): + self.add_env_files(EnvFile(path='config.env')) +``` + + +### `PortChecker.inject_envs` + +Injects environment variables into the task. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + def inject_envs(self): + self.add_envs(Env(name='DATABASE_URL')) +``` + + +### `PortChecker.inject_inputs` + +Injects custom inputs into the task. + +This method is used to programmatically add input parameters to the task, allowing +dynamic customization of the task's input data. Subclasses should override this method +to define specific inputs that the task should receive. + +__Examples:__ + +```python +from zrb import Task, Input +class MyTask(Task): + def inject_inputs(self): + self.add_input(Input(name='user_email', type='email')) +``` + + +### `PortChecker.inject_upstreams` + +Injects upstream tasks into the current task. + +This method is used for programmatically adding upstream dependencies to the task. +Upstream tasks are those that must be completed before the current task starts. +Override this method in subclasses to specify such dependencies. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + def inject_upstreams(self): + self.add_upstream(another_task) +``` + + +### `PortChecker.insert_env` + +Inserts one or more `Env` instances at the beginning of the current task's environment variable list. + +This method allows for setting or overriding environment variables for the task, with earlier entries +having precedence over later ones. + +__Arguments:__ + +- `envs` (`Env`): One or more environment variable instances to be added. + +__Examples:__ + +```python +from zrb import Task, Env +task = Task(name='task') +db_url_env = Env(name='DATABASE_URL', value='postgresql://...') +task.insert_env(env_var) +``` + + +### `PortChecker.insert_env_file` + +Inserts one or more `EnvFile` instances at the beginning of the current task's environment file list. + +This method is used to specify environment variable files whose contents should be loaded +before those of any files already in the list. This is useful for overriding or setting +additional environment configurations. + +__Arguments:__ + +- `env_files` (`EnvFile`): One or more environment file instances to be added. + +__Examples:__ + +```python +from zrb import Task, EnvFile +task = Task() +env_file = EnvFile(path='config.env') +task.insert_env_file(env_file) +``` + + +### `PortChecker.insert_input` + +Inserts one or more `AnyInput` instances at the beginning of the current task's input list. + +This method is used to add inputs that the task will process. Inserting an input at the beginning +of the list gives it precedence over those already present. + +__Arguments:__ + +- `inputs` (`AnyInput`): One or more input instances to be added to the input list. + +__Examples:__ + +```python +from zrb import Task, Input +task = Task(name='task') +email_input = Input(name='email-address') +task.insert_input(email_input) +``` + + +### `PortChecker.insert_upstream` + +Inserts one or more `AnyTask` instances at the beginning of the current task's upstream list. + +This method is used to define dependencies for the current task. Tasks in the upstream list are +executed before the current task. Adding a task to the beginning of the list means it will be +executed earlier than those already in the list. + +__Arguments:__ + +- `upstreams` (`TAnyTask`): One or more task instances to be added to the upstream list. + +__Examples:__ + +```python +from zrb import Task +task = Task(name='task') +upstream_task = Task(name='upstream-task') +task.insert_upstream(upstream_task) +``` + + +### `PortChecker.inspect` + +No documentation available. + + +### `PortChecker.log_critical` + +Log message with log level "CRITICAL" + +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + +### `PortChecker.log_debug` + +Log message with log level "DEBUG" + +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + +### `PortChecker.log_error` + +Log message with log level "ERROR" + +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + +### `PortChecker.log_info` + +Log message with log level "INFO" + +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + +### `PortChecker.log_warn` + +Log message with log level "WARNING" + +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + +### `PortChecker.on_failed` + +Specifies the behavior when the task execution fails. + +This asynchronous method should be implemented in subclasses to handle task +failure scenarios. It can include logging the error, performing retries, or +any other failure handling mechanisms. + +__Arguments:__ + +- `is_last_attempt` (`bool`): Indicates if this is the final retry attempt. +- `exception` (`Exception`): The exception that caused the task to fail. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_failed(self, is_last_attempt: bool, exception: Exception): + if is_last_attempt: + self.print_out('The task has failed with no remaining retries') + else: + self.print_out('The task failed, retrying...') +``` + + +### `PortChecker.on_ready` + +Defines actions to be performed when the task status is `ready`. + +This asynchronous method should be implemented in subclasses to specify +actions that occur when the task reaches the `ready` state. This can include +any cleanup, notification, or follow-up actions specific to the task. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_ready(self): + self.print_out('The task is ready') +``` + + +### `PortChecker.on_retry` + +Defines actions to perform when the task is retried. + +Implement this method to specify behavior when the task is retried after a failure. +This could include resetting states, logging the retry attempt, or other necessary +steps before re-execution. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_retry(self): + self.log_info('Retrying task') +``` + + +### `PortChecker.on_skipped` + +Defines actions to perform when the task status is set to `skipped`. + +Implement this method to specify behavior when the task is skipped. This could +include logging information, cleaning up resources, or any other necessary steps. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_skipped(self): + self.log_info('Task was skipped') +``` + + +### `PortChecker.on_started` + +Defines actions to perform when the task status is set to 'started'. + +Implement this method to specify behavior when the task starts its execution. This +could involve initializing resources, logging, or other startup procedures. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_started(self): + self.log_info('Task has started') +``` + + +### `PortChecker.on_triggered` + +Defines actions to perform when the task status is set to `triggered`. + +Implement this method to specify behavior when the task transitions to the +`triggered` state. This could involve setting up prerequisites or sending +notifications. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_triggered(self): + self.log_info('Task has been triggered') +``` + + +### `PortChecker.on_waiting` + +Defines actions to perform when the task status is set to `waiting`. + +Implement this method to specify behavior when the task transitions to the +`waiting` state. This state usually indicates the task is waiting for some +condition or prerequisite to be met. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_waiting(self): + self.log_info('Task is waiting to be started') +``` + + +### `PortChecker.print_err` + +Print message to stderr and style it as error. + +### `PortChecker.print_out` + +Print message to stderr as normal text. + +### `PortChecker.print_out_dark` + +Print message to stdout and style it as faint. + +### `PortChecker.print_result` + +Outputs the task result to stdout for further processing. + +Override this method in subclasses to customize how the task result is displayed +or processed. Useful for integrating the task output with other systems or +command-line tools. + +__Arguments:__ + +- `result` (`Any`): The result of the task to be printed. + +__Examples:__ + +```python +from zrb import Task +# Example of overriding in a subclass +class MyTask(Task): + def print_result(self, result: Any): + print(f'Result: {result}') +``` + + +### `PortChecker.render_any` + +Render any value. + +### `PortChecker.render_bool` + +Render int value. + +### `PortChecker.render_file` + +Render file content. + +### `PortChecker.render_float` + +Render float value. + +### `PortChecker.render_int` + +No documentation available. + + +### `PortChecker.render_str` + +Render str value. + +### `PortChecker.run` + +Executes the main logic of the task. + +This asynchronous method should be implemented in subclasses to define the +task's primary functionality. The specific behavior and the return value +depend on the task's nature and purpose. + +__Arguments:__ + +- `args` (`Any`): Variable length argument list. +- `kwargs` (`Any`): Arbitrary keyword arguments. + +__Returns:__ + +`Any`: The result of the task execution, the type of which is determined by +the specific task implementation. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def run(self, *args: Any, **kwargs: Any) -> int: + self.print_out('Doing some calculation') + return 42 +``` + + +### `PortChecker.set_checking_interval` + +Sets the interval for checking the task's readiness or completion status. + +This method defines how frequently the system should check if the task is ready or completed. +It's useful for tasks that have an indeterminate completion time. + +__Arguments:__ + +- `new_checking_interval` (`Union[float, int]`): The time interval (in seconds) for readiness or checks. + +### `PortChecker.set_color` + +Defines a new color for the current task. + +This method updates the color associated with the task. This can be useful for categorization, +priority indication, or visual differentiation in a UI. + +__Arguments:__ + +- `new_color` (`str`): A string representing the color to be assigned to the task. + +### `PortChecker.set_description` + +Sets a new description for the current task. + +This method allows updating the task's description to provide more context or details about its purpose and behavior. +Useful for enhancing clarity and maintainability in the task management system. + +__Arguments:__ + +- `new_description` (`str`): A string representing the new description of the task. + +### `PortChecker.set_icon` + +Assigns a new icon to the current task. + +This method is used for setting or updating the task's icon, which can be utilized for visual representation +in a user interface. The icon should ideally be a string identifier that maps to an actual graphical resource. + +__Arguments:__ + +- `new_icon` (`str`): A string representing the icon identifier for the task. + +### `PortChecker.set_name` + +Sets a new name for the current task. + +This method is used to update the task's name, typically after creating a copy of an existing task. +The new name helps in differentiating the task in the task management system. + +__Arguments:__ + +- `new_name` (`str`): A string representing the new name to be assigned to the task. + +### `PortChecker.set_retry` + +Sets the number of retry attempts for the task. + +This method configures how many times the task should be retried in case of failure. +It's essential for tasks that may fail transiently and need multiple attempts for successful execution. + +__Arguments:__ + +- `new_retry` (`int`): An integer representing the number of retry attempts. + +### `PortChecker.set_retry_interval` + +Specifies the interval between retry attempts for the task. + +This method sets the duration to wait before retrying the task after a failure. +This can help in scenarios where immediate retry is not desirable or effective. + +__Arguments:__ + +- `new_retry_interval` (`Union[float, int]`): The time interval (in seconds) to wait before a retry attempt. + +### `PortChecker.set_should_execute` + +Determines whether the task should execute. + +This method configures the execution criteria for the task. It can be set as a boolean value, +a string representing a condition, or a callable that returns a boolean. This is useful for +conditional task execution based on dynamic criteria. + +__Arguments:__ + +- `should_execute` (`Union[bool, str, Callable[..., bool]]`): The condition to determine if the task should execute. + +### `PortChecker.show_progress` + +No documentation available. + + +### `PortChecker.to_function` + +Converts the current task into a callable function. + +This method should be implemented to allow the task to be executed as a function. +Parameters can be used to modify the behavior of the generated function, such as +raising errors, asynchronous execution, and logging. + +__Arguments:__ + +- `env_prefix` (`str`): A prefix for environment variables. +- `raise_error` (`bool`): Whether to raise an error if the task execution fails. +- `is_async` (`bool`): Whether the resulting function should be asynchronous. +- `show_done_info` (`bool`): Whether to show information upon task completion. + +__Returns:__ + +`Callable[..., Any]`: A callable representation of the task. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def run(self, *args: Any, **kwargs: Any) -> int: + self.print_out('Doing some calculation') + return 42 +``` + +``` +>>> +```python +task = MyTask() +fn = task.to_function() +fn() +``` + + + + +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task](./README.md) diff --git a/docs/concepts/task/python-task.md b/docs/concepts/task/python-task.md index b4a0a921..f77bce33 100644 --- a/docs/concepts/task/python-task.md +++ b/docs/concepts/task/python-task.md @@ -1,82 +1,8 @@ -🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Tasks](README.md) +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task](./README.md) -# `Task` +# Python Task -You can turn any function with `args` and `kwargs` argument into a Python Task. - - -```python -from zrb import Task, Env, StrInput, runner - - -def say_hello(*args, **kwargs) -> str: - name = kwargs.get('name') - greetings = f'Hello, {name}' - return greetings - - -say_hello_task = Task( - name='say-hello', - inputs=[ - StrInput(name='name') - ], - envs=[ - Env(name='PYTHONUNBUFFERED', default='1') - ], - run=say_hello -) -runner.register(say_hello_task) -``` - -In the example, you define a function named `say_hello`. - -Then you make a task named and set it's `run` property to `say_hello` function. As you notice, Zrb will automatically pass task input into `kwargs` argument. - -You can run the task by invoking: - -``` -zrb say-hello --name John -``` - -Thiw will give you a `Hello John`. - -# Using `python_task` decorator - -Aside from defining the function and the task separately, you can also use `python_task` decorator to turn your function into a task. - -```python -from zrb import python_task, Env, StrInput, runner - -@python_task( - name='say-hello', - inputs=[ - StrInput(name='name') - ], - envs=[ - Env(name='PYTHONUNBUFFERED', default='1') - ], - runner=runner -) -def say_hello(*args, **kwargs) -> str: - name = kwargs.get('name') - greetings = f'Hello, {name}' - task = kwargs.get('_task') - task.print_out(greetings) - return greetings -``` - -Notice that you can now use `runner` as decorator argument so that you don't need to call `runner.register(say_hello)`. - -You can then run the task by invoking: - -```bash -zrb say-hello --name=John -``` - -You can also use `async` function if you think you need to. - - -# Technical Documentation +# Technical Specification ## `python_task` @@ -106,4 +32,4 @@ print(my_task) -🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Tasks](README.md) +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task](./README.md) diff --git a/docs/concepts/task/recurring-task.md b/docs/concepts/task/recurring-task.md new file mode 100644 index 00000000..8846dc5a --- /dev/null +++ b/docs/concepts/task/recurring-task.md @@ -0,0 +1,1107 @@ +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task](./README.md) + +# RecurringTask + +# Technical Specification + + +## `RecurringTask` + +Base class for all tasks. +Every task definition should be extended from this class. + +### `RecurringTask._BaseTaskModel__get_colored` + +No documentation available. + + +### `RecurringTask._BaseTaskModel__get_colored_print_prefix` + +No documentation available. + + +### `RecurringTask._BaseTaskModel__get_common_prefix` + +No documentation available. + + +### `RecurringTask._BaseTaskModel__get_executable_name` + +No documentation available. + + +### `RecurringTask._BaseTaskModel__get_log_prefix` + +No documentation available. + + +### `RecurringTask._BaseTaskModel__get_print_prefix` + +No documentation available. + + +### `RecurringTask._BaseTaskModel__get_rjust_full_cli_name` + +No documentation available. + + +### `RecurringTask._RecurringTask__run_and_play_bell` + +No documentation available. + + +### `RecurringTask._Renderer__ensure_cached_render_data` + +No documentation available. + + +### `RecurringTask._Renderer__get_render_data` + +No documentation available. + + +### `RecurringTask._cached_check` + +No documentation available. + + +### `RecurringTask._cached_run` + +No documentation available. + + +### `RecurringTask._check` + +Check current task readiness. +- If self.checkers is defined, +this will return True once every self.checkers is completed +- Otherwise, this will return check method's return value. + +### `RecurringTask._check_should_execute` + +No documentation available. + + +### `RecurringTask._end_timer` + +No documentation available. + + +### `RecurringTask._get_attempt` + +No documentation available. + + +### `RecurringTask._get_checkers` + +Retrieves the checkers set for the task. + +This internal method returns an iterable of all the checkers that have been added to +the task. It's mainly used for internal logic and debugging to understand the +validations or conditions applied to the task. + +__Returns:__ + +`Iterable[TAnyTask]`: An iterable of checkers associated with the task. + +### `RecurringTask._get_combined_env` + +No documentation available. + + +### `RecurringTask._get_combined_inputs` + +' +Getting all inputs of this task and all its upstream, non-duplicated. + +### `RecurringTask._get_elapsed_time` + +No documentation available. + + +### `RecurringTask._get_env_files` + +Retrieves the list of environment variable files associated with the task. + +Intended for internal use, this method returns a list of `EnvFile` instances that the task +uses to load environment variables, primarily for setup and configuration purposes. + +__Returns:__ + +`List[EnvFile]`: A list of `EnvFile` instances associated with the task. + +### `RecurringTask._get_envs` + +Retrieves the list of environment variables set for the task. + +For internal use, this method returns a list of `Env` instances representing the environment variables +configured for the task, essential for understanding and debugging the task's environment setup. + +__Returns:__ + +`List[Env]`: A list of `Env` instances representing the environment variables of the task. + +### `RecurringTask._get_full_cli_name` + +Retrieves the full command-line interface (CLI) name of the task. + +Intended for internal use, this method provides the complete CLI name, including any +prefixes or namespaces, used primarily for logging or debugging purposes. + +__Returns:__ + +`str`: The full CLI name of the task. + +### `RecurringTask._get_inputs` + +Retrieves the list of inputs associated with the task. + +This internal method is used to obtain all the inputs that have been set for the task, +either through static definition or via the `inject_inputs` method. It's primarily used +for introspection and debugging purposes. + +__Returns:__ + +`List[AnyInput]`: A list of `AnyInput` instances representing the inputs for the task. + +### `RecurringTask._get_max_attempt` + +No documentation available. + + +### `RecurringTask._get_task_pid` + +No documentation available. + + +### `RecurringTask._get_upstreams` + +Retrieves the upstream tasks of the current task. + +An internal method to get the list of upstream tasks that have been set for the +task, either statically or through `inject_upstreams`. This is essential for task +scheduling and dependency management. + +__Returns:__ + +`Iterable[TAnyTask]`: An iterable of upstream tasks. + +### `RecurringTask._increase_attempt` + +No documentation available. + + +### `RecurringTask._is_done` + +No documentation available. + + +### `RecurringTask._is_last_attempt` + +No documentation available. + + +### `RecurringTask._lock_upstreams` + +No documentation available. + + +### `RecurringTask._loop_check` + +For internal use. + +Regularly check whether the task is ready or not. + +### `RecurringTask._mark_awaited` + +No documentation available. + + +### `RecurringTask._mark_done` + +No documentation available. + + +### `RecurringTask._play_bell` + +No documentation available. + + +### `RecurringTask._print_result` + +For internal use. + +Directly call `print_result` + +### `RecurringTask._propagate_execution_id` + +No documentation available. + + +### `RecurringTask._run_all` + +For internal use. + +Run this task and all its upstreams. + +### `RecurringTask._run_and_check_all` + +No documentation available. + + +### `RecurringTask._set_args` + +No documentation available. + + +### `RecurringTask._set_env_map` + +No documentation available. + + +### `RecurringTask._set_execution_id` + +Sets the execution ID for the current task. + +This method is intended for internal use to assign a unique identifier to the task's execution. +This ID can be used for tracking, logging, and inter-task communication. + +This method should not be used externally, as it is meant to be managed within the task system. + +__Arguments:__ + +- `execution_id` (`str`): A string representing the unique execution ID. + +### `RecurringTask._set_has_cli_interface` + +Marks the task as having a CLI interface. + +This internal method is used to indicate that the task is accessible and executable through a CLI, +enabling the task system to appropriately handle its CLI interactions. + +### `RecurringTask._set_input_map` + +No documentation available. + + +### `RecurringTask._set_keyval` + +For internal use. + +Set current task's key values. + +### `RecurringTask._set_kwargs` + +No documentation available. + + +### `RecurringTask._set_local_keyval` + +No documentation available. + + +### `RecurringTask._set_task_pid` + +No documentation available. + + +### `RecurringTask._should_attempt` + +No documentation available. + + +### `RecurringTask._show_done_info` + +No documentation available. + + +### `RecurringTask._show_env_prefix` + +No documentation available. + + +### `RecurringTask._show_run_command` + +No documentation available. + + +### `RecurringTask._start_timer` + +No documentation available. + + +### `RecurringTask.add_env` + +Adds one or more `Env` instances to the end of the current task's environment variable list. + +Use this method to append environment variables for the task, which will be used after +any variables already set. + +__Arguments:__ + +- `envs` (`Env`): One or more environment variable instances to be added. + +__Examples:__ + +```python +from zrb import Task, Env +task = Task(name='task') +db_url_env = Env(name='DATABASE_URL', value='postgresql://...') +task.add_env(env_var) +``` + + +### `RecurringTask.add_env_file` + +Adds one or more `EnvFile` instances to the end of the current task's environment file list. + +Use this method to append environment file references, which will be processed after +any files already specified. This allows for supplementing the existing environment +configuration. + +__Arguments:__ + +- `env_files` (`EnvFile`): One or more environment file instances to be added. + +__Examples:__ + +```python +from zrb import Task, EnvFile +task = Task() +env_file = EnvFile(path='config.env') +task.add_env_file(env_file) +``` + + +### `RecurringTask.add_input` + +Adds one or more `AnyInput` instances to the end of the current task's input list. + +This method is used to append inputs for the task to process, placing them after any inputs +already specified. + +__Arguments:__ + +- `inputs` (`AnyInput`): One or more input instances to be added to the input list. + +__Examples:__ + +```python +from zrb import Task, Input +task = Task(name='task') +email_input = Input(name='email-address') +task.add_input(email_input) +``` + + +### `RecurringTask.add_upstream` + +Adds one or more `AnyTask` instances to the end of the current task's upstream list. + +This method appends tasks to the upstream list, indicating that these tasks should be executed +before the current task, but after any tasks already in the upstream list. + +__Arguments:__ + +- `upstreams` (`TAnyTask`): One or more task instances to be added to the upstream list. + +__Examples:__ + +```python +from zrb import Task +task = Task(name='task') +upstream_task = Task(name='upstream-task') +task.add_upstream(upstream_task) +``` + + +### `RecurringTask.check` + +Checks if the current task is `ready`. + +Any other tasks depends on the current task, will be `started` once the current task is `ready`. + +This method should be implemented to define the criteria for considering the task +`ready`. The specifics of this completion depend on the task's +nature and the subclass implementation. + +__Returns:__ + +`bool`: True if the task is completed, False otherwise. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def run(self, *args: Any, **kwargs: Any) -> int: + self.print_out('Doing some calculation') + self._completed = True + return 42 + async def check(self) -> bool: + return self._completed +``` + + +### `RecurringTask.copy` + +Creates and returns a copy of the current task. + +The copied task can be modified using various setter methods like `set_name`, +`set_description`, and others, depending on the subclass implementation. + +__Returns:__ + +`TAnyTask`: A copy of the current task. + +__Examples:__ + +```python +from zrb import Task +task = Task(name='my-task', cmd='echo hello') +copied_task = task.copy() +copied_task.set_name('new_name') +``` + + +### `RecurringTask.get_cli_name` + +Gets the command-line interface (CLI) name of the task. + +This method returns the name used to invoke the task via a CLI, facilitating integration with command-line tools +or scripts. + +__Returns:__ + +`str`: The CLI name of the task. + +### `RecurringTask.get_color` + +Retrieves the color associated with the current task. + +This method returns the color of the task, useful for visual differentiation, priority indication, +or categorization in user interfaces or documentation. + +__Returns:__ + +`str`: A string representing the color assigned to the task. + +### `RecurringTask.get_description` + +Fetches the current description of the task. + +This method is used to obtain the detailed description of the task, providing insights into its purpose, +functionality, and usage within the task management system. + +__Returns:__ + +`str`: The description of the task. + +### `RecurringTask.get_env_map` + +Get a map representing task's Envs and EnvFiles + +Typically used inside `run`, `check`, or in `@python_task` decorator + +__Examples:__ + +```python +from zrb import python_task, Task, Env +@python_task(name='task', envs=[Env(name='DB_URL')]) +def task(*args, **kwargs): + task: Task = kwargs.get('_task') + for key, value in task.get_env_map(): + task.print_out(f'{key}: {value}') +``` + + +### `RecurringTask.get_execution_id` + +Retrieves the execution ID of the task. + +This method returns the unique identifier associated with the task's execution. +The execution ID is crucial for tracking, logging, and differentiating between +multiple instances or runs of the same task. + +__Returns:__ + +`str`: The unique execution ID of the task. + +### `RecurringTask.get_icon` + +Retrieves the icon identifier of the current task. + +This method is used to get the icon associated with the task, which can be utilized for +visual representation in user interfaces or documentation. + +__Returns:__ + +`str`: A string representing the icon identifier for the task + +### `RecurringTask.get_input_map` + +Get a map representing task's Inputs. + +Typically used inside `run`, `check`, or in `@python_task` decorator + +__Examples:__ + +```python +from zrb import python_task, Task, Input +@python_task(name='task', inputs=[Input(name='name')]) +def task(*args, **kwargs): + task: Task = kwargs.get('_task') + for key, value in task.get_input_map(): + task.print_out(f'{key}: {value}') +``` + + +### `RecurringTask.inject_checkers` + +Injects custom checkers into the task. + +This method allows for the addition of custom validation or condition checkers. These +checkers can be used to verify certain conditions before the task execution proceeds. +Subclasses should implement this method to define task-specific checkers. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + def inject_checkers(self): + self.add_checker(some_custom_condition_checker) +``` + + +### `RecurringTask.inject_env_files` + +Injects additional `EnvFile` into the task. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + def inject_env_files(self): + self.add_env_files(EnvFile(path='config.env')) +``` + + +### `RecurringTask.inject_envs` + +Injects environment variables into the task. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + def inject_envs(self): + self.add_envs(Env(name='DATABASE_URL')) +``` + + +### `RecurringTask.inject_inputs` + +Injects custom inputs into the task. + +This method is used to programmatically add input parameters to the task, allowing +dynamic customization of the task's input data. Subclasses should override this method +to define specific inputs that the task should receive. + +__Examples:__ + +```python +from zrb import Task, Input +class MyTask(Task): + def inject_inputs(self): + self.add_input(Input(name='user_email', type='email')) +``` + + +### `RecurringTask.inject_upstreams` + +Injects upstream tasks into the current task. + +This method is used for programmatically adding upstream dependencies to the task. +Upstream tasks are those that must be completed before the current task starts. +Override this method in subclasses to specify such dependencies. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + def inject_upstreams(self): + self.add_upstream(another_task) +``` + + +### `RecurringTask.insert_env` + +Inserts one or more `Env` instances at the beginning of the current task's environment variable list. + +This method allows for setting or overriding environment variables for the task, with earlier entries +having precedence over later ones. + +__Arguments:__ + +- `envs` (`Env`): One or more environment variable instances to be added. + +__Examples:__ + +```python +from zrb import Task, Env +task = Task(name='task') +db_url_env = Env(name='DATABASE_URL', value='postgresql://...') +task.insert_env(env_var) +``` + + +### `RecurringTask.insert_env_file` + +Inserts one or more `EnvFile` instances at the beginning of the current task's environment file list. + +This method is used to specify environment variable files whose contents should be loaded +before those of any files already in the list. This is useful for overriding or setting +additional environment configurations. + +__Arguments:__ + +- `env_files` (`EnvFile`): One or more environment file instances to be added. + +__Examples:__ + +```python +from zrb import Task, EnvFile +task = Task() +env_file = EnvFile(path='config.env') +task.insert_env_file(env_file) +``` + + +### `RecurringTask.insert_input` + +Inserts one or more `AnyInput` instances at the beginning of the current task's input list. + +This method is used to add inputs that the task will process. Inserting an input at the beginning +of the list gives it precedence over those already present. + +__Arguments:__ + +- `inputs` (`AnyInput`): One or more input instances to be added to the input list. + +__Examples:__ + +```python +from zrb import Task, Input +task = Task(name='task') +email_input = Input(name='email-address') +task.insert_input(email_input) +``` + + +### `RecurringTask.insert_upstream` + +Inserts one or more `AnyTask` instances at the beginning of the current task's upstream list. + +This method is used to define dependencies for the current task. Tasks in the upstream list are +executed before the current task. Adding a task to the beginning of the list means it will be +executed earlier than those already in the list. + +__Arguments:__ + +- `upstreams` (`TAnyTask`): One or more task instances to be added to the upstream list. + +__Examples:__ + +```python +from zrb import Task +task = Task(name='task') +upstream_task = Task(name='upstream-task') +task.insert_upstream(upstream_task) +``` + + +### `RecurringTask.log_critical` + +Log message with log level "CRITICAL" + +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + +### `RecurringTask.log_debug` + +Log message with log level "DEBUG" + +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + +### `RecurringTask.log_error` + +Log message with log level "ERROR" + +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + +### `RecurringTask.log_info` + +Log message with log level "INFO" + +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + +### `RecurringTask.log_warn` + +Log message with log level "WARNING" + +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + +### `RecurringTask.on_failed` + +Specifies the behavior when the task execution fails. + +This asynchronous method should be implemented in subclasses to handle task +failure scenarios. It can include logging the error, performing retries, or +any other failure handling mechanisms. + +__Arguments:__ + +- `is_last_attempt` (`bool`): Indicates if this is the final retry attempt. +- `exception` (`Exception`): The exception that caused the task to fail. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_failed(self, is_last_attempt: bool, exception: Exception): + if is_last_attempt: + self.print_out('The task has failed with no remaining retries') + else: + self.print_out('The task failed, retrying...') +``` + + +### `RecurringTask.on_ready` + +Defines actions to be performed when the task status is `ready`. + +This asynchronous method should be implemented in subclasses to specify +actions that occur when the task reaches the `ready` state. This can include +any cleanup, notification, or follow-up actions specific to the task. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_ready(self): + self.print_out('The task is ready') +``` + + +### `RecurringTask.on_retry` + +Defines actions to perform when the task is retried. + +Implement this method to specify behavior when the task is retried after a failure. +This could include resetting states, logging the retry attempt, or other necessary +steps before re-execution. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_retry(self): + self.log_info('Retrying task') +``` + + +### `RecurringTask.on_skipped` + +Defines actions to perform when the task status is set to `skipped`. + +Implement this method to specify behavior when the task is skipped. This could +include logging information, cleaning up resources, or any other necessary steps. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_skipped(self): + self.log_info('Task was skipped') +``` + + +### `RecurringTask.on_started` + +Defines actions to perform when the task status is set to 'started'. + +Implement this method to specify behavior when the task starts its execution. This +could involve initializing resources, logging, or other startup procedures. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_started(self): + self.log_info('Task has started') +``` + + +### `RecurringTask.on_triggered` + +Defines actions to perform when the task status is set to `triggered`. + +Implement this method to specify behavior when the task transitions to the +`triggered` state. This could involve setting up prerequisites or sending +notifications. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_triggered(self): + self.log_info('Task has been triggered') +``` + + +### `RecurringTask.on_waiting` + +Defines actions to perform when the task status is set to `waiting`. + +Implement this method to specify behavior when the task transitions to the +`waiting` state. This state usually indicates the task is waiting for some +condition or prerequisite to be met. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_waiting(self): + self.log_info('Task is waiting to be started') +``` + + +### `RecurringTask.print_err` + +Print message to stderr and style it as error. + +### `RecurringTask.print_out` + +Print message to stderr as normal text. + +### `RecurringTask.print_out_dark` + +Print message to stdout and style it as faint. + +### `RecurringTask.print_result` + +Outputs the task result to stdout for further processing. + +Override this method in subclasses to customize how the task result is displayed +or processed. Useful for integrating the task output with other systems or +command-line tools. + +__Arguments:__ + +- `result` (`Any`): The result of the task to be printed. + +__Examples:__ + +```python +from zrb import Task +# Example of overriding in a subclass +class MyTask(Task): + def print_result(self, result: Any): + print(f'Result: {result}') +``` + + +### `RecurringTask.render_any` + +Render any value. + +### `RecurringTask.render_bool` + +Render int value. + +### `RecurringTask.render_file` + +Render file content. + +### `RecurringTask.render_float` + +Render float value. + +### `RecurringTask.render_int` + +No documentation available. + + +### `RecurringTask.render_str` + +Render str value. + +### `RecurringTask.run` + +Executes the main logic of the task. + +This asynchronous method should be implemented in subclasses to define the +task's primary functionality. The specific behavior and the return value +depend on the task's nature and purpose. + +__Arguments:__ + +- `args` (`Any`): Variable length argument list. +- `kwargs` (`Any`): Arbitrary keyword arguments. + +__Returns:__ + +`Any`: The result of the task execution, the type of which is determined by +the specific task implementation. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def run(self, *args: Any, **kwargs: Any) -> int: + self.print_out('Doing some calculation') + return 42 +``` + + +### `RecurringTask.set_checking_interval` + +Sets the interval for checking the task's readiness or completion status. + +This method defines how frequently the system should check if the task is ready or completed. +It's useful for tasks that have an indeterminate completion time. + +__Arguments:__ + +- `new_checking_interval` (`Union[float, int]`): The time interval (in seconds) for readiness or checks. + +### `RecurringTask.set_color` + +Defines a new color for the current task. + +This method updates the color associated with the task. This can be useful for categorization, +priority indication, or visual differentiation in a UI. + +__Arguments:__ + +- `new_color` (`str`): A string representing the color to be assigned to the task. + +### `RecurringTask.set_description` + +Sets a new description for the current task. + +This method allows updating the task's description to provide more context or details about its purpose and behavior. +Useful for enhancing clarity and maintainability in the task management system. + +__Arguments:__ + +- `new_description` (`str`): A string representing the new description of the task. + +### `RecurringTask.set_icon` + +Assigns a new icon to the current task. + +This method is used for setting or updating the task's icon, which can be utilized for visual representation +in a user interface. The icon should ideally be a string identifier that maps to an actual graphical resource. + +__Arguments:__ + +- `new_icon` (`str`): A string representing the icon identifier for the task. + +### `RecurringTask.set_name` + +Sets a new name for the current task. + +This method is used to update the task's name, typically after creating a copy of an existing task. +The new name helps in differentiating the task in the task management system. + +__Arguments:__ + +- `new_name` (`str`): A string representing the new name to be assigned to the task. + +### `RecurringTask.set_retry` + +Sets the number of retry attempts for the task. + +This method configures how many times the task should be retried in case of failure. +It's essential for tasks that may fail transiently and need multiple attempts for successful execution. + +__Arguments:__ + +- `new_retry` (`int`): An integer representing the number of retry attempts. + +### `RecurringTask.set_retry_interval` + +Specifies the interval between retry attempts for the task. + +This method sets the duration to wait before retrying the task after a failure. +This can help in scenarios where immediate retry is not desirable or effective. + +__Arguments:__ + +- `new_retry_interval` (`Union[float, int]`): The time interval (in seconds) to wait before a retry attempt. + +### `RecurringTask.set_should_execute` + +Determines whether the task should execute. + +This method configures the execution criteria for the task. It can be set as a boolean value, +a string representing a condition, or a callable that returns a boolean. This is useful for +conditional task execution based on dynamic criteria. + +__Arguments:__ + +- `should_execute` (`Union[bool, str, Callable[..., bool]]`): The condition to determine if the task should execute. + +### `RecurringTask.to_function` + +Converts the current task into a callable function. + +This method should be implemented to allow the task to be executed as a function. +Parameters can be used to modify the behavior of the generated function, such as +raising errors, asynchronous execution, and logging. + +__Arguments:__ + +- `env_prefix` (`str`): A prefix for environment variables. +- `raise_error` (`bool`): Whether to raise an error if the task execution fails. +- `is_async` (`bool`): Whether the resulting function should be asynchronous. +- `show_done_info` (`bool`): Whether to show information upon task completion. + +__Returns:__ + +`Callable[..., Any]`: A callable representation of the task. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def run(self, *args: Any, **kwargs: Any) -> int: + self.print_out('Doing some calculation') + return 42 +``` + +``` +>>> +```python +task = MyTask() +fn = task.to_function() +fn() +``` + + + + +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task](./README.md) diff --git a/docs/concepts/task/remote-cmd-task.md b/docs/concepts/task/remote-cmd-task.md index ac5b3b86..3bb8fec9 100644 --- a/docs/concepts/task/remote-cmd-task.md +++ b/docs/concepts/task/remote-cmd-task.md @@ -1,43 +1,8 @@ -🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Tasks](README.md) +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task](./README.md) # RemoteCmdTask -```python -from zrb import ( - runner, CmdTask, RemoteCmdTask, RemoteConfig, PasswordInput -) - -install_curl = RemoteCmdTask( - name='install-curl', - inputs=[ - PasswordInput(name='passsword') - ], - remote_configs=[ - RemoteConfig( - host='192.168.1.10, - user='ubuntu, - password='{{input.password}}' - ) - ], - cmd=[ - 'sudo apt update', - 'sudo apt install curl --y' - ] -) -runner.register(install_curl) -``` - -RemoteCmdTask exposes several environments that you can use on your `cmd` and `cmd_path` - -- `_CONFIG_HOST` -- `_CONFIG_PORT` -- `_CONFIG_SSH_KEY` -- `_CONFIG_USER` -- `_CONFIG_PASSWORD` -- `_CONFIG_MAP_` - - -# Technical Documentation +# Technical Specification ## `RemoteCmdTask` @@ -238,7 +203,9 @@ No documentation available. ### `RemoteCmdTask._loop_check` -For internal use +For internal use. + +Regularly check whether the task is ready or not. ### `RemoteCmdTask._mark_awaited` @@ -257,7 +224,9 @@ No documentation available. ### `RemoteCmdTask._print_result` -For internal use +For internal use. + +Directly call `print_result` ### `RemoteCmdTask._propagate_execution_id` @@ -266,7 +235,9 @@ No documentation available. ### `RemoteCmdTask._run_all` -For internal use +For internal use. + +Run this task and all its upstreams. ### `RemoteCmdTask._run_and_check_all` @@ -310,7 +281,9 @@ No documentation available. ### `RemoteCmdTask._set_keyval` -For internal use +For internal use. + +Set current task's key values. ### `RemoteCmdTask._set_kwargs` @@ -521,7 +494,20 @@ __Returns:__ ### `RemoteCmdTask.get_env_map` -No documentation available. +Get a map representing task's Envs and EnvFiles + +Typically used inside `run`, `check`, or in `@python_task` decorator + +__Examples:__ + +```python +from zrb import python_task, Task, Env +@python_task(name='task', envs=[Env(name='DB_URL')]) +def task(*args, **kwargs): + task: Task = kwargs.get('_task') + for key, value in task.get_env_map(): + task.print_out(f'{key}: {value}') +``` ### `RemoteCmdTask.get_execution_id` @@ -549,7 +535,20 @@ __Returns:__ ### `RemoteCmdTask.get_input_map` -No documentation available. +Get a map representing task's Inputs. + +Typically used inside `run`, `check`, or in `@python_task` decorator + +__Examples:__ + +```python +from zrb import python_task, Task, Input +@python_task(name='task', inputs=[Input(name='name')]) +def task(*args, **kwargs): + task: Task = kwargs.get('_task') + for key, value in task.get_input_map(): + task.print_out(f'{key}: {value}') +``` ### `RemoteCmdTask.inject_checkers` @@ -722,28 +721,33 @@ task.insert_upstream(upstream_task) ### `RemoteCmdTask.log_critical` -No documentation available. +Log message with log level "CRITICAL" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment ### `RemoteCmdTask.log_debug` -No documentation available. +Log message with log level "DEBUG" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment ### `RemoteCmdTask.log_error` -No documentation available. +Log message with log level "ERROR" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment ### `RemoteCmdTask.log_info` -No documentation available. +Log message with log level "INFO" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment ### `RemoteCmdTask.log_warn` -No documentation available. +Log message with log level "WARNING" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment ### `RemoteCmdTask.on_failed` @@ -879,18 +883,15 @@ class MyTask(Task): ### `RemoteCmdTask.print_err` -No documentation available. - +Print message to stderr and style it as error. ### `RemoteCmdTask.print_out` -No documentation available. - +Print message to stderr as normal text. ### `RemoteCmdTask.print_out_dark` -No documentation available. - +Print message to stdout and style it as faint. ### `RemoteCmdTask.print_result` @@ -906,31 +907,30 @@ __Arguments:__ __Examples:__ ->> from zrb import Task ->> # Example of overriding in a subclass ->> class MyTask(Task): ->> def print_result(self, result: Any): ->> print(f'Result: {result}') +```python +from zrb import Task +# Example of overriding in a subclass +class MyTask(Task): + def print_result(self, result: Any): + print(f'Result: {result}') +``` -### `RemoteCmdTask.render_any` -No documentation available. +### `RemoteCmdTask.render_any` +Render any value. ### `RemoteCmdTask.render_bool` -No documentation available. - +Render int value. ### `RemoteCmdTask.render_file` -No documentation available. - +Render file content. ### `RemoteCmdTask.render_float` -No documentation available. - +Render float value. ### `RemoteCmdTask.render_int` @@ -939,8 +939,7 @@ No documentation available. ### `RemoteCmdTask.render_str` -No documentation available. - +Render str value. ### `RemoteCmdTask.run` @@ -1100,4 +1099,4 @@ fn() -🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Tasks](README.md) +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task](./README.md) diff --git a/docs/concepts/task/resource-maker.md b/docs/concepts/task/resource-maker.md index 79846077..3141b97c 100644 --- a/docs/concepts/task/resource-maker.md +++ b/docs/concepts/task/resource-maker.md @@ -1,65 +1,8 @@ -🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Tasks](README.md) +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task](./README.md) # ResourceMaker -ResourceMaker helps you create text resources, whether they are code or licenses. - -For example, let's say you have the following template under `mit-license-template/license` - -``` -Copyright (c) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -``` - -You want your user to be able to add the license to any app and replacing `` and `` with user input. - -To accomplish this, you can make a resource maker: - -```python -from zrb import ResourceMaker, StrInput, runner -import os - -CURRENT_DIR = os.path.dirname(__file__) - -add_mit_license = ResourceMaker( - name='add-mit-license', - inputs=[ - StrInput(name='destination'), - StrInput(name='year'), - StrInput(name='copyright-holder') - ], - destination_path='{{input.destination}}', - template_path=os.path.join(CURRENT_DIR, 'mit-license-template'), - replacements={ - '': '{{input.year}}', - '': '{{input.copyright_holder}}', - } -) - -runner.register(add_mit_license) -``` - -Note that your template folder might contains a very complex structure. For example, you can make your application boiler plate into a template. - - -# Technical Documentation +# Technical Specification ## `ResourceMaker` @@ -265,7 +208,9 @@ No documentation available. ### `ResourceMaker._loop_check` -For internal use +For internal use. + +Regularly check whether the task is ready or not. ### `ResourceMaker._mark_awaited` @@ -284,7 +229,9 @@ No documentation available. ### `ResourceMaker._print_result` -For internal use +For internal use. + +Directly call `print_result` ### `ResourceMaker._propagate_execution_id` @@ -293,7 +240,9 @@ No documentation available. ### `ResourceMaker._run_all` -For internal use +For internal use. + +Run this task and all its upstreams. ### `ResourceMaker._run_and_check_all` @@ -337,7 +286,9 @@ No documentation available. ### `ResourceMaker._set_keyval` -For internal use +For internal use. + +Set current task's key values. ### `ResourceMaker._set_kwargs` @@ -553,7 +504,20 @@ __Returns:__ ### `ResourceMaker.get_env_map` -No documentation available. +Get a map representing task's Envs and EnvFiles + +Typically used inside `run`, `check`, or in `@python_task` decorator + +__Examples:__ + +```python +from zrb import python_task, Task, Env +@python_task(name='task', envs=[Env(name='DB_URL')]) +def task(*args, **kwargs): + task: Task = kwargs.get('_task') + for key, value in task.get_env_map(): + task.print_out(f'{key}: {value}') +``` ### `ResourceMaker.get_execution_id` @@ -581,7 +545,20 @@ __Returns:__ ### `ResourceMaker.get_input_map` -No documentation available. +Get a map representing task's Inputs. + +Typically used inside `run`, `check`, or in `@python_task` decorator + +__Examples:__ + +```python +from zrb import python_task, Task, Input +@python_task(name='task', inputs=[Input(name='name')]) +def task(*args, **kwargs): + task: Task = kwargs.get('_task') + for key, value in task.get_input_map(): + task.print_out(f'{key}: {value}') +``` ### `ResourceMaker.inject_checkers` @@ -754,28 +731,33 @@ task.insert_upstream(upstream_task) ### `ResourceMaker.log_critical` -No documentation available. +Log message with log level "CRITICAL" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment ### `ResourceMaker.log_debug` -No documentation available. +Log message with log level "DEBUG" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment ### `ResourceMaker.log_error` -No documentation available. +Log message with log level "ERROR" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment ### `ResourceMaker.log_info` -No documentation available. +Log message with log level "INFO" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment ### `ResourceMaker.log_warn` -No documentation available. +Log message with log level "WARNING" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment ### `ResourceMaker.on_failed` @@ -911,18 +893,15 @@ class MyTask(Task): ### `ResourceMaker.print_err` -No documentation available. - +Print message to stderr and style it as error. ### `ResourceMaker.print_out` -No documentation available. - +Print message to stderr as normal text. ### `ResourceMaker.print_out_dark` -No documentation available. - +Print message to stdout and style it as faint. ### `ResourceMaker.print_result` @@ -938,31 +917,30 @@ __Arguments:__ __Examples:__ ->> from zrb import Task ->> # Example of overriding in a subclass ->> class MyTask(Task): ->> def print_result(self, result: Any): ->> print(f'Result: {result}') +```python +from zrb import Task +# Example of overriding in a subclass +class MyTask(Task): + def print_result(self, result: Any): + print(f'Result: {result}') +``` + ### `ResourceMaker.render_any` -No documentation available. - +Render any value. ### `ResourceMaker.render_bool` -No documentation available. - +Render int value. ### `ResourceMaker.render_file` -No documentation available. - +Render file content. ### `ResourceMaker.render_float` -No documentation available. - +Render float value. ### `ResourceMaker.render_int` @@ -971,8 +949,7 @@ No documentation available. ### `ResourceMaker.render_str` -No documentation available. - +Render str value. ### `ResourceMaker.run` @@ -1132,4 +1109,4 @@ fn() -🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Tasks](README.md) +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task](./README.md) diff --git a/docs/concepts/task/rsync-task.md b/docs/concepts/task/rsync-task.md index e7d30e79..ba17c289 100644 --- a/docs/concepts/task/rsync-task.md +++ b/docs/concepts/task/rsync-task.md @@ -1,69 +1,8 @@ -🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Tasks](README.md) +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task](./README.md) -# RsyncTask +# RyncTask -```python -from zrb import ( - runner, CmdTask, RsyncTask, RemoteConfig, PasswordInput, StrInput -) - -upload = RsyncTask( - name='upload', - inputs=[ - PasswordInput(name='passsword'), - StrInput(name='src'), - StrInput(name='dst'), - ], - remote_configs=[ - RemoteConfig( - host='192.168.1.10, - user='ubuntu, - password='{{input.password}}', - config_map={ - 'dir': '192-168-1-10' - } - ) - ], - is_remote_src=False, - src='$_CONFIG_MAP_DIR/{{input.src}}', - is_remote_dst=True, - dst='{{input.dst}}', -) -runner.register(upload) - -download = RsyncTask( - name='download', - inputs=[ - PasswordInput(name='passsword'), - StrInput(name='src'), - StrInput(name='dst'), - ], - remote_configs=[ - RemoteConfig( - host='192.168.1.10, - user='ubuntu, - password='{{input.password}}' - ) - ], - is_remote_src=True, - src='{{input.src}}', - is_remote_dst=False, - dst='$_CONFIG_MAP_DIR/{{input.dst}}', -) -runner.register(download) -``` - -RsyncTask exposes several environments that you can use on your `src` and `dst` - -- `_CONFIG_HOST` -- `_CONFIG_PORT` -- `_CONFIG_SSH_KEY` -- `_CONFIG_USER` -- `_CONFIG_PASSWORD` -- `_CONFIG_MAP_` - - -# Technical Documentation +# Technical Specification ## `RsyncTask` @@ -269,7 +208,9 @@ No documentation available. ### `RsyncTask._loop_check` -For internal use +For internal use. + +Regularly check whether the task is ready or not. ### `RsyncTask._mark_awaited` @@ -288,7 +229,9 @@ No documentation available. ### `RsyncTask._print_result` -For internal use +For internal use. + +Directly call `print_result` ### `RsyncTask._propagate_execution_id` @@ -297,7 +240,9 @@ No documentation available. ### `RsyncTask._run_all` -For internal use +For internal use. + +Run this task and all its upstreams. ### `RsyncTask._run_and_check_all` @@ -341,7 +286,9 @@ No documentation available. ### `RsyncTask._set_keyval` -For internal use +For internal use. + +Set current task's key values. ### `RsyncTask._set_kwargs` @@ -552,7 +499,20 @@ __Returns:__ ### `RsyncTask.get_env_map` -No documentation available. +Get a map representing task's Envs and EnvFiles + +Typically used inside `run`, `check`, or in `@python_task` decorator + +__Examples:__ + +```python +from zrb import python_task, Task, Env +@python_task(name='task', envs=[Env(name='DB_URL')]) +def task(*args, **kwargs): + task: Task = kwargs.get('_task') + for key, value in task.get_env_map(): + task.print_out(f'{key}: {value}') +``` ### `RsyncTask.get_execution_id` @@ -580,7 +540,20 @@ __Returns:__ ### `RsyncTask.get_input_map` -No documentation available. +Get a map representing task's Inputs. + +Typically used inside `run`, `check`, or in `@python_task` decorator + +__Examples:__ + +```python +from zrb import python_task, Task, Input +@python_task(name='task', inputs=[Input(name='name')]) +def task(*args, **kwargs): + task: Task = kwargs.get('_task') + for key, value in task.get_input_map(): + task.print_out(f'{key}: {value}') +``` ### `RsyncTask.inject_checkers` @@ -753,28 +726,33 @@ task.insert_upstream(upstream_task) ### `RsyncTask.log_critical` -No documentation available. +Log message with log level "CRITICAL" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment ### `RsyncTask.log_debug` -No documentation available. +Log message with log level "DEBUG" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment ### `RsyncTask.log_error` -No documentation available. +Log message with log level "ERROR" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment ### `RsyncTask.log_info` -No documentation available. +Log message with log level "INFO" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment ### `RsyncTask.log_warn` -No documentation available. +Log message with log level "WARNING" +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment ### `RsyncTask.on_failed` @@ -910,18 +888,15 @@ class MyTask(Task): ### `RsyncTask.print_err` -No documentation available. - +Print message to stderr and style it as error. ### `RsyncTask.print_out` -No documentation available. - +Print message to stderr as normal text. ### `RsyncTask.print_out_dark` -No documentation available. - +Print message to stdout and style it as faint. ### `RsyncTask.print_result` @@ -937,31 +912,30 @@ __Arguments:__ __Examples:__ ->> from zrb import Task ->> # Example of overriding in a subclass ->> class MyTask(Task): ->> def print_result(self, result: Any): ->> print(f'Result: {result}') +```python +from zrb import Task +# Example of overriding in a subclass +class MyTask(Task): + def print_result(self, result: Any): + print(f'Result: {result}') +``` -### `RsyncTask.render_any` -No documentation available. +### `RsyncTask.render_any` +Render any value. ### `RsyncTask.render_bool` -No documentation available. - +Render int value. ### `RsyncTask.render_file` -No documentation available. - +Render file content. ### `RsyncTask.render_float` -No documentation available. - +Render float value. ### `RsyncTask.render_int` @@ -970,8 +944,7 @@ No documentation available. ### `RsyncTask.render_str` -No documentation available. - +Render str value. ### `RsyncTask.run` @@ -1131,4 +1104,4 @@ fn() -🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Tasks](README.md) +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task](./README.md) diff --git a/docs/concepts/task/time-watcher.md b/docs/concepts/task/time-watcher.md new file mode 100644 index 00000000..b115a7b4 --- /dev/null +++ b/docs/concepts/task/time-watcher.md @@ -0,0 +1,1112 @@ +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task](./README.md) + +# TimeWatcher + +# Technical Specification + + +## `TimeWatcher` + +Base class for all tasks. +Every task definition should be extended from this class. + +### `TimeWatcher._BaseTaskModel__get_colored` + +No documentation available. + + +### `TimeWatcher._BaseTaskModel__get_colored_print_prefix` + +No documentation available. + + +### `TimeWatcher._BaseTaskModel__get_common_prefix` + +No documentation available. + + +### `TimeWatcher._BaseTaskModel__get_executable_name` + +No documentation available. + + +### `TimeWatcher._BaseTaskModel__get_log_prefix` + +No documentation available. + + +### `TimeWatcher._BaseTaskModel__get_print_prefix` + +No documentation available. + + +### `TimeWatcher._BaseTaskModel__get_rjust_full_cli_name` + +No documentation available. + + +### `TimeWatcher._Renderer__ensure_cached_render_data` + +No documentation available. + + +### `TimeWatcher._Renderer__get_render_data` + +No documentation available. + + +### `TimeWatcher._cached_check` + +No documentation available. + + +### `TimeWatcher._cached_run` + +No documentation available. + + +### `TimeWatcher._check` + +Check current task readiness. +- If self.checkers is defined, +this will return True once every self.checkers is completed +- Otherwise, this will return check method's return value. + +### `TimeWatcher._check_should_execute` + +No documentation available. + + +### `TimeWatcher._end_timer` + +No documentation available. + + +### `TimeWatcher._get_attempt` + +No documentation available. + + +### `TimeWatcher._get_checkers` + +Retrieves the checkers set for the task. + +This internal method returns an iterable of all the checkers that have been added to +the task. It's mainly used for internal logic and debugging to understand the +validations or conditions applied to the task. + +__Returns:__ + +`Iterable[TAnyTask]`: An iterable of checkers associated with the task. + +### `TimeWatcher._get_combined_env` + +No documentation available. + + +### `TimeWatcher._get_combined_inputs` + +' +Getting all inputs of this task and all its upstream, non-duplicated. + +### `TimeWatcher._get_elapsed_time` + +No documentation available. + + +### `TimeWatcher._get_env_files` + +Retrieves the list of environment variable files associated with the task. + +Intended for internal use, this method returns a list of `EnvFile` instances that the task +uses to load environment variables, primarily for setup and configuration purposes. + +__Returns:__ + +`List[EnvFile]`: A list of `EnvFile` instances associated with the task. + +### `TimeWatcher._get_envs` + +Retrieves the list of environment variables set for the task. + +For internal use, this method returns a list of `Env` instances representing the environment variables +configured for the task, essential for understanding and debugging the task's environment setup. + +__Returns:__ + +`List[Env]`: A list of `Env` instances representing the environment variables of the task. + +### `TimeWatcher._get_full_cli_name` + +Retrieves the full command-line interface (CLI) name of the task. + +Intended for internal use, this method provides the complete CLI name, including any +prefixes or namespaces, used primarily for logging or debugging purposes. + +__Returns:__ + +`str`: The full CLI name of the task. + +### `TimeWatcher._get_inputs` + +Retrieves the list of inputs associated with the task. + +This internal method is used to obtain all the inputs that have been set for the task, +either through static definition or via the `inject_inputs` method. It's primarily used +for introspection and debugging purposes. + +__Returns:__ + +`List[AnyInput]`: A list of `AnyInput` instances representing the inputs for the task. + +### `TimeWatcher._get_max_attempt` + +No documentation available. + + +### `TimeWatcher._get_task_pid` + +No documentation available. + + +### `TimeWatcher._get_upstreams` + +Retrieves the upstream tasks of the current task. + +An internal method to get the list of upstream tasks that have been set for the +task, either statically or through `inject_upstreams`. This is essential for task +scheduling and dependency management. + +__Returns:__ + +`Iterable[TAnyTask]`: An iterable of upstream tasks. + +### `TimeWatcher._increase_attempt` + +No documentation available. + + +### `TimeWatcher._is_done` + +No documentation available. + + +### `TimeWatcher._is_last_attempt` + +No documentation available. + + +### `TimeWatcher._lock_upstreams` + +No documentation available. + + +### `TimeWatcher._loop_check` + +For internal use. + +Regularly check whether the task is ready or not. + +### `TimeWatcher._mark_awaited` + +No documentation available. + + +### `TimeWatcher._mark_done` + +No documentation available. + + +### `TimeWatcher._play_bell` + +No documentation available. + + +### `TimeWatcher._print_result` + +For internal use. + +Directly call `print_result` + +### `TimeWatcher._propagate_execution_id` + +No documentation available. + + +### `TimeWatcher._run_all` + +For internal use. + +Run this task and all its upstreams. + +### `TimeWatcher._run_and_check_all` + +No documentation available. + + +### `TimeWatcher._set_args` + +No documentation available. + + +### `TimeWatcher._set_env_map` + +No documentation available. + + +### `TimeWatcher._set_execution_id` + +Sets the execution ID for the current task. + +This method is intended for internal use to assign a unique identifier to the task's execution. +This ID can be used for tracking, logging, and inter-task communication. + +This method should not be used externally, as it is meant to be managed within the task system. + +__Arguments:__ + +- `execution_id` (`str`): A string representing the unique execution ID. + +### `TimeWatcher._set_has_cli_interface` + +Marks the task as having a CLI interface. + +This internal method is used to indicate that the task is accessible and executable through a CLI, +enabling the task system to appropriately handle its CLI interactions. + +### `TimeWatcher._set_input_map` + +No documentation available. + + +### `TimeWatcher._set_keyval` + +For internal use. + +Set current task's key values. + +### `TimeWatcher._set_kwargs` + +No documentation available. + + +### `TimeWatcher._set_local_keyval` + +No documentation available. + + +### `TimeWatcher._set_task_pid` + +No documentation available. + + +### `TimeWatcher._should_attempt` + +No documentation available. + + +### `TimeWatcher._show_done_info` + +No documentation available. + + +### `TimeWatcher._show_env_prefix` + +No documentation available. + + +### `TimeWatcher._show_run_command` + +No documentation available. + + +### `TimeWatcher._start_timer` + +No documentation available. + + +### `TimeWatcher.add_env` + +Adds one or more `Env` instances to the end of the current task's environment variable list. + +Use this method to append environment variables for the task, which will be used after +any variables already set. + +__Arguments:__ + +- `envs` (`Env`): One or more environment variable instances to be added. + +__Examples:__ + +```python +from zrb import Task, Env +task = Task(name='task') +db_url_env = Env(name='DATABASE_URL', value='postgresql://...') +task.add_env(env_var) +``` + + +### `TimeWatcher.add_env_file` + +Adds one or more `EnvFile` instances to the end of the current task's environment file list. + +Use this method to append environment file references, which will be processed after +any files already specified. This allows for supplementing the existing environment +configuration. + +__Arguments:__ + +- `env_files` (`EnvFile`): One or more environment file instances to be added. + +__Examples:__ + +```python +from zrb import Task, EnvFile +task = Task() +env_file = EnvFile(path='config.env') +task.add_env_file(env_file) +``` + + +### `TimeWatcher.add_input` + +Adds one or more `AnyInput` instances to the end of the current task's input list. + +This method is used to append inputs for the task to process, placing them after any inputs +already specified. + +__Arguments:__ + +- `inputs` (`AnyInput`): One or more input instances to be added to the input list. + +__Examples:__ + +```python +from zrb import Task, Input +task = Task(name='task') +email_input = Input(name='email-address') +task.add_input(email_input) +``` + + +### `TimeWatcher.add_upstream` + +Adds one or more `AnyTask` instances to the end of the current task's upstream list. + +This method appends tasks to the upstream list, indicating that these tasks should be executed +before the current task, but after any tasks already in the upstream list. + +__Arguments:__ + +- `upstreams` (`TAnyTask`): One or more task instances to be added to the upstream list. + +__Examples:__ + +```python +from zrb import Task +task = Task(name='task') +upstream_task = Task(name='upstream-task') +task.add_upstream(upstream_task) +``` + + +### `TimeWatcher.check` + +Checks if the current task is `ready`. + +Any other tasks depends on the current task, will be `started` once the current task is `ready`. + +This method should be implemented to define the criteria for considering the task +`ready`. The specifics of this completion depend on the task's +nature and the subclass implementation. + +__Returns:__ + +`bool`: True if the task is completed, False otherwise. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def run(self, *args: Any, **kwargs: Any) -> int: + self.print_out('Doing some calculation') + self._completed = True + return 42 + async def check(self) -> bool: + return self._completed +``` + + +### `TimeWatcher.copy` + +Creates and returns a copy of the current task. + +The copied task can be modified using various setter methods like `set_name`, +`set_description`, and others, depending on the subclass implementation. + +__Returns:__ + +`TAnyTask`: A copy of the current task. + +__Examples:__ + +```python +from zrb import Task +task = Task(name='my-task', cmd='echo hello') +copied_task = task.copy() +copied_task.set_name('new_name') +``` + + +### `TimeWatcher.get_cli_name` + +Gets the command-line interface (CLI) name of the task. + +This method returns the name used to invoke the task via a CLI, facilitating integration with command-line tools +or scripts. + +__Returns:__ + +`str`: The CLI name of the task. + +### `TimeWatcher.get_color` + +Retrieves the color associated with the current task. + +This method returns the color of the task, useful for visual differentiation, priority indication, +or categorization in user interfaces or documentation. + +__Returns:__ + +`str`: A string representing the color assigned to the task. + +### `TimeWatcher.get_description` + +Fetches the current description of the task. + +This method is used to obtain the detailed description of the task, providing insights into its purpose, +functionality, and usage within the task management system. + +__Returns:__ + +`str`: The description of the task. + +### `TimeWatcher.get_env_map` + +Get a map representing task's Envs and EnvFiles + +Typically used inside `run`, `check`, or in `@python_task` decorator + +__Examples:__ + +```python +from zrb import python_task, Task, Env +@python_task(name='task', envs=[Env(name='DB_URL')]) +def task(*args, **kwargs): + task: Task = kwargs.get('_task') + for key, value in task.get_env_map(): + task.print_out(f'{key}: {value}') +``` + + +### `TimeWatcher.get_execution_id` + +Retrieves the execution ID of the task. + +This method returns the unique identifier associated with the task's execution. +The execution ID is crucial for tracking, logging, and differentiating between +multiple instances or runs of the same task. + +__Returns:__ + +`str`: The unique execution ID of the task. + +### `TimeWatcher.get_icon` + +Retrieves the icon identifier of the current task. + +This method is used to get the icon associated with the task, which can be utilized for +visual representation in user interfaces or documentation. + +__Returns:__ + +`str`: A string representing the icon identifier for the task + +### `TimeWatcher.get_input_map` + +Get a map representing task's Inputs. + +Typically used inside `run`, `check`, or in `@python_task` decorator + +__Examples:__ + +```python +from zrb import python_task, Task, Input +@python_task(name='task', inputs=[Input(name='name')]) +def task(*args, **kwargs): + task: Task = kwargs.get('_task') + for key, value in task.get_input_map(): + task.print_out(f'{key}: {value}') +``` + + +### `TimeWatcher.inject_checkers` + +Injects custom checkers into the task. + +This method allows for the addition of custom validation or condition checkers. These +checkers can be used to verify certain conditions before the task execution proceeds. +Subclasses should implement this method to define task-specific checkers. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + def inject_checkers(self): + self.add_checker(some_custom_condition_checker) +``` + + +### `TimeWatcher.inject_env_files` + +Injects additional `EnvFile` into the task. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + def inject_env_files(self): + self.add_env_files(EnvFile(path='config.env')) +``` + + +### `TimeWatcher.inject_envs` + +Injects environment variables into the task. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + def inject_envs(self): + self.add_envs(Env(name='DATABASE_URL')) +``` + + +### `TimeWatcher.inject_inputs` + +Injects custom inputs into the task. + +This method is used to programmatically add input parameters to the task, allowing +dynamic customization of the task's input data. Subclasses should override this method +to define specific inputs that the task should receive. + +__Examples:__ + +```python +from zrb import Task, Input +class MyTask(Task): + def inject_inputs(self): + self.add_input(Input(name='user_email', type='email')) +``` + + +### `TimeWatcher.inject_upstreams` + +Injects upstream tasks into the current task. + +This method is used for programmatically adding upstream dependencies to the task. +Upstream tasks are those that must be completed before the current task starts. +Override this method in subclasses to specify such dependencies. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + def inject_upstreams(self): + self.add_upstream(another_task) +``` + + +### `TimeWatcher.insert_env` + +Inserts one or more `Env` instances at the beginning of the current task's environment variable list. + +This method allows for setting or overriding environment variables for the task, with earlier entries +having precedence over later ones. + +__Arguments:__ + +- `envs` (`Env`): One or more environment variable instances to be added. + +__Examples:__ + +```python +from zrb import Task, Env +task = Task(name='task') +db_url_env = Env(name='DATABASE_URL', value='postgresql://...') +task.insert_env(env_var) +``` + + +### `TimeWatcher.insert_env_file` + +Inserts one or more `EnvFile` instances at the beginning of the current task's environment file list. + +This method is used to specify environment variable files whose contents should be loaded +before those of any files already in the list. This is useful for overriding or setting +additional environment configurations. + +__Arguments:__ + +- `env_files` (`EnvFile`): One or more environment file instances to be added. + +__Examples:__ + +```python +from zrb import Task, EnvFile +task = Task() +env_file = EnvFile(path='config.env') +task.insert_env_file(env_file) +``` + + +### `TimeWatcher.insert_input` + +Inserts one or more `AnyInput` instances at the beginning of the current task's input list. + +This method is used to add inputs that the task will process. Inserting an input at the beginning +of the list gives it precedence over those already present. + +__Arguments:__ + +- `inputs` (`AnyInput`): One or more input instances to be added to the input list. + +__Examples:__ + +```python +from zrb import Task, Input +task = Task(name='task') +email_input = Input(name='email-address') +task.insert_input(email_input) +``` + + +### `TimeWatcher.insert_upstream` + +Inserts one or more `AnyTask` instances at the beginning of the current task's upstream list. + +This method is used to define dependencies for the current task. Tasks in the upstream list are +executed before the current task. Adding a task to the beginning of the list means it will be +executed earlier than those already in the list. + +__Arguments:__ + +- `upstreams` (`TAnyTask`): One or more task instances to be added to the upstream list. + +__Examples:__ + +```python +from zrb import Task +task = Task(name='task') +upstream_task = Task(name='upstream-task') +task.insert_upstream(upstream_task) +``` + + +### `TimeWatcher.inspect` + +No documentation available. + + +### `TimeWatcher.log_critical` + +Log message with log level "CRITICAL" + +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + +### `TimeWatcher.log_debug` + +Log message with log level "DEBUG" + +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + +### `TimeWatcher.log_error` + +Log message with log level "ERROR" + +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + +### `TimeWatcher.log_info` + +Log message with log level "INFO" + +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + +### `TimeWatcher.log_warn` + +Log message with log level "WARNING" + +You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + +### `TimeWatcher.on_failed` + +Specifies the behavior when the task execution fails. + +This asynchronous method should be implemented in subclasses to handle task +failure scenarios. It can include logging the error, performing retries, or +any other failure handling mechanisms. + +__Arguments:__ + +- `is_last_attempt` (`bool`): Indicates if this is the final retry attempt. +- `exception` (`Exception`): The exception that caused the task to fail. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_failed(self, is_last_attempt: bool, exception: Exception): + if is_last_attempt: + self.print_out('The task has failed with no remaining retries') + else: + self.print_out('The task failed, retrying...') +``` + + +### `TimeWatcher.on_ready` + +Defines actions to be performed when the task status is `ready`. + +This asynchronous method should be implemented in subclasses to specify +actions that occur when the task reaches the `ready` state. This can include +any cleanup, notification, or follow-up actions specific to the task. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_ready(self): + self.print_out('The task is ready') +``` + + +### `TimeWatcher.on_retry` + +Defines actions to perform when the task is retried. + +Implement this method to specify behavior when the task is retried after a failure. +This could include resetting states, logging the retry attempt, or other necessary +steps before re-execution. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_retry(self): + self.log_info('Retrying task') +``` + + +### `TimeWatcher.on_skipped` + +Defines actions to perform when the task status is set to `skipped`. + +Implement this method to specify behavior when the task is skipped. This could +include logging information, cleaning up resources, or any other necessary steps. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_skipped(self): + self.log_info('Task was skipped') +``` + + +### `TimeWatcher.on_started` + +Defines actions to perform when the task status is set to 'started'. + +Implement this method to specify behavior when the task starts its execution. This +could involve initializing resources, logging, or other startup procedures. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_started(self): + self.log_info('Task has started') +``` + + +### `TimeWatcher.on_triggered` + +Defines actions to perform when the task status is set to `triggered`. + +Implement this method to specify behavior when the task transitions to the +`triggered` state. This could involve setting up prerequisites or sending +notifications. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_triggered(self): + self.log_info('Task has been triggered') +``` + + +### `TimeWatcher.on_waiting` + +Defines actions to perform when the task status is set to `waiting`. + +Implement this method to specify behavior when the task transitions to the +`waiting` state. This state usually indicates the task is waiting for some +condition or prerequisite to be met. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def on_waiting(self): + self.log_info('Task is waiting to be started') +``` + + +### `TimeWatcher.print_err` + +Print message to stderr and style it as error. + +### `TimeWatcher.print_out` + +Print message to stderr as normal text. + +### `TimeWatcher.print_out_dark` + +Print message to stdout and style it as faint. + +### `TimeWatcher.print_result` + +Outputs the task result to stdout for further processing. + +Override this method in subclasses to customize how the task result is displayed +or processed. Useful for integrating the task output with other systems or +command-line tools. + +__Arguments:__ + +- `result` (`Any`): The result of the task to be printed. + +__Examples:__ + +```python +from zrb import Task +# Example of overriding in a subclass +class MyTask(Task): + def print_result(self, result: Any): + print(f'Result: {result}') +``` + + +### `TimeWatcher.render_any` + +Render any value. + +### `TimeWatcher.render_bool` + +Render int value. + +### `TimeWatcher.render_file` + +Render file content. + +### `TimeWatcher.render_float` + +Render float value. + +### `TimeWatcher.render_int` + +No documentation available. + + +### `TimeWatcher.render_str` + +Render str value. + +### `TimeWatcher.run` + +Executes the main logic of the task. + +This asynchronous method should be implemented in subclasses to define the +task's primary functionality. The specific behavior and the return value +depend on the task's nature and purpose. + +__Arguments:__ + +- `args` (`Any`): Variable length argument list. +- `kwargs` (`Any`): Arbitrary keyword arguments. + +__Returns:__ + +`Any`: The result of the task execution, the type of which is determined by +the specific task implementation. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def run(self, *args: Any, **kwargs: Any) -> int: + self.print_out('Doing some calculation') + return 42 +``` + + +### `TimeWatcher.set_checking_interval` + +Sets the interval for checking the task's readiness or completion status. + +This method defines how frequently the system should check if the task is ready or completed. +It's useful for tasks that have an indeterminate completion time. + +__Arguments:__ + +- `new_checking_interval` (`Union[float, int]`): The time interval (in seconds) for readiness or checks. + +### `TimeWatcher.set_color` + +Defines a new color for the current task. + +This method updates the color associated with the task. This can be useful for categorization, +priority indication, or visual differentiation in a UI. + +__Arguments:__ + +- `new_color` (`str`): A string representing the color to be assigned to the task. + +### `TimeWatcher.set_description` + +Sets a new description for the current task. + +This method allows updating the task's description to provide more context or details about its purpose and behavior. +Useful for enhancing clarity and maintainability in the task management system. + +__Arguments:__ + +- `new_description` (`str`): A string representing the new description of the task. + +### `TimeWatcher.set_icon` + +Assigns a new icon to the current task. + +This method is used for setting or updating the task's icon, which can be utilized for visual representation +in a user interface. The icon should ideally be a string identifier that maps to an actual graphical resource. + +__Arguments:__ + +- `new_icon` (`str`): A string representing the icon identifier for the task. + +### `TimeWatcher.set_name` + +Sets a new name for the current task. + +This method is used to update the task's name, typically after creating a copy of an existing task. +The new name helps in differentiating the task in the task management system. + +__Arguments:__ + +- `new_name` (`str`): A string representing the new name to be assigned to the task. + +### `TimeWatcher.set_retry` + +Sets the number of retry attempts for the task. + +This method configures how many times the task should be retried in case of failure. +It's essential for tasks that may fail transiently and need multiple attempts for successful execution. + +__Arguments:__ + +- `new_retry` (`int`): An integer representing the number of retry attempts. + +### `TimeWatcher.set_retry_interval` + +Specifies the interval between retry attempts for the task. + +This method sets the duration to wait before retrying the task after a failure. +This can help in scenarios where immediate retry is not desirable or effective. + +__Arguments:__ + +- `new_retry_interval` (`Union[float, int]`): The time interval (in seconds) to wait before a retry attempt. + +### `TimeWatcher.set_should_execute` + +Determines whether the task should execute. + +This method configures the execution criteria for the task. It can be set as a boolean value, +a string representing a condition, or a callable that returns a boolean. This is useful for +conditional task execution based on dynamic criteria. + +__Arguments:__ + +- `should_execute` (`Union[bool, str, Callable[..., bool]]`): The condition to determine if the task should execute. + +### `TimeWatcher.show_progress` + +No documentation available. + + +### `TimeWatcher.to_function` + +Converts the current task into a callable function. + +This method should be implemented to allow the task to be executed as a function. +Parameters can be used to modify the behavior of the generated function, such as +raising errors, asynchronous execution, and logging. + +__Arguments:__ + +- `env_prefix` (`str`): A prefix for environment variables. +- `raise_error` (`bool`): Whether to raise an error if the task execution fails. +- `is_async` (`bool`): Whether the resulting function should be asynchronous. +- `show_done_info` (`bool`): Whether to show information upon task completion. + +__Returns:__ + +`Callable[..., Any]`: A callable representation of the task. + +__Examples:__ + +```python +from zrb import Task +class MyTask(Task): + async def run(self, *args: Any, **kwargs: Any) -> int: + self.print_out('Doing some calculation') + return 42 +``` + +``` +>>> +```python +task = MyTask() +fn = task.to_function() +fn() +``` + + + + +🔖 [Table of Contents](../../README.md) / [Concepts](../README.md) / [Task](./README.md) diff --git a/src/zrb/helper/docstring.py b/src/zrb/helper/docstring.py index 4457060b..b1d00ebc 100644 --- a/src/zrb/helper/docstring.py +++ b/src/zrb/helper/docstring.py @@ -78,11 +78,21 @@ def parse_docstring(docstring: str) -> str: # Handle lines if is_code: markdown_lines.append(line[4:]) - elif line.startswith('Attributes:'): + elif ( + line.startswith('Attributes:') or + line.startswith('Attribute:') or + line.startswith('Attrs:') or + line.startswith('Attr:') + ): markdown_lines.append('__Attributes:__\n') section = 'attributes' is_new_section = True - elif line.startswith('Args:'): + elif ( + line.startswith('Args:') or + line.startswith('Arg:') or + line.startswith('Arguments:') or + line.startswith('Argument:') + ): markdown_lines.append('__Arguments:__\n') section = 'args' is_new_section = True @@ -90,7 +100,10 @@ def parse_docstring(docstring: str) -> str: markdown_lines.append('__Returns:__\n') section = 'returns' is_new_section = True - elif line.startswith('Examples:'): + elif ( + line.startswith('Examples:') or + line.startswith('Examples:') + ): markdown_lines.append('__Examples:__\n') section = 'examples' is_new_section = True diff --git a/src/zrb/task/any_task.py b/src/zrb/task/any_task.py index 33f5df09..7636dc28 100644 --- a/src/zrb/task/any_task.py +++ b/src/zrb/task/any_task.py @@ -782,48 +782,111 @@ def _get_combined_inputs(self) -> Iterable[AnyInput]: @abstractmethod def log_debug(self, message: Any): + ''' + Log message with log level "DEBUG" + + You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + ''' pass @abstractmethod def log_warn(self, message: Any): + ''' + Log message with log level "WARNING" + + You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + ''' pass @abstractmethod def log_info(self, message: Any): + ''' + Log message with log level "INFO" + + You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + ''' pass @abstractmethod def log_error(self, message: Any): + ''' + Log message with log level "ERROR" + + You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + ''' pass @abstractmethod def log_critical(self, message: Any): + ''' + Log message with log level "CRITICAL" + + You can set Zrb log level by using `ZRB_LOGGING_LEVEL` environment + ''' pass @abstractmethod def print_out(self, message: Any, trim_message: bool = True): + ''' + Print message to stderr as normal text. + ''' pass @abstractmethod def print_err(self, message: Any, trim_message: bool = True): + ''' + Print message to stderr and style it as error. + ''' pass @abstractmethod def print_out_dark(self, message: Any, trim_message: bool = True): + ''' + Print message to stdout and style it as faint. + ''' pass @abstractmethod def get_input_map(self) -> Mapping[str, Any]: + ''' + Get a map representing task's Inputs. + + Typically used inside `run`, `check`, or in `@python_task` decorator + + Examples: + >>> from zrb import python_task, Task, Input + >>> @python_task(name='task', inputs=[Input(name='name')]) + >>> def task(*args, **kwargs): + >>> task: Task = kwargs.get('_task') + >>> for key, value in task.get_input_map(): + >>> task.print_out(f'{key}: {value}') + ''' pass @abstractmethod def get_env_map(self) -> Mapping[str, Any]: + ''' + Get a map representing task's Envs and EnvFiles + + Typically used inside `run`, `check`, or in `@python_task` decorator + + Examples: + >>> from zrb import python_task, Task, Env + >>> @python_task(name='task', envs=[Env(name='DB_URL')]) + >>> def task(*args, **kwargs): + >>> task: Task = kwargs.get('_task') + >>> for key, value in task.get_env_map(): + >>> task.print_out(f'{key}: {value}') + ''' pass @abstractmethod def render_any( self, value: Any, data: Optional[Mapping[str, Any]] = None ) -> Any: + ''' + Render any value. + ''' pass @abstractmethod @@ -832,6 +895,9 @@ def render_float( value: Union[JinjaTemplate, float], data: Optional[Mapping[str, Any]] = None ) -> float: + ''' + Render float value. + ''' pass @abstractmethod @@ -848,6 +914,9 @@ def render_bool( value: Union[JinjaTemplate, bool], data: Optional[Mapping[str, Any]] = None ) -> bool: + ''' + Render int value. + ''' pass @abstractmethod @@ -856,6 +925,9 @@ def render_str( value: JinjaTemplate, data: Optional[Mapping[str, Any]] = None ) -> str: + ''' + Render str value. + ''' pass @abstractmethod @@ -864,33 +936,44 @@ def render_file( path: JinjaTemplate, data: Optional[Mapping[str, Any]] = None ) -> str: + ''' + Render file content. + ''' pass @abstractmethod def _run_all(self, *args: Any, **kwargs: Any) -> Any: ''' - For internal use + For internal use. + + Run this task and all its upstreams. ''' pass @abstractmethod def _loop_check(self, show_info: bool) -> bool: ''' - For internal use + For internal use. + + Regularly check whether the task is ready or not. ''' pass @abstractmethod def _set_keyval(self, kwargs: Mapping[str, Any], env_prefix: str): ''' - For internal use + For internal use. + + Set current task's key values. ''' pass @abstractmethod def _print_result(self, result: Any): ''' - For internal use + For internal use. + + Directly call `print_result` ''' pass @@ -907,10 +990,10 @@ def print_result(self, result: Any): result (Any): The result of the task to be printed. Examples: - >> from zrb import Task - >> # Example of overriding in a subclass - >> class MyTask(Task): - >> def print_result(self, result: Any): - >> print(f'Result: {result}') + >>> from zrb import Task + >>> # Example of overriding in a subclass + >>> class MyTask(Task): + >>> def print_result(self, result: Any): + >>> print(f'Result: {result}') ''' pass diff --git a/src/zrb/task_input/bool_input.py b/src/zrb/task_input/bool_input.py index ffc0333b..c47f74ac 100644 --- a/src/zrb/task_input/bool_input.py +++ b/src/zrb/task_input/bool_input.py @@ -1,11 +1,44 @@ from zrb.helper.typing import Any, Optional, Union from zrb.helper.typecheck import typechecked - from zrb.task_input.base_input import BaseInput +# flake8: noqa E501 + @typechecked class BoolInput(BaseInput): + ''' + A specialized input class for handling boolean values in a task input context. + + This class extends `BaseInput` and provides specific functionality for boolean type inputs, + including support for default values, prompts, flags, and various customization options. + + Args: + name (str): The name of the input. + shortcut (Optional[str]): A shortcut string for the input. + default (Optional[Any]): The default value for the input. Should be a boolean if set. + description (Optional[str]): A brief description of the input. + show_default (Union[bool, str, None]): Option to display the default value. Can be a boolean or string representation. + prompt (Union[bool, str]): A boolean or string to prompt the user for input. If `True`, uses the default prompt. + confirmation_prompt (Union[bool, str]): If set to `True`, the user is asked to confirm the input. + prompt_required (bool): If `True`, the prompt for input is mandatory. + hide_input (bool): If `True`, the input is hidden (useful for sensitive information). + is_flag (Optional[bool]): Indicates if the input is a flag. If `True`, the input accepts boolean flag values. + flag_value (Optional[Any]): The value associated with the flag if `is_flag` is `True`. + multiple (bool): If `True`, allows multiple values for the input. + count (bool): If `True`, counts the occurrences of the input. + allow_from_autoenv (bool): If `True`, allows the input to be automatically populated from the environment. + hidden (bool): If `True`, the input is not shown in help messages or documentation. + show_choices (bool): If `True`, displays the choices available for the input. + show_envvar (bool): Indicates whether to display the environment variable associated with this input. + nargs (int): The number of arguments that the input can accept. + should_render (bool): If `True`, the input is rendered in the UI or command-line interface. + + Examples: + >>> bool_input = BoolInput(name='confirm', prompt='Do you agree?', default=False) + >>> bool_input.get_default() + False + ''' def __init__( self, diff --git a/src/zrb/task_input/choice_input.py b/src/zrb/task_input/choice_input.py index 757dc8f8..a27a805c 100644 --- a/src/zrb/task_input/choice_input.py +++ b/src/zrb/task_input/choice_input.py @@ -3,9 +3,44 @@ from zrb.task_input.base_input import BaseInput import click +# flake8: noqa E501 @typechecked class ChoiceInput(BaseInput): + ''' + A specialized input class for handling choice-based inputs in a task input context. + + This class extends `BaseInput` and provides functionality for inputs where the user + must select from a predefined set of choices. It includes support for default values, + prompts, flags, and various customization options. + + Args: + name (str): The name of the input. + shortcut (Optional[str]): An optional shortcut string for the input. + choices (Iterable[Any]): An iterable of choices from which the user can select. + default (Optional[Any]): The default value for the input. Should be one of the choices if set. + description (Optional[str]): A brief description of the input. + show_default (Union[bool, str, None]): Option to display the default value. Can be a boolean or string representation. + prompt (Union[bool, str]): A boolean or string to prompt the user for input. If `True`, uses the default prompt. + confirmation_prompt (Union[bool, str]): If set to `True`, the user is asked to confirm the input. + prompt_required (bool): If `True`, the prompt for input is mandatory. + hide_input (bool): If `True`, the input is hidden (useful for sensitive information). + is_flag (Optional[bool]): Indicates if the input is a flag. If `True`, the input accepts boolean flag values. + flag_value (Optional[Any]): The value associated with the flag if `is_flag` is `True`. + multiple (bool): If `True`, allows multiple values for the input. + count (bool): If `True`, counts the occurrences of the input. + allow_from_autoenv (bool): If `True`, allows the input to be automatically populated from the environment. + hidden (bool): If `True`, the input is not shown in help messages or documentation. + show_choices (bool): If `True`, displays the available choices to the user. + show_envvar (bool): Indicates whether to display the environment variable associated with this input. + nargs (int): The number of arguments that the input can accept. + should_render (bool): If `True`, the input is rendered in the UI or command-line interface. + + Examples: + >>> choice_input = ChoiceInput(name='color', choices=['red', 'green', 'blue'], default='red') + >>> choice_input.get_default() + 'red' + ''' def __init__( self, diff --git a/src/zrb/task_input/float_input.py b/src/zrb/task_input/float_input.py index 8cff94a9..8b3a3f68 100644 --- a/src/zrb/task_input/float_input.py +++ b/src/zrb/task_input/float_input.py @@ -2,9 +2,42 @@ from zrb.helper.typecheck import typechecked from zrb.task_input.base_input import BaseInput +# flake8: noqa E501 @typechecked class FloatInput(BaseInput): + ''' + A specialized input class designed to handle floating-point numbers in a task input context. + + Extending `BaseInput`, this class facilitates the handling of float-type inputs, accommodating + various features like default values, prompts, flags, and customization options. + + Args: + name (str): The name of the input. + shortcut (Optional[str]): An optional shortcut string for the input. + default (Optional[Any]): The default value for the input, expected to be a float if set. + description (Optional[str]): A brief description of the input's purpose. + show_default (Union[bool, str, None]): Option to display the default value. Can be a boolean or string. + prompt (Union[bool, str]): A boolean or string to prompt the user for input. If `True`, uses the default prompt. + confirmation_prompt (Union[bool, str]): If `True`, the user is asked to confirm the input. + prompt_required (bool): If `True`, the prompt for input is mandatory. + hide_input (bool): If `True`, the input is hidden, useful for sensitive information. + is_flag (Optional[bool]): Indicates if the input is a flag. If `True`, the input accepts boolean flag values. + flag_value (Optional[Any]): The value associated with the flag if `is_flag` is `True`. + multiple (bool): If `True`, allows multiple float values for the input. + count (bool): If `True`, counts the occurrences of the input. + allow_from_autoenv (bool): If `True`, allows the input to be automatically populated from the environment. + hidden (bool): If `True`, the input is not shown in help messages or documentation. + show_choices (bool): If `True`, displays the available choices to the user (relevant if there are restricted float choices). + show_envvar (bool): Indicates whether to display the environment variable associated with this input. + nargs (int): The number of arguments that the input can accept. + should_render (bool): If `True`, the input is rendered in the UI or command-line interface. + + Examples: + >>> float_input = FloatInput(name='threshold', default=0.5, description='Set the threshold value') + >>> float_input.get_default() + 0.5 + ''' def __init__( self, diff --git a/src/zrb/task_input/int_input.py b/src/zrb/task_input/int_input.py index 602ecd53..e0ad307a 100644 --- a/src/zrb/task_input/int_input.py +++ b/src/zrb/task_input/int_input.py @@ -3,9 +3,43 @@ from zrb.task_input.base_input import BaseInput +# flake8: noqa E501 @typechecked class IntInput(BaseInput): + ''' + A specialized input class for handling integer values in task inputs. + + `IntInput` extends `BaseInput` to specifically handle inputs where integer values are required. + It supports various features like default values, prompts, flags, and other customization options, + making it suitable for tasks that require numerical input in the form of integers. + + Args: + name (str): The name of the input, serving as an identifier. + shortcut (Optional[str]): An optional shortcut for easier reference to the input. + default (Optional[Any]): The default value for the input, should be an integer if provided. + description (Optional[str]): A brief description of what the input represents or its intended use. + show_default (Union[bool, str, None]): Option to show the default value in prompts or documentation. + prompt (Union[bool, str]): A boolean or string to determine the prompt for user input. If `True`, uses a default prompt. + confirmation_prompt (Union[bool, str]): If `True`, the user will be asked to confirm their input. + prompt_required (bool): If `True`, makes the input prompt mandatory. + hide_input (bool): If `True`, hides the input value, typically used for sensitive information. + is_flag (Optional[bool]): Indicates if the input functions as a flag, taking boolean values. + flag_value (Optional[Any]): The value associated with the input when used as a flag. + multiple (bool): If `True`, allows entering multiple integer values. + count (bool): If `True`, counts the occurrences of the input. + allow_from_autoenv (bool): If `True`, enables automatic population of the input from environment variables. + hidden (bool): If `True`, keeps the input hidden in help messages or documentation. + show_choices (bool): If `True`, shows any restricted choices for the input value. + show_envvar (bool): If `True`, displays the associated environment variable, if applicable. + nargs (int): The number of arguments that the input can accept. + should_render (bool): If `True`, renders the input in the user interface or command-line interface. + + Examples: + >>> int_input = IntInput(name='age', default=30, description='Enter your age') + >>> int_input.get_default() + 30 + ''' def __init__( self, diff --git a/src/zrb/task_input/password_input.py b/src/zrb/task_input/password_input.py index c5cdd44b..bdab70e4 100644 --- a/src/zrb/task_input/password_input.py +++ b/src/zrb/task_input/password_input.py @@ -3,9 +3,43 @@ from zrb.task_input.base_input import BaseInput +# flake8: noqa E501 @typechecked class PasswordInput(BaseInput): + ''' + A specialized input class for handling password or sensitive data inputs in tasks. + + `PasswordInput` extends `BaseInput` to manage inputs that should be treated as sensitive, + such as passwords. It ensures that the input is hidden when entered, providing an added + layer of security and privacy. This class supports various features like default values, + prompts, and flags, tailored for the safe handling of sensitive information. + + Args: + name (str): The name of the input, serving as an identifier. + shortcut (Optional[str]): An optional shortcut string for the input. + default (Optional[Any]): The default value for the input, expected to be a string if set. + description (Optional[str]): A brief description of the input's purpose. + show_default (Union[bool, str, None]): Option to display the default value. Can be a boolean or string. + prompt (Union[bool, str]): A boolean or string to prompt the user for input. If `True`, uses the default prompt. + confirmation_prompt (Union[bool, str]): If `True`, the user is asked to confirm the input. + prompt_required (bool): If `True`, the prompt for input is mandatory. + is_flag (Optional[bool]): Indicates if the input is a flag. If `True`, the input accepts boolean flag values. + flag_value (Optional[Any]): The value associated with the flag if `is_flag` is `True`. + multiple (bool): If `True`, allows multiple values for the input. + count (bool): If `True`, counts the occurrences of the input. + allow_from_autoenv (bool): If `True`, allows the input to be automatically populated from the environment. + hidden (bool): If `True`, the input is not shown in help messages or documentation. + show_choices (bool): If `True`, displays the available choices to the user (if applicable). + show_envvar (bool): Indicates whether to display the environment variable associated with this input. + nargs (int): The number of arguments that the input can accept. + should_render (bool): If `True’, the input is rendered in the UI or command-line interface. + + Examples: + >>> password_input = PasswordInput(name='password', description='Enter your password') + >>> password_input.is_hidden() + True + ''' def __init__( self, diff --git a/src/zrb/task_input/str_input.py b/src/zrb/task_input/str_input.py index 3b67d7bc..59c7d767 100644 --- a/src/zrb/task_input/str_input.py +++ b/src/zrb/task_input/str_input.py @@ -3,9 +3,43 @@ from zrb.task_input.base_input import BaseInput +# flake8: noqa E501 @typechecked class StrInput(BaseInput): + ''' + A specialized input class for handling string-based inputs in various tasks. + + `StrInput` extends `BaseInput` to manage string-type inputs, supporting features like + default values, prompts, flags, and other customization options. This class is useful + for tasks requiring textual input, such as names, descriptions, or any other string parameters. + + Args: + name (str): The name of the input, used as an identifier. + shortcut (Optional[str]): An optional shortcut string for the input. + default (Optional[Any]): The default value for the input, expected to be a string if set. + description (Optional[str]): A brief description of the input's purpose. + show_default (Union[bool, str, None]): Option to display the default value. Can be a boolean or string. + prompt (Union[bool, str]): A boolean or string to prompt the user for input. If `True`, uses the default prompt. + confirmation_prompt (Union[bool, str]): If `True`, the user is asked to confirm the input. + prompt_required (bool): If `True’, the prompt for input is mandatory. + hide_input (bool): If `True’, hides the input value, typically used for sensitive data. + is_flag (Optional[bool]): Indicates if the input is a flag. If `True’, the input accepts boolean flag values. + flag_value (Optional[Any]): The value associated with the flag if `is_flag` is `True`. + multiple (bool): If `True’, allows multiple string values for the input. + count (bool): If `True’, counts the occurrences of the input. + allow_from_autoenv (bool): If `True’, enables automatic population of the input from environment variables. + hidden (bool): If `True’, keeps the input hidden in help messages or documentation. + show_choices (bool): If `True’, shows any restricted choices for the input value. + show_envvar (bool): If `True’, displays the associated environment variable, if applicable. + nargs (int): The number of arguments that the input can accept. + should_render (bool): If `True’, renders the input in the user interface or command-line interface. + + Examples: + >>> str_input = StrInput(name='username', default='user123', description='Enter your username') + >>> str_input.get_default() + 'user123' + ''' def __init__( self, diff --git a/src/zrb/task_input/task_input.py b/src/zrb/task_input/task_input.py index 999126e1..49a2114a 100644 --- a/src/zrb/task_input/task_input.py +++ b/src/zrb/task_input/task_input.py @@ -1,5 +1,40 @@ from zrb.task_input.base_input import BaseInput +# flake8: noqa E501 class Input(BaseInput): + ''' + Alias for BaseInput + + Attributes: + name (str): The name of the input, used as a unique identifier. + shortcut (Optional[str]): An optional single-character shortcut for the input. + default (Optional[Any]): The default value of the input. + description (Optional[str]): A brief description of what the input is for. + show_default (Union[bool, JinjaTemplate, None]): Determines whether the default value should be displayed. + prompt (Union[bool, str]): The prompt text to be displayed when asking for the input. + confirmation_prompt (Union[bool, str]): A prompt for confirmation if required. + prompt_required (bool): Indicates whether a prompt is required. + hide_input (bool): If True, the input value will be hidden (e.g., for passwords). + is_flag (Optional[bool]): Specifies whether the input is a flag. + flag_value (Optional[Any]): The value to be used if the input is a flag. + multiple (bool): Allows multiple values for this input if True. + count (bool): If True, counts the occurrences of the input. + allow_from_autoenv (bool): If True, allows values to be automatically sourced from the environment. + type (Optional[Any]): The expected type of the input value. + hidden (bool): If True, the input is hidden and not rendered. + show_choices (bool): Indicates whether to show available choices for the input. + show_envvar (bool): If True, shows the corresponding environment variable. + nargs (int): Number of arguments expected for this input. + should_render (bool): Determines whether the input should be rendered. + + Examples: + >>> from zrb import Input, Task + >>> task = Task( + >>> name='task', + >>> inputs=[ + >>> Input(name='delay', default=10, description='Delay') + >>> ] + >>> ) + ''' pass diff --git a/zrb_init.py b/zrb_init.py index ac2d2d9b..f44bda21 100644 --- a/zrb_init.py +++ b/zrb_init.py @@ -1,9 +1,10 @@ from typing import Any, Mapping from zrb import ( - runner, python_task, AnyTask, Task, CmdTask, DockerComposeTask, FlowTask, - Checker, ResourceMaker, RsyncTask, RemoteCmdTask, PathWatcher, - RecurringTask, HTTPChecker, Env, EnvFile, Group, AnyInput, Input, - BoolInput, ChoiceInput, FloatInput, IntInput, PasswordInput, StrInput + runner, python_task, Task, CmdTask, DockerComposeTask, FlowTask, Checker, + ResourceMaker, RsyncTask, RemoteCmdTask, PathChecker, PathWatcher, + TimeWatcher, PortChecker, RecurringTask, HTTPChecker, BaseRemoteCmdTask, + Env, EnvFile, Group, Input, BoolInput, ChoiceInput, FloatInput, IntInput, + PasswordInput, StrInput ) from helper.doc import inject_doc import os @@ -106,16 +107,23 @@ def make_docs(*args: Any, **kwargs: Any): os.path.join(doc_concept_dir, 'task-group.md'): Group, os.path.join(doc_concept_dir, 'task-env.md'): Env, os.path.join(doc_concept_dir, 'task-env-file.md'): EnvFile, - os.path.join(doc_concept_task_dir, 'README.md'): AnyTask, - os.path.join(doc_concept_task_dir, 'checkers.md'): Checker, + os.path.join(doc_concept_task_dir, 'README.md'): Task, + os.path.join(doc_concept_task_dir, 'base-remote-cmd-task.md'): BaseRemoteCmdTask, # noqa + os.path.join(doc_concept_task_dir, 'checker.md'): Checker, os.path.join(doc_concept_task_dir, 'cmd-task.md'): CmdTask, os.path.join(doc_concept_task_dir, 'docker-compose-task.md'): DockerComposeTask, # noqa os.path.join(doc_concept_task_dir, 'flow-task.md'): FlowTask, + os.path.join(doc_concept_task_dir, 'http-checker.md'): HTTPChecker, + os.path.join(doc_concept_task_dir, 'path-checker.md'): PathChecker, + os.path.join(doc_concept_task_dir, 'path-watcher.md'): PathWatcher, + os.path.join(doc_concept_task_dir, 'port-checker.md'): PortChecker, os.path.join(doc_concept_task_dir, 'python-task.md'): python_task, + os.path.join(doc_concept_task_dir, 'recurring-task.md'): RecurringTask, os.path.join(doc_concept_task_dir, 'remote-cmd-task.md'): RemoteCmdTask, # noqa os.path.join(doc_concept_task_dir, 'resource-maker.md'): ResourceMaker, os.path.join(doc_concept_task_dir, 'rsync-task.md'): RsyncTask, - os.path.join(doc_concept_task_input_dir, 'README.md'): AnyInput, + os.path.join(doc_concept_task_dir, 'time-watcher.md'): TimeWatcher, + os.path.join(doc_concept_task_input_dir, 'README.md'): Input, os.path.join(doc_concept_task_input_dir, 'bool-input.md'): BoolInput, os.path.join(doc_concept_task_input_dir, 'choice-input.md'): ChoiceInput, # noqa os.path.join(doc_concept_task_input_dir, 'float-input.md'): FloatInput, From 3c274b898e85cefd604077983c20ef6fd42cc436 Mon Sep 17 00:00:00 2001 From: goFrendiAsgard Date: Sun, 10 Dec 2023 14:05:43 +0700 Subject: [PATCH 11/13] update docs --- docs/concepts/task/README.md | 5 ----- docs/concepts/task/base-remote-cmd-task.md | 5 ----- docs/concepts/task/checker.md | 5 ----- docs/concepts/task/cmd-task.md | 5 ----- docs/concepts/task/docker-compose-task.md | 5 ----- docs/concepts/task/flow-task.md | 5 ----- docs/concepts/task/http-checker.md | 5 ----- docs/concepts/task/path-checker.md | 5 ----- docs/concepts/task/path-watcher.md | 5 ----- docs/concepts/task/port-checker.md | 5 ----- docs/concepts/task/recurring-task.md | 5 ----- docs/concepts/task/remote-cmd-task.md | 5 ----- docs/concepts/task/resource-maker.md | 5 ----- docs/concepts/task/rsync-task.md | 5 ----- docs/concepts/task/time-watcher.md | 5 ----- src/zrb/task/any_task.py | 1 - 16 files changed, 76 deletions(-) diff --git a/docs/concepts/task/README.md b/docs/concepts/task/README.md index e6aa1121..41391122 100644 --- a/docs/concepts/task/README.md +++ b/docs/concepts/task/README.md @@ -1165,11 +1165,6 @@ class MyTask(Task): async def run(self, *args: Any, **kwargs: Any) -> int: self.print_out('Doing some calculation') return 42 -``` - -``` ->>> -```python task = MyTask() fn = task.to_function() fn() diff --git a/docs/concepts/task/base-remote-cmd-task.md b/docs/concepts/task/base-remote-cmd-task.md index 3893d9e7..f362c03b 100644 --- a/docs/concepts/task/base-remote-cmd-task.md +++ b/docs/concepts/task/base-remote-cmd-task.md @@ -1086,11 +1086,6 @@ class MyTask(Task): async def run(self, *args: Any, **kwargs: Any) -> int: self.print_out('Doing some calculation') return 42 -``` - -``` ->>> -```python task = MyTask() fn = task.to_function() fn() diff --git a/docs/concepts/task/checker.md b/docs/concepts/task/checker.md index 092d3386..ac8ea6d3 100644 --- a/docs/concepts/task/checker.md +++ b/docs/concepts/task/checker.md @@ -1096,11 +1096,6 @@ class MyTask(Task): async def run(self, *args: Any, **kwargs: Any) -> int: self.print_out('Doing some calculation') return 42 -``` - -``` ->>> -```python task = MyTask() fn = task.to_function() fn() diff --git a/docs/concepts/task/cmd-task.md b/docs/concepts/task/cmd-task.md index 1cfbe378..2e131faf 100644 --- a/docs/concepts/task/cmd-task.md +++ b/docs/concepts/task/cmd-task.md @@ -1185,11 +1185,6 @@ class MyTask(Task): async def run(self, *args: Any, **kwargs: Any) -> int: self.print_out('Doing some calculation') return 42 -``` - -``` ->>> -```python task = MyTask() fn = task.to_function() fn() diff --git a/docs/concepts/task/docker-compose-task.md b/docs/concepts/task/docker-compose-task.md index da445de8..847cf85c 100644 --- a/docs/concepts/task/docker-compose-task.md +++ b/docs/concepts/task/docker-compose-task.md @@ -1220,11 +1220,6 @@ class MyTask(Task): async def run(self, *args: Any, **kwargs: Any) -> int: self.print_out('Doing some calculation') return 42 -``` - -``` ->>> -```python task = MyTask() fn = task.to_function() fn() diff --git a/docs/concepts/task/flow-task.md b/docs/concepts/task/flow-task.md index 3b689cb3..79796a81 100644 --- a/docs/concepts/task/flow-task.md +++ b/docs/concepts/task/flow-task.md @@ -1096,11 +1096,6 @@ class MyTask(Task): async def run(self, *args: Any, **kwargs: Any) -> int: self.print_out('Doing some calculation') return 42 -``` - -``` ->>> -```python task = MyTask() fn = task.to_function() fn() diff --git a/docs/concepts/task/http-checker.md b/docs/concepts/task/http-checker.md index c3f29220..d26e0688 100644 --- a/docs/concepts/task/http-checker.md +++ b/docs/concepts/task/http-checker.md @@ -1096,11 +1096,6 @@ class MyTask(Task): async def run(self, *args: Any, **kwargs: Any) -> int: self.print_out('Doing some calculation') return 42 -``` - -``` ->>> -```python task = MyTask() fn = task.to_function() fn() diff --git a/docs/concepts/task/path-checker.md b/docs/concepts/task/path-checker.md index aa0e8164..4e07bac0 100644 --- a/docs/concepts/task/path-checker.md +++ b/docs/concepts/task/path-checker.md @@ -1096,11 +1096,6 @@ class MyTask(Task): async def run(self, *args: Any, **kwargs: Any) -> int: self.print_out('Doing some calculation') return 42 -``` - -``` ->>> -```python task = MyTask() fn = task.to_function() fn() diff --git a/docs/concepts/task/path-watcher.md b/docs/concepts/task/path-watcher.md index 172c3a5c..437cb847 100644 --- a/docs/concepts/task/path-watcher.md +++ b/docs/concepts/task/path-watcher.md @@ -1101,11 +1101,6 @@ class MyTask(Task): async def run(self, *args: Any, **kwargs: Any) -> int: self.print_out('Doing some calculation') return 42 -``` - -``` ->>> -```python task = MyTask() fn = task.to_function() fn() diff --git a/docs/concepts/task/port-checker.md b/docs/concepts/task/port-checker.md index a630eb13..64880d83 100644 --- a/docs/concepts/task/port-checker.md +++ b/docs/concepts/task/port-checker.md @@ -1096,11 +1096,6 @@ class MyTask(Task): async def run(self, *args: Any, **kwargs: Any) -> int: self.print_out('Doing some calculation') return 42 -``` - -``` ->>> -```python task = MyTask() fn = task.to_function() fn() diff --git a/docs/concepts/task/recurring-task.md b/docs/concepts/task/recurring-task.md index 8846dc5a..cd4cc2c6 100644 --- a/docs/concepts/task/recurring-task.md +++ b/docs/concepts/task/recurring-task.md @@ -1091,11 +1091,6 @@ class MyTask(Task): async def run(self, *args: Any, **kwargs: Any) -> int: self.print_out('Doing some calculation') return 42 -``` - -``` ->>> -```python task = MyTask() fn = task.to_function() fn() diff --git a/docs/concepts/task/remote-cmd-task.md b/docs/concepts/task/remote-cmd-task.md index 3bb8fec9..91ab5cd9 100644 --- a/docs/concepts/task/remote-cmd-task.md +++ b/docs/concepts/task/remote-cmd-task.md @@ -1086,11 +1086,6 @@ class MyTask(Task): async def run(self, *args: Any, **kwargs: Any) -> int: self.print_out('Doing some calculation') return 42 -``` - -``` ->>> -```python task = MyTask() fn = task.to_function() fn() diff --git a/docs/concepts/task/resource-maker.md b/docs/concepts/task/resource-maker.md index 3141b97c..5dec436b 100644 --- a/docs/concepts/task/resource-maker.md +++ b/docs/concepts/task/resource-maker.md @@ -1096,11 +1096,6 @@ class MyTask(Task): async def run(self, *args: Any, **kwargs: Any) -> int: self.print_out('Doing some calculation') return 42 -``` - -``` ->>> -```python task = MyTask() fn = task.to_function() fn() diff --git a/docs/concepts/task/rsync-task.md b/docs/concepts/task/rsync-task.md index ba17c289..6c60684c 100644 --- a/docs/concepts/task/rsync-task.md +++ b/docs/concepts/task/rsync-task.md @@ -1091,11 +1091,6 @@ class MyTask(Task): async def run(self, *args: Any, **kwargs: Any) -> int: self.print_out('Doing some calculation') return 42 -``` - -``` ->>> -```python task = MyTask() fn = task.to_function() fn() diff --git a/docs/concepts/task/time-watcher.md b/docs/concepts/task/time-watcher.md index b115a7b4..06e1df24 100644 --- a/docs/concepts/task/time-watcher.md +++ b/docs/concepts/task/time-watcher.md @@ -1096,11 +1096,6 @@ class MyTask(Task): async def run(self, *args: Any, **kwargs: Any) -> int: self.print_out('Doing some calculation') return 42 -``` - -``` ->>> -```python task = MyTask() fn = task.to_function() fn() diff --git a/src/zrb/task/any_task.py b/src/zrb/task/any_task.py index 7636dc28..1799efa6 100644 --- a/src/zrb/task/any_task.py +++ b/src/zrb/task/any_task.py @@ -248,7 +248,6 @@ def to_function( >>> async def run(self, *args: Any, **kwargs: Any) -> int: >>> self.print_out('Doing some calculation') >>> return 42 - >>> >>> task = MyTask() >>> fn = task.to_function() >>> fn() From ccd841a0e2c18f9f2478cd4eada69a030ab9db63 Mon Sep 17 00:00:00 2001 From: goFrendiAsgard Date: Sun, 10 Dec 2023 14:13:20 +0700 Subject: [PATCH 12/13] change lifecycle diagram --- docs/concepts/task/README.md | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/docs/concepts/task/README.md b/docs/concepts/task/README.md index 41391122..b8dd1fa3 100644 --- a/docs/concepts/task/README.md +++ b/docs/concepts/task/README.md @@ -59,18 +59,17 @@ Aside from the documentation, you can always dive down into [the source code](ht Every task has its own lifecycle. ``` -Triggered ┌─────────► Ready ◄──┐ - │ │ │ - │ │ │ - ▼ │ │ - Waiting ────► Started ─────► Failed │ - │ ▲ │ │ - │ │ │ │ - ▼ │ ▼ │ - Skipped └────────── Retry │ - │ │ - │ │ - └──────────────────────────────────┘ + ┌─────────────────────────────┐ + │ │ + │ ▼ +Triggered ─────► Waiting ────► Started ─────► Failed ┌────► Ready + │ ▲ │ │ + │ │ │ │ + ▼ │ ▼ │ + Skipped └────────── Retry │ + │ │ + │ │ + └──────────────────────────────────┘ ``` - `Triggered`: Task is triggered. From 67639fd3c0b46234c89538ed9263680f1293d734 Mon Sep 17 00:00:00 2001 From: goFrendiAsgard Date: Sun, 10 Dec 2023 14:17:03 +0700 Subject: [PATCH 13/13] change to alpha, ready to merge to main branch --- .github/workflows/_zrb.yml | 2 +- pyproject.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/_zrb.yml b/.github/workflows/_zrb.yml index 8d7a0bc6..e05a5e22 100644 --- a/.github/workflows/_zrb.yml +++ b/.github/workflows/_zrb.yml @@ -17,7 +17,7 @@ jobs: Run-command: runs-on: ubuntu-latest container: - image: stalchmst/zrb:0.0.123 + image: stalchmst/zrb:0.1.0-alpha steps: - name: Check out repository code uses: actions/checkout@v3 diff --git a/pyproject.toml b/pyproject.toml index 7b3b1542..7e6ffb4b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "flit_core.buildapi" [project] name = "zrb" -version = "0.1.0" +version = "0.1.0-alpha" authors = [ { name="Go Frendi Gunawan", email="gofrendiasgard@gmail.com" }, ]