Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

requirements.refactor.rationale.names

Requirements index · View definition

evidence Valid

Requirement

In the rationale of each changed record, habeas refactor MUST rewrite each code span that is exactly an old definition name, or a name beneath one, to its new name.

Rationale

The requirement has one obligation: rewrite each code span in a changed record’s rationale that is exactly an old definition name, or a name beneath one, to its new name.

Implementation

  • src/refactor.rs#fn[rewrite_rationale] carries the {impl} reference. It finds code spans with CODE_SPAN, a backtick-delimited pattern, and maps each span through mappings.name(span).
  • Mappings::name calls beneath(name, old, '.'). That matches only when the span equals the old name or continues with a . separator. rules.client therefore does not match rules.cli.
  • A match is rewritten to `{new}{rest}`. The suffix is kept, so rules.cli.check becomes rules.core.check.
  • rewrite_record calls rewrite_rationale on the rationale field of each record it changes, so the “changed record” scope is met.
  • Spans that are not exactly a name, such as bare text without backticks, are left untouched.

Tests

  • src/refactor/tests.rs#fn[rationales_rewrite_exact_code_spans_and_list_other_mentions] has a {test} reference. It checks that `rules.cli.check` is rewritten to `rules.core.check`. It also checks that the bare rules.cli.check and `rules.client` are not rewritten.
  • tests/refactor.rs#fn[a_moved_requirement_renames_its_references_and_evidence] has a {test} reference. It checks the exact-name case: the rationale of the moved record now contains as `core.load` asks.
  • tests/refactor.rs#fn[a_moved_term_rewrites_definition_inputs_and_the_texts_using_it] has a {test} reference. It checks that the rationale becomes Nothing implements `usage.use`, which uses `glossary.term`.

No gaps found.

Inputs

Implementation

Input 3: outline src/refactor.rs fn[rewrite_rationale]
/// Rewrites a rationale's code spans that are exactly an old definition
/// name, path, or node address, and lists the other spans that mention an
/// old path.
// {impl}`requirements.refactor.rationale.names`
// {impl}`requirements.refactor.rationale.paths`
// {impl}`requirements.refactor.rationale.addresses`
// {impl}`requirements.refactor.rationale.untouched`
fn rewrite_rationale(mappings: &Mappings, rationale: &str) -> (String, Vec<String>) {
    let old_paths = mappings.old_paths();
    let mut mentions = Vec::new();
    let rewritten = CODE_SPAN.replace_all(rationale, |captures: &regex::Captures<'_>| {
        let span = &captures[1];
        let mapped = mappings.name(span).or_else(|| mappings.address(span));
        match mapped {
            Some(new) => format!("`{new}`"),
            None => {
                if old_paths.iter().any(|old| span.contains(old)) {
                    mentions.push(format!("`{span}`"));
                }
                captures[0].to_owned()
            }
        }
    });
    (rewritten.into_owned(), mentions)
}

Tests

