Coverage for collectra/gui/scss_theme.py: 88.64%

44 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-13 04:26 +0000

1"""Compile a project's SCSS theme (a few Bootstrap variables) into the GUI's CSS. 

2 

3A pipeline's ``theme: FILENAME.scss`` holds Bootstrap 5 variable overrides 

4(``$primary``, ``$body-bg``, ...). They are compiled with the bundled 

5Bootstrap sources by libsass, then the GUI's own ``--app-*`` 

6custom properties are derived from the same variables, so the theme file does 

7not have to know about them. The result is cached by content, so only the 

8first load after an edit pays for the compile. 

9""" 

10 

11import hashlib 

12import tempfile 

13from pathlib import Path 

14 

15from platformdirs import user_cache_dir 

16 

17BOOTSTRAP_VERSION = "5.3.8" 

18BOOTSTRAP_SCSS = Path(__file__).parent / "vendor" / "bootstrap" / "scss" 

19 

20# Bump when ``_APP_VARIABLES`` or the way the sheet is assembled changes, so a 

21# cached sheet from before the change is not used. 

22_CACHE_VERSION = "1" 

23 

24# Derives the GUI's --app-* properties from the Bootstrap variables the theme 

25# set (or Bootstrap's defaults for those it did not). 

26_APP_VARIABLES = """ 

27:root { 

28 --app-bg: #{$body-bg}; 

29 --app-fg: #{$body-color}; 

30 --app-fg-bright: #{mix($body-color, if(lightness($body-bg) < 50, #fff, #000), 75%)}; 

31 --app-fg-muted: #{mix($body-color, $body-bg, 65%)}; 

32 --app-surface: #{mix($body-bg, $body-color, 92%)}; 

33 --app-surface-alt: #{mix($body-bg, $body-color, 96%)}; 

34 --app-border: #{mix($body-bg, $body-color, 84%)}; 

35 --app-primary: #{$primary}; 

36 --app-primary-rgb: #{red($primary)}, #{green($primary)}, #{blue($primary)}; 

37 --app-primary-dark: #{shade-color($primary, 15%)}; 

38 --app-primary-fg: #{color-contrast($primary)}; 

39 --app-secondary: #{$secondary}; 

40 --app-secondary-rgb: #{red($secondary)}, #{green($secondary)}, #{blue($secondary)}; 

41 --app-secondary-fg: #{color-contrast($secondary)}; 

42 --app-danger: #{$danger}; 

43 --app-divider: #{rgba($primary, 0.084)}; 

44 --app-font-family: #{inspect($font-family-sans-serif)}; 

45} 

46""" 

47 

48 

49class ScssThemeError(Exception): 

50 """The theme could not be compiled; the message is for the user.""" 

51 

52 

53def _cache_key(source: str, directory: Path) -> str: 

54 digest = hashlib.sha256() 

55 for part in (BOOTSTRAP_VERSION, _CACHE_VERSION, _APP_VARIABLES, source): 

56 digest.update(part.encode("utf-8")) 

57 digest.update(b"\0") 

58 # Partials the theme may @import from beside it 

59 try: 

60 for sibling in sorted(directory.glob("*.scss")): 

61 digest.update(sibling.read_bytes()) 

62 except OSError: 

63 pass 

64 return digest.hexdigest() 

65 

66 

67def compile_theme(path: Path) -> str: 

68 """Return the CSS for the SCSS theme at ``path`` (cached by content).""" 

69 path = Path(path) 

70 source = path.read_text(encoding="utf-8") 

71 cache_file = Path(user_cache_dir("collectra")) / "themes" / f"{_cache_key(source, path.parent)}.css" 

72 try: 

73 return cache_file.read_text(encoding="utf-8") 

74 except OSError: 

75 pass 

76 

77 # The theme goes in between Bootstrap's functions and the rest of 

78 # Bootstrap, the order its docs prescribe for overriding variables. 

79 sheet = f'@import "functions";\n{source}\n@import "bootstrap";\n{_APP_VARIABLES}' 

80 try: 

81 import sass 

82 

83 css = sass.compile( 

84 string=sheet, 

85 include_paths=[str(path.parent), str(BOOTSTRAP_SCSS)], 

86 output_style="compressed", 

87 ) 

88 except ImportError as e: 

89 raise ScssThemeError("libsass is not installed (pip install libsass)") from e 

90 except sass.CompileError as e: 

91 raise ScssThemeError(f"{path.name}: {str(e).strip()}") from e 

92 try: 

93 cache_file.parent.mkdir(parents=True, exist_ok=True) 

94 with tempfile.NamedTemporaryFile( 

95 "w", encoding="utf-8", dir=cache_file.parent, delete=False 

96 ) as handle: 

97 handle.write(css) 

98 Path(handle.name).replace(cache_file) 

99 except OSError: 

100 pass # an unwritable cache only costs a recompile next time 

101 return css