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, ProfileVariantName, 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
177#[derive(Debug, Clone, Serialize, Deserialize)]
178#[serde(untagged)]
179pub enum ProfileSelection {
180 Named(ProfileVariantName),
181 Evals(BTreeMap<EvalId, ProfileVariantName>),
182}
183
184pub fn select_profiles(
186 mut config: RepoConfig,
187 selection: &Selection,
188 profile: Option<&ProfileSelection>,
189 recursive: bool,
190) -> Result<RepoConfig, String> {
191 let Some(profile) = profile else {
192 return Ok(config);
193 };
194 let evals = selection.included_evals(&config, recursive)?;
195 let included: BTreeMap<_, _> = evals.iter().map(|eval| (&eval.id, *eval)).collect();
196 let mapping: Vec<(&EvalId, &ProfileVariantName)> = match profile {
197 ProfileSelection::Named(name) => evals.iter().map(|eval| (&eval.id, name)).collect(),
198 ProfileSelection::Evals(mapping) => mapping.iter().collect(),
199 };
200 let mut profiles = BTreeMap::new();
201 for (id, name) in mapping {
202 let eval = included.get(id).ok_or_else(|| {
203 format!("Profile selection is outside the submitted Eval scope: {id}")
204 })?;
205 let variant = eval
206 .declaration
207 .profile_variants()
208 .get(name)
209 .ok_or_else(|| format!("Unknown profile variant for {id}: {name}"))?;
210 profiles.insert(id.clone(), (name.clone(), variant.clone()));
211 }
212 for eval in &mut config.evals {
213 if let Some((name, _profile)) = profiles.remove(&eval.id) {
214 eval.declaration.select_profile(&name)?;
215 eval.variant = Some(name);
216 }
217 }
218 crate::scope::resolve_config(&mut config).map_err(|error| error.to_string())?;
220 crate::scope::validate_eval_tools(&config).map_err(|error| error.to_string())?;
221 Ok(config)
222}
223
224const MAX_FILE_BYTES: usize = 4 * 1024 * 1024;
226const MAX_IDS: usize = 100_000;
228const FILE_FORMAT_ERROR: &str =
229 "Selection file must contain 1–100000 nonempty IDs, as a JSON string array or one ID per line.";
230
231fn trim(text: &str) -> &str {
233 text.trim_matches(|ch| {
234 matches!(ch,
235 '\u{0009}'..='\u{000d}' | '\u{0020}' | '\u{00a0}' | '\u{1680}' |
236 '\u{2000}'..='\u{200a}' | '\u{2028}' | '\u{2029}' | '\u{202f}' |
237 '\u{205f}' | '\u{3000}' | '\u{feff}'
238 )
239 })
240}
241
242pub fn parse_selection_file(text: &str) -> Result<Vec<String>, String> {
243 let text = text.strip_prefix('\u{feff}').unwrap_or(text);
244 if text.len() > MAX_FILE_BYTES {
245 return Err("Selection file exceeds 4 MiB.".into());
246 }
247 let ids: Vec<String> = if trim(text).starts_with('[') {
248 serde_json::from_str::<Vec<String>>(text).map_err(|error| {
249 if error.is_data() && serde_json::from_str::<crate::json::Ignored>(text).is_ok() {
252 FILE_FORMAT_ERROR.to_owned()
253 } else {
254 "Selection file contains invalid JSON.".to_owned()
255 }
256 })?
257 } else {
258 text.split('\n')
259 .map(trim)
260 .filter(|line| !line.is_empty())
261 .take(MAX_IDS + 1)
262 .map(str::to_owned)
263 .collect()
264 };
265 if ids.is_empty()
266 || ids.len() > MAX_IDS
267 || ids.iter().any(|id| {
268 id.is_empty()
269 || trim(id) != id
270 || id
271 .bytes()
272 .any(|byte| byte <= b' ' || byte == 127 || byte == b',')
273 })
274 {
275 return Err(FILE_FORMAT_ERROR.into());
276 }
277 let mut seen = BTreeSet::new();
278 Ok(ids
279 .into_iter()
280 .filter(|id| seen.insert(id.clone()))
281 .collect())
282}
283
284pub fn read_selection_file(path: &Path) -> Result<Vec<String>, String> {
285 let file = crate::platform::open_nonblocking(path)
287 .map_err(|error| format!("{}: {error}", crate::platform::path_text(path)))?;
288 let info = file.metadata().map_err(|error| error.to_string())?;
289 if !info.is_file() || info.len() > MAX_FILE_BYTES as u64 {
290 return Err("Selection input must be a regular file no larger than 4 MiB.".into());
291 }
292 let mut bytes = Vec::new();
293 file.take(MAX_FILE_BYTES as u64 + 1)
294 .read_to_end(&mut bytes)
295 .map_err(|error| error.to_string())?;
296 if bytes.len() > MAX_FILE_BYTES {
297 return Err("Selection file exceeds 4 MiB.".into());
298 }
299 parse_selection_file(&String::from_utf8_lossy(&bytes))
300}
301
302#[cfg(test)]
303mod tests;