1use std::{
9 collections::{BTreeMap, BTreeSet},
10 path::{Path, PathBuf},
11};
12
13use serde_json::Value;
14
15use super::{ConfigError, IGNORE_FILE, convert, discovery, lang};
16
17#[derive(Debug, Default, serde::Serialize)]
18#[serde(rename_all = "camelCase")]
19pub struct Migration {
20 #[serde(serialize_with = "crate::platform::serialize_paths")]
22 pub written: Vec<PathBuf>,
23 #[serde(serialize_with = "crate::platform::serialize_paths")]
25 pub removed: Vec<PathBuf>,
26 pub warnings: Vec<String>,
28}
29
30const SETTINGS: &str = "settings.toml";
31const SKIPPED: [&str; 4] = [".git", "node_modules", "target", discovery::DEFINITION_DIR];
33
34pub fn migrate(repo: &Path) -> Result<Migration, ConfigError> {
36 let root =
37 crate::platform::canonicalize(repo).map_err(|error| ConfigError::new(repo, error))?;
38 let definitions = root.join(discovery::DEFINITION_DIR);
39 let (catalog, plugin_writes) = super::plugins::migrate(&root)?;
40 let mut removed = Vec::new();
41 let profiles = settings(&definitions, &mut removed)?;
42 let mut current = BTreeMap::new();
43 let mut olds = Vec::new();
44 let mut warnings = Vec::new();
45 let has_definitions =
46 crate::platform::paths::reusable_directory(&root, discovery::DEFINITION_DIR)
47 .map_err(|error| ConfigError::new(&definitions, error))?;
48 if has_definitions {
49 for (path, text) in discovery::sources(&root)? {
50 let profiles_file = path
51 .extension()
52 .is_some_and(|extension| extension == lang::PROFILES_EXTENSION);
53 if profiles_file || !lang::looks_like_toml(&text) {
54 current.insert(path, text);
55 continue;
56 }
57 let relative = path.strip_prefix(&definitions).unwrap_or(&path).to_owned();
58 let name = path
59 .file_stem()
60 .and_then(|stem| stem.to_str())
61 .ok_or_else(|| {
62 ConfigError::new(&path, "A definition file is named after its Artifact.")
63 })?
64 .to_owned();
65 let mut table = table(&path, &text, &profiles)?;
66 if let Some(object) = table.as_object_mut() {
67 object.remove("name");
68 }
69 olds.push(convert::Old {
70 file: relative,
71 name,
72 table,
73 comments: comments(&text),
74 });
75 removed.push(path);
76 }
77 }
78 if !has_definitions {
80 olds.extend(in_tree(&root, &profiles, &mut removed, &mut warnings)?);
81 }
82 if olds.is_empty() && plugin_writes.is_empty() && removed.is_empty() {
83 return Ok(Migration::default());
84 }
85 let readers = convert::untyped_readers(&olds);
86 for old in &mut olds {
87 if readers.contains(&old.name)
88 && let Some(table) = old.table.as_object_mut()
89 {
90 table.insert("type".into(), Value::String("files".into()));
91 }
92 }
93 let namespaces: BTreeSet<String> = catalog.keys().map(ToString::to_string).collect();
94 let converted = convert::convert(&olds, &profiles, &namespaces)
95 .map_err(|error| ConfigError::new(&definitions, error))?;
96 warnings.extend(converted.warnings);
97 warnings.push(
98 "Saved results do not carry over: every eval, Agent, runtime and Human alike, runs once more under the new reuse keys."
99 .into(),
100 );
101 let mut sources = current.clone();
102 let mut written = Vec::new();
103 for (file, text) in converted.files {
104 let path = definitions.join(&file);
105 for component in file.components() {
106 crate::platform::paths::portable_component(component.as_os_str())
107 .map_err(|error| ConfigError::new(&path, error))?;
108 }
109 let taken = match (path.parent(), path.file_name()) {
112 (Some(directory), Some(name))
113 if crate::platform::paths::target_exists(directory).unwrap_or(false) =>
114 {
115 crate::platform::paths::conflicting_entry(directory, std::iter::once(name))
116 .map_err(|error| ConfigError::new(directory, error))?
117 .map(|found| directory.join(found))
118 .filter(|found| found != &path || !removed.contains(found))
119 }
120 _ => None,
121 };
122 if current.contains_key(&path) || taken.is_some() {
123 return Err(ConfigError::new(
124 &path,
125 "A file of this name is already in .artifactize/; rename it so the converted definitions can take its name.",
126 ));
127 }
128 sources.insert(path, text);
129 }
130 discovery::read_sources_with(root.clone(), &sources, catalog)?;
131 for (path, text) in plugin_writes.iter().cloned().chain(
132 sources
133 .into_iter()
134 .filter(|(path, _)| !current.contains_key(path)),
135 ) {
136 if let Some(parent) = path.parent() {
137 std::fs::create_dir_all(parent).map_err(|error| ConfigError::new(parent, error))?;
138 }
139 crate::platform::paths::restore_file(&path, text.as_bytes())
140 .map_err(|error| ConfigError::new(&path, error))?;
141 written.push(path);
142 }
143 let kept: BTreeSet<&PathBuf> = written.iter().collect();
144 let mut gone = Vec::new();
145 for path in removed {
146 if kept.contains(&path) {
147 continue;
148 }
149 crate::platform::paths::remove_regular(&path)
150 .map_err(|error| ConfigError::new(&path, error))?;
151 gone.push(path);
152 }
153 let relative = |paths: Vec<PathBuf>| -> Vec<PathBuf> {
154 paths
155 .into_iter()
156 .map(|path| path.strip_prefix(&root).map(Path::to_owned).unwrap_or(path))
157 .collect()
158 };
159 Ok(Migration {
160 written: relative(written),
161 removed: relative(gone),
162 warnings,
163 })
164}
165
166fn settings(
168 definitions: &Path,
169 removed: &mut Vec<PathBuf>,
170) -> Result<BTreeMap<String, Value>, ConfigError> {
171 let path = definitions.join(SETTINGS);
172 if !crate::platform::path_kind(&path).is_ok_and(|kind| kind == crate::platform::FileKind::File)
173 {
174 return Ok(BTreeMap::new());
175 }
176 let text =
177 discovery::read_regular_text(&path).map_err(|error| ConfigError::new(&path, error))?;
178 let table: toml::Table =
179 toml::from_str(&text).map_err(|error| ConfigError::new(&path, error))?;
180 removed.push(path.clone());
181 let Some(profiles) = table.get("profiles") else {
182 return Ok(BTreeMap::new());
183 };
184 let profiles = serde_json::to_value(profiles).expect("TOML is JSON");
185 let Value::Object(profiles) = profiles else {
186 return Err(ConfigError::new(&path, "profiles is a table."));
187 };
188 Ok(profiles
189 .into_iter()
190 .map(|(name, mut profile)| {
191 if let Some(object) = profile.as_object_mut() {
192 object
193 .entry("kind")
194 .or_insert_with(|| Value::String("agent".into()));
195 }
196 (name, profile)
197 })
198 .collect())
199}
200
201fn table(
203 path: &Path,
204 text: &str,
205 profiles: &BTreeMap<String, Value>,
206) -> Result<Value, ConfigError> {
207 let masked = artifactize_tools::artf::mask(text)
208 .map_err(|error| ConfigError::new(path, error.message))?;
209 let parsed: toml::Table =
210 toml::from_str(&masked.toml).map_err(|error| ConfigError::new(path, error))?;
211 let mut value = serde_json::to_value(parsed).expect("TOML is JSON");
212 let mut failure = None;
213 resolve(&mut value, &mut |placeholder| {
214 let index = masked.invocation_index(placeholder)?;
215 let invocation = &masked.invocations()[index];
216 let Some(base) = profiles.get(&invocation.name) else {
217 failure = Some(format!(
218 "Unknown profile alias !{}; it is not in .artifactize/settings.toml.",
219 invocation.name
220 ));
221 return None;
222 };
223 let mut profile = base.clone();
224 if let Some(span) = &invocation.overrides_span {
225 let wrapped = format!("_ = {{{}}}", &text[span.clone()]);
226 match toml::from_str::<toml::Table>(&wrapped) {
227 Ok(mut table) => {
228 let overrides = serde_json::to_value(table.remove("_")).expect("TOML is JSON");
229 if let (Some(profile), Some(overrides)) =
230 (profile.as_object_mut(), overrides.as_object())
231 {
232 profile.extend(overrides.clone());
233 }
234 }
235 Err(error) => {
236 failure = Some(format!("!{}(…): {error}", invocation.name));
237 return None;
238 }
239 }
240 }
241 Some(profile)
242 });
243 match failure {
244 Some(message) => Err(ConfigError::new(path, message)),
245 None => Ok(value),
246 }
247}
248
249fn resolve(value: &mut Value, resolved: &mut impl FnMut(&str) -> Option<Value>) {
251 match value {
252 Value::String(text) => {
253 if let Some(replacement) = resolved(text) {
254 *value = replacement;
255 }
256 }
257 Value::Array(items) => items.iter_mut().for_each(|item| resolve(item, resolved)),
258 Value::Object(fields) => fields
259 .values_mut()
260 .for_each(|field| resolve(field, resolved)),
261 _ => {}
262 }
263}
264
265fn in_tree(
269 root: &Path,
270 profiles: &BTreeMap<String, Value>,
271 removed: &mut Vec<PathBuf>,
272 warnings: &mut Vec<String>,
273) -> Result<Vec<convert::Old>, ConfigError> {
274 let ignored = ignore(root)?;
275 let mut found: Vec<(String, String, bool, Value, Vec<String>)> = Vec::new();
276 let mut pending = vec![(root.to_owned(), PathBuf::new())];
277 while let Some((directory, relative)) = pending.pop() {
278 let opened = crate::platform::open_directory(&directory)
279 .map_err(|error| ConfigError::new(&directory, error))?;
280 let mut entries = Vec::new();
281 for entry in crate::platform::read_dir(&opened)
282 .map_err(|error| ConfigError::new(&directory, error))?
283 {
284 let entry = entry.map_err(|error| ConfigError::new(&directory, error))?;
285 let kind = entry
286 .file_type()
287 .map_err(|error| ConfigError::new(&directory, error))?;
288 entries.push((entry.file_name(), kind));
289 }
290 entries.sort_by(|a, b| a.0.cmp(&b.0));
291 for (name, kind) in entries {
292 let path = directory.join(&name);
293 let Some(text_name) = name.to_str() else {
294 continue;
295 };
296 let logical = if relative.as_os_str().is_empty() {
297 PathBuf::from(text_name)
298 } else {
299 relative.join(text_name)
300 };
301 if ignored
302 .matched(&path, kind == crate::platform::FileKind::Directory)
303 .is_ignore()
304 {
305 continue;
306 }
307 if kind == crate::platform::FileKind::Directory {
308 let separate =
310 crate::platform::paths::reusable_directory(&path, discovery::DEFINITION_DIR)
311 .unwrap_or(false);
312 if !SKIPPED.contains(&text_name) && !separate {
313 pending.push((path, logical));
314 }
315 continue;
316 }
317 if kind != crate::platform::FileKind::File || !text_name.ends_with(".artf") {
318 continue;
319 }
320 let text = discovery::read_regular_text(&path)
321 .map_err(|error| ConfigError::new(&path, error))?;
322 let mut table = table(&path, &text, profiles)?;
323 let name = table
324 .get("name")
325 .and_then(Value::as_str)
326 .ok_or_else(|| {
327 ConfigError::new(&path, "An index.artf names its Artifact with `name`.")
328 })?
329 .to_owned();
330 let folder = crate::platform::path_text(&relative);
331 let (target, whole) = if text_name == ".artf" && relative.as_os_str().is_empty() {
332 (".artifactize/".to_owned(), false)
333 } else if text_name == "index.artf" {
334 let target = if folder.is_empty() {
335 "./".to_owned()
336 } else {
337 format!("{folder}/")
338 };
339 (target, table.get("select").is_none())
340 } else {
341 let file = text_name.strip_suffix(".artf").expect("an .artf file");
342 let target = if folder.is_empty() {
343 file.to_owned()
344 } else {
345 format!("{folder}/{file}")
346 };
347 (target, false)
348 };
349 if let Some(object) = table.as_object_mut() {
350 object.remove("name");
351 object.insert("path".into(), Value::String(target.clone()));
352 if target == "./" && !object.contains_key("fingerprint") {
354 object.insert(
355 "fingerprint".into(),
356 serde_json::json!({"ignore": [".artifactize/"]}),
357 );
358 warnings.push(format!(
359 "{name}: its content ignores .artifactize/, where its definitions are now."
360 ));
361 }
362 }
363 removed.push(path);
364 found.push((name, target, whole, table, comments(&text)));
365 }
366 }
367 let folders: Vec<(String, String)> = found
369 .iter()
370 .filter(|(_, _, whole, _, _)| *whole)
371 .map(|(name, target, _, _, _)| (name.clone(), target.clone()))
372 .collect();
373 let mut parts: BTreeMap<String, Vec<String>> = BTreeMap::new();
374 for (name, target, _, _, _) in &found {
375 if target == ".artifactize/" {
376 continue;
377 }
378 let owner = folders
379 .iter()
380 .filter(|(whole, prefix)| {
381 whole != name
382 && (prefix == "./" || (target.starts_with(prefix.as_str()) && target != prefix))
383 })
384 .max_by_key(|(_, prefix)| if prefix == "./" { 0 } else { prefix.len() });
385 if let Some((owner, _)) = owner {
386 parts.entry(owner.clone()).or_default().push(name.clone());
387 }
388 }
389 Ok(found
390 .into_iter()
391 .map(|(name, _, _, mut table, comments)| {
392 if let Some(added) = parts.get(&name)
393 && let Some(object) = table.as_object_mut()
394 {
395 let list = object
396 .entry("parts")
397 .or_insert_with(|| Value::Array(Vec::new()));
398 if let Some(list) = list.as_array_mut() {
399 for part in added {
400 if !list.iter().any(|value| value.as_str() == Some(part)) {
401 list.push(Value::String(part.clone()));
402 }
403 }
404 }
405 }
406 convert::Old {
407 file: PathBuf::from(format!("{name}.artf")),
408 name,
409 table,
410 comments,
411 }
412 })
413 .collect())
414}
415
416fn comments(text: &str) -> Vec<String> {
419 let mut open: Option<&str> = None;
420 let mut found = Vec::new();
421 for line in text.lines() {
422 if open.is_none()
423 && let Some(comment) = line.trim_start().strip_prefix('#')
424 {
425 found.push(
426 comment
427 .strip_prefix(' ')
428 .unwrap_or(comment)
429 .trim_end()
430 .to_owned(),
431 );
432 continue;
433 }
434 for delimiter in ["\"\"\"", "'''"] {
435 if open.is_none_or(|open| open == delimiter) && line.matches(delimiter).count() % 2 == 1
436 {
437 open = if open.is_some() {
438 None
439 } else {
440 Some(delimiter)
441 };
442 }
443 }
444 }
445 found
446}
447
448fn ignore(root: &Path) -> Result<ignore::gitignore::Gitignore, ConfigError> {
450 let file = root.join(IGNORE_FILE);
451 let mut builder = ignore::gitignore::GitignoreBuilder::new(root);
452 builder
453 .case_insensitive(false)
454 .expect("case-sensitive discovery");
455 if crate::platform::path_kind(&file).is_ok_and(|kind| kind == crate::platform::FileKind::File) {
456 let source =
457 discovery::read_regular_text(&file).map_err(|error| ConfigError::new(&file, error))?;
458 for line in source.lines() {
459 builder
460 .add_line(Some(file.clone()), line)
461 .map_err(|error| ConfigError::new(&file, error))?;
462 }
463 }
464 builder
465 .build()
466 .map_err(|error| ConfigError::new(&file, error))
467}
468
469#[cfg(test)]
470mod tests;