use std::path::PathBuf;
use std::process::Command;
const README: &str = include_str!("../README.md");
fn words(line: &str) -> Vec<String> {
let mut result = Vec::new();
let mut word = String::new();
let mut quote = None;
let mut escaped = false;
let mut started = false;
for c in line.chars() {
if escaped {
word.push(c);
escaped = false;
} else if c == '\\' && quote != Some('\'') {
escaped = true;
started = true;
} else if let Some(q) = quote {
if c == q {
quote = None;
} else {
assert!(
q == '\'' || !matches!(c, '$' | '`'),
"shell expansion unsupported: {line}"
);
word.push(c);
}
} else if matches!(c, '\'' | '"') {
quote = Some(c);
started = true;
} else if c.is_whitespace() {
if started {
result.push(std::mem::take(&mut word));
started = false;
}
} else {
assert!(
!matches!(c, '$' | '`' | ';' | '|' | '&' | '<' | '>'),
"shell syntax unsupported: {line}"
);
word.push(c);
started = true;
}
}
assert!(quote.is_none() && !escaped, "unfinished argument: {line}");
if started {
result.push(word);
}
result
}
fn commands(section: &str) -> Vec<Vec<String>> {
let mut result = Vec::new();
let mut shell = false;
let mut pending = String::new();
for line in section.lines().map(str::trim) {
if line.starts_with("```") {
assert!(pending.is_empty(), "unfinished README continuation");
shell = line == "```sh";
continue;
}
if !shell || (pending.is_empty() && !line.starts_with("instinct ")) {
continue;
}
let continued = line.strip_suffix('\\');
pending.push_str(continued.unwrap_or(line));
if continued.is_some() {
pending.push(' ');
} else {
result.push(words(&pending));
pending.clear();
}
}
assert!(pending.is_empty(), "unfinished README command");
result
}
struct Bank(PathBuf);
impl Bank {
fn new() -> Self {
let nonce = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos();
let dir =
std::env::temp_dir().join(format!("instinct-readme-{}-{}-{nonce}", std::process::id(), uniq()));
std::fs::create_dir(&dir).unwrap();
Self(dir)
}
fn run(&self, args: &[String]) -> String {
assert_eq!(args.first().map(String::as_str), Some("instinct"));
let mut command = Command::new(env!("CARGO_BIN_EXE_instinct"));
for (key, _) in std::env::vars_os() {
if key.to_string_lossy().starts_with("INSTINCT_") {
command.env_remove(key);
}
}
let out = command
.args(&args[1..])
.current_dir(&self.0)
.env("HOME", &self.0)
.env("XDG_DATA_HOME", &self.0)
.env("LOCALAPPDATA", &self.0)
.env("INSTINCT_STORE", self.0.join("bank.hxdb"))
.env("INSTINCT_METER", "0")
.output()
.unwrap();
assert!(
out.status.success(),
"{args:?}: {}",
String::from_utf8_lossy(&out.stderr)
);
assert!(
out.stderr.is_empty(),
"{args:?}: unexpected stderr: {}",
String::from_utf8_lossy(&out.stderr)
);
String::from_utf8(out.stdout).unwrap()
}
}
impl Drop for Bank {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[test]
fn github_and_crate_open_with_the_same_product_explanation() {
fn intro(doc: &str) -> String {
let doc = doc.replace("\r\n", "\n");
let mut lines = doc.lines().skip_while(|line| *line != "# Instinct");
assert_eq!(lines.next(), Some("# Instinct"), "missing product heading");
let text = lines.skip_while(|line| line.trim().is_empty())
.take_while(|line| !line.trim().is_empty()).collect::<Vec<_>>().join(" ");
assert!(text.starts_with("Instinct "), "expected product explanation directly after the title, got: {text}");
text
}
assert_eq!(intro(README), intro(include_str!("../CRATE.md")),
"update the GitHub and crates.io introductions together");
}
#[test]
fn readme_quickstart_recalls_then_learns_from_a_hit() {
let readme = README.replace("\r\n", "\n");
let section = readme
.split_once("## See it in 30 seconds\n")
.expect("README quickstart heading disappeared")
.1
.split("\n## ")
.next()
.unwrap();
let commands = commands(section);
assert_eq!(
commands.len(),
3,
"review changed quickstart commands: {commands:?}"
);
assert_eq!(commands[0].get(1).map(String::as_str), Some("bank"));
assert_eq!(commands[1].get(1).map(String::as_str), Some("recall"));
assert_eq!(commands[2].get(1).map(String::as_str), Some("hit"));
let bank = Bank::new();
let saved = bank.run(&commands[0]);
assert!(saved.starts_with("banked "), "{saved}");
let id = saved.split_whitespace().nth(1).unwrap();
let first = bank.run(&commands[1]);
assert!(
first.contains(id) && first.contains("Run the tests offline"),
"README recall returned no expected lesson: {:?}\n{first}",
commands[1]
);
assert!(first.contains("strength 0.50"), "{first}");
let unrelated = section
.split('`')
.enumerate()
.filter(|(index, _)| index % 2 == 1)
.map(|(_, code)| code)
.find(|code| code.starts_with("instinct recall ") && code.contains("birthday toast"))
.expect("README unrelated recall example disappeared");
assert!(
bank.run(&words(unrelated)).is_empty(),
"unrelated README query returned a lesson"
);
let mut hit = commands[2].clone();
assert!(hit.len() >= 3, "README hit command has no ID");
hit[2] = id.to_owned();
bank.run(&hit);
let after = bank.run(&commands[1]);
assert!(
after.contains(id) && after.contains("strength 0.67"),
"{after}"
);
}
#[test]
fn command_parser_preserves_quoted_arguments_and_continuations() {
assert_eq!(
words("instinct bank --title 'two words' --how \"say hello\" --evidence ''"),
[
"instinct",
"bank",
"--title",
"two words",
"--how",
"say hello",
"--evidence",
""
]
);
let parsed = commands("```sh\nexport IGNORED=value\ninstinct bank \\\n --title 'two words'\n```\n```text\ninstinct not-a-command\n```\n");
assert_eq!(
parsed,
vec![vec!["instinct", "bank", "--title", "two words"]]
);
}
fn uniq() -> usize {
static N: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
N.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}