requirements.refactor.dry_run
Requirements index · View definition
Requirement
With
--dry-run,habeas refactorMUST report every change it would make, in the same form as, and MUST write nothing.
Rationale
The code and test satisfy requirements.refactor.dry_run. I read the code and the one test; I did not run the test.
Obligations: with --dry-run, (1) report every change the command would make, (2) in the same form as requirements.refactor.command, and (3) write nothing.
Code: src/refactor.rs#fn[refactor] carries all three and has the {impl} reference.
- Reporting (1): the analysis runs identically in both modes.
load_records,parse_mappings,States::compute, the per-recordrewrite_recordoutcomes and the conflict-dropping loop all run before thedry_runflag is checked. Thechangedandunchangedlists and the rewritten-files set are therefore identical in both modes, and the report prints them. - Same form (2): one report builder serves both modes. Only the verbs change, from
Rewrote/Changed/LefttoWould rewrite/Would change/Would leave. The layout is shared, including thepath -> targetlines, the rationale-review lines and thepath: reasonlines. - Writes nothing (3): every
fs::write,fs::remove_file,pruneandcreate_dir_allis insideif !dry_run { ... }.States::compute(src/refactor.rs#impl[States]/fn[compute]),load_recordsandrewrite_recordonly read. Rewritten text goes into in-memory maps andOutlineCache::with_overrides.
Test: tests/refactor.rs#fn[a_dry_run_reports_the_same_changes_and_writes_nothing] carries {test} for the subject.
- It moves
loadto another file and takes a full file snapshot. - It runs
--dry-runand asserts the command succeeds and the snapshot is unchanged. This covers obligation 3. - It then runs the real command and asserts the normalized dry-run output equals the real report. This covers obligations 1 and 2.
- The moved-function scenario exercises both the rewritten-files section and the
path -> targetchanged-record lines.
Residual risk: the test does not exercise the “unchanged records” section or the “would be overwritten” conflict path under --dry-run. In the test scenario that section is empty, so the Would leave wording is not asserted. I did not count this as a gap because the requirement’s obligation is to report the changes the command would make, and those paths share their code with the real run apart from the verb text. A stricter reviewer could ask for a dry-run test covering them.
No {fixme} references apply.
Inputs
Implementation
Input 3: outline src/refactor.rs fn[refactor]
- File:
src/refactor.rs - Selector:
fn[refactor] - Kind:
fn src/refactor.rs:1122–1240
/// Runs `habeas refactor` with `--map` values, reporting what it changed,
/// or with `dry_run`, what it would change.
// {impl}`requirements.refactor.command`
// {impl}`requirements.refactor.dry_run`
// {impl}`requirements.refactor.record_files`
// {impl}`requirements.refactor.equivalence`
// {impl}`requirements.refactor.rationale.untouched`
pub fn refactor(root: &Path, values: &[String], dry_run: bool) -> Result<String, RefactorError> {
let root = fs::canonicalize(root)?;
let records = load_records(&root)?;
let mappings = parse_mappings(&root, values, &records)?;
let states = States::compute(&root, mappings)?;
let mut changed = Vec::new();
let mut unchanged = Vec::new();
let mut targets = BTreeMap::<String, usize>::new();
for (path, record) in &records {
match rewrite_record(&states, path, record)? {
Outcome::Unaffected => {}
Outcome::Unchanged(reason) => unchanged.push((path.clone(), reason)),
Outcome::Changed {
path: target,
value,
mentions,
} => {
*targets.entry(target.clone()).or_default() += 1;
changed.push((path.clone(), target, value, mentions));
}
}
}
// A move may take the place of a record that moves away, but only if
// that record's move survives: dropping one conflict can expose another,
// so conflicts are dropped until none remain.
loop {
let moving = changed
.iter()
.filter(|(path, target, ..)| path != target)
.map(|(path, ..)| path.clone())
.collect::<BTreeSet<_>>();
let before = changed.len();
changed.retain(|(path, target, ..)| {
let conflict = targets[target] > 1
|| (path != target && root.join(target).exists() && !moving.contains(target));
if conflict {
unchanged.push((path.clone(), format!("{target} would be overwritten")));
}
!conflict
});
if changed.len() == before {
break;
}
}
unchanged.sort();
if !dry_run {
for (file, (content, _)) in &states.rewritten {
fs::write(root.join(file), content)?;
}
for (path, ..) in &changed {
if !changed.iter().any(|(_, target, ..)| target == path) {
let old = root.join(path);
if fs::remove_file(&old).is_ok() {
prune(&root, &old);
}
}
}
for (_, target, value, _) in &changed {
let target = root.join(target);
if let Some(parent) = target.parent() {
fs::create_dir_all(parent)?;
}
fs::write(
&target,
format!(
"{}\n",
serde_json::to_string_pretty(value).map_err(io::Error::from)?
),
)?;
}
}
let (rewrote, change, leave) = if dry_run {
("Would rewrite", "Would change", "Would leave")
} else {
("Rewrote", "Changed", "Left")
};
let mut report = String::new();
if !states.rewritten.is_empty() {
let _ = writeln!(
report,
"{rewrote} references or anchors in {} files:",
states.rewritten.len()
);
for (file, (_, edits)) in &states.rewritten {
let _ = writeln!(report, "- {file} ({edits})");
}
}
let _ = writeln!(report, "{change} {} records:", changed.len());
for (path, target, _, mentions) in &changed {
if path == target {
let _ = writeln!(report, "- {path}");
} else {
let _ = writeln!(report, "- {path} -> {target}");
}
for mention in mentions {
let _ = writeln!(report, " - review the rationale's {mention}");
}
}
if !unchanged.is_empty() {
let _ = writeln!(
report,
"{leave} {} records unchanged; they stay stale until reassessed:",
unchanged.len()
);
for (path, reason) in &unchanged {
let _ = writeln!(report, "- {path}: {reason}");
}
}
Ok(report)
}
Tests
Input 4: outline tests/refactor.rs fn[a_dry_run_reports_the_same_changes_and_writes_nothing]
- File:
tests/refactor.rs - Selector:
fn[a_dry_run_reports_the_same_changes_and_writes_nothing] - Kind:
fn tests/refactor.rs:395–417
// {test}`requirements.refactor.dry_run`
#[test]
fn a_dry_run_reports_the_same_changes_and_writes_nothing() {
let temp = project();
let root = temp.path();
author(root);
move_load(root, "");
let before = snapshot(root);
let args = [
"--map",
"src/config.rs#fn[load]=src/config/load.rs#fn[load]",
];
let dry = refactor(root, &["--dry-run", args[0], args[1]]);
assert!(dry.status.success(), "{dry:?}");
assert_eq!(snapshot(root), before);
let report = stdout(&refactor(root, &args));
assert_eq!(
stdout(&dry)
.replace("Would change", "Changed")
.replace("Would ", ""),
report.replace("Rewrote", "rewrite")
);
}
Referenced definitions
Input 2: requirements selection requirements.refactor.command
requirements.refactor.command:md/requirements/refactor.md:12–19
:::{req} command
`habeas refactor --map <old>=<new> [--map <old>=<new>]... [--dry-run]` MUST
update the repository after the user has already moved the mapped items. It
MUST NOT move or edit code or directives itself, except as
{cite}`requirements.refactor.reference_rewrite` specifies. It MUST list each
record it changed and each record a mapping affects that it left unchanged,
with the reason, and MUST succeed when every mapping is valid.
:::
Other sources
Input 1: requirements selection requirements.refactor.dry_run
requirements.refactor.dry_run:md/requirements/refactor.md:21–25
:::{req} dry_run
With `--dry-run`, `habeas refactor` MUST report every change it would make,
in the same form as {cite}`requirements.refactor.command`, and MUST write
nothing.
:::
Input 5: 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),
})
}
Input 6: outline tests/refactor.rs fn[snapshot]
- File:
tests/refactor.rs - Selector:
fn[snapshot] - Kind:
fn tests/refactor.rs:136–152
/// Every file under `root`, by relative path.
fn snapshot(root: &Path) -> BTreeMap<String, Vec<u8>> {
let mut files = BTreeMap::new();
let mut pending = vec![root.to_owned()];
while let Some(directory) = pending.pop() {
for entry in fs::read_dir(directory).unwrap() {
let path = entry.unwrap().path();
if path.is_dir() {
pending.push(path);
} else {
let relative = path.strip_prefix(root).unwrap().display().to_string();
files.insert(relative, fs::read(&path).unwrap());
}
}
}
files
}
Input 7: outline tests/refactor.rs fn[move_load]
- File:
tests/refactor.rs - Selector:
fn[move_load] - Kind:
fn tests/refactor.rs:159–169
/// Moves `load` unchanged to `src/config/load.rs`.
fn move_load(root: &Path, extra: &str) {
fs::create_dir_all(root.join("src/config")).unwrap();
fs::write(
root.join("src/config/load.rs"),
LOAD_ALONE.replace("read();", &format!("read();{extra}")),
)
.unwrap();
let rest = config_source("").replace(LOAD_ALONE, "");
fs::write(root.join("src/config.rs"), rest).unwrap();
}