1
0
Fork 0
mirror of https://github.com/Findus23/RPGnotes.git synced 2024-09-19 15:43:45 +02:00
RPGnotes/utils/assets.py

48 lines
1.5 KiB
Python
Raw Normal View History

2022-04-11 22:43:06 +02:00
from hashlib import sha256
2021-08-22 20:10:29 +02:00
from pathlib import Path
import sass
2022-04-11 22:43:06 +02:00
from django.core.cache import cache
2021-08-22 20:10:29 +02:00
2021-08-29 22:09:22 +02:00
basedir = Path(__file__).resolve().parent.parent
2021-08-22 20:10:29 +02:00
inputdir = basedir / "static/scss/"
inputfile = inputdir / "main.scss"
outputfile = basedir / "static/css/main.css"
sourcemap = outputfile.with_suffix(".css.map")
2022-04-11 22:43:06 +02:00
def get_file_hash():
times = 0
for file in inputdir.glob("*.scss"):
times += int(file.stat().st_mtime)
return sha256(times.to_bytes(16, 'little', signed=False)).hexdigest()
2022-04-11 22:45:00 +02:00
def get_css(debug=False, ignore_cache=False):
2021-08-22 20:10:29 +02:00
sourcemap_name = "css_sourcemap" if debug else str(sourcemap)
2022-04-11 22:43:06 +02:00
stored_file_hash = cache.get("scss_file_hash")
real_file_hash = get_file_hash()
2022-04-11 22:45:00 +02:00
if not stored_file_hash or stored_file_hash != real_file_hash or ignore_cache:
2022-04-11 22:43:06 +02:00
css, sourcemap_text = sass.compile(
filename=str(inputfile),
output_style="nested" if debug else "compressed",
include_paths=[str(inputdir), str(basedir)],
source_map_filename=sourcemap_name,
source_map_contents=True
)
cache.set("scss_file_hash", real_file_hash)
cache.set("scss_css", css)
cache.set("scss_sourcemap", sourcemap_text)
return css, sourcemap_text
2021-08-22 20:10:29 +02:00
2022-04-11 22:45:00 +02:00
return cache.get("scss_css"), cache.get("scss_sourcemap")
2021-08-22 20:10:29 +02:00
def save_css():
2022-04-11 22:45:00 +02:00
css, sourcemap_text = get_css(ignore_cache=True)
2021-08-22 20:10:29 +02:00
with outputfile.open("w") as f:
f.write(css)
with sourcemap.open("w") as f:
f.write(sourcemap_text)