requirements.refactor.subject_text
Requirements index · View definition
Requirement
A record’s
requirementorexamplefield MUST be rewritten only if the mapped-back current body of its subject equals the recorded body.
Rationale
I found no gap against requirements.refactor.subject_text. It has one obligation: a record’s requirement or example field is rewritten only if the mapped-back current body of its subject equals the recorded body.
Implementation. src/refactor.rs#fn[rewrite_record] carries the {impl} reference. In the RecordKind::Definition branch it picks the example field if the record has one, and requirement otherwise.
- It builds the mapped-back body from
states.definitions_back.States::computeproduces that map by rewriting the current definition text to the new names and then applyingmappings.text_back. That matches therequirements.refactor.mapped_backdefinition: each new side of the mappings is replaced by its old side. - It matches
(Some(back), Some(current))and only setsvalue[field] = currentwhenbackequalsrecord[field]. - If the bodies differ, it pushes a “
{field}text of{new}changed” failure. A non-empty failure list makes the function returnOutcome::Unchangedbefore any new value is returned, so the record is left as it was. - If there is no current definition at all, it also records a failure and does not rewrite.
- The guard
new != *name || body(definitions) != body(definitions_post)skips only cases where nothing would change.
Tests.
tests/refactor.rs#fn[a_moved_requirement_renames_its_references_and_evidence]covers the equal case. After the move the record’sinputs[0]carries the new text and the record is moved toevidence/core.load.json.tests/refactor.rs#fn[a_requirement_edited_while_moving_keeps_its_old_record]covers the unequal case. The body is edited during the move. The report says “requirement text of core.load changed”, the old record file is byte-identical, and no new record file exists.tests/refactor.rs#fn[a_moved_term_rewrites_definition_inputs_and_the_texts_using_it]covers a case where the body changes only because of a renamed term. The mapped-back text equals the recorded text, so therequirementfield is rewritten toThe {term}glossary.termMUST be used.tests/refactor.rs#fn[a_moved_example_rewrites_its_example_field]covers theexamplefield. It is rewritten, and norequirementfield appears.
All four tests carry {test} references to the subject.
Inputs
Implementation
Input 2: outline src/refactor.rs fn[rewrite_record]
- File:
src/refactor.rs - Selector:
fn[rewrite_record] - Kind:
fn src/refactor.rs:722–894
/// Decides one record under the mappings.
// {impl}`requirements.refactor.whole_record`
// {impl}`requirements.refactor.subject_text`
// {impl}`requirements.refactor.record_fields`
// {impl}`requirements.refactor.reference_digest`
fn rewrite_record(states: &States, path: &str, record: &Value) -> io::Result<Outcome> {
let mappings = &states.mappings;
let Some(kind) = record_kind(path) else {
return Ok(Outcome::Unaffected);
};
let mut value = record.clone();
let mut changed = false;
let mut failures = Vec::new();
let new_path = match &kind {
RecordKind::Definition(name) => {
let new = mappings.name(name).unwrap_or_else(|| name.clone());
let field = if record.get("example").is_some() {
"example"
} else {
"requirement"
};
let body = |definitions: &BTreeMap<String, Declaration>, name: &str| {
definitions
.get(name)
.map(|definition| definition.text.clone())
};
if new != *name
|| body(&states.definitions, name) != body(&states.definitions_post, &new)
{
match (
body(&states.definitions_back, name),
body(&states.definitions_post, &new),
) {
(Some(back), Some(current))
if Some(back.as_str()) == record[field].as_str() =>
{
value[field] = Value::String(current);
changed = true;
}
(_, None) => {
failures.push(format!("{new}: no current definition"));
changed = true;
}
_ => {
failures.push(format!("{field} text of {new} changed"));
changed = true;
}
}
}
if let Some(recorded) = record.get("references").and_then(Value::as_str)
&& let Some((current, back)) = states.digests(&new, name)?
&& current != recorded
&& (new != *name || current != back)
{
if back == recorded {
value["references"] = Value::String(current);
changed = true;
} else {
failures.push(format!("the reference set of {new} changed"));
changed = true;
}
}
if new != *name {
changed = true;
}
format!("evidence/{new}.json")
}
RecordKind::Citation | RecordKind::Site => {
let file = record
.get("file")
.and_then(Value::as_str)
.unwrap_or_default();
let item = record
.get("item")
.and_then(Value::as_str)
.unwrap_or_default();
let (new_file, new_item) = mappings
.node(file, item)
.unwrap_or((file.to_owned(), item.to_owned()));
if (new_file.as_str(), new_item.as_str()) != (file, item) {
value["file"] = json!(new_file);
value["item"] = json!(new_item);
changed = true;
}
match &kind {
RecordKind::Citation => {
if let Some(citations) =
value.get_mut("citations").and_then(Value::as_array_mut)
{
for citation in citations {
let name = citation["name"].as_str().unwrap_or_default();
if let Some(new) = mappings.name(name) {
citation["name"] = json!(new);
changed = true;
}
let commentary = citation["commentary"]
.as_str()
.unwrap_or_default()
.to_owned();
let (new, edits) =
rewrite_source(mappings, Path::new("commentary"), &commentary);
if edits > 0 {
citation["commentary"] = json!(new);
changed = true;
}
}
}
// :::{impl} requirements.refactor.equivalence
// A citation review validates against the citations its
// item currently carries, so a review whose rewritten
// citations differ from those would validate differently
// after the move; the record is left unchanged instead.
// :::
if changed && !same_citations(states, &new_file, &new_item, &value) {
failures.push(format!(
"the citations of {} differ from the recorded ones",
address(&new_file, &new_item)
));
}
crate::citations::review_path(&new_file, &new_item)
}
_ => {
let requirement = record
.get("requirement")
.and_then(Value::as_str)
.unwrap_or_default();
let new = mappings
.name(requirement)
.unwrap_or_else(|| requirement.to_owned());
if new != requirement {
value["requirement"] = json!(new);
changed = true;
}
crate::sites::review_path(&new, &new_file, &new_item)
}
}
}
};
if let Some(inputs) = value.get_mut("inputs").and_then(Value::as_array_mut) {
for (index, input) in inputs.iter_mut().enumerate() {
match rewrite_input(states, input) {
None => {}
Some(Ok(new)) => {
if new != *input {
*input = new;
changed = true;
}
}
Some(Err(error)) => {
failures.push(format!("inputs[{index}]: {error}"));
changed = true;
}
}
}
}
if !changed {
return Ok(Outcome::Unaffected);
}
if !failures.is_empty() {
return Ok(Outcome::Unchanged(failures.join("; ")));
}
let mut mentions = Vec::new();
if let Some(rationale) = value.get("rationale").and_then(Value::as_str) {
let (rewritten, found) = rewrite_rationale(mappings, rationale);
value["rationale"] = Value::String(rewritten);
mentions = found;
}
Ok(Outcome::Changed {
path: new_path,
value,
mentions,
})
}
Tests
Input 3: outline tests/refactor.rs fn[a_moved_requirement_renames_its_references_and_evidence]
- File:
tests/refactor.rs - Selector:
fn[a_moved_requirement_renames_its_references_and_evidence] - Kind:
fn tests/refactor.rs:276–366
// {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 4: outline tests/refactor.rs fn[a_requirement_edited_while_moving_keeps_its_old_record]
- File:
tests/refactor.rs - Selector:
fn[a_requirement_edited_while_moving_keeps_its_old_record] - Kind:
fn tests/refactor.rs:731–752
// {test}`requirements.refactor.subject_text`
// {test}`requirements.refactor.whole_record`
#[test]
fn a_requirement_edited_while_moving_keeps_its_old_record() {
let temp = project();
let root = temp.path();
author(root);
move_load_requirement(root, "Configuration MUST load quickly.");
let before = fs::read(root.join("evidence/rules.load.json")).unwrap();
let output = refactor(root, &["--map", "rules.load=core.load"]);
assert!(output.status.success(), "{output:?}");
let report = stdout(&output);
assert!(
report.contains("- evidence/rules.load.json: requirement text of core.load changed"),
"{report}"
);
assert_eq!(
fs::read(root.join("evidence/rules.load.json")).unwrap(),
before
);
assert!(!root.join("evidence/core.load.json").exists());
}
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());
}
Input 6: outline tests/refactor.rs fn[a_moved_example_rewrites_its_example_field]
- File:
tests/refactor.rs - Selector:
fn[a_moved_example_rewrites_its_example_field] - Kind:
fn tests/refactor.rs:1090–1162
// {test}`requirements.refactor.subject_text`
// {test}`requirements.refactor.record_files`
#[test]
fn a_moved_example_rewrites_its_example_field() {
let temp = project();
let root = temp.path();
author(root);
// The role's brace is an argument, so this source holds no reference.
let body = |name: &str| format!("Loading works. {{cite}}`{name}`");
fs::write(
root.join("md/cases.md"),
format!(
"# Cases\n\n:::{{example}} loading\n{}\n:::\n",
body("rules.load")
),
)
.unwrap();
fs::write(
root.join("evidence/cases.loading.json"),
serde_json::to_string_pretty(&json!({
"example": body("rules.load"),
"determination": false,
"rationale": "No test covers `cases.loading`.",
"references": habeas::reference_set_digest_for(root, "cases.loading").unwrap(),
"inputs": [
requirements_input("cases.loading", &["cases.loading"], &[":::{example} loading", &body("rules.load"), ":::"]),
requirements_input("rules.load", &["rules.load"], &LOAD_TEXT),
],
}))
.unwrap(),
)
.unwrap();
let case_errors = |root: &Path| {
errors(root)
.into_iter()
.filter(|error| error.starts_with("evidence/cases."))
.collect::<Vec<_>>()
};
let before = case_errors(root);
// The example moves to the `examples` chapter.
fs::remove_file(root.join("md/cases.md")).unwrap();
fs::write(
root.join("md/examples.md"),
format!(
"# Examples\n\n:::{{example}} loading\n{}\n:::\n",
body("rules.load")
),
)
.unwrap();
let output = refactor(root, &["--map", "cases.loading=examples.loading"]);
assert!(output.status.success(), "{output:?}");
let record: Value = serde_json::from_str(
&fs::read_to_string(root.join("evidence/examples.loading.json")).unwrap(),
)
.unwrap();
assert_eq!(record["example"], body("rules.load"));
assert!(record.get("requirement").is_none());
// It fails validation exactly as before, under its new name.
let after = errors(root)
.into_iter()
.filter(|error| error.starts_with("evidence/examples."))
.map(|error| error.replace("examples.loading", "cases.loading"))
.collect::<Vec<_>>();
let before = before
.into_iter()
.map(|error| {
error
.replacen("evidence/cases.", "evidence/examples.", 1)
.replace("examples.loading", "cases.loading")
})
.collect::<Vec<_>>();
assert_eq!(after, before);
}
Referenced definitions
Input 7: definition requirements.refactor.mapped_back
requirements.refactor.mapped_back:md/requirements/refactor.md:58–63
:::{definition} mapped_back
:phrase: mapped-back
The *mapped-back* form of current text or a current address is the text or
address with each new side of the mappings replaced by its old side.
:::
Other sources
Input 1: requirements selection requirements.refactor.subject_text
requirements.refactor.subject_text:md/requirements/refactor.md:81–85
:::{req} subject_text
A record's `requirement` or `example` field MUST be rewritten only if the
{term}`requirements.refactor.mapped_back` current body of its subject equals
the recorded body.
:::
Input 8: outline src/refactor.rs impl[States]/fn[compute]
- File:
src/refactor.rs - Selector:
impl[States]/fn[compute] - Kind:
fn src/refactor.rs:394–514
/// Computes the post and mapped-back states from the current repository.
// {impl}`requirements.refactor.definition_inputs`
fn compute(root: &Path, mappings: Mappings) -> io::Result<Self> {
let definitions = crate::evidence::load_definitions(root)?;
let mut failures = Vec::new();
let files = crate::evidence::discovered_files(root, &mut failures);
let references = crate::evidence::collect_references_with_progress(
root,
&files,
&mut failures,
&mut |_| {},
);
if !failures.is_empty() {
return Err(io::Error::other(failures.join("\n")));
}
let mut sources = files
.iter()
.map(|file| display_path(root, file))
.collect::<BTreeSet<_>>();
sources.extend(
definitions
.values()
.map(|definition| definition.file.clone()),
);
let mut rewritten = BTreeMap::new();
let mut post = HashMap::new();
let mut back = HashMap::new();
for file in &sources {
let Ok(content) = fs::read_to_string(root.join(file)) else {
continue;
};
let (new, edits) = rewrite_source(&mappings, Path::new(file), &content);
let reverted = mappings.text_back(&new);
if reverted != content {
back.insert(file.clone(), reverted);
}
if edits > 0 {
post.insert(file.clone(), new.clone());
rewritten.insert(file.clone(), (new, edits));
}
}
let rewrite = |text: &str, file: &str| rewrite_source(&mappings, Path::new(file), text).0;
let definitions_post = definitions
.iter()
.map(|(name, definition)| {
let mut definition = definition.clone();
definition.text = rewrite(&definition.text, &definition.file);
definition.raw_lines = rewrite(&definition.raw_lines.join("\n"), &definition.file)
.split('\n')
.map(str::to_owned)
.collect();
for anchor in &mut definition.anchors {
if let Some(new) = mappings.address(&anchor.label()) {
*anchor = Anchor::parse(anchor.kind, &new);
}
}
(name.clone(), definition)
})
.collect::<BTreeMap<_, _>>();
let definitions_back = definitions_post
.iter()
.map(|(name, definition)| {
let old = mappings.name_back(name).unwrap_or_else(|| name.clone());
let mut definition = definition.clone();
definition.text = mappings.text_back(&definition.text);
definition.raw_lines = definition
.raw_lines
.iter()
.map(|line| mappings.text_back(line))
.collect();
if let Some(opening) = definition.raw_lines.first_mut() {
*opening = opening_back(opening, name, &old);
}
for anchor in &mut definition.anchors {
if let Some(old) = mappings.address_back(&anchor.label()) {
*anchor = Anchor::parse(anchor.kind, &old);
}
}
(old, definition)
})
.collect();
let references_post = references
.iter()
.map(|reference| {
let mut reference = reference.clone();
if let Some(new) = mappings.name(&reference.name) {
reference.name = new;
}
if let Some(body) = &mut reference.commentary {
*body = rewrite_source(&mappings, Path::new("commentary"), body).0;
}
reference
})
.collect::<Vec<_>>();
let references_back = references_post
.iter()
.map(|reference| {
let mut reference = reference.clone();
if let Some(old) = mappings.name_back(&reference.name) {
reference.name = old;
}
if let Some(body) = &mut reference.commentary {
*body = mappings.text_back(body);
}
reference
})
.collect();
Ok(Self {
root: root.to_owned(),
mappings,
files,
rewritten,
definitions,
definitions_post,
definitions_back,
references_post,
references_back,
outlines_post: OutlineCache::with_overrides(post),
outlines_back: OutlineCache::with_overrides(back),
})
}