1use std::collections::BTreeMap;
13use std::path::{Path, PathBuf};
14
15use yk_core::Result;
16
17#[derive(Clone, Debug, Eq, PartialEq)]
23pub struct HttpResponse {
24 pub status: u16,
28 pub body: String,
30}
31
32#[async_trait::async_trait]
33
34#[async_trait::async_trait]
36pub trait Host: Send + Sync {
37 async fn read_file(&self, path: &Path) -> Result<String>;
43
44 async fn http_get(&self, url: &str) -> Result<String>;
50
51 async fn http_post_json(
69 &self,
70 url: &str,
71 headers: &BTreeMap<String, String>,
72 body: &str,
73 ) -> Result<HttpResponse>;
74
75 fn env(&self, name: &str) -> Option<String>;
85}
86
87#[derive(Clone, Copy, Debug, Default)]
92pub struct DenyHost;
93
94#[async_trait::async_trait]
95impl Host for DenyHost {
96 async fn read_file(&self, path: &Path) -> Result<String> {
97 Err(yk_core::Error::Tool {
98 tool: "host.read_file".to_owned(),
99 reason: format!(
100 "no host is configured, so `{}` was not read",
101 path.display()
102 ),
103 })
104 }
105
106 async fn http_get(&self, url: &str) -> Result<String> {
107 Err(yk_core::Error::Tool {
108 tool: "host.http_get".to_owned(),
109 reason: format!("no host is configured, so `{url}` was not fetched"),
110 })
111 }
112
113 async fn http_post_json(
114 &self,
115 url: &str,
116 _headers: &BTreeMap<String, String>,
117 _body: &str,
118 ) -> Result<HttpResponse> {
119 Err(yk_core::Error::Tool {
120 tool: "host.http_post_json".to_owned(),
121 reason: format!("no host is configured, so nothing was posted to `{url}`"),
122 })
123 }
124
125 fn env(&self, name: &str) -> Option<String> {
126 let _ = name;
127 None
128 }
129}
130
131#[derive(Clone, Debug, Default)]
137pub struct ExtensionSources {
138 pub user: Option<PathBuf>,
140 pub repo: Option<PathBuf>,
142 pub trust_repo: bool,
144}
145
146impl ExtensionSources {
147 #[must_use]
152 pub fn active(&self) -> Vec<PathBuf> {
153 let mut dirs: Vec<PathBuf> = self.user.iter().cloned().collect();
154 if self.trust_repo
155 && let Some(repo) = &self.repo
156 {
157 dirs.push(repo.clone());
158 }
159 dirs
160 }
161
162 #[must_use]
164 pub fn skipped(&self) -> Vec<PathBuf> {
165 if self.trust_repo {
166 Vec::new()
167 } else {
168 self.repo.iter().cloned().collect()
169 }
170 }
171}
172
173#[must_use]
175pub fn user_dir() -> PathBuf {
176 let base = std::env::var_os("XDG_CONFIG_HOME").map_or_else(
177 || {
178 std::env::var_os("HOME")
179 .map_or_else(|| PathBuf::from("."), PathBuf::from)
180 .join(".config")
181 },
182 PathBuf::from,
183 );
184
185 base.join("yk").join("lua")
186}
187
188#[must_use]
193pub fn session_dir(project_root: &Path) -> PathBuf {
194 project_root.join(".yk").join("extensions")
195}
196
197#[must_use]
204pub fn extension_sources(project_root: &Path, trust_repo: bool) -> ExtensionSources {
205 ExtensionSources {
206 user: Some(user_dir()),
207 repo: Some(project_root.join(".yk").join("lua")),
208 trust_repo,
209 }
210}
211
212#[cfg(test)]
213mod tests {
214 #![allow(
215 clippy::unwrap_used,
216 clippy::expect_used,
217 clippy::indexing_slicing,
218 clippy::as_conversions,
219 clippy::arithmetic_side_effects
220 )]
221
222 use std::collections::BTreeMap;
223 use std::path::{Path, PathBuf};
224
225 use yk_core::Result;
226
227 use super::{DenyHost, Host, HttpResponse, extension_sources, session_dir, user_dir};
228
229 #[tokio::test]
230 async fn a_denying_host_refuses_rather_than_pretending() {
231 let host = DenyHost;
232 let error = host
233 .read_file(Path::new("a.txt"))
234 .await
235 .expect_err("must fail");
236 assert!(
237 error.to_string().contains("no host is configured"),
238 "{error}"
239 );
240
241 let error = host
242 .http_get("https://example.com")
243 .await
244 .expect_err("must fail");
245 assert!(error.to_string().contains("no host"), "{error}");
246
247 let error = host
248 .http_post_json("https://example.com", &BTreeMap::new(), "{}")
249 .await
250 .expect_err("must fail");
251 assert!(error.to_string().contains("nothing was posted"), "{error}");
252 }
253
254 #[test]
255 fn a_denying_host_reports_no_environment_rather_than_an_empty_one() {
256 assert_eq!(DenyHost.env("PATH"), None);
259 }
260
261 #[test]
262 fn the_user_directory_is_always_active() {
263 let found = extension_sources(Path::new("/project"), false);
264 assert!(found.active().contains(&user_dir()));
265 }
266
267 #[test]
268 fn a_repository_is_not_loaded_without_trust() {
269 let found = extension_sources(Path::new("/project"), false);
271
272 assert!(
273 !found.active().iter().any(|dir| dir.starts_with("/project")),
274 "project scripts loaded without trust: {:?}",
275 found.active()
276 );
277 assert_eq!(found.skipped().len(), 1);
278 }
279
280 #[test]
281 fn a_trusted_repository_is_loaded() {
282 let found = extension_sources(Path::new("/project"), true);
283
284 assert_eq!(found.active().len(), 2);
285 assert!(found.skipped().is_empty());
286 }
287
288 #[test]
289 fn the_user_directory_loads_before_the_project_one() {
290 let found = extension_sources(Path::new("/project"), true);
292 let active = found.active();
293
294 assert_eq!(active.first(), Some(&user_dir()));
295 }
296
297 #[test]
298 fn model_written_extensions_live_under_dot_yk_extensions() {
299 let dir = session_dir(Path::new("/project"));
300 assert_eq!(dir, PathBuf::from("/project/.yk/extensions"));
301 }
302
303 #[test]
304 fn a_trusted_repository_still_reports_nothing_skipped() {
305 let found = extension_sources(Path::new("/project"), true);
306 assert!(found.skipped().is_empty());
307 }
308
309 struct Fixed(String);
311
312 #[async_trait::async_trait]
313 impl Host for Fixed {
314 async fn read_file(&self, _path: &Path) -> Result<String> {
315 Ok(self.0.clone())
316 }
317
318 async fn http_get(&self, _url: &str) -> Result<String> {
319 Ok(self.0.clone())
320 }
321
322 async fn http_post_json(
323 &self,
324 _url: &str,
325 headers: &BTreeMap<String, String>,
326 body: &str,
327 ) -> Result<HttpResponse> {
328 let encoded = headers.len().saturating_mul(100).saturating_add(body.len());
332 Ok(HttpResponse {
333 status: 200,
334 body: encoded.to_string(),
335 })
336 }
337
338 fn env(&self, name: &str) -> Option<String> {
339 (name == "SET").then(|| "value".to_owned())
340 }
341 }
342
343 #[tokio::test]
344 async fn a_host_can_be_implemented_outside_this_crate() {
345 let host = Fixed("content".to_owned());
346 assert_eq!(
347 host.read_file(Path::new("a")).await.expect("reads"),
348 "content"
349 );
350 assert_eq!(host.http_get("x").await.expect("fetches"), "content");
351
352 let mut headers = BTreeMap::new();
353 headers.insert("Authorization".to_owned(), "Bearer k".to_owned());
354 let reply = host
355 .http_post_json("x", &headers, "{}")
356 .await
357 .expect("posts");
358 assert_eq!(reply.status, 200);
359 assert_eq!(reply.body, "102");
362
363 assert_eq!(host.env("SET").as_deref(), Some("value"));
364 assert_eq!(host.env("UNSET"), None);
365 }
366}