Skip to main content

artifactize_core/config/
workspace.rs

1//! Resolved Artifacts, their Evals, and the workspace model shared by callers.
2
3use super::{
4    ArtifactKind, ArtifactName, ChildPrefix, ConfigError, EvalDeclaration, EvalId, Fingerprint,
5    LogicalPath, Profile, ProfileName, Site, Target, Views,
6    site::{declaration_of, folder_of},
7};
8use serde::Serialize;
9use std::{
10    collections::{BTreeMap, BTreeSet},
11    path::{Path, PathBuf},
12    sync::Arc,
13};
14
15/// Where an Artifact is bound: the line of its `artf` statement and the macro it calls.
16#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
17#[serde(rename_all = "camelCase")]
18pub struct Binding {
19    pub line: usize,
20    #[serde(rename = "macro", skip_serializing_if = "Option::is_none")]
21    pub macro_name: Option<String>,
22}
23
24/// Nested folder paths with their Artifacts as tool-side IDs. Discovery validated both, so a
25/// failure here is a bug.
26fn tool_nested(
27    nested: &BTreeMap<ChildPrefix, ArtifactName>,
28) -> BTreeMap<artifactize_tools::scope::ChildPrefix, artifactize_tools::scope::ArtifactId> {
29    nested
30        .iter()
31        .map(|(path, name)| {
32            (
33                artifactize_tools::scope::ChildPrefix::new(path.as_ref())
34                    .expect("validated child prefix"),
35                crate::scope::tool_id(name),
36            )
37        })
38        .collect()
39}
40
41#[derive(Debug, Clone)]
42pub struct Artifact {
43    pub definition: PathBuf,
44    /// Exact PATH from a definition node; legacy migration inputs lack this field.
45    pub(crate) authored_path: Option<String>,
46    /// Current target availability is not part of the saved declaration or its identity.
47    pub target_error: Option<String>,
48    pub path: Target,
49    /// Folder Artifacts declared in subfolders, by their path here. Their files are theirs,
50    /// not this Artifact's; discovery also records them as parts.
51    pub nested: BTreeMap<ChildPrefix, ArtifactName>,
52    /// A folder part at the same target or an ancestor, owning every file here.
53    pub covering_part: Option<ArtifactName>,
54    /// What it is made of: the Artifacts its folder holds and those its `parts` names.
55    pub parts: BTreeSet<ArtifactName>,
56    pub name: ArtifactName,
57    pub tags: Vec<String>,
58    pub views: Views,
59    /// The tool expression as written (`files & html`) and the toolsets it composes.
60    pub tools: Option<String>,
61    pub toolsets: Vec<String>,
62    /// Absent only for Artifacts read from saved Runs.
63    pub binding: Option<Binding>,
64    pub basis: Option<bool>,
65    pub fingerprint: Option<Fingerprint>,
66}
67
68impl serde::Serialize for Artifact {
69    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
70        use serde::ser::SerializeMap;
71        let mut map = serializer.serialize_map(None)?;
72        map.serialize_entry("definition", &crate::platform::path_text(&self.definition))?;
73        map.serialize_entry("path", &self.path)?;
74        map.serialize_entry("kind", &self.kind())?;
75        map.serialize_entry("nested", &self.nested)?;
76        if let Some(part) = &self.covering_part {
77            map.serialize_entry("coveringPart", part)?;
78        }
79        if !self.select().is_empty() {
80            map.serialize_entry("select", self.select())?;
81        }
82        if !self.parts.is_empty() {
83            map.serialize_entry("parts", &self.parts)?;
84        }
85        map.serialize_entry("name", &self.name)?;
86        map.serialize_entry("tags", &self.tags)?;
87        map.serialize_entry("views", &self.views)?;
88        if let Some(tools) = &self.tools {
89            map.serialize_entry("tools", tools)?;
90            map.serialize_entry("toolsets", &self.toolsets)?;
91        }
92        if let Some(binding) = &self.binding {
93            map.serialize_entry("binding", binding)?;
94        }
95        map.serialize_entry("basis", &self.basis)?;
96        map.serialize_entry("fingerprint", &self.fingerprint)?;
97        map.end()
98    }
99}
100
101impl Artifact {
102    pub fn kind(&self) -> ArtifactKind {
103        self.path.kind()
104    }
105    /// Its `path` as written: a folder ends in `/`, a Live Artifact is an address.
106    pub fn written_path(&self) -> String {
107        self.authored_path
108            .clone()
109            .unwrap_or_else(|| self.path.to_string())
110    }
111    pub fn select(&self) -> &[LogicalPath] {
112        self.path.select()
113    }
114    pub(crate) fn tool_scope(&self) -> artifactize_tools::scope::Artifact {
115        artifactize_tools::scope::Artifact {
116            path: self.path.clone(),
117            name: self.name.to_string(),
118            nested: tool_nested(&self.nested),
119            covering_part: self.covering_part.as_ref().map(crate::scope::tool_id),
120        }
121    }
122
123    /// Runtime commands and relative declarations use the containing folder.
124    pub fn folder(&self) -> &Path {
125        folder_of(self.kind(), &self.path)
126    }
127
128    /// What `{name}` stands for: the folder or file, or an aspect's folder, since an
129    /// aspect's path is only its declaration's label.
130    pub fn referenced_path(&self) -> Option<&Path> {
131        if self.kind() == ArtifactKind::Aspect {
132            Some(self.folder())
133        } else {
134            self.path.local()
135        }
136    }
137
138    pub fn file_name(&self) -> Option<&str> {
139        (self.kind() == ArtifactKind::File)
140            .then(|| {
141                self.path
142                    .local()
143                    .and_then(Path::file_name)
144                    .and_then(|name| name.to_str())
145            })
146            .flatten()
147    }
148
149    pub fn declaration_path(&self) -> PathBuf {
150        if self.definition.as_os_str().is_empty() {
151            declaration_of(self.kind(), &self.path)
152        } else {
153            self.definition.clone()
154        }
155    }
156
157    /// Where it is declared.
158    pub fn site(&self) -> Site {
159        Site {
160            path: self.path.clone(),
161            definition: self.declaration_path(),
162        }
163    }
164}
165
166#[derive(Debug, Serialize)]
167pub struct Eval {
168    /// Workspace-qualified id; declaration.id remains the owner's local id.
169    pub id: EvalId,
170    pub target: ArtifactName,
171    pub references: BTreeMap<crate::config::ReferenceName, ArtifactName>,
172    pub deps: Vec<ArtifactName>,
173    pub declaration: EvalDeclaration,
174}
175
176#[derive(Debug, Clone, Copy, PartialEq, Eq)]
177pub enum ReviewRequirement {
178    Basis,
179    Unreviewed,
180    Evals,
181    /// No evals of its own: its parts' verdicts are its verdict.
182    Parts,
183}
184
185#[derive(Debug)]
186pub struct RepoConfig {
187    pub root: PathBuf,
188    pub artifacts: BTreeMap<ArtifactName, Artifact>,
189    pub evals: Vec<Eval>,
190    pub relations: Vec<crate::scope::Relation>,
191    /// The project's profiles, each in the branch the environment selects.
192    pub profiles: BTreeMap<ProfileName, Profile>,
193    /// The code the declarations were read from; absent for configurations saved with Runs.
194    pub(crate) program: Option<Arc<super::lang::Program>>,
195    /// The plugins whose toolsets it may compose, with their viewers.
196    pub(crate) plugins: super::plugins::Catalog,
197}
198
199impl RepoConfig {
200    /// An error at the declaration of `artifact` that `keys` names (`["evals", id,
201    /// "instruction"]`, `["parts"]`, …), with the call site when a macro made it.
202    pub(crate) fn error_at(
203        &self,
204        artifact: &ArtifactName,
205        keys: &[&str],
206        message: impl Into<String>,
207    ) -> ConfigError {
208        let message = message.into();
209        let Some(program) = &self.program else {
210            let definition = self
211                .artifacts
212                .get(artifact)
213                .map(Artifact::declaration_path)
214                .unwrap_or_default();
215            return ConfigError::new(self.root.join(definition), message);
216        };
217        let lowered = program
218            .artifacts
219            .iter()
220            .find(|lowered| lowered.name == artifact.as_str());
221        let Some(lowered) = lowered else {
222            return ConfigError::new(&self.root, message);
223        };
224        super::discovery::located(
225            &self.root,
226            program,
227            lowered,
228            super::lang::span_of(lowered, keys),
229            message,
230        )
231    }
232
233    /// Every Artifact `name` is made of, directly or through its parts, each once.
234    pub fn descendants<'a>(&'a self, name: &'a ArtifactName) -> Vec<&'a ArtifactName> {
235        let mut seen = BTreeSet::new();
236        let mut pending = vec![name];
237        while let Some(next) = pending.pop() {
238            for part in self.artifacts.get(next).into_iter().flat_map(|a| &a.parts) {
239                if seen.insert(part) {
240                    pending.push(part);
241                }
242            }
243        }
244        seen.into_iter().collect()
245    }
246
247    /// Local obligations only; a basis does not satisfy its dependency scope.
248    pub fn review_requirement(&self, artifact_id: &str) -> Option<ReviewRequirement> {
249        let artifact = self.artifacts.get(artifact_id)?;
250        Some(if artifact.basis == Some(true) {
251            ReviewRequirement::Basis
252        } else if self.evals.iter().any(|eval| eval.target == artifact_id) {
253            ReviewRequirement::Evals
254        } else if !artifact.parts.is_empty() {
255            ReviewRequirement::Parts
256        } else {
257            ReviewRequirement::Unreviewed
258        })
259    }
260}