Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions atomic-cli/src/commands/memory/new.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,19 @@ impl Command for MemoryNew {
let id = self.id.clone().unwrap_or_else(generate_ulid_lowercased);
let vault_path = bridge::normalize_memory_path(&id);

// Do not overwrite a memory or invalidate its attestation.
if repo
.vault_retrieve(&vault_path)
.map_err(CliError::Repository)?
.is_some()
{
return Err(CliError::InvalidArgument {
message: format!(
"memory '{id}' already exists at .vault/{vault_path}; choose a different --id"
),
});
}

// Build the frontmatter SPINE as FLAT SCALAR/array fields only (so it
// survives yaml_frontmatter_to_json round-trip). Do NOT write
// attributedTo/proof/contentHash — attest fills those. createdAt is
Expand Down Expand Up @@ -304,4 +317,61 @@ mod tests {
assert_eq!(node.derived_from[0], "urn:atomic:intent:demo-1");
assert!(node.text.contains("health-check timeout"));
}

#[test]
#[serial_test::serial]
fn test_new_refuses_duplicate_id() {
struct DirGuard {
original: std::path::PathBuf,
}
impl DirGuard {
fn new() -> Self {
Self {
original: std::env::current_dir()
.unwrap_or_else(|_| std::path::PathBuf::from("/")),
}
}
}
impl Drop for DirGuard {
fn drop(&mut self) {
let _ = std::env::set_current_dir(&self.original);
}
}

let _guard = DirGuard::new();
let dir = tempdir().unwrap();
{
let repo = Repository::init(dir.path()).unwrap();
repo.init_vault().unwrap();
}
std::env::set_current_dir(dir.path()).unwrap();

let first = MemoryNew {
kind: "constraint".into(),
about: vec![],
derived_from: vec![],
text: Some("original fact".into()),
id: Some("dup01".into()),
status: "active".into(),
};
first.run().expect("first create succeeds");

let overwrite = MemoryNew {
kind: "preference".into(),
about: vec![],
derived_from: vec![],
text: Some("REPLACED".into()),
id: Some("dup01".into()),
status: "active".into(),
};
let err = overwrite.run().expect_err("duplicate id must be rejected");
assert!(
err.to_string().contains("already exists"),
"unexpected error: {err}"
);

let on_disk = std::fs::read_to_string(dir.path().join(".vault/memory/dup01.md")).unwrap();
assert!(on_disk.contains("original fact"));
assert!(!on_disk.contains("REPLACED"));
}
}
209 changes: 171 additions & 38 deletions atomic-cli/src/commands/mv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
//!
//! Options:
//! -n, --dry-run Show what would be moved without doing it
//! -f, --force Force move even if destination exists
//! -h, --help Print help information
//! ```
//!
Expand Down Expand Up @@ -75,7 +74,6 @@ use crate::output::{print_hint, print_success, print_warning};
/// # Options
///
/// - `--dry-run` / `-n`: Preview what would be moved
/// - `--force` / `-f`: Force move even if destination exists (overwrite tracking)
#[derive(Parser, Debug, Clone)]
#[command(name = "move")]
#[derive(Default)]
Expand All @@ -98,14 +96,6 @@ pub struct Move {
/// modify the repository or filesystem.
#[arg(short = 'n', long = "dry-run")]
pub dry_run: bool,

/// Force move even if destination tracking exists.
///
/// This will overwrite the destination's tracking entry if it exists.
/// The destination file on disk is NOT overwritten unless you explicitly
/// remove it first.
#[arg(short = 'f', long = "force")]
pub force: bool,
}

impl Move {
Expand All @@ -115,7 +105,6 @@ impl Move {
source: source.into(),
destination: destination.into(),
dry_run: false,
force: false,
}
}

Expand All @@ -125,12 +114,6 @@ impl Move {
self
}

/// Builder: set the force flag.
pub fn with_force(mut self, force: bool) -> Self {
self.force = force;
self
}

