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.
114    pub fn included_evals<'a>(
115        &self,
116        config: &'a RepoConfig,
117        recursive: bool,
118    ) -> Result<Vec<&'a Eval>, String> {
119        let selected = self.resolve(config)?;
120        if !recursive {
121            return Ok(selected.evals);
122        }
123        let graph = Graph::new(config).map_err(|error| error.to_string())?;
124        let required: BTreeSet<_> = graph
125            .dependency_closure(&selected.roots)
126            .map_err(|error| error.to_string())?
127            .into_iter()
128            .collect();
129        Ok(config
130            .evals
131            .iter()
132            .filter(|eval| required.contains(&eval.target))
133            .collect())
134    }
135}
136
137fn nonempty<T>(ids: &[T]) -> Result<(), String> {
138    if ids.is_empty() {
139        return Err("Multi-root selection requires a nonempty array of IDs.".into());
140    }
141    Ok(())
142}
143
144fn selected_artifact<'a>(config: &'a RepoConfig, id: &str) -> Result<&'a ArtifactName, String> {
145    config
146        .artifacts
147        .get_key_value(id)
148        .map(|(id, _)| id)
149        .ok_or_else(|| format!("Unknown Artifact: {id}"))
150}
151
152#[derive(Debug, Clone, Serialize, Deserialize)]
153#[serde(untagged)]
154pub enum ProfileSelection {
155    Named(ProfileVariantName),
156    Evals(BTreeMap<EvalId, ProfileVariantName>),
157}
158
159/// Resolve complete declared profiles in owned configuration, never rewriting source files.
160pub fn select_profiles(
161    mut config: RepoConfig,
162    selection: &Selection,
163    profile: Option<&ProfileSelection>,
164    recursive: bool,
165) -> Result<RepoConfig, String> {
166    let Some(profile) = profile else {
167        return Ok(config);
168    };
169    let evals = selection.included_evals(&config, recursive)?;
170    let included: BTreeMap<_, _> = evals.iter().map(|eval| (&eval.id, *eval)).collect();
171    let mapping: Vec<(&EvalId, &ProfileVariantName)> = match profile {
172        ProfileSelection::Named(name) => evals.iter().map(|eval| (&eval.id, name)).collect(),
173        ProfileSelection::Evals(mapping) => mapping.iter().collect(),
174    };
175    let mut profiles = BTreeMap::new();
176    for (id, name) in mapping {
177        let eval = included.get(id).ok_or_else(|| {
178            format!("Profile selection is outside the submitted Eval scope: {id}")
179        })?;
180        let variant = eval
181            .declaration
182            .profile_variants()
183            .get(name)
184            .ok_or_else(|| format!("Unknown profile variant for {id}: {name}"))?;
185        profiles.insert(id.clone(), (name.clone(), variant.clone()));
186    }
187    for eval in &mut config.evals {
188        if let Some((name, _profile)) = profiles.remove(&eval.id) {
189            eval.declaration.select_profile(&name)?;
190            eval.variant = Some(name);
191        }
192    }
193    // Runtime variants can introduce or remove argv references and dependency gates.
194    crate::scope::resolve_config(&mut config).map_err(|error| error.to_string())?;
195    Ok(config)
196}
197
198/// Bound selection-file parsing/allocation before resolving any project work.
199const MAX_FILE_BYTES: usize = 4 * 1024 * 1024;
200/// Bound resolution and deduplication work even for files containing many short IDs.
201const MAX_IDS: usize = 100_000;
202const FILE_FORMAT_ERROR: &str =
203    "Selection file must contain 1–100000 nonempty IDs, as a JSON string array or one ID per line.";
204
205// Match ECMAScript trim, including BOM but excluding NEXT LINE.
206fn trim(text: &str) -> &str {
207    text.trim_matches(|ch| {
208        matches!(ch,
209            '\u{0009}'..='\u{000d}' | '\u{0020}' | '\u{00a0}' | '\u{1680}' |
210            '\u{2000}'..='\u{200a}' | '\u{2028}' | '\u{2029}' | '\u{202f}' |
211            '\u{205f}' | '\u{3000}' | '\u{feff}'
212        )
213    })
214}
215
216pub fn parse_selection_file(text: &str) -> Result<Vec<String>, String> {
217    let text = text.strip_prefix('\u{feff}').unwrap_or(text);
218    if text.len() > MAX_FILE_BYTES {
219        return Err("Selection file exceeds 4 MiB.".into());
220    }
221    let ids: Vec<String> = if trim(text).starts_with('[') {
222        serde_json::from_str::<Vec<String>>(text).map_err(|error| {
223            // A valid array containing a non-string is a format error, not broken JSON.
224            // Validate only syntax after a data error, preserving malformed-array precedence.
225            if error.is_data() && serde_json::from_str::<crate::json::Ignored>(text).is_ok() {
226                FILE_FORMAT_ERROR.to_owned()
227            } else {
228                "Selection file contains invalid JSON.".to_owned()
229            }
230        })?
231    } else {
232        text.split('\n')
233            .map(trim)
234            .filter(|line| !line.is_empty())
235            .take(MAX_IDS + 1)
236            .map(str::to_owned)
237            .collect()
238    };
239    if ids.is_empty()
240        || ids.len() > MAX_IDS
241        || ids.iter().any(|id| {
242            id.is_empty()
243                || trim(id) != id
244                || id
245                    .bytes()
246                    .any(|byte| byte <= b' ' || byte == 127 || byte == b',')
247        })
248    {
249        return Err(FILE_FORMAT_ERROR.into());
250    }
251    let mut seen = BTreeSet::new();
252    Ok(ids
253        .into_iter()
254        .filter(|id| seen.insert(id.clone()))
255        .collect())
256}
257
258pub fn read_selection_file(path: &Path) -> Result<Vec<String>, String> {
259    // Nonblocking open lets us reject a FIFO without waiting for its writer.
260    let file = crate::platform::open_nonblocking(path)
261        .map_err(|error| format!("{}: {error}", crate::platform::path_text(path)))?;
262    let info = file.metadata().map_err(|error| error.to_string())?;
263    if !info.is_file() || info.len() > MAX_FILE_BYTES as u64 {
264        return Err("Selection input must be a regular file no larger than 4 MiB.".into());
265    }
266    let mut bytes = Vec::new();
267    file.take(MAX_FILE_BYTES as u64 + 1)
268        .read_to_end(&mut bytes)
269        .map_err(|error| error.to_string())?;
270    if bytes.len() > MAX_FILE_BYTES {
271        return Err("Selection file exceeds 4 MiB.".into());
272    }
273    parse_selection_file(&String::from_utf8_lossy(&bytes))
274}
275
276#[cfg(test)]
277mod tests;