Skip to content

Instantly share code, notes, and snippets.

@marconi
Created October 6, 2012 03:46
Show Gist options
  • Save marconi/3843698 to your computer and use it in GitHub Desktop.
Save marconi/3843698 to your computer and use it in GitHub Desktop.
A more intelligent less file compiler.
# -*- coding: utf-8 -*-
"""
Watchless will compile your less files whenever it detects changes.
Accepts one argument, the path where your less files are stored.
Say your less files are store in /static/less and it contains the file
layout.less, watchless will compile it and store the compiled css file
in /static/css/layout.css.
Usage:
python watchless.py <path to less directory>
"""
import sys
import os
import pyinotify
wm = pyinotify.WatchManager()
mask = pyinotify.IN_MODIFY | pyinotify.IN_CREATE
class EventHandler(pyinotify.ProcessEvent):
def __init__(self, *args, **kwargs):
self.css_root = kwargs.pop('css_root')
self.less_root = kwargs.pop('less_root')
if not os.path.exists(self.css_root):
os.makedirs(self.css_root)
super(EventHandler, self).__init__(*args, **kwargs)
def _compile_less(self, less_file):
if not less_file.endswith('.less'):
return
print "Compiling %s" % less_file
# mirror mirror on the wall, is the directory present in css path
parent_less_path = os.path.dirname(less_file)
relative_less_path = parent_less_path.replace(self.less_root, '')[1:]
parent_css_path = os.path.join(self.css_root, relative_less_path)
if not os.path.exists(parent_css_path):
os.makedirs(parent_css_path)
filename, __ = os.path.splitext(os.path.basename(less_file))
css_file = "%s.css" % os.path.join(parent_css_path, filename)
os.system("lessc %(from)s > %(to)s -x" % {"from": less_file,
"to": css_file})
def process_IN_MODIFY(self, event):
self._compile_less(event.pathname)
def process_IN_CREATE(self, event):
self._compile_less(event.pathname)
if __name__ == '__main__':
if len(sys.argv) != 2:
print "You need to specify the path where .less files are located."
sys.exit(1)
if not os.path.exists(sys.argv[1]):
print "The path you specified doesn't exist."
sys.exit(1)
LESS_ROOT = sys.argv[1]
CSS_ROOT = os.path.join(os.path.split(LESS_ROOT)[0], 'css')
handler = EventHandler(less_root=LESS_ROOT, css_root=CSS_ROOT)
notifier = pyinotify.Notifier(wm, handler)
wdd = wm.add_watch(LESS_ROOT, mask, rec=True, auto_add=True)
print "Imma watch your less baby!"
notifier.loop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment