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.mappings

Requirements index · View definition

evidence Valid

Requirement

Each --map MUST have one of these forms:

  • a file or directory path, which maps that file, or every file under that directory, to the same relative path under the new side;
  • <file>#<selector>, which maps one outline node, and its outline descendants, to the node at the new file and selector;
  • a definition name, which maps that full name, and every full name beginning with it followed by ., to the same suffix under the new name.

A mapping whose old side names a recorded definition, or a prefix of one followed by ., MUST be a definition-name mapping.

Rationale

Obligations derived from requirements.refactor.mappings

  1. A path mapping maps a file, or every file under a directory, to the same relative path on the new side.
  2. A <file>#<selector> mapping maps that node and its outline descendants to the new file and selector.
  3. A definition-name mapping maps the full name, and every name that begins with it followed by ., to the same suffix under the new name.
  4. If the old side names a recorded definition, or a prefix of one followed by ., the mapping MUST be a definition-name mapping. A mapping that could also be a path is rejected.

Coverage

  • Name mappings. src/refactor/tests.rs#fn[mappings_cover_names_paths_and_nodes_beneath_them] covers the name form.
    • rules.cli maps to rules.core, and rules.cli.check maps to rules.core.check.
    • rules.client is not mapped, so the . boundary is enforced.
    • The reverse mapping and the glob selection are also checked.
  • Name mappings end to end. tests/refactor.rs#fn[a_moved_chapter_rewrites_glob_selections_and_their_matches] runs the prefix mapping rules=core and checks the resulting core.* selection and its matches. tests/refactor.rs#fn[a_moved_requirement_renames_its_references_and_evidence] runs the full-name mapping rules.load=core.load and checks the rewritten references and the moved evidence.
  • Path mappings. The unit test maps the directory src/config to src/settings. It checks a file beneath the directory and checks that src/configure.rs is not mapped. tests/refactor.rs#fn[a_moved_file_rewrites_anchors_and_paths] covers a single-file mapping from the CLI (data.txt=info.txt).
  • Node mappings.
    • The unit test maps src/a.rs#mod[m] to src/b.rs#mod[n].
    • A descendant (mod[m]/fn[f]) is mapped.
    • The sibling mod[mm] and the empty selector are not mapped.
    • The reverse mapping and address are checked.
    • A root mapping to a node is covered.
    • tests/refactor.rs#fn[a_moved_function_keeps_its_evidence_current] runs src/config.rs#fn[load]=src/config/load.rs#fn[load] end to end and asserts the record input and rationale.
  • Definition mappings must be name mappings. tests/refactor.rs#fn[invalid_mappings_fail_with_a_usage_error_and_change_nothing] creates a directory rules.load and maps rules.load=core.load. The mapping is rejected with “ambiguous” and exit code 2, and nothing on disk changes. The same test also rejects malformed or non-resolving forms.
    • These include a missing side, a node without a file, an old side that names nothing, and a new side that does not exist.

Residual note The ambiguity test uses a full definition name rather than a proper prefix, such as a directory rules when rules.load is recorded. I read parse_mappings in src/refactor.rs to check this. It computes name_like with the same prefix-aware beneath(name, old, '.') test that the prefix mapping rules=core exercises. So the prefix case runs through the same tested code path. I do not count it as a gap.

All obligations have tests that exercise the behavior and assert the outcomes.

Inputs

Implementation

