Debian Codegraph @

django_sass/management/commands/sass.py

raw symbols SCIP
1 from typing import Dict
2 import os
3 import sys
4 import time
5
6 from django.core.management.base import BaseCommand
7 import sass
8
9 from django_sass import compile_sass, find_static_scss
10
11
12 class Command(BaseCommand):
13 help = "Runs libsass including all paths from STATICFILES_FINDERS."
14
15 def add_arguments(self, parser):
16 parser.add_argument(
17 "in",
18 type=str,
19 nargs="+",
20 help="An scss file, or directory containing scss files",
21 )
22 parser.add_argument(
23 "out",
24 type=str,
25 nargs="+",
26 help="A file or directory in which to output transpiled css",
27 )
28 parser.add_argument(
29 "-g",
30 dest="g",
31 action="store_true",
32 help="Build a sourcemap. Only applicable if input is a file, not a directory.",
33 )
34 parser.add_argument(
35 "-t",
36 type=str,
37 dest="t",
38 default="expanded",
39 help="Output type. One of 'expanded', 'nested', 'compact', 'compressed'",
40 )
41 parser.add_argument(
42 "-p",
43 type=int,
44 dest="p",
45 default=8,
46 help="Precision. Defaults to 8",
47 )
48 parser.add_argument(
49 "--watch",
50 dest="watch",
51 action="store_true",
52 default=False,
53 help="Watch input path and re-generate css files when scss files are changed.",
54 )
55
56 def handle(self, *args, **options) -> None:
57 """
58 Finds all static paths used by the project, and runs sass
59 including those paths.
60 """
61
62 # Parse options.
63 o_inpath = options["in"][0]
64 o_outpath = options["out"][0]
65 o_srcmap = options["g"]
66 o_precision = options["p"]
67 o_style = options["t"]
68
69 # Watch files for changes if specified.
70 if options["watch"]:
71 try:
72 self.stdout.write("Watching...")
73
74 # Track list of files to watch and their modified time.
75 watchfiles = {} # type: Dict[str, float]
76 while True:
77 needs_updated = False
78
79 # Build/update list of ALL scss files in static paths.
80 for fullpath in find_static_scss():
81 prev_mtime = watchfiles.get(fullpath, 0)
82 curr_mtime = os.stat(fullpath).st_mtime
83 if curr_mtime > prev_mtime:
84 needs_updated = True
85 watchfiles.update({fullpath: curr_mtime})
86
87 # Recompile the sass if needed.
88 if needs_updated:
89 # Catch compile errors to keep the watcher running.
90 try:
91 compile_sass(
92 inpath=o_inpath,
93 outpath=o_outpath,
94 output_style=o_style,
95 precision=o_precision,
96 source_map=o_srcmap,
97 )
98 self.stdout.write(
99 "Updated files at %s" % time.time()
100 )
101 except sass.CompileError as exc:
102 self.stdout.write(str(exc))
103
104 # Go back to sleep.
105 time.sleep(3)
106
107 except (KeyboardInterrupt, InterruptedError):
108 self.stdout.write("Bye.")
109 sys.exit(0)
110
111 # Write css.
112 self.stdout.write("Writing css...")
113 compile_sass(
114 inpath=o_inpath,
115 outpath=o_outpath,
116 output_style=o_style,
117 precision=o_precision,
118 source_map=o_srcmap,
119 )
120 self.stdout.write("Done.")