comparison piecrust/processing/sass.py @ 196:154b8df04829

processing: Add Compass and Sass processors. The Sass processor is similar to the Less processor, i.e. it tries to be part of the structured pipeline processing by using the mapfile produced by the Sass compiler in order to provide a list of dependencies. The Compass processor is completely acting outside of the pipeline, so the server won't know what's up to date and what's not. It's expected that the user will run `compass watch` to keep things up to date. However, it will require to pass the server's cache directory to put things in, so we'll need to add some easy way to get that path for the user.
author Ludovic Chabant <ludovic@chabant.com>
date Sun, 11 Jan 2015 23:08:49 -0800
parents
children c2ca72fb7f0b
comparison
equal deleted inserted replaced
195:b4724e577a8c 196:154b8df04829
1 import os
2 import os.path
3 import json
4 import hashlib
5 import logging
6 import platform
7 import subprocess
8 from piecrust.processing.base import SimpleFileProcessor
9 from piecrust.processing.tree import FORCE_BUILD
10
11
12 logger = logging.getLogger(__name__)
13
14
15 class SassProcessor(SimpleFileProcessor):
16 PROCESSOR_NAME = 'sass'
17
18 def __init__(self):
19 super(SassProcessor, self).__init__(
20 extensions={'scss': 'css', 'sass': 'css'})
21 self._conf = None
22 self._map_dir = None
23
24 def initialize(self, app):
25 super(SassProcessor, self).initialize(app)
26
27 def onPipelineStart(self, pipeline):
28 super(SassProcessor, self).onPipelineStart(pipeline)
29 self._map_dir = os.path.join(pipeline.tmp_dir, 'sass')
30 if not os.path.isdir(self._map_dir):
31 os.makedirs(self._map_dir)
32
33 # Ignore include-only Sass files.
34 pipeline.addSkipPatterns(['_*.scss', '_*.sass'])
35
36 def getDependencies(self, path):
37 if _is_include_only(path):
38 raise Exception("Include only Sass files should be ignored!")
39
40 map_path = self._getMapPath(path)
41 try:
42 with open(map_path, 'r') as f:
43 dep_map = json.load(f)
44 except IOError:
45 # Map file not found... rebuild.
46 logger.debug("No map file found for Sass file '%s' at '%s'. "
47 "Rebuilding." % (path, map_path))
48 return FORCE_BUILD
49
50 if dep_map.get('version') != 3:
51 logger.warning("Unknown Sass map version. Rebuilding.")
52 return FORCE_BUILD
53
54 sources = dep_map.get('sources', [])
55 deps = list(map(_clean_scheme, sources))
56 return deps
57
58 def _doProcess(self, in_path, out_path):
59 self._ensureInitialized()
60
61 if _is_include_only(in_path):
62 raise Exception("Include only Sass files should be ignored!")
63
64 sourcemap = 'none'
65 if self.app.cache.enabled:
66 sourcemap = 'file'
67
68 args = [self._conf['bin'],
69 '--sourcemap=%s' % sourcemap,
70 '--style', self._conf['style']]
71
72 cache_dir = self._conf['cache_dir']
73 if cache_dir:
74 args += ['--cache-location', cache_dir]
75 else:
76 args += ['--no-cache']
77
78 for lp in self._conf['load_paths']:
79 args += ['-I', lp]
80
81 args += self._conf['options']
82 args += [in_path, out_path]
83 logger.debug("Processing Sass file: %s" % args)
84
85 # On Windows, we need to run the process in a shell environment
86 # otherwise it looks like `PATH` isn't taken into account.
87 shell = (platform.system() == 'Windows')
88 try:
89 retcode = subprocess.call(args, shell=shell)
90 except FileNotFoundError as ex:
91 logger.error("Tried running Sass processor with command: %s" %
92 args)
93 raise Exception("Error running Sass processor. "
94 "Did you install it?") from ex
95
96 # The sourcemap is generated next to the CSS file... there doesn't
97 # seem to be any option to override that, sadly... so we need to move
98 # it to the cache directory.
99 if self.app.cache.enabled:
100 src_map_file = out_path + '.map'
101 dst_map_file = self._getMapPath(in_path)
102 try:
103 os.rename(src_map_file, dst_map_file)
104 except OSError:
105 pass
106
107 if retcode != 0:
108 raise Exception("Error occured in Sass compiler. Please check "
109 "log messages above for more information.")
110
111 return True
112
113 def _ensureInitialized(self):
114 if self._conf is not None:
115 return
116
117 self._conf = self.app.config.get('sass') or {}
118 self._conf.setdefault('bin', 'scss')
119 self._conf.setdefault('style', 'nested')
120 self._conf.setdefault('load_paths', [])
121 if not isinstance(self._conf['load_paths'], list):
122 raise Exception("The `sass/load_paths` configuration setting "
123 "must be an array of paths.")
124 self._conf.setdefault('options', [])
125 if not isinstance(self._conf['options'], list):
126 raise Exception("The `sass/options` configuration setting "
127 "must be an array of arguments.")
128
129 cache_dir = None
130 if self.app.cache.enabled:
131 cache_dir = os.path.join(self.app.cache_dir, 'sass')
132 self._conf.setdefault('cache_dir', cache_dir)
133
134 def _getMapPath(self, path):
135 map_name = "%s_%s.map" % (
136 os.path.basename(path),
137 hashlib.md5(path.encode('utf8')).hexdigest())
138 map_path = os.path.join(self._map_dir, map_name)
139 return map_path
140
141
142 def _clean_scheme(p):
143 if p.startswith('file://'):
144 return p[7:]
145 return p
146
147
148 def _is_include_only(path):
149 name = os.path.basename(path)
150 return len(name) > 0 and name[0] == '_'
151