use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use yk_core::Result;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct HttpResponse {
pub status: u16,
pub body: String,
}
#[async_trait::async_trait]
#[async_trait::async_trait]
pub trait Host: Send + Sync {
async fn read_file(&self, path: &Path) -> Result<String>;
async fn http_get(&self, url: &str) -> Result<String>;
async fn http_post_json(
&self,
url: &str,
headers: &BTreeMap<String, String>,
body: &str,
) -> Result<HttpResponse>;
fn env(&self, name: &str) -> Option<String>;
}
#[derive(Clone, Copy, Debug, Default)]
pub struct DenyHost;
#[async_trait::async_trait]
impl Host for DenyHost {
async fn read_file(&self, path: &Path) -> Result<String> {
Err(yk_core::Error::Tool {
tool: "host.read_file".to_owned(),
reason: format!(
"no host is configured, so `{}` was not read",
path.display()
),
})
}
async fn http_get(&self, url: &str) -> Result<String> {
Err(yk_core::Error::Tool {
tool: "host.http_get".to_owned(),
reason: format!("no host is configured, so `{url}` was not fetched"),
})
}
async fn http_post_json(
&self,
url: &str,
_headers: &BTreeMap<String, String>,
_body: &str,
) -> Result<HttpResponse> {
Err(yk_core::Error::Tool {
tool: "host.http_post_json".to_owned(),
reason: format!("no host is configured, so nothing was posted to `{url}`"),
})
}
fn env(&self, name: &str) -> Option<String> {
let _ = name;
None
}
}
#[derive(Clone, Debug, Default)]
pub struct ExtensionSources {
pub user: Option<PathBuf>,
pub repo: Option<PathBuf>,
pub trust_repo: bool,
}
impl ExtensionSources {
#[must_use]
pub fn active(&self) -> Vec<PathBuf> {
let mut dirs: Vec<PathBuf> = self.user.iter().cloned().collect();
if self.trust_repo
&& let Some(repo) = &self.repo
{
dirs.push(repo.clone());
}
dirs
}
#[must_use]
pub fn skipped(&self) -> Vec<PathBuf> {
if self.trust_repo {
Vec::new()
} else {
self.repo.iter().cloned().collect()
}
}
}
#[must_use]
pub fn user_dir() -> PathBuf {
let base = std::env::var_os("XDG_CONFIG_HOME").map_or_else(
|| {
std::env::var_os("HOME")
.map_or_else(|| PathBuf::from("."), PathBuf::from)
.join(".config")
},
PathBuf::from,
);
base.join("yk").join("lua")
}
#[must_use]
pub fn session_dir(project_root: &Path) -> PathBuf {
project_root.join(".yk").join("extensions")
}
#[must_use]
pub fn extension_sources(project_root: &Path, trust_repo: bool) -> ExtensionSources {
ExtensionSources {
user: Some(user_dir()),
repo: Some(project_root.join(".yk").join("lua")),
trust_repo,
}
}
#[cfg(test)]
mod tests {
#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::indexing_slicing,
clippy::as_conversions,
clippy::arithmetic_side_effects
)]
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use yk_core::Result;
use super::{DenyHost, Host, HttpResponse, extension_sources, session_dir, user_dir};
#[tokio::test]
async fn a_denying_host_refuses_rather_than_pretending() {
let host = DenyHost;
let error = host
.read_file(Path::new("a.txt"))
.await
.expect_err("must fail");
assert!(
error.to_string().contains("no host is configured"),
"{error}"
);
let error = host
.http_get("https://example.com")
.await
.expect_err("must fail");
assert!(error.to_string().contains("no host"), "{error}");
let error = host
.http_post_json("https://example.com", &BTreeMap::new(), "{}")
.await
.expect_err("must fail");
assert!(error.to_string().contains("nothing was posted"), "{error}");
}
#[test]
fn a_denying_host_reports_no_environment_rather_than_an_empty_one() {
assert_eq!(DenyHost.env("PATH"), None);
}
#[test]
fn the_user_directory_is_always_active() {
let found = extension_sources(Path::new("/project"), false);
assert!(found.active().contains(&user_dir()));
}
#[test]
fn a_repository_is_not_loaded_without_trust() {
let found = extension_sources(Path::new("/project"), false);
assert!(
!found.active().iter().any(|dir| dir.starts_with("/project")),
"project scripts loaded without trust: {:?}",
found.active()
);
assert_eq!(found.skipped().len(), 1);
}
#[test]
fn a_trusted_repository_is_loaded() {
let found = extension_sources(Path::new("/project"), true);
assert_eq!(found.active().len(), 2);
assert!(found.skipped().is_empty());
}
#[test]
fn the_user_directory_loads_before_the_project_one() {
let found = extension_sources(Path::new("/project"), true);
let active = found.active();
assert_eq!(active.first(), Some(&user_dir()));
}
#[test]
fn model_written_extensions_live_under_dot_yk_extensions() {
let dir = session_dir(Path::new("/project"));
assert_eq!(dir, PathBuf::from("/project/.yk/extensions"));
}
#[test]
fn a_trusted_repository_still_reports_nothing_skipped() {
let found = extension_sources(Path::new("/project"), true);
assert!(found.skipped().is_empty());
}
struct Fixed(String);
#[async_trait::async_trait]
impl Host for Fixed {
async fn read_file(&self, _path: &Path) -> Result<String> {
Ok(self.0.clone())
}
async fn http_get(&self, _url: &str) -> Result<String> {
Ok(self.0.clone())
}
async fn http_post_json(
&self,
_url: &str,
headers: &BTreeMap<String, String>,
body: &str,
) -> Result<HttpResponse> {
let encoded = headers.len().saturating_mul(100).saturating_add(body.len());
Ok(HttpResponse {
status: 200,
body: encoded.to_string(),
})
}
fn env(&self, name: &str) -> Option<String> {
(name == "SET").then(|| "value".to_owned())
}
}
#[tokio::test]
async fn a_host_can_be_implemented_outside_this_crate() {
let host = Fixed("content".to_owned());
assert_eq!(
host.read_file(Path::new("a")).await.expect("reads"),
"content"
);
assert_eq!(host.http_get("x").await.expect("fetches"), "content");
let mut headers = BTreeMap::new();
headers.insert("Authorization".to_owned(), "Bearer k".to_owned());
let reply = host
.http_post_json("x", &headers, "{}")
.await
.expect("posts");
assert_eq!(reply.status, 200);
assert_eq!(reply.body, "102");
assert_eq!(host.env("SET").as_deref(), Some("value"));
assert_eq!(host.env("UNSET"), None);
}
}