]> git.lizzy.rs Git - cheatdb.git/blob - app/views/sass.py
Implement forum parser to increase accuracy
[cheatdb.git] / app / views / 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 from app import app
19
20 def _convert(dir, src, dst):
21         original_wd = os.getcwd()
22         os.chdir(dir)
23
24         css = Scss()
25         source = codecs.open(src, 'r', encoding='utf-8').read()
26         output = css.compile(source)
27
28         os.chdir(original_wd)
29
30         outfile = codecs.open(dst, 'w', encoding='utf-8')
31         outfile.write(output)
32         outfile.close()
33
34 def _getDirPath(originalPath, create=False):
35         path = originalPath
36
37         if not os.path.isdir(path):
38                 path = os.path.join(app.root_path, path)
39
40         if not os.path.isdir(path):
41                 if create:
42                         os.mkdir(path)
43                 else:
44                         raise IOError("Unable to find " + originalPath)
45
46         return path
47
48 def sass(app, inputDir='scss', outputPath='static', force=False, cacheDir="public/static"):
49         static_url_path = app.static_url_path
50         inputDir = _getDirPath(inputDir)
51         cacheDir = _getDirPath(cacheDir or outputPath, True)
52
53         def _sass(filepath):
54                 sassfile = "%s/%s.scss" % (inputDir, filepath)
55                 cacheFile = "%s/%s.css" % (cacheDir, filepath)
56
57                 # Source file exists, and needs regenerating
58                 if os.path.isfile(sassfile) and (force or not os.path.isfile(cacheFile) or \
59                                 os.path.getmtime(sassfile) > os.path.getmtime(cacheFile)):
60                         _convert(inputDir, sassfile, cacheFile)
61                         app.logger.debug('Compiled %s into %s' % (sassfile, cacheFile))
62
63                 return send_from_directory(cacheDir, filepath + ".css")
64
65         app.add_url_rule("/%s/<path:filepath>.css" % (outputPath), 'sass', _sass)
66
67 sass(app)