]> git.lizzy.rs Git - cheatdb.git/blob - app/sass.py
Improve MinetestCheck name validation
[cheatdb.git] / app / sass.py
1 # -*- coding: utf-8 -*-
2 """
3 A small Flask extension that makes it easy to use Sass (SCSS) with your
4 Flask application.
5
6 Code unabashedly adapted from https://github.com/weapp/flask-coffee2js
7
8 :copyright: (c) 2012 by Ivan Miric.
9 :license: MIT, see LICENSE for more details.
10 """
11
12 import os
13 import os.path
14 import codecs
15 from flask import *
16 from scss import Scss
17
18 def _convert(dir, src, dst):
19         original_wd = os.getcwd()
20         os.chdir(dir)
21
22         css = Scss()
23         source = codecs.open(src, 'r', encoding='utf-8').read()
24         output = css.compile(source)
25
26         os.chdir(original_wd)
27
28         outfile = codecs.open(dst, 'w', encoding='utf-8')
29         outfile.write(output)
30         outfile.close()
31
32 def _getDirPath(app, originalPath, create=False):
33         path = originalPath
34
35         if not os.path.isdir(path):
36                 path = os.path.join(app.root_path, path)
37
38         if not os.path.isdir(path):
39                 if create:
40                         os.mkdir(path)
41                 else:
42                         raise IOError("Unable to find " + originalPath)
43
44         return path
45
46 def sass(app, inputDir='scss', outputPath='static', force=False, cacheDir="public/static"):
47         static_url_path = app.static_url_path
48         inputDir = _getDirPath(app, inputDir)
49         cacheDir = _getDirPath(app, cacheDir or outputPath, True)
50
51         def _sass(filepath):
52                 sassfile = "%s/%s.scss" % (inputDir, filepath)
53                 cacheFile = "%s/%s.css" % (cacheDir, filepath)
54
55                 # Source file exists, and needs regenerating
56                 if os.path.isfile(sassfile) and (force or not os.path.isfile(cacheFile) or \
57                                 os.path.getmtime(sassfile) > os.path.getmtime(cacheFile)):
58                         _convert(inputDir, sassfile, cacheFile)
59                         app.logger.debug('Compiled %s into %s' % (sassfile, cacheFile))
60
61                 return send_from_directory(cacheDir, filepath + ".css")
62
63         app.add_url_rule("/%s/<path:filepath>.css" % (outputPath), 'sass', _sass)