Input 8: outline src/refactor.rs fn[parse_mappings]
/// Parses and checks the mappings against the repository.
// {impl}`requirements.refactor.mappings`
// {impl}`requirements.refactor.invalid_mappings`
fn parse_mappings(
    root: &Path,
    values: &[String],
    records: &[(String, Value)],
) -> Result<Mappings, RefactorError> {
    let usage = |message: String| Err(RefactorError::Usage(message));
    let definitions = crate::evidence::load_definitions(root)?;
    let mut names = definitions.keys().cloned().collect::<BTreeSet<_>>();
    let mut files = BTreeSet::new();
    for (path, record) in records {
        if let Some(RecordKind::Definition(name)) = record_kind(path) {
            names.insert(name);
        }
        if let Some(name) = record.get("requirement").and_then(Value::as_str)
            && matches!(record_kind(path), Some(RecordKind::Site))
        {
            names.insert(name.to_owned());
        }
        if let Some(file) = record.get("file").and_then(Value::as_str) {
            files.insert(file.to_owned());
        }
        for input in record
            .get("inputs")
            .and_then(Value::as_array)
            .into_iter()
            .flatten()
        {
            if let Some(file) = input.get("file").and_then(Value::as_str) {
                files.insert(file.to_owned());
            }
            for name in input
                .get("matches")
                .and_then(Value::as_array)
                .into_iter()
                .flatten()
                .filter_map(Value::as_str)
                .chain(input.get("definition").and_then(Value::as_str))
            {
                names.insert(name.to_owned());
            }
        }
    }
    let mut mappings = Mappings::default();
    let outlines = OutlineCache::default();
    for value in values {
        let Some((old, new)) = value
            .split_once('=')
            .filter(|(old, new)| !old.is_empty() && !new.is_empty() && old != new)
        else {
            return usage(format!(
                "invalid mapping {value:?}: expected <old>=<new> with different, nonempty sides"
            ));
        };
        if let Some((old_file, old_item)) = old.split_once('#') {
            let (new_file, new_item) = new.split_once('#').unwrap_or((new, ""));
            if old_file.is_empty() || new_file.is_empty() {
                return usage(format!("invalid mapping {value:?}: a node needs a file"));
            }
            let parsed = outlines.parse(root, new_file);
            if parsed
                .as_ref()
                .as_ref()
                .map_err(Clone::clone)
                .and_then(|parsed| parsed.resolve(new_file, new_item))
                .is_err()
            {
                return usage(format!("mapping {value:?}: {new} does not exist"));
            }
            mappings.nodes.push((
                (old_file.to_owned(), old_item.to_owned()),
                (new_file.to_owned(), new_item.to_owned()),
            ));
            continue;
        }
        let name_like = names.iter().any(|name| beneath(name, old, '.').is_some());
        let path_like = old.contains('/')
            || files.iter().any(|file| beneath(file, old, '/').is_some())
            || root.join(old).exists();
        match (name_like, path_like) {
            (true, true) => {
                return usage(format!(
                    "mapping {value:?} is ambiguous: {old} names both a definition and a path"
                ));
            }
            (true, false) => {
                if !definitions
                    .keys()
                    .any(|name| beneath(name, new, '.').is_some())
                {
                    return usage(format!(
                        "mapping {value:?}: no definition named {new} exists"
                    ));
                }
                mappings.names.push((old.to_owned(), new.to_owned()));
            }
            (false, true) => {
                if !root.join(new).exists() {
                    return usage(format!("mapping {value:?}: {new} does not exist"));
                }
                mappings.paths.push((old.to_owned(), new.to_owned()));
            }
            (false, false) => {
                return usage(format!(
                    "mapping {value:?}: {old} names no recorded definition, file, or node"
                ));
            }
        }
    }
    let overlap = |a: &str, b: &str, separator| {
        beneath(a, b, separator).is_some() || beneath(b, a, separator).is_some()
    };
    let paths = mappings
        .paths
        .iter()
        .map(|(old, _)| (old.as_str(), None))
        .chain(
            mappings
                .nodes
                .iter()
                .map(|((file, item), _)| (file.as_str(), Some(item.as_str()))),
        )
        .collect::<Vec<_>>();
    for (index, (a, a_item)) in paths.iter().enumerate() {
        for (b, b_item) in &paths[index + 1..] {
            let clash = match (a_item, b_item) {
                (Some(a_item), Some(b_item)) => {
                    a == b
                        && (beneath_node(a_item, b_item).is_some()
                            || beneath_node(b_item, a_item).is_some())
                }
                _ => overlap(a, b, '/'),
            };
            if clash {
                return usage(format!("mappings of {a} and {b} overlap"));
            }
        }
    }
    for (index, (a, _)) in mappings.names.iter().enumerate() {
        for (b, _) in &mappings.names[index + 1..] {
            if overlap(a, b, '.') {
                return usage(format!("mappings of {a} and {b} overlap"));
            }
        }
    }
    Ok(mappings)
}

Tests

