Skip to main content

artifactize_core/config/
site.rs

1//! Where an Artifact is declared: its target and the file that binds it. Moving a binding to
2//! another file, or its target elsewhere, is a move; anything else about the file is not.
3use super::*;
4
5#[derive(Debug, Clone, PartialEq, Eq)]
6pub struct Site {
7    pub path: Target,
8    pub definition: PathBuf,
9}
10impl Site {
11    /// Base of relative commands and inputs, not the definition's containing folder.
12    pub fn folder(&self) -> &Path {
13        folder_of(self.path.kind(), &self.path)
14    }
15    pub fn declaration_path(&self) -> PathBuf {
16        self.definition.clone()
17    }
18}
19pub(super) fn folder_of(kind: ArtifactKind, path: &Target) -> &Path {
20    match kind {
21        ArtifactKind::Folder | ArtifactKind::Aspect | ArtifactKind::Graph => {
22            path.local().expect("filesystem kind")
23        }
24        ArtifactKind::File => path
25            .local()
26            .expect("filesystem kind")
27            .parent()
28            .unwrap_or(Path::new("")),
29        ArtifactKind::Live => Path::new(""),
30    }
31}
32/// Old locations are used only while migrating and when reading pre-migration saved Runs.
33pub(super) fn declaration_of(kind: ArtifactKind, target: &Target) -> PathBuf {
34    let path = target.local().unwrap_or(Path::new(""));
35    match kind {
36        ArtifactKind::Live => PathBuf::new(),
37        ArtifactKind::Graph => PathBuf::from(".artf"),
38        ArtifactKind::Folder => logical_join(path, std::ffi::OsStr::new(CONFIG_FILE)),
39        ArtifactKind::File | ArtifactKind::Aspect => {
40            let mut path = path.as_os_str().to_owned();
41            path.push(".artf");
42            PathBuf::from(path)
43        }
44    }
45}
46
47/// Names and files reached from recorded declarations, not a grant of access. Each file is
48/// opened again and live declarations are resolved before the operation uses them.
49#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
50pub struct DeclarationScope {
51    names: BTreeSet<ArtifactName>,
52    files: BTreeSet<LogicalPath>,
53}
54
55impl DeclarationScope {
56    pub(crate) fn of<'a>(
57        config: &RepoConfig,
58        roots: impl IntoIterator<Item = &'a ArtifactName>,
59    ) -> Self {
60        Self::collect(roots.into_iter().cloned(), |name| {
61            let artifact = config.artifacts.get(name)?;
62            Some((imports(config, artifact), links(config, artifact)))
63        })
64    }
65
66    fn collect(
67        roots: impl IntoIterator<Item = ArtifactName>,
68        mut entry: impl FnMut(&ArtifactName) -> Option<(BTreeSet<LogicalPath>, BTreeSet<ArtifactName>)>,
69    ) -> Self {
70        let mut scope = Self {
71            names: BTreeSet::new(),
72            files: BTreeSet::new(),
73        };
74        let mut pending: Vec<_> = roots.into_iter().collect();
75        while let Some(name) = pending.pop() {
76            if scope.names.insert(name.clone())
77                && let Some((files, links)) = entry(&name)
78            {
79                scope.files.extend(files);
80                pending.extend(links);
81            }
82        }
83        scope
84    }
85
86    pub(crate) fn read(
87        &self,
88        repo: &Path,
89        evals: Evals<'_>,
90        environment: lang::Environment<'_>,
91    ) -> Result<RepoConfig, ConfigError> {
92        let files = self
93            .files
94            .iter()
95            .map(|file| PathBuf::from(file.as_str()))
96            .collect();
97        let config = discovery::read_subset(repo, &self.names, &files, evals, environment)?;
98        if let Some(name) = self
99            .names
100            .iter()
101            .find(|name| !config.artifacts.contains_key(*name))
102        {
103            return Err(ConfigError::new(
104                repo,
105                format!("No recorded site still declares {name}."),
106            ));
107        }
108        Ok(config)
109    }
110}
111
112#[derive(Clone, Copy)]
113pub(crate) enum Evals<'a> {
114    All,
115    One(&'a EvalId),
116    None,
117}
118
119fn imports(config: &RepoConfig, artifact: &Artifact) -> BTreeSet<LogicalPath> {
120    let from_program = config.program.as_ref().into_iter().flat_map(|program| {
121        let items = &program.artifacts;
122        items
123            .binary_search_by(|item| item.name.as_str().cmp(artifact.name.as_str()))
124            .ok()
125            .into_iter()
126            .flat_map(|at| &items[at].imports)
127            .map(|&id| program.sources.file(id).path.as_path())
128    });
129    std::iter::once(artifact.definition.as_path())
130        .chain(from_program)
131        .filter_map(|path| crate::platform::path_text(path).parse().ok())
132        .collect()
133}
134
135fn links(config: &RepoConfig, artifact: &Artifact) -> BTreeSet<ArtifactName> {
136    use crate::scope::Argument;
137    let agent = artifact
138        .views
139        .agent_tools
140        .values()
141        .filter_map(|tool| match tool {
142            AgentTool::Command(command) => Some(command.args.as_slice()),
143            _ => None,
144        });
145    let human = artifact
146        .views
147        .human_tools
148        .values()
149        .filter_map(|tool| match tool {
150            HumanTool::Command(command) => Some(command.args.as_slice()),
151            HumanTool::Builtin(builtin) => Some(builtin.args.as_slice()),
152            HumanTool::Viewer(_) => None,
153        });
154    let fingerprint = match &artifact.fingerprint {
155        Some(Fingerprint::Script { args, .. }) => Some(args.as_slice()),
156        _ => None,
157    };
158    artifact
159        .parts
160        .iter()
161        .chain(artifact.covering_part.iter())
162        .cloned()
163        .chain(
164            agent
165                .chain(human)
166                .chain(fingerprint)
167                .flatten()
168                .filter_map(|argument| match argument {
169                    Argument::Reference { name, .. } => config
170                        .artifacts
171                        .get_key_value(name.as_str())
172                        .map(|(id, _)| id.clone()),
173                    _ => None,
174                }),
175        )
176        .collect()
177}
178
179#[derive(Debug, Clone)]
180struct Indexed {
181    site: Site,
182    files: BTreeSet<LogicalPath>,
183    links: BTreeSet<ArtifactName>,
184    inputs: BTreeSet<ArtifactName>,
185}
186
187/// Compact per-name lookup built when a caller has already read the whole workspace. It
188/// owns no syntax trees, instructions, tools or expanded declarations.
189#[derive(Debug, Clone, Default)]
190pub struct SiteIndex(BTreeMap<ArtifactName, Indexed>);
191
192impl SiteIndex {
193    pub fn read(repo: &Path) -> Result<Self, ConfigError> {
194        let result = discovery::read_workspace_declarations(repo).map(|config| Self::new(&config));
195        crate::platform::release_free_memory();
196        result
197    }
198
199    pub(crate) fn new(config: &RepoConfig) -> Self {
200        let mut entries: BTreeMap<_, _> = config
201            .artifacts
202            .iter()
203            .map(|(id, artifact)| {
204                (
205                    id.clone(),
206                    Indexed {
207                        site: artifact.site(),
208                        files: imports(config, artifact),
209                        links: links(config, artifact),
210                        inputs: BTreeSet::new(),
211                    },
212                )
213            })
214            .collect();
215        for eval in &config.evals {
216            entries
217                .get_mut(&eval.target)
218                .expect("eval target")
219                .inputs
220                .extend(eval.deps.iter().cloned());
221        }
222        Self(entries)
223    }
224
225    pub fn site(&self, name: &ArtifactName) -> Option<&Site> {
226        self.0.get(name).map(|entry| &entry.site)
227    }
228
229    pub(crate) fn subset(
230        &self,
231        repo: &Path,
232        roots: impl IntoIterator<Item = ArtifactName>,
233        evals: Evals<'_>,
234        environment: lang::Environment<'_>,
235    ) -> Result<RepoConfig, ConfigError> {
236        let scope = DeclarationScope::collect(roots, |name| {
237            let entry = self.0.get(name)?;
238            let mut links = entry.links.clone();
239            if matches!(evals, Evals::All) {
240                links.extend(entry.inputs.iter().cloned());
241            }
242            Some((entry.files.clone(), links))
243        });
244        let config = scope.read(repo, evals, environment)?;
245        for (name, artifact) in &config.artifacts {
246            check_site(&config, name, &self.0[name].site)
247                .map_err(|error| ConfigError::new(repo, error))?;
248            debug_assert_eq!(&artifact.name, name);
249        }
250        Ok(config)
251    }
252}
253
254/// Where every Artifact of the project is declared now.
255pub fn read_sites(repo: &Path) -> Result<BTreeMap<ArtifactName, Site>, ConfigError> {
256    let config = discovery::read_workspace_declarations(repo)?;
257    Ok(config
258        .artifacts
259        .into_iter()
260        .map(|(name, artifact)| {
261            let site = artifact.site();
262            (name, site)
263        })
264        .collect())
265}
266
267#[derive(Debug, Error)]
268pub enum ScopeReadError {
269    #[error("{name} is no longer declared at {}.", crate::platform::path_text(.path))]
270    Moved { name: ArtifactName, path: PathBuf },
271    #[error(transparent)]
272    Config(#[from] ConfigError),
273}
274
275fn check_site(config: &RepoConfig, name: &ArtifactName, site: &Site) -> Result<(), ScopeReadError> {
276    if config
277        .artifacts
278        .get(name)
279        .is_some_and(|artifact| artifact.site() == *site)
280    {
281        Ok(())
282    } else {
283        Err(ScopeReadError::Moved {
284            name: name.clone(),
285            path: site.declaration_path(),
286        })
287    }
288}
289
290pub(crate) fn read_artifact_scope(
291    repo: &Path,
292    name: &ArtifactName,
293    site: &Site,
294) -> Result<RepoConfig, ScopeReadError> {
295    let mut config = discovery::read_workspace_declarations(repo)?;
296    check_site(&config, name, site)?;
297    config.evals.clear();
298    Ok(config)
299}
300
301/// The project as declared now with only eval `id`, when every Artifact it reads is still
302/// declared where `sites` says; none when the eval is no longer declared.
303pub(crate) fn read_eval_scope(
304    repo: &Path,
305    id: &EvalId,
306    sites: &BTreeMap<ArtifactName, Site>,
307    saved: Option<&DeclarationScope>,
308) -> Result<Option<RepoConfig>, ScopeReadError> {
309    let legacy;
310    let scope = match saved {
311        Some(scope) => scope,
312        None => {
313            legacy = DeclarationScope {
314                names: sites.keys().cloned().collect(),
315                files: sites
316                    .values()
317                    .filter_map(|site| crate::platform::path_text(&site.definition).parse().ok())
318                    .collect(),
319            };
320            &legacy
321        }
322    };
323    let config = scope.read(repo, Evals::One(id), &lang::process_environment)?;
324    for (name, site) in sites {
325        check_site(&config, name, site)?;
326    }
327    Ok((!config.evals.is_empty()).then_some(config))
328}
329
330#[cfg(test)]
331mod tests;