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    let settings = super::settings::read(&root)?;
49    discovery::sources(&root)?
50        .into_iter()
51        .map(|(file, source)| {
52            let name = discovery::definition_name(
53                file.file_stem()
54                    .and_then(crate::platform::os_text)
55                    .unwrap_or_default(),
56            )
57            .map_err(|error| ConfigError::new(&file, error))?;
58            let parsed = discovery::parse_definition(
59                &name,
60                &source,
61                &settings,
62                &mut schemas::Schemas::default(),
63            )
64            .map_err(|error| ConfigError::new(&file, error))?;
65            let path = parsed
66                .path
67                .with_kind(parsed.kind, parsed.declaration.select.unwrap_or_default())
68                .map_err(|error| ConfigError::new(&file, error))?;
69            Ok((
70                name,
71                Site {
72                    path,
73                    definition: file.strip_prefix(&root).unwrap().to_owned(),
74                },
75            ))
76        })
77        .collect()
78}
79#[derive(Debug, Error)]
80pub enum ScopeReadError {
81    #[error("{name} is no longer declared at {}.", crate::platform::path_text(.path))]
82    Moved { name: ArtifactName, path: PathBuf },
83    #[error(transparent)]
84    Config(#[from] ConfigError),
85}
86fn read_declared(
87    repo: &Path,
88    name: &ArtifactName,
89    site: &Site,
90) -> Result<RepoConfig, ScopeReadError> {
91    let root =
92        crate::platform::canonicalize(repo).map_err(|error| ConfigError::new(repo, error))?;
93    let all = discovery::files(&root)?;
94    let by_name = all
95        .iter()
96        .map(|(file, _)| file)
97        .filter_map(|file| {
98            file.file_stem()
99                .and_then(crate::platform::os_text)
100                .map(|name| (name.to_owned(), file))
101        })
102        .collect::<BTreeMap<_, _>>();
103    let expected = root.join(site.declaration_path());
104    if by_name
105        .get(name.as_str())
106        .is_none_or(|file| **file != expected)
107    {
108        return Err(ScopeReadError::Moved {
109            name: name.clone(),
110            path: site.declaration_path(),
111        });
112    }
113    let settings = super::settings::read(&root)?;
114    let mut selected = BTreeMap::new();
115    let mut pending = vec![name.clone()];
116    while let Some(next) = pending.pop() {
117        let file = if next == *name {
118            root.join(site.declaration_path())
119        } else {
120            by_name
121                .get(next.as_str())
122                .map(|file| (*file).clone())
123                .ok_or_else(|| ConfigError::new(&root, format!("Unknown Artifact {next}.")))?
124        };
125        if selected.contains_key(&file) {
126            continue;
127        }
128        let source = read_regular_text(&file).map_err(|error| {
129            if error.kind() == std::io::ErrorKind::NotFound {
130                ScopeReadError::Moved {
131                    name: next.clone(),
132                    path: site.declaration_path(),
133                }
134            } else {
135                ScopeReadError::Config(ConfigError::new(&file, error))
136            }
137        })?;
138        let parsed = discovery::parse_definition(
139            &next,
140            &source,
141            &settings,
142            &mut schemas::Schemas::default(),
143        )
144        .map_err(|error| ConfigError::new(&file, error))?;
145        pending.extend(parsed.declaration.parts.into_iter().flatten());
146        selected.insert(file, source);
147    }
148    let mut config = discovery::read_sources_unresolved(root, &selected)?;
149    discovery::inspect_targets(&mut config);
150    if !config
151        .artifacts
152        .get(name)
153        .is_some_and(|artifact| artifact.site() == *site)
154    {
155        return Err(ScopeReadError::Moved {
156            name: name.clone(),
157            path: site.declaration_path(),
158        });
159    }
160    Ok(config)
161}
162pub(crate) fn read_artifact_scope(
163    repo: &Path,
164    name: &ArtifactName,
165    site: &Site,
166) -> Result<RepoConfig, ScopeReadError> {
167    let mut config = read_declared(repo, name, site)?;
168    config.evals.clear();
169    Ok(config)
170}
171pub(crate) fn read_eval_scope(
172    repo: &Path,
173    id: &EvalId,
174    sites: &BTreeMap<ArtifactName, Site>,
175) -> Result<Option<RepoConfig>, ScopeReadError> {
176    let mut combined: Option<RepoConfig> = None;
177    for (name, site) in sites {
178        let mut read = read_declared(repo, name, site)?;
179        read.evals.retain(|eval| &eval.id == id);
180        if let Some(config) = &mut combined {
181            config.artifacts.extend(read.artifacts);
182            if config.evals.is_empty() {
183                config.evals = read.evals;
184            }
185        } else {
186            combined = Some(read);
187        }
188    }
189    let Some(mut config) = combined else {
190        return Ok(None);
191    };
192    if crate::scope::resolve_config(&mut config)
193        .and_then(|()| crate::scope::validate_eval_tools(&config))
194        .is_err()
195    {
196        return Ok(None);
197    }
198    Ok(Some(config))
199}