artifactize-core 0.32.0

The library behind artifactize: Artifacts, evals, reviews, the monitor and review models, and the shared operations every interface calls.
Documentation
//! An instruction as people read it: its text and the Artifacts it names, each with its path.
use std::collections::{BTreeMap, BTreeSet};

use super::{InstructionPart, artifact_instruction};
use crate::config::{ArtifactName, Eval, RepoConfig};

/// An instruction split into its text and the Artifacts its `@{artf …}` slots name, with the
/// path of each named Artifact where it is known.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Instruction {
    pub parts: Vec<InstructionPart>,
    pub paths: BTreeMap<ArtifactName, String>,
}

impl Instruction {
    /// Plain text that names no Artifact, such as a runtime eval's command.
    pub fn text(text: String) -> Self {
        Self {
            parts: if text.is_empty() {
                Vec::new()
            } else {
                vec![InstructionPart::Text(text)]
            },
            paths: BTreeMap::new(),
        }
    }

    /// A declared eval's instruction, each slot where its declaration put it, and the paths of
    /// the Artifacts it names as their declarations write them.
    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)
        })
    }

    /// An instruction as a request saved it: the text its slots filled with the names of the
    /// Artifacts they named, and those Artifacts (`named`). The slots' places are not saved, so
    /// each place where one of those names stands as a whole word, not inside a path or a
    /// file name, is taken as its slot. `path` gives a named Artifact's path where it is known.
    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 }
    }
}

/// A byte an Artifact name may hold: `[A-Za-z0-9_-]`.
fn name_byte(byte: u8) -> bool {
    byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_')
}

/// `text` with each whole word that is one of `named` as an Artifact part. A word right after a
/// path separator or a dot, or right before a dot that a name byte follows (`notes.md`), is part
/// of a path or a file name and stays text.
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));
        // Name bytes are ASCII, so the word's ends are character boundaries.
        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, []);
    }
}