Skip to content

Instantly share code, notes, and snippets.

@mdellavo
Created June 10, 2010 02:18
Show Gist options
  • Save mdellavo/432483 to your computer and use it in GitHub Desktop.
Save mdellavo/432483 to your computer and use it in GitHub Desktop.
import shutils, hashlib, os
from pylons import config, request
from webhelpers.html.tags import javascript_link, stylesheet_link
sha1 = lambda x : hashlib.sha1(x).hexdigest()
mtime = lambda path: os.path.stat(path).st_mtime
# FIXME factor out pylons adapter
class Glommer(object):
@property
def key(self):
return 'glom.' + self.type
@property
def files(self):
return request.environ.get(self.key, [])
def src_path(self, path):
return os.path.join(config['static_files'], self.type, path)
def dest_path(self, filename):
dir_path = os.path.join(config['static_files'], config['glom.emit_dirname'], self.type)
if not os.path.is_dir(dir_path):
os.makedirs(dir_path)
return os.path.join(dir_path, path)
def link_path(self, filename):
return '/' + config['glom.emit_dirname'] +'/' + self.type '/' + self.filename
def add_file(self, path):
key = self.key
if key not in request.environ:
request.environ[key] = []
request.environ[key].append(path)
return ''
@property
def is_debug(self):
return config['debug']
def build_tag(self, path):
return self.builder(path)
def include(self, path):
return self.add_file(path) if not self.is_debug else self.build_tag(path)
def emit(self, filename=None):
files = self.files
paths = [ self.src_path(f) for f in files ]
if not paths:
return ''
if filename is None:
filename = sha1(','.join(files)) + '.' + self.type
dest_path = self.dest_path(filename)
dest_mtime = mtime(dest_path)
src_mtime = max(mtime(f) for f in paths)
if not os.path.is_file(dest_path) or src_mtime > dest_mtime:
dest = open(dest_path, 'wb')
for f in paths:
shutil.copyfile(open(f, 'wb'), dest)
dest.close()
return self.build_tag(self.link_path(filename))
class JSGlommer(Glommer):
type = 'js'
builder = javascript_link
class CSSGlommer(Glommer):
type = 'css'
builder = stylesheet_link
js = JSGlommer()
css = CSSGlommer()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment