use std::path::{Path, PathBuf};
use crate::console::ConsoleClient;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Memory {
memfile: String,
}
impl Memory {
pub fn new(memfile: impl Into<String>) -> Self {
Self {
memfile: memfile.into(),
}
}
pub fn memfile(&self) -> &str {
&self.memfile
}
pub async fn search(
&self,
console: &mut ConsoleClient,
query: impl AsRef<str>,
) -> anyhow::Result<Vec<String>> {
self.run(console, "search", [query.as_ref()]).await
}
pub async fn insert(
&self,
console: &mut ConsoleClient,
memories: impl IntoIterator<Item = impl AsRef<str>>,
) -> anyhow::Result<Vec<String>> {
let memories: Vec<String> = memories
.into_iter()
.map(|m| m.as_ref().to_string())
.collect();
self.run(console, "insert", &memories).await
}
async fn run(
&self,
console: &mut ConsoleClient,
subcommand: &str,
rest: impl IntoIterator<Item = impl AsRef<str>>,
) -> anyhow::Result<Vec<String>> {
let memfile = &self.memfile;
let mut argv = vec!["mem".to_string(), subcommand.to_string(), memfile.clone()];
argv.extend(rest.into_iter().map(|arg| arg.as_ref().to_string()));
let result = console
.exec(&argv, None)
.await
.map_err(|e| anyhow::anyhow!("`mem {subcommand} {memfile}` could not be run: {e}"))?;
if result.code != 0 {
let said = String::from_utf8_lossy(&result.stderr);
let said = said.trim();
anyhow::bail!(if said.is_empty() {
format!("`mem {subcommand} {memfile}` failed (exit {})", result.code)
} else {
said.to_string()
});
}
Ok(String::from_utf8_lossy(&result.stdout)
.lines()
.filter(|line| !line.trim().is_empty())
.map(|line| line.to_string())
.collect())
}
}
impl From<String> for Memory {
fn from(memfile: String) -> Self {
Self::new(memfile)
}
}
impl From<&str> for Memory {
fn from(memfile: &str) -> Self {
Self::new(memfile)
}
}
impl From<PathBuf> for Memory {
fn from(memfile: PathBuf) -> Self {
Self::new(memfile.to_string_lossy().into_owned())
}
}
impl From<&Path> for Memory {
fn from(memfile: &Path) -> Self {
Self::new(memfile.to_string_lossy().into_owned())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_console;
async fn store(console: &mut ConsoleClient) -> Memory {
let dir = tempfile::tempdir().unwrap();
let path = dir
.keep()
.join("notes.sqlite")
.to_string_lossy()
.to_string();
let init = console.exec(["mem", "init", &path], None).await.unwrap();
assert_eq!(init.code, 0, "{}", String::from_utf8_lossy(&init.stderr));
Memory::new(path)
}
async fn filled(console: &mut ConsoleClient, memories: &[&str]) -> Memory {
let memory = store(console).await;
let mut argv = vec![
"mem".to_string(),
"insert".to_string(),
memory.memfile().to_string(),
];
argv.extend(memories.iter().map(|m| m.to_string()));
let insert = console.exec(&argv, None).await.unwrap();
assert_eq!(
insert.code,
0,
"{}",
String::from_utf8_lossy(&insert.stderr)
);
memory
}
fn missing() -> Memory {
let dir = tempfile::tempdir().unwrap();
Memory::new(
dir.keep()
.join("missing.sqlite")
.to_string_lossy()
.to_string(),
)
}
#[test_with::executable(mem)]
#[tokio::test]
async fn test_search_finds_the_nearest_memory() {
let mut console = test_console().await;
let memory = filled(
&mut console,
&["User drinks tea", "User switched to oat milk"],
)
.await;
let found = memory.search(&mut console, "oat milk").await.unwrap();
assert_eq!(found, ["User switched to oat milk"]);
}
#[test_with::executable(mem)]
#[tokio::test]
async fn test_search_with_nothing_near_is_empty() {
let mut console = test_console().await;
let memory = filled(&mut console, &["User drinks tea"]).await;
let found = memory.search(&mut console, "almond").await.unwrap();
assert!(found.is_empty(), "nothing near the query: {found:?}");
}
#[test_with::executable(mem)]
#[tokio::test]
async fn test_search_on_a_store_that_is_not_there_is_an_error() {
let mut console = test_console().await;
let memory = missing();
let e = memory
.search(&mut console, "oat milk")
.await
.expect_err("there is no such store");
assert!(e.to_string().contains(memory.memfile()), "{e}");
}
#[test_with::executable(mem)]
#[tokio::test]
async fn test_insert_writes_what_it_was_given() {
let mut console = test_console().await;
let memory = store(&mut console).await;
let written = memory
.insert(
&mut console,
["User switched to oat milk", "User drinks tea"],
)
.await
.unwrap();
assert_eq!(written, ["User switched to oat milk", "User drinks tea"]);
let found = memory.search(&mut console, "oat milk").await.unwrap();
assert_eq!(found, ["User switched to oat milk"]);
}
#[test_with::executable(mem)]
#[tokio::test]
async fn test_insert_with_nothing_to_write_writes_nothing() {
let mut console = test_console().await;
let memory = store(&mut console).await;
let written = memory
.insert(&mut console, Vec::<String>::new())
.await
.unwrap();
assert!(written.is_empty(), "no memories, so no lines: {written:?}");
}
#[test_with::executable(mem)]
#[tokio::test]
async fn test_insert_refuses_an_empty_memory() {
let mut console = test_console().await;
let memory = store(&mut console).await;
memory
.insert(&mut console, ["User drinks tea", " "])
.await
.expect_err("a memory is a statement, and the second is empty");
let found = memory.search(&mut console, "tea").await.unwrap();
assert!(found.is_empty(), "nothing was written: {found:?}");
}
#[test_with::executable(mem)]
#[tokio::test]
async fn test_insert_into_a_store_that_is_not_there_is_an_error() {
let mut console = test_console().await;
let memory = missing();
let e = memory
.insert(&mut console, ["User drinks tea"])
.await
.expect_err("there is no such store");
assert!(e.to_string().contains(memory.memfile()), "{e}");
assert!(
!std::path::Path::new(memory.memfile()).exists(),
"a failed insert made nothing"
);
}
}