artifactize_core/project/
selection.rs1use std::{
4 collections::{BTreeMap, BTreeSet},
5 io::Read,
6 path::Path,
7};
8
9use serde::{Deserialize, Serialize};
10
11use crate::{
12 config::{ArtifactName, Eval, EvalId, RepoConfig},
13 graph::Graph,
14};
15
16#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
17#[serde(tag = "kind", rename_all = "lowercase", deny_unknown_fields)]
18pub enum Selection {
19 All,
20 Artifact {
21 #[serde(rename = "artifactId")]
22 artifact_id: ArtifactName,
23 },
24 Eval {
25 #[serde(rename = "evalId")]
26 eval_id: EvalId,
27 },
28 Artifacts {
29 #[serde(rename = "artifactIds")]
30 artifact_ids: Vec<ArtifactName>,
31 },
32 Evals {
33 #[serde(rename = "evalIds")]
34 eval_ids: Vec<EvalId>,
35 },
36}
37
38#[derive(Debug)]
39pub struct ResolvedSelection<'a> {
40 pub evals: Vec<&'a Eval>,
41 pub roots: Vec<&'a ArtifactName>,
42}
43
44impl Selection {
45 pub fn resolve<'a>(&self, config: &'a RepoConfig) -> Result<ResolvedSelection<'a>, String> {
48 let evals_by_id: BTreeMap<_, _> = config
49 .evals
50 .iter()
51 .map(|eval| (eval.id.as_str(), eval))
52 .collect();
53 let mut evals_by_target: BTreeMap<&ArtifactName, Vec<&Eval>> = BTreeMap::new();
54 for eval in &config.evals {
55 evals_by_target.entry(&eval.target).or_default().push(eval);
56 }
57 let mut result = ResolvedSelection {
58 evals: Vec::new(),
59 roots: Vec::new(),
60 };
61 match self {
62 Self::All => {
63 result.evals.extend(&config.evals);
64 result.roots.extend(config.artifacts.keys());
65 }
66 Self::Artifact { artifact_id } => {
67 result.roots.push(selected_artifact(config, artifact_id)?);
68 }
69 Self::Artifacts { artifact_ids } => {
70 nonempty(artifact_ids)?;
71 for id in artifact_ids {
72 result.roots.push(selected_artifact(config, id)?);
73 }
74 }
75 Self::Eval { eval_id } => {
76 result.evals.push(
77 *evals_by_id
78 .get(eval_id.as_str())
79 .ok_or_else(|| format!("Unknown Eval: {eval_id}"))?,
80 );
81 }
82 Self::Evals { eval_ids } => {
83 nonempty(eval_ids)?;
84 for id in eval_ids {
85 result.evals.push(
86 *evals_by_id
87 .get(id.as_str())
88 .ok_or_else(|| format!("Unknown Eval: {id}"))?,
89 );
90 }
91 }
92 }
93 if matches!(self, Self::Eval { .. } | Self::Evals { .. }) {
94 result
95 .roots
96 .extend(result.evals.iter().map(|eval| &eval.target));
97 }
98 if matches!(self, Self::Artifact { .. } | Self::Artifacts { .. }) {
100 let parts: Vec<_> = result
101 .roots
102 .iter()
103 .flat_map(|&id| config.descendants(id))
104 .collect();
105 result.roots.extend(parts);
106 }
107 let mut seen = BTreeSet::new();
108 result.roots.retain(|id| seen.insert(*id));
109 if matches!(self, Self::Artifact { .. } | Self::Artifacts { .. }) {
110 result.evals.extend(
111 result
112 .roots
113 .iter()
114 .filter_map(|id| evals_by_target.get(id))
115 .flatten(),
116 );
117 }
118 let mut seen_evals = BTreeSet::new();
119 result
120 .evals
121 .retain(|eval| seen_evals.insert(eval.id.as_str()));
122 Ok(result)
123 }
124
125 pub fn included_evals<'a>(
129 &self,
130 config: &'a RepoConfig,
131 recursive: bool,
132 ) -> Result<Vec<&'a Eval>, String> {
133 let selected = self.resolve(config)?;
134 let peers = matches!(self, Self::Artifact { .. } | Self::Artifacts { .. });
135 if !recursive && !peers {
136 return Ok(selected.evals);
137 }
138 let graph = Graph::new(config).map_err(|error| error.to_string())?;
139 let required: BTreeSet<_> = if recursive {
140 graph.dependency_closure(&selected.roots)
141 } else {
142 graph.cycle_members(&selected.roots)
143 }
144 .map_err(|error| error.to_string())?
145 .into_iter()
146 .collect();
147 let included = config
148 .evals
149 .iter()
150 .filter(|eval| required.contains(&eval.target));
151 if recursive {
152 return Ok(included.collect());
153 }
154 let selected_ids: BTreeSet<_> = selected.evals.iter().map(|&eval| &eval.id).collect();
155 let peer_evals: Vec<_> = included
156 .filter(|eval| !selected_ids.contains(&eval.id))
157 .collect();
158 Ok(selected.evals.into_iter().chain(peer_evals).collect())
159 }
160}
161
162fn nonempty<T>(ids: &[T]) -> Result<(), String> {
163 if ids.is_empty() {
164 return Err("Multi-root selection requires a nonempty array of IDs.".into());
165 }
166 Ok(())
167}
168
169fn selected_artifact<'a>(config: &'a RepoConfig, id: &str) -> Result<&'a ArtifactName, String> {
170 config
171 .artifacts
172 .get_key_value(id)
173 .map(|(id, _)| id)
174 .ok_or_else(|| format!("Unknown Artifact: {id}"))
175}
176
177const MAX_FILE_BYTES: usize = 4 * 1024 * 1024;
179const MAX_IDS: usize = 100_000;
181const FILE_FORMAT_ERROR: &str =
182 "Selection file must contain 1–100000 nonempty IDs, as a JSON string array or one ID per line.";
183
184fn trim(text: &str) -> &str {
186 text.trim_matches(|ch| {
187 matches!(ch,
188 '\u{0009}'..='\u{000d}' | '\u{0020}' | '\u{00a0}' | '\u{1680}' |
189 '\u{2000}'..='\u{200a}' | '\u{2028}' | '\u{2029}' | '\u{202f}' |
190 '\u{205f}' | '\u{3000}' | '\u{feff}'
191 )
192 })
193}
194
195pub fn parse_selection_file(text: &str) -> Result<Vec<String>, String> {
196 let text = text.strip_prefix('\u{feff}').unwrap_or(text);
197 if text.len() > MAX_FILE_BYTES {
198 return Err("Selection file exceeds 4 MiB.".into());
199 }
200 let ids: Vec<String> = if trim(text).starts_with('[') {
201 serde_json::from_str::<Vec<String>>(text).map_err(|error| {
202 if error.is_data() && serde_json::from_str::<crate::json::Ignored>(text).is_ok() {
205 FILE_FORMAT_ERROR.to_owned()
206 } else {
207 "Selection file contains invalid JSON.".to_owned()
208 }
209 })?
210 } else {
211 text.split('\n')
212 .map(trim)
213 .filter(|line| !line.is_empty())
214 .take(MAX_IDS + 1)
215 .map(str::to_owned)
216 .collect()
217 };
218 if ids.is_empty()
219 || ids.len() > MAX_IDS
220 || ids.iter().any(|id| {
221 id.is_empty()
222 || trim(id) != id
223 || id
224 .bytes()
225 .any(|byte| byte <= b' ' || byte == 127 || byte == b',')
226 })
227 {
228 return Err(FILE_FORMAT_ERROR.into());
229 }
230 let mut seen = BTreeSet::new();
231 Ok(ids
232 .into_iter()
233 .filter(|id| seen.insert(id.clone()))
234 .collect())
235}
236
237pub fn read_selection_file(path: &Path) -> Result<Vec<String>, String> {
238 let file = crate::platform::open_nonblocking(path)
240 .map_err(|error| format!("{}: {error}", crate::platform::path_text(path)))?;
241 let info = file.metadata().map_err(|error| error.to_string())?;
242 if !info.is_file() || info.len() > MAX_FILE_BYTES as u64 {
243 return Err("Selection input must be a regular file no larger than 4 MiB.".into());
244 }
245 let mut bytes = Vec::new();
246 file.take(MAX_FILE_BYTES as u64 + 1)
247 .read_to_end(&mut bytes)
248 .map_err(|error| error.to_string())?;
249 if bytes.len() > MAX_FILE_BYTES {
250 return Err("Selection file exceeds 4 MiB.".into());
251 }
252 parse_selection_file(&String::from_utf8_lossy(&bytes))
253}
254
255#[cfg(test)]
256mod tests;