Skip to main content

artifactize_core/project/
selection.rs

1//! Project selectors, selection files, and profile variants.
2
3use 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    /// Preserve selector order, then declaration order, keeping each root/Eval once. An
46    /// Artifact selector's roots are the Artifact and its parts.
47    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        // An Artifact is made of its parts, so selecting it selects them too.
99        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    /// Recursive execution includes every Eval in the required Artifact scope. An Artifact
126    /// selection also includes its cycle peers' Evals, after the selected ones: they review
127    /// the selected Artifact, so only this Run can give them current results.
128    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
184/// Resolve complete declared profiles in owned configuration, never rewriting source files.
185pub 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    // Runtime variants can introduce or remove argv references and dependency gates.
219    crate::scope::resolve_config(&mut config).map_err(|error| error.to_string())?;
220    Ok(config)
221}
222
223/// Bound selection-file parsing/allocation before resolving any project work.
224const MAX_FILE_BYTES: usize = 4 * 1024 * 1024;
225/// Bound resolution and deduplication work even for files containing many short IDs.
226const MAX_IDS: usize = 100_000;
227const FILE_FORMAT_ERROR: &str =
228    "Selection file must contain 1–100000 nonempty IDs, as a JSON string array or one ID per line.";
229
230// Match ECMAScript trim, including BOM but excluding NEXT LINE.
231fn trim(text: &str) -> &str {
232    text.trim_matches(|ch| {
233        matches!(ch,
234            '\u{0009}'..='\u{000d}' | '\u{0020}' | '\u{00a0}' | '\u{1680}' |
235            '\u{2000}'..='\u{200a}' | '\u{2028}' | '\u{2029}' | '\u{202f}' |
236            '\u{205f}' | '\u{3000}' | '\u{feff}'
237        )
238    })
239}
240
241pub fn parse_selection_file(text: &str) -> Result<Vec<String>, String> {
242    let text = text.strip_prefix('\u{feff}').unwrap_or(text);
243    if text.len() > MAX_FILE_BYTES {
244        return Err("Selection file exceeds 4 MiB.".into());
245    }
246    let ids: Vec<String> = if trim(text).starts_with('[') {
247        serde_json::from_str::<Vec<String>>(text).map_err(|error| {
248            // A valid array containing a non-string is a format error, not broken JSON.
249            // Validate only syntax after a data error, preserving malformed-array precedence.
250            if error.is_data() && serde_json::from_str::<crate::json::Ignored>(text).is_ok() {
251                FILE_FORMAT_ERROR.to_owned()
252            } else {
253                "Selection file contains invalid JSON.".to_owned()
254            }
255        })?
256    } else {
257        text.split('\n')
258            .map(trim)
259            .filter(|line| !line.is_empty())
260            .take(MAX_IDS + 1)
261            .map(str::to_owned)
262            .collect()
263    };
264    if ids.is_empty()
265        || ids.len() > MAX_IDS
266        || ids.iter().any(|id| {
267            id.is_empty()
268                || trim(id) != id
269                || id
270                    .bytes()
271                    .any(|byte| byte <= b' ' || byte == 127 || byte == b',')
272        })
273    {
274        return Err(FILE_FORMAT_ERROR.into());
275    }
276    let mut seen = BTreeSet::new();
277    Ok(ids
278        .into_iter()
279        .filter(|id| seen.insert(id.clone()))
280        .collect())
281}
282
283pub fn read_selection_file(path: &Path) -> Result<Vec<String>, String> {
284    // Nonblocking open lets us reject a FIFO without waiting for its writer.
285    let file = crate::platform::open_nonblocking(path)
286        .map_err(|error| format!("{}: {error}", crate::platform::path_text(path)))?;
287    let info = file.metadata().map_err(|error| error.to_string())?;
288    if !info.is_file() || info.len() > MAX_FILE_BYTES as u64 {
289        return Err("Selection input must be a regular file no larger than 4 MiB.".into());
290    }
291    let mut bytes = Vec::new();
292    file.take(MAX_FILE_BYTES as u64 + 1)
293        .read_to_end(&mut bytes)
294        .map_err(|error| error.to_string())?;
295    if bytes.len() > MAX_FILE_BYTES {
296        return Err("Selection file exceeds 4 MiB.".into());
297    }
298    parse_selection_file(&String::from_utf8_lossy(&bytes))
299}
300
301#[cfg(test)]
302mod tests;