Skip to content

Instantly share code, notes, and snippets.

@jsmesami
Created November 13, 2011 17:00
Show Gist options
  • Save jsmesami/1362331 to your computer and use it in GitHub Desktop.
Save jsmesami/1362331 to your computer and use it in GitHub Desktop.
Watch for Coffeescript or Less files in your project tree and compile them on save.
#!/usr/bin/env python
import os, time
import optparse
import subprocess
def watch(watchpath, delay=1):
"""\
recursively iterates over files in a directory tree and watches for the ones that have been changed
returns an infinite iterator object containing filenames of changed files
"""
watched_files = {}
while True:
for root, dirnames, filenames in os.walk(watchpath):
for file in filenames:
path = os.path.join(root, file)
try:
mod_time = os.stat(path).st_mtime
except OSError: # inaccessible
continue
try:
if watched_files[path] < mod_time:
yield path
except KeyError:
pass
watched_files[path] = mod_time
time.sleep(delay)
if __name__ == '__main__':
commands = {
'.less': 'lessc {file}.less > {file}.css',
'.coffee': 'coffee -c {file}.coffee',
# add more
}
usage = 'usage: %prog [options] PATH'
parser = optparse.OptionParser(usage=usage, description='Less CSS and Coffeescript compilig automator')
parser.add_option('-d', '--delay', type=int, default=1, help='polling interval in seconds')
parser.add_option('-q', '--quiet', action='store_true', default=False, help='turn off informational messages')
options, args = parser.parse_args()
watchpath = '.' if not args else args[0]
try:
for file in watch(watchpath, options.delay):
basename, extension = os.path.splitext(os.path.abspath(file))
try:
command = commands[extension].format(file=basename)
if not options.quiet: print('envoking compiler for {file}:\n{command}'.format(file=file, command=command))
ret = subprocess.call(command, shell=True)
if not options.quiet: print('\033[92m[success]\033[0m' if not ret else '\033[91m[failed]\033[0m')
except KeyError: # command not defined
pass
except KeyboardInterrupt:
if not options.quiet: print('\n\033[94m[end]\033[0m')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment