Coverage for fastblocks / adapters / templates / _base.py: 77%

92 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-01-02 20:00 -0800

1import typing as t 

2from abc import ABC 

3 

4from anyio import Path as AsyncPath 

5from oneiric.core.config import OneiricSettings 

6from oneiric.core.resolution import Resolver 

7from starlette.requests import Request 

8from starlette.responses import Response 

9 

10 

11# Custom implementations for ACB compatibility 

12def get_adapters() -> list[t.Any]: 

13 """Custom implementation for Oneiric compatibility.""" 

14 # This will be implemented using Oneiric's adapter system 

15 return [] 

16 

17 

18def root_path() -> str: 

19 """Custom implementation for Oneiric compatibility.""" 

20 # This will be implemented using Oneiric's path system 

21 return "/" 

22 

23 

24# Oneiric resolver for dependency injection 

25depends = Resolver() 

26 

27# Placeholder for pkg_registry (will be implemented with Oneiric) 

28pkg_registry = None 

29 

30 

31async def safe_await(func_or_value: t.Any) -> t.Any: 

32 if callable(func_or_value): 

33 try: 

34 result = func_or_value() 

35 if hasattr(result, "__await__") and callable(result.__await__): 

36 return await t.cast("t.Awaitable[t.Any]", result) 

37 return result 

38 except Exception: 

39 return True 

40 return func_or_value 

41 

42 

43TemplateContext: t.TypeAlias = dict[str, t.Any] 

44TemplateResponse: t.TypeAlias = Response 

45TemplateStr: t.TypeAlias = str 

46TemplatePath: t.TypeAlias = str 

47T = t.TypeVar("T") 

48 

49 

50class TemplateRenderer(t.Protocol): 

51 async def render_template( 

52 self, 

53 request: Request, 

54 template: TemplatePath, 

55 _: TemplateContext | None = None, 

56 ) -> TemplateResponse: ... 

57 

58 

59class TemplateLoader(t.Protocol): 

60 async def get_template(self, name: TemplatePath) -> t.Any: ... 

61 

62 async def list_templates(self) -> list[TemplatePath]: ... 

63 

64 

65class TemplatesBaseSettings(OneiricSettings, ABC): 

66 cache_timeout: int = 300 

67 

68 def __init__(self, **values: t.Any) -> None: 

69 # Extract cache_timeout from values before passing to parent 

70 cache_timeout = values.pop("cache_timeout", 300) 

71 super().__init__(**values) 

72 # For now, set cache_timeout directly 

73 # In a full migration, this would use Oneiric's configuration system 

74 self.cache_timeout = cache_timeout 

75 

76 

77class TemplatesProtocol(t.Protocol): 

78 def get_searchpath(self, adapter: t.Any, path: AsyncPath) -> None: ... 

79 

80 async def get_searchpaths(self, adapter: t.Any) -> list[AsyncPath]: ... 

81 

82 @staticmethod 

83 def get_storage_path(path: AsyncPath) -> AsyncPath: ... 

84 

85 @staticmethod 

86 def get_cache_key(path: AsyncPath) -> str: ... 

87 

88 

89class AdapterBase: 

90 """Custom AdapterBase for Oneiric compatibility.""" 

91 

92 pass 

93 

94 

95class TemplatesBase(AdapterBase): 

96 app: t.Any | None = None 

97 admin: t.Any | None = None 

98 app_searchpaths: list[AsyncPath] | None = None 

99 admin_searchpaths: list[AsyncPath] | None = None 

100 

101 def __init__(self, **kwargs: t.Any) -> None: 

102 # Initialize base attributes 

103 for key, value in kwargs.items(): 

104 setattr(self, key, value) 

105 

106 def get_searchpath(self, adapter: t.Any, path: AsyncPath) -> list[AsyncPath]: 

107 style = getattr(self.config.app, "style", "vanilla") 

108 base_path = path / "base" 

109 style_path = path / style 

110 style_adapter_path = path / style / adapter.name 

111 theme_adapter_path = style_adapter_path / "theme" 

112 return [theme_adapter_path, style_adapter_path, style_path, base_path] 

113 

114 async def get_searchpaths(self, adapter: t.Any) -> list[AsyncPath]: 

115 searchpaths = [] 

116 base_root = self._get_base_root() 

117 

118 if adapter and hasattr(adapter, "category"): 

119 searchpaths.extend( 

120 self.get_searchpath( 

121 adapter, base_root / "templates" / adapter.category 

122 ), 

123 ) 

124 

125 if adapter and hasattr(adapter, "category") and adapter.category == "app": 

126 searchpaths.extend(await self._get_app_searchpaths(adapter)) 

127 

128 # Only use pkg_registry if it's available 

129 if pkg_registry: 

130 searchpaths.extend(await self._get_pkg_registry_searchpaths(adapter)) 

131 

132 return searchpaths 

133 

134 def _get_base_root(self) -> AsyncPath: 

135 if callable(root_path): 

136 return AsyncPath(root_path()) 

137 return AsyncPath(root_path) 

138 

139 async def _get_app_searchpaths(self, adapter: t.Any) -> list[AsyncPath]: 

140 searchpaths = [] 

141 for a in ( 

142 a 

143 for a in get_adapters() 

144 if a 

145 and hasattr(a, "category") 

146 and a.category not in ("app", "admin", "secret") 

147 ): 

148 exists_result = await safe_await((a.path / "_templates").exists) 

149 if exists_result: 

150 searchpaths.append(a.path / "_templates") 

151 return searchpaths 

152 

153 async def _get_pkg_registry_searchpaths(self, adapter: t.Any) -> list[AsyncPath]: 

154 searchpaths = [] 

155 for pkg in pkg_registry.get(): 

156 if ( 

157 pkg 

158 and hasattr(pkg, "path") 

159 and adapter 

160 and hasattr(adapter, "category") 

161 ): 

162 searchpaths.extend( 

163 self.get_searchpath( 

164 adapter, 

165 pkg.path / "adapters" / adapter.category / "_templates", 

166 ), 

167 ) 

168 return searchpaths 

169 

170 @staticmethod 

171 def get_storage_path(path: AsyncPath) -> AsyncPath: 

172 templates_path_name = "templates" 

173 if templates_path_name not in path.parts: 

174 templates_path_name = "_templates" 

175 depth = path.parts.index(templates_path_name) - 1 

176 _path = list(path.parts[depth:]) 

177 _path.insert(1, _path.pop(0)) 

178 return AsyncPath("/".join(_path)) 

179 depth = path.parts.index(templates_path_name) 

180 return AsyncPath("/".join(path.parts[depth:])) 

181 

182 @staticmethod 

183 def get_cache_key(path: AsyncPath) -> str: 

184 return ":".join(path.parts) 

185 

186 

187# Oneiric migration indicator 

188_using_oneiric = True