view python/ppci/tasks.py @ 332:87feb8a23b4d

Added task list command
author Windel Bouwman
date Fri, 07 Feb 2014 12:51:55 +0100
parents 8f6f3ace4e78
children 6f4753202b9a
line wrap: on
line source


class TaskError(Exception):
    pass


class Task:
    """ Task that can run, and depend on other tasks """
    def __init__(self, name):
        self.name = name
        self.subtasks = []
        self.completed = False
        self.dependencies = []

    def run(self):
        raise NotImplementedError("Implement this abstract method!")

    def fire(self):
        assert all(t.completed for t in self.dependencies)
        self.run()
        self.completed = True

    def addSubTask(self, tsk):
        self.subtasks.append(tsk)
        return tsk

    def addDependency(self, task):
        self.dependencies.append(task)
        return task

    def __repr__(self):
        return 'Task "{}"'.format(self.name)


class TaskRunner:
    """ Basic task runner that can run some tasks in sequence """
    def __init__(self):
        self.task_list = []

    def add_task(self, task):
        self.task_list.append(task)

    def run_tasks(self):
        try:
            for t in self.task_list:
                #print('Running {}'.format(t.name))
                t.fire()
        except TaskError as e:
            print('Error: {}'.format(e))
            return 1
        return 0

    def display(self):
        """ Display task how they would be run """
        for task in self.task_list:
            print(task)