Input 2: outline src/refactor/tests.rs fn[mappings_cover_names_paths_and_nodes_beneath_them]
// {test}`requirements.refactor.mappings`
#[test]
fn mappings_cover_names_paths_and_nodes_beneath_them() {
    let names = mappings(&[("name", "rules.cli", "rules.core")]);
    assert_eq!(names.name("rules.cli").as_deref(), Some("rules.core"));
    assert_eq!(
        names.name("rules.cli.check").as_deref(),
        Some("rules.core.check")
    );
    assert_eq!(names.name("rules.client"), None);
    assert_eq!(
        names.name_back("rules.core.check").as_deref(),
        Some("rules.cli.check")
    );
    assert_eq!(
        names.selection("rules.cli.*").as_deref(),
        Some("rules.core.*")
    );

    let paths = mappings(&[("path", "src/config", "src/settings")]);
    assert_eq!(
        paths.node("src/config/load.rs", "fn[load]"),
        Some(("src/settings/load.rs".to_owned(), "fn[load]".to_owned()))
    );
    assert_eq!(paths.path("src/configure.rs"), None);
    assert_eq!(
        paths.path_back("src/settings/a.rs").as_deref(),
        Some("src/config/a.rs")
    );

    let nodes = mappings(&[("node", "src/a.rs#mod[m]", "src/b.rs#mod[n]")]);
    assert_eq!(
        nodes.node("src/a.rs", "mod[m]/fn[f]"),
        Some(("src/b.rs".to_owned(), "mod[n]/fn[f]".to_owned()))
    );
    assert_eq!(nodes.node("src/a.rs", "mod[mm]"), None);
    assert_eq!(nodes.node("src/a.rs", ""), None);
    assert_eq!(
        nodes.node_back("src/b.rs", "mod[n]"),
        Some(("src/a.rs".to_owned(), "mod[m]".to_owned()))
    );
    assert_eq!(
        nodes.address("src/a.rs#mod[m]").as_deref(),
        Some("src/b.rs#mod[n]")
    );
    // A root mapping covers every node of the file.
    let root = mappings(&[("node", "src/a.rs", "src/b.rs#mod[a]")]);
    assert_eq!(
        root.node("src/a.rs", "fn[f]"),
        Some(("src/b.rs".to_owned(), "mod[a]/fn[f]".to_owned()))
    );
}
Input 3: outline tests/refactor.rs fn[a_moved_function_keeps_its_evidence_current]
// {test}`requirements.refactor.moved_function`
// {test}`requirements.refactor.command`
// {test}`requirements.refactor.outline_inputs`
// {test}`requirements.refactor.reference_digest`
// {test}`requirements.refactor.rationale.addresses`
// {test}`requirements.refactor.rationale.untouched`
// {test}`requirements.refactor.record_fields`
// {test}`requirements.refactor.equivalence`
// {test}`requirements.refactor.whole_record`
// {test}`requirements.refactor.mappings`
#[test]
fn a_moved_function_keeps_its_evidence_current() {
    let temp = project();
    let root = temp.path();
    author(root);
    assert_eq!(errors(root), Vec::<String>::new());
    move_load(root, "");
    let stale = errors(root);
    assert!(
        stale.iter().any(|error| error.contains("fn[load]")),
        "{stale:#?}"
    );
    let unaffected = fs::read(root.join("evidence/rules.check.json")).unwrap();

    let output = refactor(
        root,
        &[
            "--map",
            "src/config.rs#fn[load]=src/config/load.rs#fn[load]",
        ],
    );
    assert!(output.status.success(), "{output:?}");
    let report = stdout(&output);
    assert!(
        report.contains("Changed 1 records:\n- evidence/rules.load.json\n"),
        "{report}"
    );
    // The other mention of the old file is listed for review.
    assert!(
        report.contains("review the rationale's `src/config.rs`"),
        "{report}"
    );
    // `rules.check` reads no moved node, so it is unaffected and unchanged.
    assert!(!report.contains("rules.check"), "{report}");
    assert_eq!(
        fs::read(root.join("evidence/rules.check.json")).unwrap(),
        unaffected
    );
    assert_eq!(errors(root), Vec::<String>::new());
    let record: Value =
        serde_json::from_str(&fs::read_to_string(root.join("evidence/rules.load.json")).unwrap())
            .unwrap();
    assert_eq!(record["inputs"][1]["file"], "src/config/load.rs");
    assert_eq!(
        record["rationale"],
        "`src/config/load.rs#fn[load]` loads it, as `rules.load` asks; `verify` tests it in `src/config.rs`."
    );
    // Running it again changes nothing.
    let again = refactor(
        root,
        &[
            "--map",
            "src/config.rs#fn[load]=src/config/load.rs#fn[load]",
        ],
    );
    assert!(
        stdout(&again).contains("Changed 0 records:"),
        "{}",
        stdout(&again)
    );
}
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_file_rewrites_anchors_and_paths]
// {test}`requirements.refactor.reference_rewrite`
// {test}`requirements.refactor.reference_digest`
// {test}`requirements.refactor.rationale.paths`
// {test}`requirements.refactor.equivalence`
// {test}`requirements.refactor.mappings`
#[test]
fn a_moved_file_rewrites_anchors_and_paths() {
    let temp = project();
    let root = temp.path();
    author(root);
    fs::rename(root.join("data.txt"), root.join("info.txt")).unwrap();
    let output = refactor(root, &["--map", "data.txt=info.txt"]);
    assert!(output.status.success(), "{output:?}");
    let book = fs::read_to_string(root.join("md/rules.md")).unwrap();
    assert!(book.contains(":impl: info.txt\n"), "{book}");
    let record: Value =
        serde_json::from_str(&fs::read_to_string(root.join("evidence/rules.check.json")).unwrap())
            .unwrap();
    assert!(
        record["rationale"]
            .as_str()
            .unwrap()
            .starts_with("`info.txt` is checked")
    );
    assert_eq!(errors(root), Vec::<String>::new());
}
Input 6: outline tests/refactor.rs fn[invalid_mappings_fail_with_a_usage_error_and_change_nothing]
  • File: tests/refactor.rs
  • Selector: fn[invalid_mappings_fail_with_a_usage_error_and_change_nothing]
  • Kind: fn
  • tests/refactor.rs:419–486
