Example #1
0
def main(args):
    try:
        url = args[1]
        filename = args[2]
    except IndexError:
        raise ValueError("usage: python copier `url` `filename`")
    try:
        driver = get_driver(url)

        print "loading %s..." % url
        driver.execute_script('window.onbeforeunload = function() {}')
        driver.get(url)
        print "getting handler..."
        h = get_handler(driver, url)
        print "loaded %s..." % driver.current_url

        def handler(event_type, src_path):
            # TODO: filename in src_path might be a little insecure
            if event_type == "modified" and filename in src_path:
                with open(src_path) as f:
                    contents = f.read()
                    h(contents)
                    print contents
        print "watching for changes..."
        easywatch.watch(".", handler)
    finally:
        driver.close()
Example #2
0
    def watch(self):
        """Watch and reload modified templates."""
        import easywatch

        self.site.logger.info("Watching '%s' for changes...", self.searchpath)
        self.site.logger.info("Press Ctrl+C to stop.")
        easywatch.watch(self.searchpath, self.event_handler)
Example #3
0
    def _watch(self):
        """Watch and reload templates."""
        import easywatch

        self.logger.info("Watching '%s' for changes..." %
                          self.template_folder)
        self.logger.info("Press Ctrl+C to stop.")

        def handler(event_type, src_path):
            template_name = os.path.relpath(src_path, self.template_folder)
            if event_type == "modified":
                if src_path.startswith(self.template_folder):
                    try:
                        if self.filter_func(template_name):
                            self.render_template(template_name)
                        else:
                            # Wait a bit, since some editors (e.g., vim) make
                            # the file disappear when writing, and inotify might
                            # be too fast, put it in the template_names list and
                            # later fail when trying to access it.
                            time.sleep(0.1)

                            # As reported in #16, when an ignored file is changed,
                            # some dependency management would be required. For
                            # example, if a _base.html is modified, only those files
                            # importing it should be regenerated. In the meanwhile...
                            self.render_templates()
                    except:
                        # Keep working, but show exceptions
                        traceback.print_exc()
        easywatch.watch(self.template_folder, handler)
Example #4
0
def main(searchpath="templates", outpath=".", filter_func=None, contexts=None,
         extensions=None, rules=None, autoreload=True):
    """
    Render each of the templates and then recompile on any changes.
    *   searchpath should be the directory that contains the templates.
        Defaults to "templates".
    *   outpath should be the name of the directory to build the templates to.
    *   filter_func should be a function that takes a filename and returns
        a boolean indicating whether or not a template should be rendered.
        Defaults to ignore any files with '.' or '_' prefixes.
    *   contexts should be a map of template names to functions where each
        function should return a context for that template.
    *   extensions should be any extensions to add to the Environment.
    *   autoreload should be a boolean indicating whether or not to
        automatically recompile templates. Defaults to true.
    """
    if extensions is None:
        extensions = []

    # Get calling module
    mod = inspect.getmodule(inspect.stack()[-1][0])
    # Absolute path to project
    project_path = os.path.realpath(os.path.dirname(mod.__file__))
    # Absolute path to templates
    template_path = os.path.join(project_path, searchpath)

    loader = FileSystemLoader(searchpath=searchpath)
    env = Environment(loader=loader,
                      extensions=extensions)

    def build_all():
        render_templates(env, outpath, contexts, filter_func=filter_func,
                         rules=rules)
        print "Templates built."

    build_all()

    if autoreload:
        print "Watching '%s' for changes..." % searchpath
        print "Press Ctrl+C to stop."

        def handler(event_type, src_path):
            if event_type == "modified":
                if src_path.startswith(template_path):
                    build_all()
        easywatch.watch("./" + searchpath, handler)

        set_exit_on_sigint()

        print "Process killed."

    return 0
