artifactize_core/scope/
instruction.rs1use std::collections::{BTreeMap, BTreeSet};
3
4use super::{InstructionPart, artifact_instruction};
5use crate::config::{ArtifactName, Eval, RepoConfig};
6
7#[derive(Debug, Clone, Default, PartialEq, Eq)]
10pub struct Instruction {
11 pub parts: Vec<InstructionPart>,
12 pub paths: BTreeMap<ArtifactName, String>,
13}
14
15impl Instruction {
16 pub fn text(text: String) -> Self {
18 Self {
19 parts: if text.is_empty() {
20 Vec::new()
21 } else {
22 vec![InstructionPart::Text(text)]
23 },
24 paths: BTreeMap::new(),
25 }
26 }
27
28 pub fn declared(config: &RepoConfig, eval: &Eval) -> Self {
31 Self::with_paths(artifact_instruction(eval), |name| {
32 config
33 .artifacts
34 .get(name)
35 .map(crate::config::Artifact::written_path)
36 })
37 }
38
39 pub fn saved<'a>(
44 text: &str,
45 named: impl IntoIterator<Item = &'a ArtifactName>,
46 path: impl Fn(&ArtifactName) -> Option<String>,
47 ) -> Self {
48 Self::with_paths(split(text, &named.into_iter().collect()), path)
49 }
50
51 fn with_paths(
52 parts: Vec<InstructionPart>,
53 path: impl Fn(&ArtifactName) -> Option<String>,
54 ) -> Self {
55 let paths = parts
56 .iter()
57 .filter_map(|part| match part {
58 InstructionPart::Artifact(name) => Some(name),
59 InstructionPart::Text(_) => None,
60 })
61 .filter_map(|name| path(name).map(|path| (name.clone(), path)))
62 .collect();
63 Self { parts, paths }
64 }
65}
66
67fn name_byte(byte: u8) -> bool {
69 byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_')
70}
71
72fn split(text: &str, named: &BTreeSet<&ArtifactName>) -> Vec<InstructionPart> {
76 let bytes = text.as_bytes();
77 let mut parts = Vec::new();
78 let (mut text_start, mut at) = (0, 0);
79 while at < bytes.len() {
80 if !name_byte(bytes[at]) {
81 at += 1;
82 continue;
83 }
84 let end = at
85 + bytes[at..]
86 .iter()
87 .take_while(|byte| name_byte(**byte))
88 .count();
89 let inside_path = at > 0 && matches!(bytes[at - 1], b'/' | b'\\' | b'.')
90 || bytes.get(end) == Some(&b'.')
91 && bytes.get(end + 1).is_some_and(|byte| name_byte(*byte));
92 let found = (!inside_path)
94 .then(|| named.iter().find(|name| name.as_str() == &text[at..end]))
95 .flatten();
96 if let Some(name) = found {
97 if text_start < at {
98 parts.push(InstructionPart::Text(text[text_start..at].into()));
99 }
100 parts.push(InstructionPart::Artifact((*name).clone()));
101 text_start = end;
102 }
103 at = end;
104 }
105 if text_start < text.len() {
106 parts.push(InstructionPart::Text(text[text_start..].into()));
107 }
108 parts
109}
110
111#[cfg(test)]
112mod tests {
113 use super::*;
114
115 fn name(text: &str) -> ArtifactName {
116 text.parse().unwrap()
117 }
118
119 fn text(text: &str) -> InstructionPart {
120 InstructionPart::Text(text.into())
121 }
122
123 fn artifact(text: &str) -> InstructionPart {
124 InstructionPart::Artifact(name(text))
125 }
126
127 #[test]
128 fn a_saved_instruction_finds_the_names_its_slots_filled() {
129 let named = [
130 name("perf-bench"),
131 name("perf-bench-definition"),
132 name("docs"),
133 ];
134 let shown = Instruction::saved(
135 "Read perf-bench-definition, then perf-bench and docs/guide.",
136 &named,
137 |name| (name.as_str() == "docs").then(|| "docs/".to_owned()),
138 );
139 assert_eq!(
140 shown.parts,
141 [
142 text("Read "),
143 artifact("perf-bench-definition"),
144 text(", then "),
145 artifact("perf-bench"),
146 text(" and "),
147 artifact("docs"),
148 text("/guide."),
149 ]
150 );
151 assert_eq!(
152 shown.paths,
153 BTreeMap::from([(name("docs"), "docs/".to_owned())])
154 );
155 }
156
157 #[test]
158 fn a_name_inside_a_path_a_file_name_or_a_longer_word_stays_text() {
159 let named = [name("notes"), name("app")];
160 let written = "See crates/notes, notes.md, app-shell and appendix; then notes.";
161 assert_eq!(
162 Instruction::saved(written, &named, |_| None).parts,
163 [
164 text("See crates/notes, notes.md, app-shell and appendix; then "),
165 artifact("notes"),
166 text("."),
167 ]
168 );
169 }
170
171 #[test]
172 fn a_saved_instruction_without_named_artifacts_is_its_text() {
173 assert_eq!(
174 Instruction::saved("Read the notes.", [], |_| None),
175 Instruction::text("Read the notes.".into())
176 );
177 assert_eq!(Instruction::text(String::new()).parts, []);
178 }
179}