1use std::fmt::Write as _;
20use toml_edit::{DocumentMut, Item, Table, Value};
21
22use crate::error::RkError;
23
24const CLASS_MARKERS: [&str; 3] = ["# P:", "# N:", "# F:"];
29
30fn templated(decor: Option<&str>) -> bool {
32 decor.is_some_and(|text| {
33 let trimmed = text.trim_start();
34 CLASS_MARKERS
35 .iter()
36 .any(|marker| trimmed.starts_with(marker))
37 })
38}
39
40pub(crate) fn template_comment(path: &[&str]) -> Option<String> {
47 let text = crate::embedded::BLOCKS
48 .get_file("target-config.toml.in")
49 .and_then(include_dir::File::contents_utf8)?;
50 let (key, table) = path.split_last()?;
51 let wanted = table.join(".");
52 let mut current = String::new();
53 for line in text.lines() {
54 let trimmed = line.trim();
55 if let Some(name) = trimmed
56 .strip_prefix('[')
57 .and_then(|rest| rest.strip_suffix(']'))
58 {
59 name.clone_into(&mut current);
60 continue;
61 }
62 let Some((name, rest)) = trimmed.split_once(" = ") else {
63 continue;
64 };
65 if name != *key || current != wanted {
66 continue;
67 }
68 let comment = rest.find(" # ").map(|at| rest[at + 1..].to_owned());
69 return comment.map(|comment| format!(" {comment}"));
70 }
71 None
72}
73
74fn refresh_comment(document: &mut DocumentMut, path: &[&str], add_missing: bool) -> bool {
83 let Some(comment) = template_comment(path) else {
84 return false;
85 };
86 let mut item = document.as_item_mut();
87 for segment in path {
88 if item.get(segment).is_none() {
89 return false;
90 }
91 item = &mut item[segment];
92 }
93 let Some(value) = item.as_value_mut() else {
94 return false;
95 };
96 let current = value.decor().suffix().and_then(|raw| raw.as_str());
97 if current == Some(comment.as_str()) {
98 return false;
99 }
100 if (current.is_none() && add_missing) || templated(current) {
101 value.decor_mut().set_suffix(comment);
102 return true;
103 }
104 false
105}
106
107pub(crate) fn refresh_comments(document: &mut DocumentMut) -> bool {
119 let mut changed = false;
120 for path in value_paths(document.as_table(), &[]) {
121 let borrowed: Vec<&str> = path.iter().map(String::as_str).collect();
122 changed |= refresh_comment(document, &borrowed, false);
123 }
124 changed
125}
126
127fn value_paths(table: &Table, prefix: &[String]) -> Vec<Vec<String>> {
129 let mut paths = Vec::new();
130 for (key, item) in table {
131 let mut path = prefix.to_vec();
132 path.push(key.to_owned());
133 match item {
134 Item::Table(inner) => paths.extend(value_paths(inner, &path)),
135 Item::Value(_) => paths.push(path),
136 _ => {}
137 }
138 }
139 paths
140}
141
142fn move_key(from: &mut Table, key: &str, to: &mut Table, name: &str) -> Option<Value> {
145 let carried = crate::config::key_comments(from, key);
150 let item = from.remove(key)?;
151 let value = item.into_value().ok()?;
152 to.insert(name, Item::Value(value.clone()));
153 if let Some(carried) = carried {
154 crate::config::set_key_comments(to, name, &carried);
155 }
156 Some(value)
157}
158
159fn dropped_or_kept(table: &mut Table, key: &str) -> (Option<Value>, Option<String>) {
168 let carried = crate::config::key_comments(table, key);
169 let empty_answer = table.get(key).and_then(Item::as_value).is_some_and(empty);
170 if empty_answer {
171 crate::config::take_comments(table, key);
172 return (None, None);
173 }
174 let value = table.remove(key).and_then(|item| item.into_value().ok());
175 (value, carried)
176}
177
178const LANDING_KEYS: [&str; 5] = ["workflow", "style", "nix", "scorecard", "code_scanning"];
180
181fn empty(value: &Value) -> bool {
183 value.as_str().is_some_and(str::is_empty)
184}
185
186#[allow(
193 clippy::too_many_lines,
194 reason = "one pass moves every schema 1 key into the domain that owns it, and splitting it would separate a move from the decor it carries"
195)]
196pub fn to_schema_2(text: &str) -> Result<String, RkError> {
197 let mut document = text
198 .parse::<DocumentMut>()
199 .map_err(|error| super::invalid(error.to_string()))?;
200 if document.get("schema_version").and_then(Item::as_integer) != Some(1) {
201 return Ok(text.to_owned());
202 }
203 for name in ["profile", "git", "capabilities"] {
209 if document.get(name).is_some() {
210 return Err(super::invalid(format!(
211 "[{name}] is a schema 2 table and this file states schema_version = 1; set schema_version = 2, or remove the table"
212 )));
213 }
214 }
215 for name in ["project", "landing", "setup"] {
216 if document
217 .get(name)
218 .is_some_and(|item| item.as_table().is_none())
219 {
220 return Err(super::invalid(format!(
221 "{name} must be a table in a schema 1 file"
222 )));
223 }
224 }
225 document["schema_version"] = toml_edit::value(2);
226 if let Some(item) = document.get_mut("schema_version")
227 && let Some(value) = item.as_value_mut()
228 {
229 let old = text
231 .parse::<DocumentMut>()
232 .ok()
233 .and_then(|old| old.get("schema_version").and_then(Item::as_value).cloned());
234 if let Some(old) = old {
235 *value.decor_mut() = old.decor().clone();
236 }
237 }
238
239 let mut project = document
240 .remove("project")
241 .and_then(|item| item.into_table().ok())
242 .unwrap_or_default();
243 let mut landing = document
244 .remove("landing")
245 .and_then(|item| item.into_table().ok())
246 .unwrap_or_default();
247
248 let mut profile = Table::new();
252 let (tech, tech_comments) = dropped_or_kept(&mut project, "tech");
253 if let Some(tech) = tech {
254 let mut list = toml_edit::Array::new();
255 list.push(tech.as_str().unwrap_or_default());
256 let mut value = Value::Array(list);
257 *value.decor_mut() = tech.decor().clone();
258 profile.insert("technologies", Item::Value(value));
259 if let Some(carried) = &tech_comments {
260 crate::config::set_key_comments(&mut profile, "technologies", carried);
261 }
262 let mut release = Table::new();
263 release.insert("mode", toml_edit::value("automatic"));
264 release.insert(
265 "driver",
266 toml_edit::value(tech.as_str().unwrap_or_default()),
267 );
268 move_key(&mut landing, "style", &mut release, "style");
269 let mut setup_table = document
270 .remove("setup")
271 .and_then(|item| item.into_table().ok())
272 .unwrap_or_default();
273 move_key(&mut setup_table, "line_prefix", &mut release, "line_prefix");
274 document.insert("setup", Item::Table(setup_table));
275 profile.insert("release", Item::Table(release));
276 } else {
277 if let Some(setup) = document.get_mut("setup").and_then(Item::as_table_mut) {
282 crate::config::take_comments(setup, "line_prefix");
283 }
284 crate::config::take_comments(&mut landing, "style");
285 }
286 let (forge, forge_comments) = dropped_or_kept(&mut project, "forge");
287 if let Some(forge) = forge {
288 profile.insert("forge", Item::Value(forge));
289 if let Some(carried) = &forge_comments {
290 crate::config::set_key_comments(&mut profile, "forge", carried);
291 }
292 }
293
294 let mut git = Table::new();
296 move_key(&mut project, "trunk", &mut git, "trunk");
297 let mode_comments = crate::config::key_comments(&landing, "workflow");
301 if let Some(mode) = landing
302 .remove("workflow")
303 .and_then(|item| item.into_value().ok())
304 {
305 let renamed = match mode.as_str() {
306 Some("worktree") => Some("linked-worktree"),
307 Some("branches") => Some("main-worktree"),
308 _ => None,
309 };
310 let mut value = renamed.map_or_else(|| mode.clone(), Value::from);
311 *value.decor_mut() = mode.decor().clone();
312 git.insert("checkout_mode", Item::Value(value));
313 if let Some(carried) = &mode_comments {
314 crate::config::set_key_comments(&mut git, "checkout_mode", carried);
315 }
316 }
317
318 let mut capabilities = Table::new();
321 move_key(&mut landing, "nix", &mut capabilities, "nix_packaging");
322 capabilities.insert("reporting_policy", toml_edit::value(true));
323 move_key(&mut landing, "scorecard", &mut capabilities, "scorecard");
324 move_key(
325 &mut landing,
326 "code_scanning",
327 &mut capabilities,
328 "code_scanning",
329 );
330
331 if let Some(unknown) = landing.iter().map(|(key, _)| key).next() {
338 let mut message = format!("landing.{unknown} is not a key this migration knows");
339 if let Some(nearest) = crate::config::nearest_known(unknown, &LANDING_KEYS) {
340 let _ = write!(message, "; nearest known key: landing.{nearest}");
341 }
342 return Err(super::invalid(message));
343 }
344 let orphaned = crate::config::take_header_comments(&mut landing);
347
348 let mut rest: Vec<(String, Item)> = Vec::new();
352 for name in ["security", "setup", "protection"] {
353 if let Some(item) = document.remove(name) {
354 rest.push((name.to_owned(), item));
355 }
356 }
357 document.insert("project", Item::Table(project));
358 for (name, table) in [
359 ("profile", profile),
360 ("git", git),
361 ("capabilities", capabilities),
362 ] {
363 let mut table = table;
364 table.set_implicit(table.is_empty());
365 if name == "profile"
366 && let Some(release) = table.get_mut("release").and_then(Item::as_table_mut)
367 {
368 release.set_implicit(release.is_empty());
369 }
370 document.insert(name, Item::Table(table));
371 }
372 for (name, item) in rest {
373 document.insert(&name, item);
374 }
375 for path in value_paths(document.as_table(), &[]) {
380 let borrowed: Vec<&str> = path.iter().map(String::as_str).collect();
381 refresh_comment(&mut document, &borrowed, true);
382 }
383 crate::config::prune_empty_tables(&mut document, &["project"]);
389 if let Some(orphaned) = orphaned {
390 crate::config::place_carried(&mut document, &orphaned);
391 }
392 Ok(document.to_string())
393}
394
395#[cfg(test)]
396mod tests {
397 use super::to_schema_2;
398
399 #[test]
402 fn a_schema_1_text_migrates_with_its_comments() {
403 let old = "# heading\nschema_version = 1 # the schema\n\n[project]\nrepo = \"acme/widget\" # operator note\nforge = \"github\" # P: forge\ntech = \"rust\" # P: binding\ntrunk = \"main\" # N: trunk\n\n[landing]\nworkflow = \"worktree\" # P: mode\nstyle = \"lines\" # P: style\nnix = true # P: nix\nscorecard = false\ncode_scanning = \"semgrep\"\n\n[security]\ncontact = \"team\" # keep\n\n[setup]\nrequired_check = \"gate\"\nline_prefix = \"stable/\" # P: prefix\n";
404 let migrated = to_schema_2(old).expect("migrates");
405 let doc: toml::Table = migrated.parse().expect("the result parses");
406 assert_eq!(doc["schema_version"].as_integer(), Some(2));
407 assert!(migrated.contains("schema_version = 2 # the schema"));
408 assert_eq!(doc["project"]["repo"].as_str(), Some("acme/widget"));
409 assert!(doc["project"].get("tech").is_none());
410 assert_eq!(
411 doc["profile"]["technologies"].as_array().map(Vec::len),
412 Some(1)
413 );
414 assert_eq!(doc["profile"]["forge"].as_str(), Some("github"));
415 assert_eq!(
416 doc["profile"]["release"]["mode"].as_str(),
417 Some("automatic")
418 );
419 assert_eq!(doc["profile"]["release"]["driver"].as_str(), Some("rust"));
420 assert_eq!(doc["profile"]["release"]["style"].as_str(), Some("lines"));
421 assert!(
422 migrated.contains("style = \"lines\" # P: trunk or lines; automatic alone"),
423 "the template's own comment states what the key means now: {migrated}"
424 );
425 assert_eq!(
426 doc["profile"]["release"]["line_prefix"].as_str(),
427 Some("stable/")
428 );
429 assert!(migrated.contains("line_prefix = \"stable/\" # P: release-line branch prefix"));
430 assert_eq!(doc["git"]["trunk"].as_str(), Some("main"));
431 assert_eq!(
432 doc["git"]["checkout_mode"].as_str(),
433 Some("linked-worktree")
434 );
435 assert!(
436 migrated.contains(
437 "checkout_mode = \"linked-worktree\" # P: linked-worktree or main-worktree"
438 ),
439 "a renamed vocabulary takes the template's own sentence: {migrated}"
440 );
441 assert!(
442 migrated.contains("repo = \"acme/widget\" # operator note"),
443 "a comment the operator wrote travels with its value: {migrated}"
444 );
445 assert_eq!(doc["capabilities"]["nix_packaging"].as_bool(), Some(true));
446 assert_eq!(
447 doc["capabilities"]["reporting_policy"].as_bool(),
448 Some(true)
449 );
450 assert_eq!(doc["capabilities"]["scorecard"].as_bool(), Some(false));
451 assert_eq!(
452 doc["capabilities"]["code_scanning"].as_str(),
453 Some("semgrep")
454 );
455 assert!(doc.get("landing").is_none());
456 assert!(doc["setup"].get("line_prefix").is_none());
457 assert_eq!(doc["setup"]["required_check"].as_str(), Some("gate"));
458 assert!(migrated.contains("contact = \"team\" # keep"));
459 assert!(migrated.starts_with("# heading\n"));
460 assert_eq!(to_schema_2(&migrated).expect("passes"), migrated);
462 }
463
464 #[test]
467 fn an_empty_detect_answer_becomes_an_absent_key() {
468 let migrated = to_schema_2(
469 "schema_version = 1\n[project]\nforge = \"\"\ntech = \"\"\n[landing]\nworkflow = \"branches\"\n",
470 )
471 .expect("migrates");
472 let doc: toml::Table = migrated.parse().expect("parses");
473 assert!(doc.get("profile").is_none_or(|p| p.get("forge").is_none()));
474 assert!(
475 doc.get("profile")
476 .is_none_or(|p| p.get("technologies").is_none())
477 );
478 assert_eq!(doc["git"]["checkout_mode"].as_str(), Some("main-worktree"));
479 assert!(
480 !migrated.contains("[project]"),
481 "a table every one of whose keys dropped goes with them: {migrated}"
482 );
483 }
484
485 #[test]
489 fn an_emptied_project_header_goes_and_its_comment_stays() {
490 let migrated = to_schema_2(
491 "schema_version = 1\n\n# the operator's note\n[project]\nforge = \"\"\ntech = \"\"\n\n[security]\ncontact = \"team\"\n",
492 )
493 .expect("migrates");
494 assert!(
495 !migrated.contains("[project]"),
496 "a table every one of whose keys dropped goes with them: {migrated}"
497 );
498 assert!(
499 migrated.contains("# the operator's note"),
500 "the comment the header carried survives: {migrated}"
501 );
502 crate::config::parse(&migrated).expect("the strict schema 2 reader accepts it");
503 }
504
505 #[test]
512 fn an_empty_technology_still_clears_the_automatic_release_keys() {
513 let migrated = to_schema_2(
514 "schema_version = 1\n[project]\ntech = \"\"\nforge = \"github\"\nrepo = \"acme/widget\"\n[landing]\nstyle = \"lines\"\n[setup]\nline_prefix = \"stable/\"\nrequired_check = \"gate\"\n",
515 )
516 .expect("migrates");
517 let doc: toml::Table = migrated.parse().expect("parses");
518 assert!(
519 doc["setup"].get("line_prefix").is_none(),
520 "the prefix belongs to an automatic release: {migrated}"
521 );
522 assert!(
523 doc.get("profile")
524 .is_none_or(|profile| profile.get("release").is_none()),
525 "no technology means no release intent: {migrated}"
526 );
527 assert!(doc.get("landing").is_none(), "{migrated}");
528 assert_eq!(doc["setup"]["required_check"].as_str(), Some("gate"));
529 crate::config::parse(&migrated).expect("the strict schema 2 reader accepts it");
530 }
531
532 #[test]
537 fn a_dropped_schema_1_key_keeps_the_operators_comment() {
538 let migrated = to_schema_2(concat!(
539 "schema_version = 1\n\n[project]\nrepo = \"acme/widget\"\n",
540 "# this project has no forge yet\n",
541 "forge = \"\" # P: forge\n",
542 "# and no binding release-kit knows\n",
543 "tech = \"\" # P: binding\n\n",
544 "[landing]\n# the style we used to ask for\nstyle = \"lines\"\n\n",
545 "[setup]\nrequired_check = \"gate\"\n",
546 "# the prefix we used to ask for\nline_prefix = \"stable/\"\n"
547 ))
548 .expect("migrates");
549 for note in [
550 "# this project has no forge yet",
551 "# and no binding release-kit knows",
552 "# the style we used to ask for",
553 "# the prefix we used to ask for",
554 ] {
555 assert!(
556 migrated.contains(note),
557 "authored text survives the migration: {note}: {migrated}"
558 );
559 }
560 assert!(!migrated.contains("forge ="), "{migrated}");
561 assert!(!migrated.contains("tech ="), "{migrated}");
562 assert!(!migrated.contains("style ="), "{migrated}");
563 assert!(!migrated.contains("line_prefix ="), "{migrated}");
564 crate::config::parse(&migrated).expect("the strict schema 2 reader accepts it");
565 }
566
567 #[test]
571 fn a_moved_key_takes_the_comment_above_it() {
572 let migrated = to_schema_2(concat!(
573 "schema_version = 1\n\n[project]\nrepo = \"acme/widget\"\n",
574 "# the one binding this project releases from\ntech = \"rust\"\n",
575 "forge = \"github\"\n",
576 "# why this branch is fixed\ntrunk = \"main\"\n\n",
577 "[landing]\n# why this project takes lines\nstyle = \"lines\"\n",
578 "# why topics use the main checkout\nworkflow = \"branches\"\n"
579 ))
580 .expect("migrates");
581 for note in [
582 "# the one binding this project releases from",
583 "# why this branch is fixed",
584 "# why this project takes lines",
585 "# why topics use the main checkout",
586 ] {
587 assert!(migrated.contains(note), "{note}: {migrated}");
588 }
589 let doc: toml::Table = migrated.parse().expect("parses");
590 assert_eq!(doc["git"]["trunk"].as_str(), Some("main"));
591 assert_eq!(doc["profile"]["release"]["style"].as_str(), Some("lines"));
592 assert_eq!(doc["git"]["checkout_mode"].as_str(), Some("main-worktree"));
593 crate::config::parse(&migrated).expect("the strict schema 2 reader accepts it");
594 }
595
596 #[test]
601 fn an_unknown_schema_1_landing_key_refuses_by_name() {
602 let refusal = to_schema_2("schema_version = 1\n[landing]\nworkflo = \"branches\"\n")
603 .expect_err("an unknown key refuses")
604 .to_string();
605 assert!(refusal.contains("workflo"), "{refusal}");
606 assert!(
607 refusal.contains("nearest known key: landing.workflow"),
608 "{refusal}"
609 );
610 }
611
612 #[test]
617 fn a_schema_1_file_with_a_schema_2_shape_refuses() {
618 for (text, named) in [
619 (
620 "schema_version = 1\n[profile]\nforg = \"github\"\n",
621 "[profile]",
622 ),
623 ("schema_version = 1\n[git]\ntrunk = \"main\"\n", "[git]"),
624 (
625 "schema_version = 1\n[capabilities]\nscorecard = true\n",
626 "[capabilities]",
627 ),
628 ("schema_version = 1\nproject = \"acme/widget\"\n", "project"),
629 ("schema_version = 1\nlanding = 3\n", "landing"),
630 (
631 "schema_version = 1\nsetup = \"operator value\"\n[project]\ntech = \"rust\"\n",
632 "setup",
633 ),
634 ] {
635 let refusal = to_schema_2(text)
636 .expect_err("a shape schema 1 never had refuses")
637 .to_string();
638 assert!(refusal.contains(named), "{named}: {refusal}");
639 }
640 }
641}