use std::collections::{BTreeMap, BTreeSet};
use super::{InstructionPart, artifact_instruction};
use crate::config::{ArtifactName, Eval, RepoConfig};
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Instruction {
pub parts: Vec<InstructionPart>,
pub paths: BTreeMap<ArtifactName, String>,
}
impl Instruction {
pub fn text(text: String) -> Self {
Self {
parts: if text.is_empty() {
Vec::new()
} else {
vec![InstructionPart::Text(text)]
},
paths: BTreeMap::new(),
}
}
pub fn declared(config: &RepoConfig, eval: &Eval) -> Self {
Self::with_paths(artifact_instruction(eval), |name| {
config
.artifacts
.get(name)
.map(crate::config::Artifact::written_path)
})
}
pub fn saved<'a>(
text: &str,
named: impl IntoIterator<Item = &'a ArtifactName>,
path: impl Fn(&ArtifactName) -> Option<String>,
) -> Self {
Self::with_paths(split(text, &named.into_iter().collect()), path)
}
fn with_paths(
parts: Vec<InstructionPart>,
path: impl Fn(&ArtifactName) -> Option<String>,
) -> Self {
let paths = parts
.iter()
.filter_map(|part| match part {
InstructionPart::Artifact(name) => Some(name),
InstructionPart::Text(_) => None,
})
.filter_map(|name| path(name).map(|path| (name.clone(), path)))
.collect();
Self { parts, paths }
}
}
fn name_byte(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_')
}
fn split(text: &str, named: &BTreeSet<&ArtifactName>) -> Vec<InstructionPart> {
let bytes = text.as_bytes();
let mut parts = Vec::new();
let (mut text_start, mut at) = (0, 0);
while at < bytes.len() {
if !name_byte(bytes[at]) {
at += 1;
continue;
}
let end = at
+ bytes[at..]
.iter()
.take_while(|byte| name_byte(**byte))
.count();
let inside_path = at > 0 && matches!(bytes[at - 1], b'/' | b'\\' | b'.')
|| bytes.get(end) == Some(&b'.')
&& bytes.get(end + 1).is_some_and(|byte| name_byte(*byte));
let found = (!inside_path)
.then(|| named.iter().find(|name| name.as_str() == &text[at..end]))
.flatten();
if let Some(name) = found {
if text_start < at {
parts.push(InstructionPart::Text(text[text_start..at].into()));
}
parts.push(InstructionPart::Artifact((*name).clone()));
text_start = end;
}
at = end;
}
if text_start < text.len() {
parts.push(InstructionPart::Text(text[text_start..].into()));
}
parts
}
#[cfg(test)]
mod tests {
use super::*;
fn name(text: &str) -> ArtifactName {
text.parse().unwrap()
}
fn text(text: &str) -> InstructionPart {
InstructionPart::Text(text.into())
}
fn artifact(text: &str) -> InstructionPart {
InstructionPart::Artifact(name(text))
}
#[test]
fn a_saved_instruction_finds_the_names_its_slots_filled() {
let named = [
name("perf-bench"),
name("perf-bench-definition"),
name("docs"),
];
let shown = Instruction::saved(
"Read perf-bench-definition, then perf-bench and docs/guide.",
&named,
|name| (name.as_str() == "docs").then(|| "docs/".to_owned()),
);
assert_eq!(
shown.parts,
[
text("Read "),
artifact("perf-bench-definition"),
text(", then "),
artifact("perf-bench"),
text(" and "),
artifact("docs"),
text("/guide."),
]
);
assert_eq!(
shown.paths,
BTreeMap::from([(name("docs"), "docs/".to_owned())])
);
}
#[test]
fn a_name_inside_a_path_a_file_name_or_a_longer_word_stays_text() {
let named = [name("notes"), name("app")];
let written = "See crates/notes, notes.md, app-shell and appendix; then notes.";
assert_eq!(
Instruction::saved(written, &named, |_| None).parts,
[
text("See crates/notes, notes.md, app-shell and appendix; then "),
artifact("notes"),
text("."),
]
);
}
#[test]
fn a_saved_instruction_without_named_artifacts_is_its_text() {
assert_eq!(
Instruction::saved("Read the notes.", [], |_| None),
Instruction::text("Read the notes.".into())
);
assert_eq!(Instruction::text(String::new()).parts, []);
}
}