Source

AutoRebuild / autorebuild.py

Full commit
"""
AutoRebuild
===========

A plugin that will perform a rebuild when a file changes.
"""
import os
import glob

from cherrypy.process.plugins import Autoreloader


class AutoRebuild(Autoreloader):

    taskmap = {}

    def tasks(self):
        """
        See if any files have changed for a certain task.
        """
        tasks = []
        for regex, task in self.taskmap.iteritems():
            changed = []
            for filename in glob.iglob(regex):
                oldtime = self.mtimes.get(filename, 0)
                if oldtime is None:
                    continue

                try:
                    mtime = os.stat(filename).st_mtime
                except OSError:
                    mtime = None

                self.mtimes[filename] = mtime

                if mtime is None or mtime > oldtime:
                    changed.append(filename)

            if changed:
                tasks.append((task, changed))
        return tasks

    def run(self):
        for task, changed in self.tasks():
            self.bus.log('Executing %s. These changed: %s' % (task, changed))
            task()


if __name__ == '__main__':
    import cherrypy
    from subprocess import call

    class Root(object):
        def index(self):
            return 'Hello World!'
        index.exposed = True

    def build_css():
        call(['make', 'css'])

    cherrypy.engine.autorebuild = AutoRebuild(cherrypy.engine)
    cherrypy.engine.autorebuild.subscribe()

    cherrypy.config.update({
            'engine.autorebuild.on': True,
            'engine.autorebuild.taskmap': {'*.less': build_css}})

    cherrypy.tree.mount(Root(), '/')
    cherrypy.engine.start()
    cherrypy.engine.block()