// {test}`requirements.refactor.invalid_mappings`
// {test}`requirements.refactor.mappings`
#[test]
fn invalid_mappings_fail_with_a_usage_error_and_change_nothing() {
    let temp = project();
    let root = temp.path();
    author(root);
    fs::create_dir_all(root.join("rules.load")).unwrap();
    let before = snapshot(root);
    for (args, message) in [
        (vec!["--map", "rules.load"], "expected <old>=<new>"),
        (vec!["--map", "=core.load"], "expected <old>=<new>"),
        (vec!["--map", "rules.check="], "expected <old>=<new>"),
        (vec!["--map", "src/config.rs="], "expected <old>=<new>"),
        (vec!["--map", "rules.check=rules.check"], "different"),
        (vec!["--map", "rules.load=core.load"], "ambiguous"),
        (
            vec!["--map", "rules.check=core.check"],
            "no definition named core.check",
        ),
        (
            vec!["--map", "src/config.rs=src/gone.rs"],
            "src/gone.rs does not exist",
        ),
        (
            vec!["--map", "src/config.rs#fn[load]=src/config.rs#fn[gone]"],
            "does not exist",
        ),
        (
            vec!["--map", "src=md", "--map", "src/config.rs=data.txt"],
            "overlap",
        ),
        (
            vec![
                "--map",
                "rules.check=rules.load",
                "--map",
                "rules=rules.load",
            ],
            "mappings of rules.check and rules overlap",
        ),
        (
            vec![
                "--map",
                "src/config.rs#fn[load]=src/config.rs#fn[check]",
                "--map",
                "src/config.rs#=src/config.rs#fn[verify]",
            ],
            "overlap",
        ),
        (
            vec!["--map", "#fn[load]=src/config.rs#fn[load]"],
            "a node needs a file",
        ),
        (
            vec!["--map", "nothing.here=data.txt"],
            "names no recorded definition, file, or node",
        ),
    ] {
        let output = refactor(root, &args);
        assert_eq!(output.status.code(), Some(2), "{args:?}: {output:?}");
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(stderr.contains(message), "{args:?}: {stderr}");
        assert!(stderr.contains("Usage:"), "{stderr}");
        assert_eq!(snapshot(root), before, "{args:?}");
    }
    assert_eq!(refactor(root, &[]).status.code(), Some(2));
}
Input 7: outline tests/refactor.rs fn[a_moved_chapter_rewrites_glob_selections_and_their_matches]
  • File: tests/refactor.rs
  • Selector: fn[a_moved_chapter_rewrites_glob_selections_and_their_matches]
  • Kind: fn
  • tests/refactor.rs:955–982
// {test}`requirements.refactor.record_fields`
// {test}`requirements.refactor.definition_inputs`
// {test}`requirements.refactor.equivalence`
// {test}`requirements.refactor.mappings`
#[test]
fn a_moved_chapter_rewrites_glob_selections_and_their_matches() {
    let temp = project();
    let root = temp.path();
    author(root);
    let chapter = fs::read_to_string(root.join("md/rules.md")).unwrap();
    fs::remove_file(root.join("md/rules.md")).unwrap();
    fs::write(
        root.join("md/core.md"),
        chapter.replace("# Rules", "# Core"),
    )
    .unwrap();
    let output = refactor(root, &["--map", "rules=core"]);
    assert!(output.status.success(), "{output:?}");
    let record: Value =
        serde_json::from_str(&fs::read_to_string(root.join("evidence/core.check.json")).unwrap())
            .unwrap();
    assert_eq!(record["inputs"][0]["requirements"], "core.*");
    assert_eq!(
        record["inputs"][0]["matches"],
        json!(["core.check", "core.load"])
    );
    assert_eq!(errors(root), Vec::<String>::new());
}

Other sources

Input 1: requirements selection requirements.refactor.mappings
:::{req} mappings
Each `--map` MUST have one of these forms:

- a file or directory path, which maps that file, or every file under that
  directory, to the same relative path under the new side;
- `<file>#<selector>`, which maps one outline node, and its outline
  descendants, to the node at the new file and selector;
- a definition name, which maps that full name, and every full name beginning
  with it followed by `.`, to the same suffix under the new name.

A mapping whose old side names a recorded definition, or a prefix of one
followed by `.`, MUST be a definition-name mapping.
:::