Skip to main content

release_kit/config/
migrate.rs

1//! The one bounded migration of a schema 1 configuration into the schema
2//! 2 domains, over the authored text, so every comment survives.
3//!
4//! Schema 1 kept the technology, the forge, and the trunk under
5//! `[project]`, the checkout mode, the style, and every opt-in under
6//! `[landing]`, and the line prefix under `[setup]`. Schema 2 states each
7//! under the domain that owns it. The migration moves each value with the
8//! decor it carried, so a comment the operator wrote travels with its
9//! line, renames the two checkout-mode values, and states the reporting
10//! policy the older landing carried implicitly.
11//!
12//! A comment the template itself wrote is refreshed rather than carried:
13//! a key whose vocabulary moved would otherwise stand beside a sentence
14//! describing the key it replaced. The template's own comments are the
15//! ones marked `# P:`, `# N:`, and `# F:`, and only those are replaced.
16//!
17//! SATISFIES project-profile:a-schema-one-configuration-migrates-in-place
18
19use std::fmt::Write as _;
20use toml_edit::{DocumentMut, Item, Table, Value};
21
22use crate::error::RkError;
23
24/// The three class markers the authored template opens its comments with.
25/// A trailing comment beginning with one of these is the template's own,
26/// so a migration refreshes it; anything else is the operator's and
27/// travels with its value.
28const CLASS_MARKERS: [&str; 3] = ["# P:", "# N:", "# F:"];
29
30/// Whether a trailing comment is the template's own.
31fn 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
40/// The authored template's trailing comment for one schema 2 key path,
41/// where the template carries one.
42///
43/// The template is a TOML skeleton whose values are substitution tokens,
44/// so it is read line by line rather than parsed: a `[table]` header
45/// names the path above each `key = TOKEN # comment` line below it.
46pub(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
74/// Give the value at `path` the template's own comment, where the comment
75/// it carries is the template's rather than the operator's, answering
76/// whether the text changed.
77///
78/// `add_missing` decides what a value carrying no comment at all takes. A
79/// migration gives it the template's, because the key it describes is new
80/// to that value. An ordinary rewrite does not, because a comment the
81/// operator deleted is a comment the operator deleted.
82fn 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
107/// Give every value in `document` the template's own comment, answering
108/// whether any changed.
109///
110/// A target keeps its configuration across upgrades while this binary
111/// keeps rewriting the values in it, so a comment left alone outlives the
112/// text it explains. A target that moves to local integration reads
113/// `# F: invariant, contains all four rules` beside two of them, which is
114/// the binary stating something false about its own file.
115///
116/// Only the template's own comments, marked by [`CLASS_MARKERS`]. The
117/// operator's carry no marker and are never touched.
118pub(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
127/// Every path to a value under `table`, each carrying `prefix` ahead of it.
128fn 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
142/// Move `key` out of `from` into `to` under `name`, decor and all, where
143/// `from` carries it.
144fn move_key(from: &mut Table, key: &str, to: &mut Table, name: &str) -> Option<Value> {
145    // The comment standing above the key is read before the move: the
146    // parser holds it on the source key, which the move discards, and
147    // `project-profile:a-schema-one-configuration-migrates-in-place` asks
148    // for every free-standing comment to survive.
149    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
159/// The key's value where schema 1 stated one, `None` where it stated the
160/// empty "detect" answer.
161///
162/// A dropped detect answer may still carry a comment the operator wrote,
163/// and `project-profile:a-schema-one-configuration-migrates-in-place` asks
164/// for every free-standing comment to survive the migration. The comment
165/// moves onto the table's header, which carries it further if the table
166/// itself empties.
167fn 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
178/// Every key schema 1's `[landing]` table could carry.
179const LANDING_KEYS: [&str; 5] = ["workflow", "style", "nix", "scorecard", "code_scanning"];
180
181/// Whether a value is the empty string, which schema 1 used for "detect".
182fn empty(value: &Value) -> bool {
183    value.as_str().is_some_and(str::is_empty)
184}
185
186/// A schema 1 configuration's text as schema 2, or the text unchanged
187/// where it already states schema 2.
188///
189/// # Errors
190///
191/// Returns the reader's refusal for text that does not parse as TOML.
192#[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    // A file stating schema 1 must have a schema 1 shape. The strict
204    // reader never sees this text, so a table schema 1 did not have, or a
205    // legacy container that is not a table, has to refuse here: writing
206    // the generated table over it would replace the operator's content
207    // with a valid file and report success.
208    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        // The schema line keeps whatever decor the authored one carried.
230        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    // `[profile]`: the one technology becomes the sole entry of the list,
249    // and the forge moves as it is. An empty value meant "detect" and
250    // becomes an absent key.
251    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        // No technology, whether the key is absent or the schema 1 detect
278        // value: the setup table still loses its prefix key and the style
279        // key goes, because neither belongs to a profile with no automatic
280        // release.
281        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    // `[git]`: the trunk, and the checkout mode with its values renamed.
295    let mut git = Table::new();
296    move_key(&mut project, "trunk", &mut git, "trunk");
297    // The checkout mode renames its key and its vocabulary at once, so it
298    // cannot go through `move_key`; it reads the source key's comments the
299    // same way, because a rename is still a move to the operator.
300    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    // `[capabilities]`: the opt-ins, and the reporting policy the older
319    // landing carried without a key.
320    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    // The `[landing]` table has no schema 2 successor, so it is discarded
332    // with whatever is left in it. A key still standing in it is one this
333    // migration does not know, and silently dropping it would take the
334    // unknown-key policy off the schema 1 path: the strict reader never
335    // sees the original text, so this is where `target-config:an-unknown-key-refuses`
336    // has to hold.
337    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    // A comment still standing on its header, including one carried off a
345    // key this migration dropped, outlives it.
346    let orphaned = crate::config::take_header_comments(&mut landing);
347
348    // Reassemble in the schema 2 order: the project table keeps its
349    // remaining keys and its decor, the new tables follow it, and the
350    // tables schema 2 keeps stand after them in their authored order.
351    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    // Every key the migration writes states what it means now: a comment
376    // the operator wrote stays, and the template's own is refreshed. Every
377    // value the document carries rather than a named list, because a list
378    // is one more place a key added later must be remembered.
379    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    // A schema 1 file whose project keys all moved or dropped leaves an
384    // empty table, which
385    // `target-config:an-unanswered-key-is-absent-and-not-empty` asks the
386    // writer to leave out. Pruning it rather than hiding it keeps every
387    // comment the header carried, which hiding would suppress with it.
388    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    /// Every moved key keeps its trailing comment, the mode values rename,
400    /// the reporting policy appears, and the unmoved tables survive.
401    #[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        // Idempotent: a schema 2 text passes through unchanged.
461        assert_eq!(to_schema_2(&migrated).expect("passes"), migrated);
462    }
463
464    /// A schema 1 file with an empty technology and forge, the "detect"
465    /// answers, migrates to absent keys.
466    #[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    /// SATISFIES project-profile:a-schema-one-configuration-migrates-in-place
486    /// The migrated file loses the header whose every key moved or
487    /// dropped, and keeps the comment that header carried.
488    #[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    /// SATISFIES project-profile:a-schema-one-configuration-migrates-in-place
506    /// The detect answer and the absent key take the same cleanup path. A
507    /// schema 1 file could state `tech = ""` beside a release-line prefix
508    /// and a style, and both keys belong to an automatic release the
509    /// migrated profile does not have. Leaving either behind writes a
510    /// schema 2 file the strict reader then rejects.
511    #[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    /// SATISFIES project-profile:a-schema-one-configuration-migrates-in-place
533    /// A schema 1 key the migration drops takes the template's own comment
534    /// with it and leaves the operator's behind. Every free-standing
535    /// comment survives, which is what the rule asks for.
536    #[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    /// SATISFIES project-profile:a-schema-one-configuration-migrates-in-place
568    /// A comment standing above a key the migration moves travels with the
569    /// value it describes, rather than staying beside a key that is gone.
570    #[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    /// SATISFIES target-config:an-unknown-key-refuses
597    /// The strict reader never sees the schema 1 text, so a key the
598    /// migration does not know refuses here. Dropping it silently would
599    /// accept a typo and land the default behaviour under it.
600    #[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    /// SATISFIES target-config:an-unknown-key-refuses
613    /// A file that states schema 1 must have a schema 1 shape. The
614    /// generated tables would otherwise be written over whatever stood
615    /// where they go, and the result would read as valid.
616    #[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}