feat: directory moves — mirrored batch relocation of every indexed file under a dir

- MovePlan gains moves[] (file move = 1 relocation), left_behind[] for
  unindexable files that deliberately stay, prune_dirs[] applied after the
  batch (remove_dir only succeeds when empty, leftovers keep their home)
- plan::dir: nesting/target-exists guards, merged per-file rewrites
- apply: atomic N-rename batch (per-file git mv), rollback restores every
  move, rewrite and created dir newest-first
- mv_reject accepts dirs; --json adds moved_files/would_move_files only for
  real dir moves (single-file contract byte-identical); summary shows
  (N files) and left-behind count
- engine rollback/prune tests moved to tests/apply.rs (public API; a
  mid-batch failure cannot be forced through the CLI), java-rule e2e split
  into its own binary to keep every file under the 250-line budget
This commit is contained in:
loki5512344 2026-09-15 18:30:33 +02:00
parent b96deeaf2f
commit 6f7a2190e6
Signed by: boba
GPG key ID: 253067914055423B
17 changed files with 842 additions and 293 deletions

View file

@ -136,12 +136,45 @@ pub struct MvData {
pub target: String,
/// Importer files touched by the move.
pub changed_files: Vec<ChangedFile>,
/// Number of files moved (always 1 in Phase 1).
/// Number of files physically moved (1 for a file move, N for a dir).
pub moved: usize,
/// Total specifiers rewritten across all importers.
pub updated_imports: usize,
/// Rename backend: `"git"` (staged in the index) or `"fs"`.
/// Rename backend: `"git"` (every rename staged in the index) or `"fs"`.
pub moved_via: &'static str,
/// Directory moves only: each `(from, to)` relocation (omitted for file moves).
#[serde(skip_serializing_if = "Vec::is_empty")]
pub moved_files: Vec<FileMoveData>,
/// Directory moves only: unindexable files staying in place (omitted when empty).
#[serde(skip_serializing_if = "Vec::is_empty")]
pub left_behind: Vec<String>,
}
/// One `(from, to)` relocation of a directory move.
#[derive(Debug, Serialize)]
pub struct FileMoveData {
/// Project-relative path moved away.
pub from: String,
/// Project-relative destination path.
pub to: String,
}
impl FileMoveData {
fn from(m: &crate::core::plan::FileMove) -> Self {
Self {
from: rel_str(&m.source),
to: rel_str(&m.target),
}
}
}
// Relocation list, present only when the plan moved more than one file.
fn dir_moves(plan: &MovePlan) -> Vec<FileMoveData> {
if plan.moves.len() > 1 {
plan.moves.iter().map(FileMoveData::from).collect()
} else {
Vec::new()
}
}
impl MvData {
@ -152,9 +185,12 @@ impl MvData {
source: rel_str(&plan.source),
target: rel_str(&plan.target),
changed_files,
moved: 1,
moved: plan.moves.len(),
updated_imports: plan.rewrites.len(),
moved_via: if via_git { "git" } else { "fs" },
// A single-file move keeps the old contract: no extra fields.
moved_files: dir_moves(plan),
left_behind: plan.left_behind.iter().map(|p| rel_str(p)).collect(),
}
}
}
@ -175,6 +211,9 @@ pub struct MvDryRunData {
pub diff: String,
/// Rename backend a real run would use: `"git"` or `"fs"`.
pub would_move_via: &'static str,
/// Directory moves only: every relocation that would happen.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub would_move_files: Vec<FileMoveData>,
}
impl MvDryRunData {
@ -191,32 +230,11 @@ impl MvDryRunData {
.collect(),
diff,
would_move_via: if via_git { "git" } else { "fs" },
would_move_files: dir_moves(plan),
}
}
}
/// One unresolvable relative import found by `check`.
#[derive(Debug, Serialize)]
pub struct BrokenImport {
/// Project-relative file declaring the import.
pub file: String,
/// 1-based line of the specifier.
pub line: usize,
/// Specifier text as written.
pub import: String,
/// Stable reason code, currently always `"file_not_found"`.
pub reason: &'static str,
}
/// Success payload of `check --json` (flattened under the envelope).
#[derive(Debug, Serialize)]
pub struct CheckData {
/// Broken imports, sorted by file then line.
pub broken_imports: Vec<BrokenImport>,
/// Number of broken imports (kept as an explicit counter for agents).
pub total: usize,
}
/// Serialize `value` as pretty JSON to stdout.
pub fn print<T: Serialize>(value: &T) {
match serde_json::to_string_pretty(value) {

View file

@ -17,7 +17,7 @@ use crate::core::index::Index;
use crate::core::plan::{self, MovePlan};
use crate::core::{self, JmoveError, JmoveResult};
use json::{CheckData, Envelope, ErrorData, MvData, MvDryRunData};
use json::{Envelope, ErrorData, MvData, MvDryRunData};
/// jmove — move source files, keep every import intact.
#[derive(Debug, Parser)]
@ -204,7 +204,7 @@ fn check(root: &Path, source_root: Option<&Path>, json: bool) -> Flow<i32> {
if json {
let total = broken.len();
let data = CheckData {
let data = output::CheckData {
broken_imports: broken,
total,
};

View file

@ -4,6 +4,8 @@
//! Pure functions returning data, except [`report_check`] and
//! [`print_error`] which perform the only I/O (stdout and stderr).
use serde::Serialize;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
@ -11,7 +13,7 @@ use crate::core::index::Index;
use crate::core::plan::{MovePlan, Rewrite};
use crate::core::{JmoveResult, rel_str};
use super::json::{BrokenImport, Change, ChangedFile, ErrorData};
use super::json::{Change, ChangedFile, ErrorData};
/// `check` stdout line when the project has no broken imports.
const CHECK_CLEAN: &str = "check: no broken imports found";
@ -107,7 +109,8 @@ pub fn mv_reject(root: &Path, source: &Path, target: &Path) -> Option<ErrorData>
let msg = "source and target are the same path".into();
return bad("INVALID_ARGUMENT", msg, "pick a different destination");
}
if !root.join(source).is_file() {
let src_path = root.join(source);
if !src_path.is_file() && !src_path.is_dir() {
let msg = format!("source file '{}' does not exist", rel_str(source));
return bad(
"SOURCE_NOT_FOUND",
@ -137,14 +140,23 @@ pub fn mv_reject(root: &Path, source: &Path, target: &Path) -> Option<ErrorData>
}
/// `moved src -> tgt, updated N imports in M files` success summary,
/// noting when the rename went through `git mv`.
/// noting the `git mv` backend and, for directory moves, the file count
/// and anything unindexable that stays behind.
#[must_use]
pub fn mv_summary(plan: &MovePlan, via_git: bool) -> String {
let imports = plan.rewrites.len();
let files = group_by_file(&plan.rewrites).len();
let git = if via_git { " (via git mv)" } else { "" };
let batch = match plan.moves.len() {
1 => String::new(),
n => format!(" ({n} files)"),
};
let left = match plan.left_behind.len() {
0 => String::new(),
n => format!(", {} unsupported {} left behind", n, plural(n, "file")),
};
format!(
"moved {} -> {}{git}, updated {} {} in {} {}",
"moved {} -> {}{batch}{git}, updated {} {} in {} {}{left}",
rel_str(&plan.source),
rel_str(&plan.target),
imports,
@ -186,3 +198,25 @@ pub(crate) fn plural(count: usize, noun: &str) -> String {
format!("{noun}s")
}
}
/// One unresolvable relative import found by `check`.
#[derive(Debug, Serialize)]
pub struct BrokenImport {
/// Project-relative file declaring the import.
pub file: String,
/// 1-based line of the specifier.
pub line: usize,
/// Specifier text as written.
pub import: String,
/// Stable reason code, currently always `"file_not_found"`.
pub reason: &'static str,
}
/// Success payload of `check --json` (flattened under the envelope).
#[derive(Debug, Serialize)]
pub struct CheckData {
/// Broken imports, sorted by file then line.
pub broken_imports: Vec<BrokenImport>,
/// Number of broken imports (kept as an explicit counter for agents).
pub total: usize,
}

View file

@ -18,8 +18,10 @@ use crate::core::{JmoveResult, rel_str};
pub fn render_diff(root: &Path, plan: &MovePlan) -> JmoveResult<String> {
let mut out = render_edits_diff(root, &group_by_file(plan))?;
if !out.is_empty() {
let (src, dst) = (rel_str(&plan.source), rel_str(&plan.target));
out.push_str(&format!("move {src} -> {dst}\n"));
for m in &plan.moves {
let (src, dst) = (rel_str(&m.source), rel_str(&m.target));
out.push_str(&format!("move {src} -> {dst}\n"));
}
}
Ok(out)
}
@ -47,7 +49,7 @@ pub fn render_edits_diff(
mod tests {
use super::render_diff;
use crate::core::JmoveResult;
use crate::core::plan::{MovePlan, Rewrite};
use crate::core::plan::{FileMove, MovePlan, Rewrite};
use std::path::Path;
const OLD: &str = "import {\n fmt,\n} from '../lib/fmt';\n";
@ -56,12 +58,25 @@ mod tests {
MovePlan {
source: "lib/fmt.ts".into(),
target: "deep/fmt.ts".into(),
moves: vec![
FileMove {
source: "lib/fmt.ts".into(),
target: "deep/fmt.ts".into(),
},
// A second move proves the dir flavour renders one line each.
FileMove {
source: "lib/gfx.ts".into(),
target: "deep/gfx.ts".into(),
},
],
rewrites: vec![Rewrite {
file: "src/app.ts".into(),
span: 24..34,
old_text: "../lib/fmt".into(),
new_text: "../deep/fmt".into(),
}],
left_behind: Vec::new(),
prune_dirs: Vec::new(),
}
}
@ -74,7 +89,10 @@ mod tests {
assert!(diff.contains("--- src/app.ts") && diff.contains("+++ src/app.ts"));
assert!(diff.contains("@@"));
assert!(diff.contains("-} from '../lib/fmt';") && diff.contains("+} from '../deep/fmt';"));
assert!(diff.ends_with("move lib/fmt.ts -> deep/fmt.ts\n"));
assert!(
diff.ends_with("move lib/fmt.ts -> deep/fmt.ts\nmove lib/gfx.ts -> deep/gfx.ts\n"),
"{diff}"
);
let mut empty = plan();
empty.rewrites.clear();
assert_eq!(render_diff(dir.path(), &empty)?, "");

View file

@ -22,7 +22,7 @@ use crate::core::Edit;
use crate::core::apply::fsops::{
create_missing_dirs, group_by_file, rewrite_bytes, sibling_temp, write_durable,
};
use crate::core::plan::MovePlan;
use crate::core::plan::{FileMove, MovePlan};
use crate::core::{JmoveError, JmoveResult, rel_str};
/// Summary of a successfully applied plan.
@ -30,22 +30,22 @@ use crate::core::{JmoveError, JmoveResult, rel_str};
pub struct Applied {
/// Number of files whose imports were rewritten.
pub files_rewritten: usize,
/// The moved file's new project-relative path.
/// The moved file's new project-relative path (directory moves: the
/// requested destination, mirroring [`crate::core::plan::MovePlan::target`]).
pub new_path: PathBuf,
/// Whether the physical rename went through `git mv`.
/// Whether every physical rename went through `git mv`.
pub via_git: bool,
}
// Rollback state for one run: originals of rewritten files (newest last),
// dirs created for the target, and the final rename once it happened.
// dirs created for the targets, and the renames once they happened.
#[derive(Default)]
struct Run {
root: PathBuf,
backups: Vec<(PathBuf, Vec<u8>)>,
dirs: Vec<PathBuf>,
// Root-relative (src, dst) of the executed rename.
moved: Option<(PathBuf, PathBuf)>,
via_git: bool,
// Executed root-relative renames (src, dst, went-through-git), oldest first.
moved: Vec<(PathBuf, PathBuf, bool)>,
}
/// Apply `plan` under `root` atomically (see module docs). Rollback is
@ -80,25 +80,45 @@ impl Run {
fn try_apply(&mut self, plan: &MovePlan, mode: GitMode) -> JmoveResult<Applied> {
let by_file = group_by_file(plan);
self.write_all(&by_file)?;
// The move comes last, after every importer was rewritten.
let (src, dst) = (self.root.join(&plan.source), self.root.join(&plan.target));
self.dirs = create_missing_dirs(&dst)?;
// git mv needs the destination dir to exist; tracked sources are
// renamed through git so the change lands staged in the index.
self.via_git = would_use_git(&self.root, &plan.source, mode);
if self.via_git {
git::mv(&self.root, &plan.source, &plan.target)?;
} else {
fs::rename(&src, &dst)?;
// The moves come last, after every importer was rewritten. A
// directory plan is applied file by file in sorted order; any
// failure rolls the whole batch back.
for m in &plan.moves {
self.move_one(mode, m)?;
}
// Directory moves leave their emptied source dirs behind otherwise;
// remove_dir only succeeds when truly empty, so `left_behind` files
// keep their home. This is the last step: nothing can fail after it.
for d in &plan.prune_dirs {
let _ = fs::remove_dir(self.root.join(d));
}
self.moved = Some((plan.source.clone(), plan.target.clone()));
Ok(Applied {
files_rewritten: by_file.len(),
new_path: plan.target.clone(),
via_git: self.via_git,
via_git: !self.moved.is_empty() && self.moved.iter().all(|(_, _, g)| *g),
})
}
fn move_one(&mut self, mode: GitMode, m: &FileMove) -> JmoveResult<()> {
let (src, dst) = (self.root.join(&m.source), self.root.join(&m.target));
for created in create_missing_dirs(&dst)? {
self.dirs.push(created);
}
// git mv needs the destination dir to exist; tracked sources are
// renamed through git so the change lands staged in the index.
let via_git = would_use_git(&self.root, &m.source, mode);
let done = if via_git {
git::mv(&self.root, &m.source, &m.target)
.map(|()| (m.source.clone(), m.target.clone(), true))
} else {
fs::rename(&src, &dst)
.map(|()| (m.source.clone(), m.target.clone(), false))
.map_err(Into::into)
};
self.moved.push(done?);
Ok(())
}
fn try_fix(&mut self, by_file: &BTreeMap<PathBuf, Vec<Edit>>) -> JmoveResult<usize> {
self.write_all(by_file)?;
Ok(by_file.len())
@ -131,8 +151,12 @@ impl Run {
// problems to its message.
fn undo(&mut self, err: JmoveError) -> JmoveError {
let mut problems = Vec::new();
if let Some((src, dst)) = self.moved.take() {
let back = if self.via_git {
for (src, dst, via_git) in self.moved.drain(..).rev() {
// The prune step never runs before a failure, but a later move
// can fail after git mv created target dirs that a rollback
// through git may expect; ensure the original parent exists.
let _ = fs::create_dir_all(self.root.join(&src).parent().unwrap());
let back = if via_git {
git::mv(&self.root, &dst, &src)
} else {
fs::rename(self.root.join(&dst), self.root.join(&src)).map_err(Into::into)
@ -156,94 +180,3 @@ impl Run {
JmoveError::Io(std::io::Error::other(msg))
}
}
#[cfg(test)]
mod tests {
use super::{GitMode, apply};
use crate::core::JmoveResult;
use crate::core::plan::{MovePlan, Rewrite};
use std::fs;
use std::path::{Path, PathBuf};
const OLD: &str = "import {\n fmt,\n} from '../lib/fmt';\n";
const NEW: &str = "import {\n fmt,\n} from '../deep/fmt';\n";
// Byte span of `../lib/fmt` (between the quotes) inside OLD.
const SPAN: std::ops::Range<usize> = 24..34;
// Plan moving lib/fmt.ts -> deep/fmt.ts, rewriting src/app.ts.
fn plan() -> MovePlan {
let rewrite = Rewrite {
file: "src/app.ts".into(),
span: SPAN,
old_text: "../lib/fmt".into(),
new_text: "../deep/fmt".into(),
};
MovePlan {
source: "lib/fmt.ts".into(),
target: "deep/fmt.ts".into(),
rewrites: vec![rewrite],
}
}
fn mk(dir: &Path, rel: &str, body: &str) -> JmoveResult<()> {
let path = dir.join(rel);
fs::create_dir_all(path.parent().unwrap())?;
fs::write(path, body)?;
Ok(())
}
#[test]
fn apply_rewrites_spans_creates_dirs_and_moves_last() -> JmoveResult<()> {
assert_eq!(&OLD[SPAN], "../lib/fmt"); // sanity: the span is real
let dir = tempfile::TempDir::new()?;
let root = dir.path();
mk(root, "src/app.ts", OLD)?;
mk(root, "lib/fmt.ts", "export const fmt = 1;\n")?;
let applied = apply(root, &plan(), GitMode::Disabled)?;
assert_eq!(
(applied.files_rewritten, &applied.new_path),
(1, &PathBuf::from("deep/fmt.ts"))
);
assert!(!root.join("lib/fmt.ts").exists());
assert_eq!(
fs::read_to_string(root.join("deep/fmt.ts"))?,
"export const fmt = 1;\n"
);
// Only the specifier bytes changed; the layout is kept byte-exact.
assert_eq!(fs::read_to_string(root.join("src/app.ts"))?, NEW);
assert!(!root.join("src/app.ts.jmove-tmp").exists());
Ok(())
}
#[test]
fn apply_rolls_back_when_the_move_fails() -> JmoveResult<()> {
// Missing source: the last rename fails after the rewrite landed.
let dir = tempfile::TempDir::new()?;
mk(dir.path(), "src/app.ts", OLD)?;
let err = apply(dir.path(), &plan(), GitMode::Disabled).expect_err("missing source");
assert!(matches!(err, crate::core::JmoveError::Io(_)), "{err}");
// Importer restored to its exact original bytes; created dirs gone.
assert_eq!(fs::read_to_string(dir.path().join("src/app.ts"))?, OLD);
assert!(!dir.path().join("deep").exists());
Ok(())
}
#[test]
fn apply_rejects_a_stale_plan_without_writing() -> JmoveResult<()> {
// SPAN was computed on OLD's layout; a single-line importer has
// different bytes there, so the run fails before any write.
let other = "import { fmt } from '../lib/fmt';\n";
let dir = tempfile::TempDir::new()?;
let root = dir.path();
mk(root, "src/app.ts", other)?;
mk(root, "lib/fmt.ts", "export const fmt = 1;\n")?;
let err = apply(root, &plan(), GitMode::Disabled).expect_err("span mismatch");
assert!(
matches!(err, crate::core::JmoveError::StaleIndex(_)),
"{err}"
);
assert_eq!(fs::read_to_string(root.join("src/app.ts"))?, other);
assert!(root.join("lib/fmt.ts").exists());
Ok(())
}
}

226
src/core/plan/dir.rs Normal file
View file

@ -0,0 +1,226 @@
//! Directory moves: relocate every indexed file under `source` into the
//! mirrored layout under `target`, merging the per-file rewrite plans.
//!
//! A directory move is exactly N file moves that must apply atomically
//! together, so it reuses the per-file planner and folds its rewrites;
//! a file that imports two moved classes from the same directory simply
//! gets both specifier edits. Files that exist on disk but are not
//! indexable (assets, binaries) cannot be rewritten and would silently
//! stay behind — they are reported as `left_behind` instead of being
//! moved blindly.
use std::path::{Path, PathBuf};
use super::{FileMove, MovePlan, Rewrite};
use crate::core::index::Index;
use crate::core::{JmoveError, JmoveResult, rel_str};
pub(super) fn plan_dir(index: &Index, source: &Path, target: &Path) -> JmoveResult<MovePlan> {
let rejected = |msg: String| JmoveError::PlanRejected(format!("Directory move: {msg}"));
if source.starts_with(target) || target.starts_with(source) {
return Err(rejected(format!(
"'{}' and '{}' are nested; a directory cannot move into or out of itself",
rel_str(source),
rel_str(target)
)));
}
let members: Vec<PathBuf> = index
.files
.sorted()
.into_iter()
.filter(|f| f.starts_with(source))
.collect();
if members.is_empty() {
let s = rel_str(source);
return Err(JmoveError::InvalidArgument(format!(
"source '{s}' has no indexed source files"
)));
}
let moves: Vec<FileMove> = members
.iter()
.map(|f| {
let dst = target.join(f.strip_prefix(source).unwrap_or(f));
FileMove {
source: f.clone(),
target: dst,
}
})
.collect();
for m in &moves {
if index.files.contains(&m.target) {
let t = rel_str(&m.target);
return Err(rejected(format!("target '{t}' already exists")));
}
}
let mut rewrites: Vec<Rewrite> = moves
.iter()
.map(|m| super::file_rewrites(index, &m.source, &m.target))
.collect::<JmoveResult<Vec<_>>>()?
.into_iter()
.flatten()
.collect();
rewrites.sort_by_key(|r| (r.file.clone(), r.span.start));
rewrites.dedup();
let mut prune_dirs = prune_chain(source, &members);
prune_dirs.sort_by_key(|d| std::cmp::Reverse(d.components().count()));
Ok(MovePlan {
source: source.to_path_buf(),
target: target.to_path_buf(),
moves,
rewrites,
left_behind: unsupported_left_behind(index, source),
prune_dirs,
})
}
// Every directory that loses files: the moved members' parent chains up to
// and including `source` itself.
fn prune_chain(source: &Path, members: &[PathBuf]) -> Vec<PathBuf> {
let mut out: Vec<PathBuf> = Vec::new();
for m in members {
let mut dir = m.parent().unwrap_or(Path::new("")).to_path_buf();
loop {
if dir == source {
if !out.contains(&source.to_path_buf()) {
out.push(source.to_path_buf());
}
break;
}
if !out.contains(&dir) {
out.push(dir.clone());
}
let Some(up) = dir.parent() else { break };
dir = up.to_path_buf();
}
}
out
}
// Real files anywhere under `source` that the index does not know (and
// therefore this plan will not move). Walked with the same gitignore rules
// as the scanner; hidden paths are nobody's source files and skipped.
fn unsupported_left_behind(index: &Index, source: &Path) -> Vec<PathBuf> {
let mut out = Vec::new();
let walk = ignore::WalkBuilder::new(index.root.join(source))
.require_git(false)
.build();
for entry in walk.flatten() {
if entry.path_is_symlink() || !entry.file_type().is_some_and(|t| t.is_file()) {
continue;
}
let Ok(stripped) = entry.path().strip_prefix(&index.root) else {
continue;
};
let Some(rel) = crate::core::normalize_rel_path(stripped) else {
continue;
};
let hidden = rel
.components()
.any(|c| c.as_os_str().to_string_lossy().starts_with('.'));
if !hidden && !index.files.contains(&rel) {
out.push(rel);
}
}
out.sort();
out
}
/// Shared `#[cfg(test)]` graph builders for the plan submodules.
#[cfg(test)]
pub(crate) mod tests_support {
use std::ops::Range;
use std::path::PathBuf;
use crate::core::index::ResolvedImport;
use crate::parser::ImportRecord;
/// Hand-wired resolved edge: plan tests never touch the parser.
pub(crate) fn edge(spec: &str, span: Range<usize>, target: &str) -> ResolvedImport {
let record = ImportRecord {
specifier: spec.into(),
span,
is_dynamic: false,
};
ResolvedImport {
record,
target: Some(PathBuf::from(target)),
}
}
}
#[cfg(test)]
mod tests {
use crate::core::JmoveResult;
use crate::core::index::Index;
use crate::core::plan::plan_move;
use std::fs;
use std::path::{Path, PathBuf};
fn project() -> JmoveResult<tempfile::TempDir> {
let dir = tempfile::TempDir::new()?;
let root = dir.path().to_path_buf();
let write = |rel: &str, body: &str| -> JmoveResult<()> {
let p = root.join(rel);
fs::create_dir_all(p.parent().unwrap())?;
fs::write(p, body)?;
Ok(())
};
write("docs/notes.md", "not source\n")?;
write("lib/a.ts", "export const a = 1;\n")?;
write("lib/b.ts", "export const b = 2;\n")?;
write("lib/data.json", "{}\n")?;
write(
"app.ts",
"import { a } from './lib/a';\nimport { b } from './lib/b';\n",
)?;
write("deep/c.ts", "import { a } from '../lib/a';\n")?;
Ok(dir)
}
#[test]
fn dir_plan_moves_every_indexed_file_and_merges_rewrites() -> JmoveResult<()> {
let dir = project()?;
let index = Index::build(dir.path())?;
let plan = plan_move(&index, Path::new("lib"), Path::new("core/lib"))?;
assert_eq!(plan.prune_dirs, [PathBuf::from("lib")]);
let moves: Vec<(&str, &str)> = plan
.moves
.iter()
.map(|m| (m.source.to_str().unwrap(), m.target.to_str().unwrap()))
.collect();
assert_eq!(
moves,
[("lib/a.ts", "core/lib/a.ts"), ("lib/b.ts", "core/lib/b.ts"),]
);
// app.ts (root) imports both moved modules: two merged specifier
// edits; deep/c.ts gets its own relative rewrite.
let app: Vec<_> = plan
.rewrites
.iter()
.filter(|r| r.file == Path::new("app.ts"))
.map(|r| r.new_text.as_str())
.collect();
assert_eq!(app, ["./core/lib/a", "./core/lib/b"]);
// The unindexed JSON would stay on disk: report, never silently move.
assert_eq!(plan.left_behind, [PathBuf::from("lib/data.json")]);
Ok(())
}
#[test]
fn dir_plan_rejects_nested_and_empty_moves() -> JmoveResult<()> {
let dir = project()?;
let index = Index::build(dir.path())?;
let err = plan_move(&index, Path::new("lib"), Path::new("lib/sub")).unwrap_err();
assert!(
matches!(err, crate::core::JmoveError::PlanRejected(_)),
"{err}"
);
// `docs` exists but holds no indexable file: nothing to move.
let err = plan_move(&index, Path::new("docs"), Path::new("core")).unwrap_err();
assert!(
matches!(err, crate::core::JmoveError::InvalidArgument(_)),
"{err}"
);
Ok(())
}
}

View file

@ -2,12 +2,14 @@
//!
//! A plan is pure data (no disk writes), so dry-run and `--json` can render
//! it without touching the filesystem. Specifier arithmetic lives in
//! [`specifier`]; the Java package/directory flavour in [`java`].
//! [`specifier`]; the Java package/directory flavour in [`java`], and the
//! mirrored batch move of a whole directory in [`dir`].
mod dir;
mod java;
mod specifier;
#[cfg(test)]
pub(crate) mod tests_support;
pub(crate) use dir::tests_support;
mod specifier;
pub use specifier::relative_specifier;
@ -42,24 +44,44 @@ impl From<&Rewrite> for Edit {
}
}
/// Complete plan for moving `source` to `target`.
/// One physical file relocation inside a plan.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MovePlan {
/// Project-relative path being moved.
pub struct FileMove {
/// Project-relative file being moved.
pub source: PathBuf,
/// Project-relative destination path.
pub target: PathBuf,
/// Specifier rewrites, sorted by (file, span).
pub rewrites: Vec<Rewrite>,
}
/// Compute the rewrite plan for `source -> target`.
/// Complete plan for moving `source` to `target`: a file move produces one
/// [`FileMove`], a directory move one per indexed member (see [`dir`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MovePlan {
/// Requested source: the file, or the directory whose members move.
pub source: PathBuf,
/// Requested destination.
pub target: PathBuf,
/// Every physical relocation, in sorted source order.
pub moves: Vec<FileMove>,
/// Specifier/package rewrites, merged across moves, sorted by (file, span).
pub rewrites: Vec<Rewrite>,
/// Directory moves only: real files under `source` that no plan step
/// moves (unindexable assets) — reported, never silently relocated.
pub left_behind: Vec<PathBuf>,
/// Directory moves only: source directories to prune (deepest first)
/// once every move landed. Removal only succeeds when a directory is
/// empty, so `left_behind` files keep their home in place — exactly right.
pub prune_dirs: Vec<PathBuf>,
}
/// Compute the rewrite plan for `source -> target`; a `source` that is a
/// directory on disk becomes a mirrored move of all indexed members below it.
///
/// TS/JS: every indexed import whose resolved target equals `source` gets a
/// new relative specifier from the importer's directory to `target` (see
/// [`relative_specifier`]). Java moves additionally rewrite the moved file's
/// `package` declaration (see [`java`]). Rewrites whose result equals the
/// old specifier are dropped; the result is sorted by (file, span).
/// TS/JS: every indexed import whose resolved target equals a moved file gets
/// a new relative specifier from the importer's directory to its destination
/// (see [`relative_specifier`]). Java moves additionally rewrite the moved
/// file's `package` declaration (see [`java`]). Rewrites whose result equals
/// the old specifier are dropped; the result is sorted by (file, span).
pub fn plan_move(index: &Index, source: &Path, target: &Path) -> JmoveResult<MovePlan> {
let rel = |label: &str, p: &Path| match normalize_rel_path(p) {
Some(r) => Ok(r),
@ -69,36 +91,54 @@ pub fn plan_move(index: &Index, source: &Path, target: &Path) -> JmoveResult<Mov
))),
};
let (source, target) = (rel("source path", source)?, rel("target path", target)?);
if source == target {
return Err(JmoveError::PlanRejected(
"source and target are the same".into(),
));
}
// A directory on disk turns the command into a mirrored batch move.
if index.root.join(&source).is_dir() {
return dir::plan_dir(index, &source, &target);
}
if !index.files.contains(&source) {
let s = rel_str(&source);
return Err(JmoveError::InvalidArgument(format!(
"source '{s}' is not an indexed file"
)));
}
if source == target {
return Err(JmoveError::PlanRejected(
"source and target are the same".into(),
));
}
if index.files.contains(&target) {
let t = rel_str(&target);
return Err(JmoveError::PlanRejected(format!(
"target '{t}' already exists"
)));
}
let rewrites = if SourceLanguage::for_path(&source) == Some(SourceLanguage::Java) {
java::java_rewrites(index, &source, &target)?
} else {
ts_rewrites(index, &source, &target)
};
let rewrites = file_rewrites(index, &source, &target)?;
Ok(MovePlan {
source,
target,
source: source.clone(),
target: target.clone(),
moves: vec![FileMove { source, target }],
rewrites,
left_behind: Vec::new(),
prune_dirs: Vec::new(),
})
}
/// The per-file rewrite set: Java moves rewrite the `package` declaration
/// too; shared by single-file and directory planning.
pub(super) fn file_rewrites(
index: &Index,
source: &Path,
target: &Path,
) -> JmoveResult<Vec<Rewrite>> {
Ok(
if SourceLanguage::for_path(source) == Some(SourceLanguage::Java) {
java::java_rewrites(index, source, target)?
} else {
ts_rewrites(index, source, target)
},
)
}
// Relative-specifier rewrites for the TS/JS flavour of the graph.
fn ts_rewrites(index: &Index, source: &Path, target: &Path) -> Vec<Rewrite> {
let mut rewrites = Vec::new();
@ -126,10 +166,10 @@ fn ts_rewrites(index: &Index, source: &Path, target: &Path) -> Vec<Rewrite> {
#[cfg(test)]
mod tests {
use super::tests_support::edge;
use super::{Rewrite, plan_move};
use crate::core::JmoveError;
use crate::core::index::{Index, ResolvedImport};
use crate::core::plan::tests_support::edge;
use std::path::{Path, PathBuf};
fn index_with(files: &[&str], imports: &[(&str, Vec<ResolvedImport>)]) -> Index {
@ -170,6 +210,7 @@ mod tests {
new_text: "./sub/deep/s".into(),
}
);
assert_eq!(plan.moves.len(), 1);
}
#[test]

View file

@ -1,20 +0,0 @@
//! Shared `#[cfg(test)]` graph builders for the plan submodules.
use std::ops::Range;
use std::path::PathBuf;
use crate::core::index::ResolvedImport;
use crate::parser::ImportRecord;
/// Hand-wired resolved edge: plan tests never touch the parser.
pub(crate) fn edge(spec: &str, span: Range<usize>, target: &str) -> ResolvedImport {
let record = ImportRecord {
specifier: spec.into(),
span,
is_dynamic: false,
};
ResolvedImport {
record,
target: Some(PathBuf::from(target)),
}
}