Skip to main content

artifactize_core/config/
site.rs

1//! Target and definition locations are independent; moving a definition changes no meaning.
2use super::*;
3
4#[derive(Debug, Clone, PartialEq, Eq)]
5pub struct Site {
6    pub path: Target,
7    pub definition: PathBuf,
8}
9impl Site {
10    /// Base of relative commands and inputs, not the definition's containing folder.
11    pub fn folder(&self) -> &Path {
12        folder_of(self.path.kind(), &self.path)
13    }
14    pub fn declaration_path(&self) -> PathBuf {
15        self.definition.clone()
16    }
17}
18pub(super) fn folder_of(kind: ArtifactKind, path: &Target) -> &Path {
19    match kind {
20        ArtifactKind::Folder | ArtifactKind::Aspect | ArtifactKind::Graph => {
21            path.local().expect("filesystem kind")
22        }
23        ArtifactKind::File => path
24            .local()
25            .expect("filesystem kind")
26            .parent()
27            .unwrap_or(Path::new("")),
28        ArtifactKind::Live => Path::new(""),
29    }
30}
31/// Old locations are used only while migrating and when reading pre-migration saved Runs.
32pub(super) fn declaration_of(kind: ArtifactKind, target: &Target) -> PathBuf {
33    let path = target.local().unwrap_or(Path::new(""));
34    match kind {
35        ArtifactKind::Live => PathBuf::new(),
36        ArtifactKind::Graph => PathBuf::from(".artf"),
37        ArtifactKind::Folder => logical_join(path, std::ffi::OsStr::new(CONFIG_FILE)),
38        ArtifactKind::File | ArtifactKind::Aspect => {
39            let mut path = path.as_os_str().to_owned();
40            path.push(".artf");
41            PathBuf::from(path)
42        }
43    }
44}
45pub fn read_sites(repo: &Path) -> Result<BTreeMap<ArtifactName, Site>, ConfigError> {
46    let root =
47        crate::platform::canonicalize(repo).map_err(|error| ConfigError::new(repo, error))?;
48    discovery::sources(&root)?
49        .into_iter()
50        .map(|(file, source)| {
51            let name = discovery::definition_name(
52                file.file_stem()
53                    .and_then(|name| name.to_str())
54                    .unwrap_or_default(),
55            )
56            .map_err(|error| ConfigError::new(&file, error))?;
57            let parsed =
58                discovery::parse_definition(&name, &source, &mut schemas::Schemas::default())
59                    .map_err(|error| ConfigError::new(&file, error))?;
60            let path = parsed
61                .path
62                .with_kind(parsed.kind, parsed.declaration.select.unwrap_or_default())
63                .map_err(|error| ConfigError::new(&file, error))?;
64            Ok((
65                name,
66                Site {
67                    path,
68                    definition: file.strip_prefix(&root).unwrap().to_owned(),
69                },
70            ))
71        })
72        .collect()
73}
74#[derive(Debug, Error)]
75pub enum ScopeReadError {
76    #[error("{name} is no longer declared at {}.", crate::platform::path_text(.path))]
77    Moved { name: ArtifactName, path: PathBuf },
78    #[error(transparent)]
79    Config(#[from] ConfigError),
80}
81fn read_declared(
82    repo: &Path,
83    name: &ArtifactName,
84    site: &Site,
85) -> Result<RepoConfig, ScopeReadError> {
86    let root =
87        crate::platform::canonicalize(repo).map_err(|error| ConfigError::new(repo, error))?;
88    let all = discovery::files(&root)?;
89    let by_name = all
90        .iter()
91        .map(|(file, _)| file)
92        .filter_map(|file| {
93            file.file_stem()
94                .and_then(|name| name.to_str())
95                .map(|name| (name.to_owned(), file))
96        })
97        .collect::<BTreeMap<_, _>>();
98    let mut selected = BTreeMap::new();
99    let mut pending = vec![name.clone()];
100    while let Some(next) = pending.pop() {
101        let file = if next == *name {
102            root.join(site.declaration_path())
103        } else {
104            by_name
105                .get(next.as_str())
106                .map(|file| (*file).clone())
107                .ok_or_else(|| ConfigError::new(&root, format!("Unknown Artifact {next}.")))?
108        };
109        if selected.contains_key(&file) {
110            continue;
111        }
112        let source = read_regular_text(&file).map_err(|error| {
113            if error.kind() == std::io::ErrorKind::NotFound {
114                ScopeReadError::Moved {
115                    name: next.clone(),
116                    path: site.declaration_path(),
117                }
118            } else {
119                ScopeReadError::Config(ConfigError::new(&file, error))
120            }
121        })?;
122        let parsed = discovery::parse_definition(&next, &source, &mut schemas::Schemas::default())
123            .map_err(|error| ConfigError::new(&file, error))?;
124        pending.extend(parsed.declaration.parts.into_iter().flatten());
125        selected.insert(file, source);
126    }
127    let mut config = discovery::read_sources_unresolved(root, &selected)?;
128    discovery::inspect_targets(&mut config);
129    if !config
130        .artifacts
131        .get(name)
132        .is_some_and(|artifact| artifact.site() == *site)
133    {
134        return Err(ScopeReadError::Moved {
135            name: name.clone(),
136            path: site.declaration_path(),
137        });
138    }
139    Ok(config)
140}
141pub(crate) fn read_artifact_scope(
142    repo: &Path,
143    name: &ArtifactName,
144    site: &Site,
145) -> Result<RepoConfig, ScopeReadError> {
146    let mut config = read_declared(repo, name, site)?;
147    config.evals.clear();
148    Ok(config)
149}
150pub(crate) fn read_eval_scope(
151    repo: &Path,
152    id: &EvalId,
153    sites: &BTreeMap<ArtifactName, Site>,
154) -> Result<Option<RepoConfig>, ScopeReadError> {
155    let mut combined: Option<RepoConfig> = None;
156    for (name, site) in sites {
157        let mut read = read_declared(repo, name, site)?;
158        read.evals.retain(|eval| &eval.id == id);
159        if let Some(config) = &mut combined {
160            config.artifacts.extend(read.artifacts);
161            if config.evals.is_empty() {
162                config.evals = read.evals;
163            }
164        } else {
165            combined = Some(read);
166        }
167    }
168    let Some(mut config) = combined else {
169        return Ok(None);
170    };
171    if crate::scope::resolve_config(&mut config).is_err() {
172        return Ok(None);
173    }
174    Ok(Some(config))
175}