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.
46    pub fn resolve<'a>(&self, config: &'a RepoConfig) -> Result<ResolvedSelection<'a>, String> {
47        let evals_by_id: BTreeMap<_, _> = config
48            .evals
49            .iter()
50            .map(|eval| (eval.id.as_str(), eval))
51            .collect();
52        let mut evals_by_target: BTreeMap<&ArtifactName, Vec<&Eval>> = BTreeMap::new();
53        for eval in &config.evals {
54            evals_by_target.entry(&eval.target).or_default().push(eval);
55        }
56        let mut result = ResolvedSelection {
57            evals: Vec::new(),
58            roots: Vec::new(),
59        };
60        match self {
61            Self::All => {
62                result.evals.extend(&config.evals);
63                result.roots.extend(config.artifacts.keys());
64            }
65            Self::Artifact { artifact_id } => {
66                result.roots.push(selected_artifact(config, artifact_id)?);
67            }
68            Self::Artifacts { artifact_ids } => {
69                nonempty(artifact_ids)?;
70                for id in artifact_ids {
71                    result.roots.push(selected_artifact(config, id)?);
72                }
73            }
74            Self::Eval { eval_id } => {
75                result.evals.push(
76                    *evals_by_id
77                        .get(eval_id.as_str())
78                        .ok_or_else(|| format!("Unknown Eval: {eval_id}"))?,
79                );
80            }
81            Self::Evals { eval_ids } => {
82                nonempty(eval_ids)?;
83                for id in eval_ids {
84                    result.evals.push(
85                        *evals_by_id
86                            .get(id.as_str())
87                            .ok_or_else(|| format!("Unknown Eval: {id}"))?,
88                    );
89                }
90            }
91        }
92        if matches!(self, Self::Eval { .. } | Self::Evals { .. }) {
93            result
94                .roots
95                .extend(result.evals.iter().map(|eval| &eval.target));
96        }
97        let mut seen = BTreeSet::new();
98        result.roots.retain(|id| seen.insert(*id));
99        if matches!(self, Self::Artifact { .. } | Self::Artifacts { .. }) {
100            for id in &result.roots {
101                if let Some(evals) = evals_by_target.get(id) {
102                    result.evals.extend(evals);
103                }
104            }
105        }
106        let mut seen_evals = BTreeSet::new();
107        result
108            .evals
109            .retain(|eval| seen_evals.insert(eval.id.as_str()));
110        Ok(result)
111    }
112
113    /// Recursive execution includes every Eval in the required Artifact scope. An Artifact
114    /// selection also includes its cycle peers' Evals, after the selected ones: they review
115    /// the selected Artifact, so only this Run can give them current results.
116    pub fn included_evals<'a>(
117        &self,
118        config: &'a RepoConfig,
119        recursive: bool,
120    ) -> Result<Vec<&'a Eval>, String> {
121        let selected = self.resolve(config)?;
122        let peers = matches!(self, Self::Artifact { .. } | Self::Artifacts { .. });
123        if !recursive && !peers {
124            return Ok(selected.evals);
125        }
126        let graph = Graph::new(config).map_err(|error| error.to_string())?;
127        let required: BTreeSet<_> = if recursive {
128            graph.dependency_closure(&selected.roots)
129        } else {
130            graph.cycle_members(&selected.roots)
131        }
132        .map_err(|error| error.to_string())?
133        .into_iter()
134        .collect();
135        let included = config
136            .evals
137            .iter()
138            .filter(|eval| required.contains(&eval.target));
139        if recursive {
140            return Ok(included.collect());
141        }
142        let selected_ids: BTreeSet<_> = selected.evals.iter().map(|&eval| &eval.id).collect();
143        let peer_evals: Vec<_> = included
144            .filter(|eval| !selected_ids.contains(&eval.id))
145            .collect();
146        Ok(selected.evals.into_iter().chain(peer_evals).collect())
147    }
148}
149
150fn nonempty<T>(ids: &[T]) -> Result<(), String> {
151    if ids.is_empty() {
152        return Err("Multi-root selection requires a nonempty array of IDs.".into());
153    }
154    Ok(())
155}
156
157fn selected_artifact<'a>(config: &'a RepoConfig, id: &str) -> Result<&'a ArtifactName, String> {
158    config
159        .artifacts
160        .get_key_value(id)
161        .map(|(id, _)| id)
162        .ok_or_else(|| format!("Unknown Artifact: {id}"))
163}
164
165#[derive(Debug, Clone, Serialize, Deserialize)]
166#[serde(untagged)]
167pub enum ProfileSelection {
168    Named(ProfileVariantName),
169    Evals(BTreeMap<EvalId, ProfileVariantName>),
170}
171
172/// Resolve complete declared profiles in owned configuration, never rewriting source files.
173pub fn select_profiles(
174    mut config: RepoConfig,
175    selection: &Selection,
176    profile: Option<&ProfileSelection>,
177    recursive: bool,
178) -> Result<RepoConfig, String> {
179    let Some(profile) = profile else {
180        return Ok(config);
181    };
182    let evals = selection.included_evals(&config, recursive)?;
183    let included: BTreeMap<_, _> = evals.iter().map(|eval| (&eval.id, *eval)).collect();
184    let mapping: Vec<(&EvalId, &ProfileVariantName)> = match profile {
185        ProfileSelection::Named(name) => evals.iter().map(|eval| (&eval.id, name)).collect(),
186        ProfileSelection::Evals(mapping) => mapping.iter().collect(),
187    };
188    let mut profiles = BTreeMap::new();
189    for (id, name) in mapping {
190        let eval = included.get(id).ok_or_else(|| {
191            format!("Profile selection is outside the submitted Eval scope: {id}")
192        })?;
193        let variant = eval
194            .declaration
195            .profile_variants()
196            .get(name)
197            .ok_or_else(|| format!("Unknown profile variant for {id}: {name}"))?;
198        profiles.insert(id.clone(), (name.clone(), variant.clone()));
199    }
200    for eval in &mut config.evals {
201        if let Some((name, _profile)) = profiles.remove(&eval.id) {
202            eval.declaration.select_profile(&name)?;
203            eval.variant = Some(name);
204        }
205    }
206    // Runtime variants can introduce or remove argv references and dependency gates.
207    crate::scope::resolve_config(&mut config).map_err(|error| error.to_string())?;
208    Ok(config)
209}
210
211/// Bound selection-file parsing/allocation before resolving any project work.
212const MAX_FILE_BYTES: usize = 4 * 1024 * 1024;
213/// Bound resolution and deduplication work even for files containing many short IDs.
214const MAX_IDS: usize = 100_000;
215const FILE_FORMAT_ERROR: &str =
216    "Selection file must contain 1–100000 nonempty IDs, as a JSON string array or one ID per line.";
217
218// Match ECMAScript trim, including BOM but excluding NEXT LINE.
219fn trim(text: &str) -> &str {
220    text.trim_matches(|ch| {
221        matches!(ch,
222            '\u{0009}'..='\u{000d}' | '\u{0020}' | '\u{00a0}' | '\u{1680}' |
223            '\u{2000}'..='\u{200a}' | '\u{2028}' | '\u{2029}' | '\u{202f}' |
224            '\u{205f}' | '\u{3000}' | '\u{feff}'
225        )
226    })
227}
228
229pub fn parse_selection_file(text: &str) -> Result<Vec<String>, String> {
230    let text = text.strip_prefix('\u{feff}').unwrap_or(text);
231    if text.len() > MAX_FILE_BYTES {
232        return Err("Selection file exceeds 4 MiB.".into());
233    }
234    let ids: Vec<String> = if trim(text).starts_with('[') {
235        serde_json::from_str::<Vec<String>>(text).map_err(|error| {
236            // A valid array containing a non-string is a format error, not broken JSON.
237            // Validate only syntax after a data error, preserving malformed-array precedence.
238            if error.is_data() && serde_json::from_str::<crate::json::Ignored>(text).is_ok() {
239                FILE_FORMAT_ERROR.to_owned()
240            } else {
241                "Selection file contains invalid JSON.".to_owned()
242            }
243        })?
244    } else {
245        text.split('\n')
246            .map(trim)
247            .filter(|line| !line.is_empty())
248            .take(MAX_IDS + 1)
249            .map(str::to_owned)
250            .collect()
251    };
252    if ids.is_empty()
253        || ids.len() > MAX_IDS
254        || ids.iter().any(|id| {
255            id.is_empty()
256                || trim(id) != id
257                || id
258                    .bytes()
259                    .any(|byte| byte <= b' ' || byte == 127 || byte == b',')
260        })
261    {
262        return Err(FILE_FORMAT_ERROR.into());
263    }
264    let mut seen = BTreeSet::new();
265    Ok(ids
266        .into_iter()
267        .filter(|id| seen.insert(id.clone()))
268        .collect())
269}
270
271pub fn read_selection_file(path: &Path) -> Result<Vec<String>, String> {
272    // Nonblocking open lets us reject a FIFO without waiting for its writer.
273    let file = crate::platform::open_nonblocking(path)
274        .map_err(|error| format!("{}: {error}", crate::platform::path_text(path)))?;
275    let info = file.metadata().map_err(|error| error.to_string())?;
276    if !info.is_file() || info.len() > MAX_FILE_BYTES as u64 {
277        return Err("Selection input must be a regular file no larger than 4 MiB.".into());
278    }
279    let mut bytes = Vec::new();
280    file.take(MAX_FILE_BYTES as u64 + 1)
281        .read_to_end(&mut bytes)
282        .map_err(|error| error.to_string())?;
283    if bytes.len() > MAX_FILE_BYTES {
284        return Err("Selection file exceeds 4 MiB.".into());
285    }
286    parse_selection_file(&String::from_utf8_lossy(&bytes))
287}
288
289#[cfg(test)]
290mod tests;