/// Normalize a path relative to the repository root.
fn normalize_path(&self, repo_root: &Path, path: &str) -> CliResult<String> {
let p = Path::new(path);
Expand Down Expand Up @@ -217,17 +200,30 @@ impl Command for Move {
return Err(CliError::FileNotFound { path: source_path });
}

// Check if destination is already tracked (unless force)
if !self.force
&& repo
.is_tracked(&destination)
.map_err(CliError::Repository)?
// The repository cannot move onto an already tracked path.
if repo
.is_tracked(&destination)
.map_err(CliError::Repository)?
{
return Err(CliError::FileAlreadyTracked {
path: PathBuf::from(&destination),
});
}

// `rename` overwrites existing files, so reject any destination entry.
// `symlink_metadata` also detects dangling symlinks.
let destination_disk = repo_root.join(&destination);
if std::fs::symlink_metadata(&destination_disk).is_ok()
&& !is_same_file(&source_path, &destination_disk)
{
return Err(CliError::InvalidArgument {
message: format!(
"destination '{}' already exists on disk; move it away or choose another name",
destination
),
});
}

// Dry run mode
if self.dry_run {
println!("Would move: {} → {}", source, destination);
Expand Down Expand Up @@ -272,6 +268,19 @@ impl Command for Move {
}
}

/// Returns true when both paths resolve to the same entry.
///
/// This allows case-only renames. Errors return false so moves fail safely.
fn is_same_file(source: &Path, destination: &Path) -> bool {
match (
std::fs::canonicalize(source),
std::fs::canonicalize(destination),
) {
(Ok(source), Ok(destination)) => source == destination,
_ => false,
}
}

// Tests

#[cfg(test)]
Expand All @@ -286,7 +295,6 @@ mod tests {
assert_eq!(cmd.source, "old.rs");
assert_eq!(cmd.destination, "new.rs");
assert!(!cmd.dry_run);
assert!(!cmd.force);
}

#[test]
Expand All @@ -295,7 +303,6 @@ mod tests {
assert!(cmd.source.is_empty());
assert!(cmd.destination.is_empty());
assert!(!cmd.dry_run);
assert!(!cmd.force);
}

#[test]
Expand All @@ -304,22 +311,13 @@ mod tests {
assert!(cmd.dry_run);
}

#[test]
fn test_move_with_force() {
let cmd = Move::new("old.rs", "new.rs").with_force(true);
assert!(cmd.force);
}

#[test]
fn test_move_builder_chain() {
let cmd = Move::new("src/old.rs", "src/new.rs")
.with_dry_run(true)
.with_force(true);
let cmd = Move::new("src/old.rs", "src/new.rs").with_dry_run(true);

assert_eq!(cmd.source, "src/old.rs");
assert_eq!(cmd.destination, "src/new.rs");
assert!(cmd.dry_run);
assert!(cmd.force);
}

// Path Resolution Tests
Expand Down Expand Up @@ -370,15 +368,12 @@ mod tests {

#[test]
fn test_move_clone() {
let cmd = Move::new("old.rs", "new.rs")
.with_dry_run(true)
.with_force(true);
let cmd = Move::new("old.rs", "new.rs").with_dry_run(true);
let cloned = cmd.clone();

assert_eq!(cloned.source, cmd.source);
assert_eq!(cloned.destination, cmd.destination);
assert_eq!(cloned.dry_run, cmd.dry_run);
assert_eq!(cloned.force, cmd.force);
}

// Normalize Path Tests
Expand Down Expand Up @@ -409,4 +404,142 @@ mod tests {
let result = cmd.normalize_path(temp.path(), "/completely/different/path.rs");
assert!(result.is_err());
}

// Run-level Data-Safety Tests

struct DirGuard {
original: PathBuf,
}

impl DirGuard {
fn new() -> Self {
Self {
original: std::env::current_dir().unwrap_or_else(|_| PathBuf::from("/")),
}
}
}

impl Drop for DirGuard {
fn drop(&mut self) {
let _ = std::env::set_current_dir(&self.original);
}
}

fn init_repo_with_tracked(files: &[(&str, &str)]) -> tempfile::TempDir {
let temp = tempfile::tempdir().unwrap();
{
let _repo = atomic_repository::Repository::init(temp.path()).unwrap();
}
for (name, content) in files {
std::fs::write(temp.path().join(name), content).unwrap();
}
std::env::set_current_dir(temp.path()).unwrap();
let add = crate::commands::add::Add::new()
.with_files(files.iter().map(|(n, _)| n.to_string()).collect::<Vec<_>>());
add.run().unwrap();
temp
}

#[test]
#[serial_test::serial]
fn test_move_refuses_existing_untracked_destination() {
let _guard = DirGuard::new();
let temp = init_repo_with_tracked(&[("src.txt", "SOURCE")]);
std::fs::write(temp.path().join("dest.txt"), "PRECIOUS-UNTRACKED").unwrap();

let result = Move::new("src.txt", "dest.txt").run();

assert!(result.is_err(), "move onto an existing file must fail");
let dest = std::fs::read_to_string(temp.path().join("dest.txt")).unwrap();
assert_eq!(dest, "PRECIOUS-UNTRACKED", "destination must be untouched");
let src = std::fs::read_to_string(temp.path().join("src.txt")).unwrap();
assert_eq!(src, "SOURCE", "source must still exist");
}

#[test]
#[serial_test::serial]
fn test_move_refuses_tracked_destination() {
let _guard = DirGuard::new();
let temp = init_repo_with_tracked(&[("a.txt", "A"), ("b.txt", "TRACKED-B")]);

let result = Move::new("a.txt", "b.txt").run();

assert!(result.is_err(), "move onto a tracked file must fail");
assert_eq!(
std::fs::read_to_string(temp.path().join("b.txt")).unwrap(),
"TRACKED-B"
);
assert_eq!(
std::fs::read_to_string(temp.path().join("a.txt")).unwrap(),
"A"
);
}

#[test]
#[serial_test::serial]
fn test_move_into_existing_directory_works() {
let _guard = DirGuard::new();
let temp = init_repo_with_tracked(&[("file.txt", "CONTENT")]);
std::fs::create_dir(temp.path().join("sub")).unwrap();

let result = Move::new("file.txt", "sub").run();

assert!(
result.is_ok(),
"move into a directory failed: {:?}",
result.err()
);
assert_eq!(
std::fs::read_to_string(temp.path().join("sub/file.txt")).unwrap(),
"CONTENT"
);
assert!(!temp.path().join("file.txt").exists());
}

#[test]
#[serial_test::serial]
fn test_move_allows_case_only_rename() {
let _guard = DirGuard::new();
let temp = init_repo_with_tracked(&[("File.txt", "CONTENT")]);

// The destination is the source on case-insensitive filesystems.
let result = Move::new("File.txt", "file.txt").run();

assert!(
result.is_ok(),
"case-only rename must be allowed: {:?}",
result.err()
);
assert_eq!(
std::fs::read_to_string(temp.path().join("file.txt")).unwrap(),
"CONTENT"
);
}

#[test]
#[serial_test::serial]
#[cfg(unix)]
fn test_move_refuses_dangling_symlink_destination() {
let _guard = DirGuard::new();
let temp = init_repo_with_tracked(&[("src.txt", "SOURCE")]);
let dangling = temp.path().join("dangling.txt");
std::os::unix::fs::symlink(temp.path().join("no-such-target"), &dangling).unwrap();

let result = Move::new("src.txt", "dangling.txt").run();

assert!(
result.is_err(),
"move onto a dangling symlink must fail — Path::exists() reports \
false for it, which let rename destroy the link"
);
assert!(
std::fs::symlink_metadata(&dangling).unwrap().is_symlink(),
"the symlink must survive"
);
assert_eq!(
std::fs::read_to_string(temp.path().join("src.txt")).unwrap(),
"SOURCE",
"source must still exist"
);
}
}
Loading