diff options
Diffstat (limited to '')
| -rwxr-xr-x | taskipy/cli.py | 27 | ||||
| -rw-r--r-- | taskipy/exceptions.py | 51 | ||||
| -rw-r--r-- | taskipy/pyproject.py | 42 | ||||
| -rw-r--r-- | taskipy/run.py | 74 | ||||
| -rw-r--r-- | taskipy/task.py | 64 | ||||
| -rw-r--r-- | taskipy/task_runner.py | 33 |
6 files changed, 213 insertions, 78 deletions
diff --git a/taskipy/cli.py b/taskipy/cli.py index f37d5f6..06acd6c 100755 --- a/taskipy/cli.py +++ b/taskipy/cli.py @@ -1,14 +1,33 @@ #!/usr/bin/env python3 import argparse -from taskipy.run import run_task +import sys +from pathlib import Path + +from taskipy.exceptions import TaskipyError +from taskipy.task_runner import TaskRunner + def main(): - parser = argparse.ArgumentParser(prog='task', description='runs a task specified in your pyproject.toml under [tool.taskipy.tasks]') + parser = argparse.ArgumentParser( + prog='task', + description='runs a task specified in your pyproject.toml under [tool.taskipy.tasks]', + ) parser.add_argument('name', help='name of the task') - parser.add_argument('args', nargs=argparse.REMAINDER, help='arguments to pass to the task') + parser.add_argument( + 'args', nargs=argparse.REMAINDER, help='arguments to pass to the task' + ) args = parser.parse_args() - run_task(args.name, args.args) + try: + exit_code = TaskRunner(Path.cwd() / 'pyproject.toml').run(args.name, args.args) + sys.exit(exit_code) + except TaskipyError as e: + print(e) + sys.exit(e.exit_code) + except Exception as e: + print(e) + sys.exit(1) + if __name__ == '__main__': main() diff --git a/taskipy/exceptions.py b/taskipy/exceptions.py new file mode 100644 index 0000000..8f03ed3 --- /dev/null +++ b/taskipy/exceptions.py @@ -0,0 +1,51 @@ +class TaskipyError(Exception): + exit_code = 1 + + +class InvalidRunnerTypeError(TaskipyError): + def __str__(self): + return ( + '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' + + +class MalformedPyProjectError(TaskipyError): + def __str__(self): + return 'pyproject.toml file is malformed and could not be read' + + +class TaskNotFoundError(TaskipyError): + exit_code = 127 + + def __init__(self, task_name: str): + super().__init__() + self.task = task_name + + def __str__(self): + return f'could not find task "{self.task}"' + + +class MissingTaskipySettingsSectionError(TaskipyError): + exit_code = 127 + + def __str__(self): + return ( + 'no settings found. add a [tools.taskipy.settings]' + 'section to your pyproject.toml' + ) + + +class MissingTaskipyTasksSectionError(TaskipyError): + exit_code = 127 + + def __str__(self): + return ( + 'no tasks found. add a [tool.taskipy.tasks] ' + 'section to your pyproject.toml' + ) diff --git a/taskipy/pyproject.py b/taskipy/pyproject.py new file mode 100644 index 0000000..4b55834 --- /dev/null +++ b/taskipy/pyproject.py @@ -0,0 +1,42 @@ +from pathlib import Path +from typing import Any, MutableMapping, Union + +import toml + +from taskipy.exceptions import ( + MalformedPyProjectError, + MissingPyProjectFileError, + MissingTaskipyTasksSectionError, + MissingTaskipySettingsSectionError +) + + +class PyProject: + def __init__(self, file_path: Union[str, Path]): + self.__items = PyProject.__load_toml_file(file_path) + + @property + def tasks(self) -> dict: + try: + return self.__items['tool']['taskipy']['tasks'] + except KeyError: + raise MissingTaskipyTasksSectionError() + + @property + def settings(self) -> dict: + try: + return self.__items['tool']['taskipy']['settings'] + except KeyError: + raise MissingTaskipySettingsSectionError() + + @staticmethod + def __load_toml_file(file_path: Union[str, Path]) -> MutableMapping[str, Any]: + try: + if isinstance(file_path, str): + file_path = Path(file_path).resolve() + + return toml.load(file_path) + except FileNotFoundError: + raise MissingPyProjectFileError() + except toml.TomlDecodeError: + raise MalformedPyProjectError() diff --git a/taskipy/run.py b/taskipy/run.py deleted file mode 100644 index 2b7f007..0000000 --- a/taskipy/run.py +++ /dev/null @@ -1,74 +0,0 @@ -import os -import subprocess -import sys -import toml -import shlex -from os import path -from typing import List - -def run_task(task_name: str, args: List[str], cwd=os.curdir): - def run_commands_and_bail_on_first_fail(cmds: List[str], runner: str = None) -> int: - for cmd in cmds: - if runner is not None: - cmd = f'{runner} {cmd}' - - p = subprocess.Popen(cmd, shell=True, cwd=cwd) - - try: - p.wait() - except KeyboardInterrupt: - pass - - if p.returncode != 0: - return p.returncode - - return 0 - - try: - pyproject = toml.load(path.join(cwd, 'pyproject.toml')) - except FileNotFoundError: - print('no pyproject.toml file found in this directory') - sys.exit(1) - except toml.TomlDecodeError: - print('pyproject.toml file is malformed and could not be read') - sys.exit(1) - - try: - tasks = pyproject['tool']['taskipy']['tasks'] - except KeyError: - print('no tasks found. add a [tool.taskipy.tasks] section to your pyproject.toml') - sys.exit(127) - - commands = [] - - try: - task = tasks[task_name] - except KeyError: - print(f'could not find task "{task_name}""') - sys.exit(127) - - command_with_passed_args = ' '.join([task] + [shlex.quote(arg) for arg in args]) - commands.append(command_with_passed_args) - - try: - pre_task = tasks[f'pre_{task_name}'] - commands.insert(0, pre_task) - except KeyError: - pass - - try: - post_task = tasks[f'post_{task_name}'] - commands.append(post_task) - except KeyError: - pass - - try: - runner = pyproject['tool']['taskipy']['settings']['runner'].strip() - except KeyError: - runner = None - except AttributeError: - print('invalid value: runner is not a string. please check [tool.taskipy.settings.runner]') - sys.exit(1) - - exit_code = run_commands_and_bail_on_first_fail(commands, runner=runner) - sys.exit(exit_code) diff --git a/taskipy/task.py b/taskipy/task.py new file mode 100644 index 0000000..231dacf --- /dev/null +++ b/taskipy/task.py @@ -0,0 +1,64 @@ +import shlex +from typing import Optional, List + +from taskipy.exceptions import ( + InvalidRunnerTypeError, + TaskNotFoundError, + MissingTaskipySettingsSectionError +) +from taskipy.pyproject import PyProject + + +class Task: + def __init__(self, task_name: str, args: List[str], project: PyProject): + self.project = project + self.name = task_name + self.args = args + + def __str__(self) -> str: + return self.name + + @property + def pre_task(self) -> Optional[str]: + return self.__find_hooks('pre') + + @property + def post_task(self) -> Optional[str]: + return self.__find_hooks('post') + + @property + def commands(self) -> List[str]: + try: + command = self.project.tasks[self.name] + commands = [] + commands.append( + ' '.join([command] + [shlex.quote(arg) for arg in self.args]) + ) + + if self.pre_task: + commands.insert(0, self.pre_task) + + if self.post_task: + commands.append(self.post_task) + + return commands + except KeyError: + raise TaskNotFoundError(self.name) + + @property + def runner(self) -> Optional[str]: + try: + runner = self.project.settings['runner'] + + if not isinstance(runner, str): + raise InvalidRunnerTypeError() + + return runner.strip() + except (KeyError, MissingTaskipySettingsSectionError): + return None + + def __find_hooks(self, hook_type: str) -> Optional[str]: + try: + return self.project.tasks[f'{hook_type}_{self.name}'] + except KeyError: + return None diff --git a/taskipy/task_runner.py b/taskipy/task_runner.py new file mode 100644 index 0000000..cce472d --- /dev/null +++ b/taskipy/task_runner.py @@ -0,0 +1,33 @@ +import subprocess +from pathlib import Path +from typing import List, Union + +from taskipy.task import Task +from taskipy.pyproject import PyProject + + +class TaskRunner: + def __init__(self, pyproject_path: Union[str, Path]): + self.__pyproject_path = pyproject_path + self.__project = PyProject(pyproject_path) + + def run(self, task_name: str, args: List[str]) -> int: + task = Task(task_name, args, self.__project) + + for command in task.commands: + if task.runner is not None: + command = f'{task.runner} {command}' + + process = subprocess.Popen( + command, shell=True, cwd=Path(self.__pyproject_path).parent + ) + + try: + process.wait() + except KeyboardInterrupt: + pass + + if process.returncode != 0: + return process.returncode + + return 0 |