Example #5
0
    def _watch(self):
        """Watch and reload templates."""
        import easywatch

        self.logger.info("Watching '%s' for changes..." %
                          self.template_folder)
        self.logger.info("Press Ctrl+C to stop.")

        def handler(event_type, src_path):
            template_name = os.path.relpath(src_path, self.template_folder)
            if event_type == "modified":
                if src_path.startswith(self.template_folder):
                    self.render_template(template_name)
        easywatch.watch(self.template_folder, handler)
Example #6
0
 def watch(self):
     """Watch and reload modified templates."""
     import easywatch
     easywatch.watch(self.searchpath, self.event_handler)
Example #7
0
    """
    Function that is passed to a watcher that polls for changes
    in a directory. This is run when some sort of change (an `event_type`)
    is detected.
    """
    # there are four kinds of event types:
    #  created, deleted, modified, moved

    # ignore all files that start with `.`
    if os.path.basename(src_path)[0] == '.':
        return

    # only re-build when a file is deleted, modified, or moved
    if event_type != 'created':
        print('detected a change in ' + src_path)
        build('templates', 'templates', 'index.html', '.', 'output.html')


if __name__ == '__main__':
    if "--help" in sys.argv or "-h" in sys.argv:
        print("python build.py [--watch]")
    else:
        # if argv = [command name, --watch, ...]
        if len(sys.argv) > 1 and sys.argv[1] == '--watch':
            import easywatch
            print("Watching course-pages/templates for changes")
            print("Ctrl-c to quit")
            easywatch.watch('./templates/templates', handler)
        else:
            build('templates', 'templates', 'index.html', '.', 'output.html')
Example #8
0
    if time.time() - nextRunTime < 0:
        print_skip( 'Skipping %s action on %s, timeout from last run (%.02f)' % ( action, filename, nextRunTime - time.time() ) )
        return

    if action not in args.actions:
        print_skip( 'Skipping %s action on %s' % ( action, filename ) )
        return

    if args.skip_directory and not os.path.isfile( filename ):
        print_skip( 'Skipping %s action on %s, is a directory' % ( action, filename ) )
        return
    
    for n in skip_regexes:
        regex, reason = n

        if regex.match( filename ):
            print_skip( 'Skipping %s action on %s, %s' % ( action, filename, reason ) )
            return

    print_start( 'Updating for %s action on %s.' % ( action, filename ) )
    run()
    nextRunTime = time.time() + float(args.run_wait_time)
    print_done( 'Done running command.' )

if args.initial_run:
    print_start( 'Doing initial run.' )
    run()
    print_done( 'Beginning with watching.' )

easywatch.watch( args.path, onUpdate )
Example #9
0
        if filename.startswith(('.', '_')):
            return False
        if not filename.endswith('.html'):
            return False
        return True

    def dont_render(*args, **kwargs):
        print "Rendering..."
        pass

    if options.customwatch:
        options.dont_stop = True

    renderer = Renderer(outpath='./output', rules=[('.*.tmp', dont_render), ('.*.swx', dont_render), ('.*.swp', dont_render)])
    renderer._env.filters["markdown"] = markdown_filter
    renderer._env.filters['datetimeformat'] = datetimeformat
    renderer.filter_func = filter_func

    renderer.run(debug=True, use_reloader=not options.dont_stop)

    if options.customwatch:
        import easywatch

        def handler(file, handler):
            print "Detected changes: rendering again."
            renderer.run(debug=True, use_reloader=False)
            print "Render finished. Watching for changes..."

        print "Watching out for changes..."
        easywatch.watch("./templates", handler)
def watch_assets():
    print('Monitoring assets...')
    easywatch.watch("./template_assets/", asset_handler)
Example #11
0
	def watch(self):
	    import easywatch
	    easywatch.watch(self.searchpath, self.eventHandler)
Example #12
0
 def watch(self):
     """Watch and reload modified templates."""
     import easywatch
     easywatch.watch(self.searchpath, self.event_handler)
Example #13
0
 def watch(self):
     import easywatch
     easywatch.watch(self.watch_paths, self.event_handler)
def watch_assets():
    print 'Monitoring assets...'
    easywatch.watch("./template_assets/", asset_handler)