Input 2: outline src/refactor/tests.rs fn[rationales_rewrite_exact_code_spans_and_list_other_mentions]
// {test}`requirements.refactor.rationale.names`
// {test}`requirements.refactor.rationale.paths`
// {test}`requirements.refactor.rationale.addresses`
// {test}`requirements.refactor.rationale.untouched`
#[test]
fn rationales_rewrite_exact_code_spans_and_list_other_mentions() {
    let map = mappings(&[
        ("name", "rules.cli", "rules.core"),
        ("path", "src/old", "src/new"),
        ("node", "src/a.rs#fn[f]", "src/b.rs#fn[f]"),
    ]);
    let (rewritten, mentions) = rewrite_rationale(
        &map,
        "`rules.cli.check` holds; `src/old/x.rs` and `src/a.rs#fn[f]` do it. \
         `src/a.rs` stays, as does `src/a.rs:3`, rules.cli.check, and `rules.client`.",
    );
    assert_eq!(
        rewritten,
        "`rules.core.check` holds; `src/new/x.rs` and `src/b.rs#fn[f]` do it. \
         `src/a.rs` stays, as does `src/a.rs:3`, rules.cli.check, and `rules.client`."
    );
    assert_eq!(mentions, ["`src/a.rs`", "`src/a.rs:3`"]);
}
Input 4: outline tests/refactor.rs fn[a_moved_requirement_renames_its_references_and_evidence]
// {test}`requirements.refactor.moved_requirement`
// {test}`requirements.refactor.reference_rewrite`
// {test}`requirements.refactor.record_files`
// {test}`requirements.refactor.definition_inputs`
// {test}`requirements.refactor.subject_text`
// {test}`requirements.refactor.rationale.names`
// {test}`requirements.refactor.command`
// {test}`requirements.refactor.mappings`
#[test]
fn a_moved_requirement_renames_its_references_and_evidence() {
    let temp = project();
    let root = temp.path();
    author(root);
    fs::write(
        root.join("md/notes.md"),
        "Loading follows {cite}`rules.load`.\n",
    )
    .unwrap();
    // `load` moves to the `core` chapter; references still name the old name.
    fs::write(
        root.join("md/rules.md"),
        "# Rules\n\n:::{req} check\n:impl: data.txt\nThe data MUST be checked.\n:::\n",
    )
    .unwrap();
    fs::write(
        root.join("md/core.md"),
        "# Core\n\n:::{req} load\nConfiguration MUST load.\n:::\n",
    )
    .unwrap();
    let before = snapshot(root);
    let output = refactor(root, &["--map", "rules.load=core.load"]);
    assert!(output.status.success(), "{output:?}");
    let report = stdout(&output);
    assert!(report.contains("- src/config.rs (2)"), "{report}");
    assert!(report.contains("- md/notes.md (1)"), "{report}");
    assert_eq!(
        fs::read_to_string(root.join("md/notes.md")).unwrap(),
        "Loading follows {cite}`core.load`.\n"
    );
    // Only the rewritten references and the moved evidence changed.
    let after = snapshot(root);
    let differing = before
        .keys()
        .chain(after.keys())
        .filter(|file| before.get(*file) != after.get(*file))
        .cloned()
        .collect::<std::collections::BTreeSet<_>>();
    assert_eq!(
        differing.into_iter().collect::<Vec<_>>(),
        [
            "evidence/core.load.json",
            "evidence/rules.load.json",
            "md/notes.md",
            "src/config.rs",
        ]
    );
    assert!(
        report.contains("- evidence/rules.load.json -> evidence/core.load.json"),
        "{report}"
    );
    // The glob no longer matches what it recorded, so that record is stale.
    assert!(
        report.contains(
            "- evidence/rules.check.json: inputs[0]: rules.* no longer selects what it recorded"
        ),
        "{report}"
    );
    assert!(!root.join("evidence/rules.load.json").exists());
    let source = fs::read_to_string(root.join("src/config.rs")).unwrap();
    assert!(source.contains("// {impl}`core.load`") && source.contains("// {test}`core.load`"));
    let record: Value =
        serde_json::from_str(&fs::read_to_string(root.join("evidence/core.load.json")).unwrap())
            .unwrap();
    assert_eq!(
        record["inputs"][0],
        requirements_input("core.load", &["core.load"], &LOAD_TEXT)
    );
    assert!(
        record["rationale"]
            .as_str()
            .unwrap()
            .contains("as `core.load` asks")
    );
    let remaining = errors(root);
    assert!(
        remaining
            .iter()
            .all(|error| error.starts_with("evidence/rules.check.json")),
        "{remaining:#?}"
    );
}
Input 5: outline tests/refactor.rs fn[a_moved_term_rewrites_definition_inputs_and_the_texts_using_it]
  • File: tests/refactor.rs
  • Selector: fn[a_moved_term_rewrites_definition_inputs_and_the_texts_using_it]
  • Kind: fn
  • tests/refactor.rs:832–868
// {test}`requirements.refactor.definition_inputs`
// {test}`requirements.refactor.subject_text`
// {test}`requirements.refactor.reference_rewrite`
// {test}`requirements.refactor.rationale.names`
// {test}`requirements.refactor.record_fields`
#[test]
fn a_moved_term_rewrites_definition_inputs_and_the_texts_using_it() {
    let temp = project();
    let root = temp.path();
    add_term(root);
    assert_eq!(usage_errors(root), Vec::<String>::new());
    fs::remove_file(root.join("md/terms.md")).unwrap();
    fs::write(
        root.join("md/glossary.md"),
        "# Glossary\n\n:::{definition} term\n:phrase: term\n\nA word.\n:::\n",
    )
    .unwrap();
    let output = refactor(root, &["--map", "terms.term=glossary.term"]);
    assert!(output.status.success(), "{output:?}");
    assert_eq!(
        fs::read_to_string(root.join("md/usage.md")).unwrap(),
        "# Usage\n\n:::{req} use\nThe {term}`glossary.term` MUST be used.\n:::\n"
    );
    let record: Value =
        serde_json::from_str(&fs::read_to_string(root.join("evidence/usage.use.json")).unwrap())
            .unwrap();
    assert_eq!(
        record["requirement"],
        "The {term}`glossary.term` MUST be used."
    );
    assert_eq!(record["inputs"][1]["definition"], "glossary.term");
    assert_eq!(
        record["rationale"],
        "Nothing implements `usage.use`, which uses `glossary.term`."
    );
    assert_eq!(usage_errors(root), Vec::<String>::new());
}

Other sources

Input 1: requirements selection requirements.refactor.rationale.names
:::{req} rationale.names
In the rationale of each changed record, `habeas refactor` MUST rewrite each
code span that is exactly an old definition name, or a name beneath one, to its
new name.
:::
Input 6: outline src/refactor.rs impl[Mappings]/fn[name]
    /// A definition name's new name, if a mapping covers it.
    fn name(&self, name: &str) -> Option<String> {
        self.names
            .iter()
            .find_map(|(old, new)| beneath(name, old, '.').map(|rest| format!("{new}{rest}")))
    }
Input 7: outline src/refactor.rs static[CODE_SPAN]
/// A backtick-delimited code span.
static CODE_SPAN: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"`([^`\n]+)`").expect("code span pattern"));