diff options
Diffstat (limited to '')
| -rwxr-xr-x | taskipy/cli.py | 16 | ||||
| -rw-r--r-- | taskipy/exceptions.py | 35 | ||||
| -rw-r--r-- | taskipy/list.py | 18 | ||||
| -rw-r--r-- | taskipy/pyproject.py | 25 | ||||
| -rw-r--r-- | taskipy/task.py | 46 | ||||
| -rw-r--r-- | taskipy/task_runner.py | 30 |
6 files changed, 104 insertions, 66 deletions
diff --git a/taskipy/cli.py b/taskipy/cli.py index 6ef5df3..7d2195f 100755 --- a/taskipy/cli.py +++ b/taskipy/cli.py @@ -25,12 +25,16 @@ def run(args: List[str], cwd: Union[str, Path, None] = None) -> int: 0 on success; > 0 for an error. """ parser = argparse.ArgumentParser( - prog='task', - description='runs a task specified in your pyproject.toml under [tool.taskipy.tasks]', + prog="task", + description="runs a task specified in your pyproject.toml under [tool.taskipy.tasks]", + ) + parser.add_argument( + "-l", "--list", help="show list of available tasks", action="store_true" + ) + parser.add_argument("name", help="name of the task", nargs="?") + parser.add_argument( + "args", nargs=argparse.REMAINDER, help="arguments to pass to the task" ) - parser.add_argument('-l', '--list', help='show list of available tasks', action='store_true') - parser.add_argument('name', help='name of the task', nargs='?') - parser.add_argument('args', nargs=argparse.REMAINDER, help='arguments to pass to the task') parsed_args = parser.parse_args(args=args) try: @@ -53,5 +57,5 @@ def run(args: List[str], cwd: Union[str, Path, None] = None) -> int: return 1 -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/taskipy/exceptions.py b/taskipy/exceptions.py index 65ecfb0..d34fdf9 100644 --- a/taskipy/exceptions.py +++ b/taskipy/exceptions.py @@ -9,14 +9,14 @@ class TaskipyError(Exception): class InvalidRunnerTypeError(TaskipyError): def __str__(self): return ( - 'invalid value: runner is not a string. ' - 'please check [tool.taskipy.settings.runner]' + "invalid value: runner is not a string. " + "please check [tool.taskipy.settings.runner]" ) class MissingPyProjectFileError(TaskipyError): def __str__(self): - return 'no pyproject.toml file found in this directory or parent directories' + return "no pyproject.toml file found in this directory or parent directories" class MalformedPyProjectError(TaskipyError): @@ -25,10 +25,10 @@ class MalformedPyProjectError(TaskipyError): self.reason = reason def __str__(self): - message = 'pyproject.toml file is malformed and could not be read' + message = "pyproject.toml file is malformed and could not be read" if self.reason: - message += f'. reason: {self.reason}' + message += f". reason: {self.reason}" return message @@ -43,9 +43,12 @@ class TaskNotFoundError(TaskipyError): def __str__(self): if self.suggestion: - return f'could not find task "{self.task}", did you mean "{self.suggestion}"?' + return ( + f'could not find task "{self.task}", did you mean "{self.suggestion}"?' + ) return f'could not find task "{self.task}"' + class MalformedTaskError(TaskipyError): def __init__(self, task_name: str, reason: str): super().__init__() @@ -55,6 +58,7 @@ class MalformedTaskError(TaskipyError): def __str__(self): return f'the task "{self.task}" in the pyproject.toml file is malformed. reason: {self.reason}' + class InvalidUsageError(TaskipyError): exit_code = 127 @@ -63,15 +67,16 @@ class InvalidUsageError(TaskipyError): self.__parser = parser def __str__(self): - return self.__parser.format_usage().strip('\n') + return self.__parser.format_usage().strip("\n") + class MissingTaskipySettingsSectionError(TaskipyError): exit_code = 127 def __str__(self): return ( - 'no settings found. add a [tools.taskipy.settings]' - 'section to your pyproject.toml' + "no settings found. add a [tools.taskipy.settings]" + "section to your pyproject.toml" ) @@ -80,8 +85,8 @@ class MissingTaskipyTasksSectionError(TaskipyError): def __str__(self): return ( - 'no tasks found. add a [tool.taskipy.tasks] ' - 'section to your pyproject.toml' + "no tasks found. add a [tool.taskipy.tasks] " + "section to your pyproject.toml" ) @@ -90,8 +95,8 @@ class EmptyTasksSectionError(TaskipyError): def __str__(self): return ( - 'no tasks found. create your first task ' - 'by adding it to your pyproject.toml file under [tool.taskipy.tasks]' + "no tasks found. create your first task " + "by adding it to your pyproject.toml file under [tool.taskipy.tasks]" ) @@ -99,7 +104,7 @@ class CircularVariableError(TaskipyError): exit_code = 127 def __str__(self): - return 'cannot resolve variables, found variables that depend on each other.' + return "cannot resolve variables, found variables that depend on each other." class InvalidVariableError(TaskipyError): @@ -111,4 +116,4 @@ class InvalidVariableError(TaskipyError): self.reason = reason def __str__(self): - return f'variable {self.variable} is invalid. reason: {self.reason}' + return f"variable {self.variable} is invalid. reason: {self.reason}" diff --git a/taskipy/list.py b/taskipy/list.py index a179f62..92c6af2 100644 --- a/taskipy/list.py +++ b/taskipy/list.py @@ -23,18 +23,22 @@ class TasksListFormatter: tasks_col = [task.name for task in self.__tasks] longest_item_in_tasks_col = len(max(tasks_col, key=len)) - desc_col_wrap_indent = ' ' * (longest_item_in_tasks_col + 1) + desc_col_wrap_indent = " " * (longest_item_in_tasks_col + 1) desc_col_width = line_width - len(desc_col_wrap_indent) for task in self.__tasks: name_text = task.name desc_text = task.description or task.command - tasks_col_text = f'{name_text:<{longest_item_in_tasks_col}}' - desc_col_text = '\n'.join(textwrap.wrap(desc_text, - width=desc_col_width, - subsequent_indent=desc_col_wrap_indent)) - print(f'{self.__highlight(tasks_col_text)} {desc_col_text}') + tasks_col_text = f"{name_text:<{longest_item_in_tasks_col}}" + desc_col_text = "\n".join( + textwrap.wrap( + desc_text, + width=desc_col_width, + subsequent_indent=desc_col_wrap_indent, + ) + ) + print(f"{self.__highlight(tasks_col_text)} {desc_col_text}") def __highlight(self, text: str): - return f'{colorama.Fore.CYAN}{text}{colorama.Style.RESET_ALL}' + return f"{colorama.Fore.CYAN}{text}{colorama.Style.RESET_ALL}" diff --git a/taskipy/pyproject.py b/taskipy/pyproject.py index a0b421b..9bb6ff1 100644 --- a/taskipy/pyproject.py +++ b/taskipy/pyproject.py @@ -25,7 +25,7 @@ class PyProject: @property def tasks(self) -> Dict[str, Task]: try: - toml_tasks = self.__items['tool']['taskipy']['tasks'].items() + toml_tasks = self.__items["tool"]["taskipy"]["tasks"].items() except KeyError: raise MissingTaskipyTasksSectionError() @@ -42,7 +42,7 @@ class PyProject: @property def variables(self) -> Dict[str, Variable]: try: - toml_vars = self.__items['tool']['taskipy'].get('variables', {}) + toml_vars = self.__items["tool"]["taskipy"].get("variables", {}) except KeyError: return {} @@ -50,21 +50,20 @@ class PyProject: for name, toml_contents in toml_vars.items(): if isinstance(toml_contents, str): vars_dict[name] = Variable(name, toml_contents, recursive=False) - elif ( - isinstance(toml_contents, dict) - and isinstance(toml_contents.get('var'), str) + elif isinstance(toml_contents, dict) and isinstance( + toml_contents.get("var"), str ): vars_dict[name] = Variable( name, - toml_contents['var'], - toml_contents.get('recursive', False), + toml_contents["var"], + toml_contents.get("recursive", False), ) else: raise InvalidVariableError( name, - f'expected variable to contain a string or be a table ' + f"expected variable to contain a string or be a table " 'with a key "var" that contains a string value, got ' - f'{toml_contents}.' + f"{toml_contents}.", ) return vars_dict @@ -72,14 +71,14 @@ class PyProject: @property def settings(self) -> dict: try: - return self.__items['tool']['taskipy']['settings'] + return self.__items["tool"]["taskipy"]["settings"] except KeyError: return {} @property def runner(self) -> Optional[str]: try: - runner = self.settings['runner'] + runner = self.settings["runner"] if not isinstance(runner, str): raise InvalidRunnerTypeError() @@ -94,7 +93,7 @@ class PyProject: if isinstance(file_path, str): file_path = Path(file_path).resolve() - with open(file_path, 'rb') as file: + with open(file_path, "rb") as file: return tomllib.load(file) except FileNotFoundError: raise MissingPyProjectFileError() @@ -109,7 +108,7 @@ class PyProject: yield parent for candidate_dir in candidate_dirs(base_dir): - pyproject = candidate_dir / 'pyproject.toml' + pyproject = candidate_dir / "pyproject.toml" if pyproject.exists(): return pyproject diff --git a/taskipy/task.py b/taskipy/task.py index a065fd8..ce3f999 100644 --- a/taskipy/task.py +++ b/taskipy/task.py @@ -36,12 +36,18 @@ class Task: return None if isinstance(task_toml_contents, dict): - value = task_toml_contents.get('use_vars') + value = task_toml_contents.get("use_vars") if value is not None and not isinstance(value, bool): - raise MalformedTaskError(self.__task_name, f'task\'s "use_vars" arg has to be bool type got {type(value)}') + raise MalformedTaskError( + self.__task_name, + f'task\'s "use_vars" arg has to be bool type got {type(value)}', + ) return value - raise MalformedTaskError(self.__task_name, 'tasks must be strings, or dicts that contain { cmd, cwd, help, use_vars }') + raise MalformedTaskError( + self.__task_name, + "tasks must be strings, or dicts that contain { cmd, cwd, help, use_vars }", + ) def __extract_task_command(self, task_toml_contents: object) -> str: if isinstance(task_toml_contents, str): @@ -49,32 +55,46 @@ class Task: if isinstance(task_toml_contents, dict): try: - return task_toml_contents['cmd'] + return task_toml_contents["cmd"] except KeyError: - raise MalformedTaskError(self.__task_name, 'the task item does not have the "cmd" property') + raise MalformedTaskError( + self.__task_name, 'the task item does not have the "cmd" property' + ) - raise MalformedTaskError(self.__task_name, 'tasks must be strings, or dicts that contain { cmd, cwd, help, use_vars }') + raise MalformedTaskError( + self.__task_name, + "tasks must be strings, or dicts that contain { cmd, cwd, help, use_vars }", + ) def __extract_task_workdir(self, task_toml_contents: object) -> Optional[str]: if isinstance(task_toml_contents, str): return None if isinstance(task_toml_contents, dict): - value = task_toml_contents.get('cwd') + value = task_toml_contents.get("cwd") if value is not None and not isinstance(value, str): - raise MalformedTaskError(self.__task_name, f'task\'s "cwd" arg has to be str type got {type(value)}') + raise MalformedTaskError( + self.__task_name, + f'task\'s "cwd" arg has to be str type got {type(value)}', + ) return value - raise MalformedTaskError(self.__task_name, 'tasks must be strings, or dicts that contain { cmd, cwd, help, use_vars }') + raise MalformedTaskError( + self.__task_name, + "tasks must be strings, or dicts that contain { cmd, cwd, help, use_vars }", + ) def __extract_task_description(self, task_toml_contents: object) -> str: if isinstance(task_toml_contents, str): - return '' + return "" if isinstance(task_toml_contents, dict): try: - return task_toml_contents['help'] + return task_toml_contents["help"] except KeyError: - return '' + return "" - raise MalformedTaskError(self.__task_name, 'tasks must be strings, or dicts that contain { cmd, cwd, help, use_vars }') + raise MalformedTaskError( + self.__task_name, + "tasks must be strings, or dicts that contain { cmd, cwd, help, use_vars }", + ) diff --git a/taskipy/task_runner.py b/taskipy/task_runner.py index ffeb682..4e16a3b 100644 --- a/taskipy/task_runner.py +++ b/taskipy/task_runner.py @@ -18,7 +18,7 @@ from taskipy.pyproject import PyProject from taskipy.task import Task from taskipy.variable import Variable -if platform.system() == 'Windows': +if platform.system() == "Windows": import mslex as shlex # type: ignore # pylint: disable=E0401 else: import shlex # type: ignore[no-redef] @@ -37,7 +37,7 @@ class TaskRunner: def run(self, task_name: str, args: List[str]) -> int: pre_command, command, post_command = self.__get_formatted_commands(task_name) - self.__working_dir = self.__get_working_dir(task_name) or self.__working_dir + self.__working_dir = self.__get_working_dir(task_name) or self.__working_dir if pre_command is not None: exit_code = self.__run_command_and_return_exit_code(pre_command) @@ -62,7 +62,7 @@ class TaskRunner: should_resolve_vars = ( self.__is_using_vars([pre_task, task, post_task]) - or self.__project.settings.get('use_vars') is True + or self.__project.settings.get("use_vars") is True ) variables = self.__resolve_variables() if should_resolve_vars else {} @@ -78,7 +78,9 @@ class TaskRunner: return pre_command, command, post_command - def __get_tasks(self, task_name: str) -> Tuple[Optional[Task], Task, Optional[Task]]: + def __get_tasks( + self, task_name: str + ) -> Tuple[Optional[Task], Task, Optional[Task]]: pre_task = self.__pre_task(task_name) post_task = self.__post_task(task_name) @@ -86,7 +88,9 @@ class TaskRunner: task = self.__project.tasks[task_name] except KeyError: suggestion = None - closest_match = get_close_matches(task_name, self.__project.tasks, n=1, cutoff=0.5) + closest_match = get_close_matches( + task_name, self.__project.tasks, n=1, cutoff=0.5 + ) if closest_match: suggestion = closest_match[0] @@ -95,10 +99,10 @@ class TaskRunner: return pre_task, task, post_task def __pre_task(self, task_name: str) -> Optional[Task]: - return self.__project.tasks.get(f'pre_{task_name}') + return self.__project.tasks.get(f"pre_{task_name}") def __post_task(self, task_name: str) -> Optional[Task]: - return self.__project.tasks.get(f'post_{task_name}') + return self.__project.tasks.get(f"post_{task_name}") def __is_using_vars(self, tasks: List[Optional[Task]]) -> bool: use_vars = False @@ -116,7 +120,9 @@ class TaskRunner: ) while len(recursive_vars) > 0: - count_of_previously_resolved_vars = len(nonrecursive_vars) # pylint: disable=C0103 + count_of_previously_resolved_vars = len( + nonrecursive_vars + ) # pylint: disable=C0103 for name, value in recursive_vars.copy().items(): try: @@ -146,14 +152,14 @@ class TaskRunner: def __format_task_command(self, task: Task, variables: dict) -> str: if task.use_vars or ( - task.use_vars is None and self.__project.settings.get('use_vars') + task.use_vars is None and self.__project.settings.get("use_vars") ): try: return task.command.format(**variables) except KeyError as e: raise MalformedTaskError( task.name, - f'{e} variable expected in [tool.taskipy.variables]', + f"{e} variable expected in [tool.taskipy.variables]", ) return task.command @@ -165,9 +171,9 @@ class TaskRunner: args = [] if self.__project.runner is not None: - command = f'{self.__project.runner} {command}' + command = f"{self.__project.runner} {command}" - command_with_args = ' '.join([command] + [shlex.quote(arg) for arg in args]) + command_with_args = " ".join([command] + [shlex.quote(arg) for arg in args]) process = subprocess.Popen( command_with_args, shell=True, cwd=self.__working_dir ) |