1
+ import json
1
2
import os
2
3
import posixpath
3
4
import re
@@ -21,8 +22,9 @@ class LESS(base.BaseCompiler):
21
22
IMPORT_RE = re .compile (r"@import\s+(.+?)\s*;" , re .DOTALL )
22
23
IMPORT_ITEM_RE = re .compile (r"([\"'])(.+?)\1" )
23
24
24
- def __init__ (self , executable = settings .LESS_EXECUTABLE ):
25
+ def __init__ (self , executable = settings .LESS_EXECUTABLE , sourcemap_enabled = False ):
25
26
self .executable = executable
27
+ self .is_sourcemap_enabled = sourcemap_enabled
26
28
super (LESS , self ).__init__ ()
27
29
28
30
def should_compile (self , source_path , from_management = False ):
@@ -34,20 +36,46 @@ def should_compile(self, source_path, from_management=False):
34
36
def compile_file (self , source_path ):
35
37
full_source_path = self .get_full_source_path (source_path )
36
38
full_output_path = self .get_full_output_path (source_path )
37
- args = [
38
- self .executable ,
39
- self .get_full_source_path (source_path ),
40
- full_output_path ,
41
- ]
39
+
42
40
# `cwd` is a directory containing `source_path`.
43
41
# Ex: source_path = '1/2/3', full_source_path = '/abc/1/2/3' -> cwd = '/abc'
44
42
cwd = os .path .normpath (os .path .join (full_source_path , * ([".." ] * len (source_path .split ("/" )))))
43
+
44
+ args = [
45
+ self .executable
46
+ ]
47
+ if self .is_sourcemap_enabled :
48
+ args .extend ([
49
+ "--source-map"
50
+ ])
51
+
52
+ args .extend ([
53
+ self .get_full_source_path (source_path ),
54
+ full_output_path ,
55
+ ])
45
56
out , errors = utils .run_command (args , cwd = cwd )
46
57
if errors :
47
58
raise exceptions .StaticCompilationError (errors )
48
59
49
60
utils .convert_urls (full_output_path , source_path )
50
61
62
+ if self .is_sourcemap_enabled :
63
+ sourcemap_full_path = full_output_path + ".map"
64
+
65
+ with open (sourcemap_full_path ) as sourcemap_file :
66
+ sourcemap = json .loads (sourcemap_file .read ())
67
+
68
+ # LESS, unlike SASS, can't add correct relative paths in source map when the compiled file
69
+ # is not in the same dir as the source file. We fix it here.
70
+ sourcemap ["sources" ] = [
71
+ "../" * len (source_path .split ("/" )) + posixpath .dirname (source_path ) + "/" + source
72
+ for source in sourcemap ["sources" ]
73
+ ]
74
+ sourcemap ["file" ] = posixpath .basename (source_path )
75
+
76
+ with open (sourcemap_full_path , "w" ) as sourcemap_file :
77
+ sourcemap_file .write (json .dumps (sourcemap ))
78
+
51
79
return self .get_output_path (source_path )
52
80
53
81
def compile_source (self , source ):
0 commit comments