From d917b8f63df0a315606229d3127c823409d7041a Mon Sep 17 00:00:00 2001 From: Vincent Date: Thu, 21 May 2026 01:53:00 -0400 Subject: [PATCH 1/3] fix: reset discards named files without --force, like git restore --- atomic-cli/src/commands/reset.rs | 425 +++++++++++++++------ atomic-cli/src/error.rs | 27 ++ atomic-cli/src/main.rs | 3 - atomic-cli/tests/reset_integration_test.rs | 179 +++++++++ 4 files changed, 522 insertions(+), 112 deletions(-) create mode 100644 atomic-cli/tests/reset_integration_test.rs diff --git a/atomic-cli/src/commands/reset.rs b/atomic-cli/src/commands/reset.rs index 4106300f..10d48e1c 100644 --- a/atomic-cli/src/commands/reset.rs +++ b/atomic-cli/src/commands/reset.rs @@ -12,7 +12,6 @@ //! [FILES]... Optional files/directories to reset (default: all) //! //! Options: -//! --view Reset to a specific view and switch to it //! -n, --dry-run Preview what would be reset without changes //! -f, --force Force reset even with uncommitted changes //! -h, --help Print help information @@ -22,9 +21,10 @@ //! //! The `reset` command: //! 1. Compares working copy with pristine state -//! 2. Restores files to match the view state +//! 2. Restores files to match the last recorded state //! 3. Discards any unrecorded modifications -//! 4. Optionally switches to a different view +//! +//! Switching views is a separate concern handled by `atomic view switch`. //! //! **Warning**: Reset discards uncommitted changes permanently. //! @@ -44,13 +44,6 @@ //! ✓ Reset 1 file //! ``` //! -//! Switch views: -//! ```text -//! $ atomic reset --view main -//! Switching to view 'main'... -//! ✓ Reset working copy to view 'main' -//! ``` -//! //! Dry run (preview): //! ```text //! $ atomic reset --dry-run src/ @@ -61,7 +54,8 @@ use std::path::{Path, PathBuf}; -use atomic_repository::{FileStatus, Repository, StatusOptions}; +use atomic_repository::tracking::TrackingOptions; +use atomic_repository::{FileStatus, Repository, RepositoryStatus, StatusOptions}; use clap::Parser; use crate::commands::{find_repository_root, Command}; @@ -70,6 +64,17 @@ use crate::output::{print_hint, print_success, print_warning}; // Reset Command +/// The result of resetting a single path. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum ResetOutcome { + /// Content was restored from the pristine state. + Restored, + /// An added-but-unrecorded file was untracked (kept on disk). + Untracked, + /// Nothing was done (no pristine content available). + Skipped, +} + /// Reset the working copy to the last recorded state. /// /// The `reset` command restores the working copy to match the pristine state @@ -78,9 +83,8 @@ use crate::output::{print_hint, print_success, print_warning}; /// /// # Behavior /// -/// - Without arguments: Resets entire working copy -/// - With file arguments: Resets only specified files -/// - With `--view`: Switches to that view and resets +/// - Without arguments: Resets entire working copy (requires `--force`) +/// - With file arguments: Resets only the specified files /// /// # Warning /// @@ -95,11 +99,12 @@ pub struct Reset { #[arg(value_name = "FILES")] pub files: Vec, - /// Reset to a specific view and switch to it. + /// Deprecated: switching views is no longer done via reset. /// - /// The working copy will be updated to match the specified view's - /// pristine state. - #[arg(long)] + /// Use `atomic view switch ` instead. Passing `--view` here returns + /// an error pointing to the correct command. This flag is kept only to + /// give a clear migration message and will be removed in a later release. + #[arg(long, hide = true)] pub view: Option, /// Dry run - show what would be reset without doing it. @@ -161,6 +166,29 @@ impl Reset { !self.files.is_empty() } + /// Whether this invocation must be blocked until `--force` is supplied. + /// + /// Only a whole-working-copy reset (no paths named) is guarded, because it + /// would discard *all* uncommitted work. Naming specific files is explicit + /// consent (like `git restore `), and `--force` / `--dry-run` always + /// bypass the guard. + fn requires_force(&self, has_changes: bool) -> bool { + !self.is_partial_reset() && has_changes && !self.force && !self.dry_run + } + + /// Message shown when there is nothing to reset. + /// + /// For a partial reset we must not claim the whole working copy is clean + /// (other paths may still be dirty) — only that the named paths had + /// nothing to reset. + fn nothing_to_reset_message(&self) -> &'static str { + if self.is_partial_reset() { + "Nothing to reset for the specified path(s)" + } else { + "Nothing to reset - working copy is clean" + } + } + /// Normalize a path relative to the repository root. /// /// If the path is absolute and under the repo root, strips the prefix. @@ -201,28 +229,43 @@ impl Reset { false } - /// Get files that need to be reset based on status. - fn get_files_to_reset(&self, repo: &Repository) -> CliResult> { - let status = repo - .status(StatusOptions::default()) - .map_err(CliError::Repository)?; + /// Status options used by reset. + /// + /// Reset only ever touches *tracked* dirty files (Modified / Deleted / + /// Added), so we skip the (potentially expensive) untracked-file scan. + fn status_options() -> StatusOptions { + StatusOptions { + include_untracked: false, + ..StatusOptions::default() + } + } + /// Get the files that need to be reset, paired with their status. + /// + /// Derives the list from a status that was already computed by the + /// caller (so reset doesn't walk the tree twice). Only tracked, dirty + /// states are considered; untracked files are never touched. + /// + /// - `Modified` / `Deleted`: content will be restored from pristine. + /// - `Added`: tracking will be undone (file kept on disk as untracked), + /// so that `status` stops reporting a pending "new file" change. + fn get_files_to_reset(&self, status: &RepositoryStatus) -> Vec<(PathBuf, FileStatus)> { let mut files_to_reset = Vec::new(); for entry in status.entries() { - // Only reset modified, deleted files (not untracked) - match entry.status() { - FileStatus::Modified | FileStatus::Deleted => { + let file_status = entry.status(); + match file_status { + FileStatus::Modified | FileStatus::Deleted | FileStatus::Added => { let path_str = entry.path().to_string_lossy(); if self.matches_filter(&path_str) { - files_to_reset.push(entry.path().to_path_buf()); + files_to_reset.push((entry.path().to_path_buf(), file_status)); } } _ => {} } } - Ok(files_to_reset) + files_to_reset } /// Execute dry-run for a single file - output pristine content to stdout. @@ -247,9 +290,31 @@ impl Reset { } } - /// Reset a single file to pristine state. - fn reset_file(&self, repo: &Repository, repo_root: &Path, path: &Path) -> CliResult { - // Get content from pristine + /// Reset a single file according to its status. + /// + /// - `Added` (tracked but not recorded): undo tracking. The file stays + /// on disk and becomes untracked, so we never destroy content the user + /// created. This is what makes `reset ` honest about the + /// "new file" change reported by `status`. + /// - Otherwise (`Modified` / `Deleted`): restore the file's content from + /// the pristine state. + /// + /// Returns the outcome so the caller can report it accurately. + fn reset_file( + &self, + repo: &Repository, + repo_root: &Path, + path: &Path, + status: FileStatus, + ) -> CliResult { + if status == FileStatus::Added { + // Undo the `add`: stop tracking, but keep the file on disk. + repo.remove(path, TrackingOptions::default().with_recursive(false)) + .map_err(CliError::Repository)?; + return Ok(ResetOutcome::Untracked); + } + + // Restore content from pristine. let content = repo.get_file_content(path).map_err(|e| { CliError::Internal(anyhow::anyhow!("Failed to get file content: {}", e)) })?; @@ -258,7 +323,8 @@ impl Reset { match content { Some(bytes) => { - // Ensure parent directory exists + // Ensure parent directory exists (a Deleted file may have had + // its directory removed too). if let Some(parent) = full_path.parent() { std::fs::create_dir_all(parent).map_err(|e| { CliError::Internal(anyhow::anyhow!("Failed to create directory: {}", e)) @@ -270,31 +336,14 @@ impl Reset { CliError::Internal(anyhow::anyhow!("Failed to write file: {}", e)) })?; - Ok(true) + Ok(ResetOutcome::Restored) } None => { - // File doesn't exist in pristine - it was added but not recorded - // For reset, we leave it as-is (it's untracked) - Ok(false) + // No pristine content available; nothing safe to do. + Ok(ResetOutcome::Skipped) } } } - - /// Switch to a different view. - fn switch_view(&self, repo: &mut Repository, view_name: &str) -> CliResult<()> { - // Check view exists - if !repo.view_exists(view_name).map_err(CliError::Repository)? { - return Err(CliError::ViewNotFound { - name: view_name.to_string(), - }); - } - - // Switch view - repo.set_current_view(view_name) - .map_err(CliError::Repository)?; - - Ok(()) - } } impl Default for Reset { @@ -308,50 +357,60 @@ impl Command for Reset { /// /// # Process /// - /// 1. Find and open the repository - /// 2. Check for uncommitted changes (unless --force) - /// 3. If --view, switch to that view + /// 1. Reject `--view` (use `atomic view switch` instead) + /// 2. Find and open the repository + /// 3. Guard a whole-tree reset behind `--force` /// 4. Determine files to reset - /// 5. If --dry-run, preview changes + /// 5. If `--dry-run`, preview changes /// 6. Otherwise, reset files to pristine state fn run(&self) -> CliResult<()> { + // `reset` is for discarding working-copy changes only. Switching views + // is a separate concern owned by `atomic view switch`, which performs a + // proper materialization. Reset must not reimplement that, so reject + // `--view` with a clear migration message rather than half-doing it. + if let Some(view_name) = &self.view { + return Err(CliError::InvalidArgument { + message: format!( + "'atomic reset --view' is no longer supported. \ + Use 'atomic view switch {view_name}' to switch views." + ), + }); + } + // Find repository let repo_root = find_repository_root()?; - let mut repo = Repository::open(&repo_root).map_err(CliError::Repository)?; + let repo = Repository::open(&repo_root).map_err(CliError::Repository)?; - // Get current status + // Compute status once. Reset only touches tracked files, so we skip + // the untracked scan, and we reuse this single status for both the + // safety guard and the file list (no second tree walk). let status = repo - .status(StatusOptions::default()) + .status(Self::status_options()) .map_err(CliError::Repository)?; let has_changes = !status.is_clean(); - // Check for uncommitted changes (unless force) - if has_changes && !self.force && !self.dry_run { - print_warning("Cannot reset: there are uncommitted changes."); - print_hint("Use 'atomic diff' to see changes"); - print_hint("Use 'atomic reset --force' to discard changes"); - print_hint("Use 'atomic record' to save changes first"); - return Err(CliError::Internal(anyhow::anyhow!( - "Uncommitted changes would be lost" - ))); - } - - // Handle view switching - if let Some(ref view_name) = self.view { - if !self.dry_run { - println!("Switching to view '{}'...", view_name); - self.switch_view(&mut repo, view_name)?; - } else { - println!("Would switch to view '{}'", view_name); - } + // Safety guard: only a whole-working-copy reset (no paths named) + // requires --force. Naming specific files is explicit consent to + // discard them, exactly like `git restore `. + if self.requires_force(has_changes) { + return Err(CliError::RequiresForce { + operation: "reset".to_string(), + }); } - // Get files to reset - let files_to_reset = self.get_files_to_reset(&repo)?; - - // Handle dry-run for single file (output content) - if self.dry_run && self.files.len() == 1 && files_to_reset.len() <= 1 { + // Determine files to reset, paired with their status. + let files_to_reset = self.get_files_to_reset(&status); + + // Handle dry-run for a single file by printing its pristine content to + // stdout (useful for piping). This only makes sense for files that + // have pristine content; an Added file would be untracked, not + // restored, so fall through to the listing branch below. + let single_added = files_to_reset + .first() + .map(|(_, s)| *s == FileStatus::Added) + .unwrap_or(false); + if self.dry_run && self.files.len() == 1 && files_to_reset.len() <= 1 && !single_added { let path = &self.files[0]; return self.dry_run_single_file(&repo, path); } @@ -359,10 +418,14 @@ impl Command for Reset { // Dry run mode - just show what would happen if self.dry_run { if files_to_reset.is_empty() { - println!("Nothing to reset - working copy is clean"); + println!("{}", self.nothing_to_reset_message()); } else { - for path in &files_to_reset { - println!("Would reset: {}", path.display()); + for (path, file_status) in &files_to_reset { + if *file_status == FileStatus::Added { + println!("Would untrack: {} (kept on disk)", path.display()); + } else { + println!("Would reset: {}", path.display()); + } } println!(); print_hint(&format!( @@ -375,14 +438,7 @@ impl Command for Reset { // Check if there's anything to reset if files_to_reset.is_empty() { - if let Some(view) = &self.view { - print_success(&format!( - "Switched to view '{}' (working copy already clean)", - view - )); - } else { - println!("Nothing to reset - working copy is clean"); - } + println!("{}", self.nothing_to_reset_message()); return Ok(()); } @@ -392,17 +448,20 @@ impl Command for Reset { let mut reset_count = 0; let mut error_count = 0; - for path in &files_to_reset { + for (path, file_status) in &files_to_reset { let path_display = path.display(); - match self.reset_file(&repo, &repo_root, path) { - Ok(true) => { + match self.reset_file(&repo, &repo_root, path, *file_status) { + Ok(ResetOutcome::Restored) => { println!(" Reset: {}", path_display); reset_count += 1; } - Ok(false) => { - // File not in pristine (was newly added) - // We don't delete untracked files by default + Ok(ResetOutcome::Untracked) => { + println!(" Untracked: {} (kept on disk)", path_display); + reset_count += 1; + } + Ok(ResetOutcome::Skipped) => { + // No pristine content to restore; nothing to do. } Err(e) => { print_warning(&format!("Failed to reset '{}': {}", path_display, e)); @@ -414,15 +473,7 @@ impl Command for Reset { // Summary println!(); if reset_count > 0 { - if let Some(ref view_name) = self.view { - print_success(&format!( - "Reset {} to view '{}'", - format_count(reset_count, "file"), - view_name - )); - } else { - print_success(&format!("Reset {}", format_count(reset_count, "file"))); - } + print_success(&format!("Reset {}", format_count(reset_count, "file"))); } if error_count > 0 { @@ -624,4 +675,160 @@ mod tests { assert_eq!(cloned.view, cmd.view); assert_eq!(cloned.force, cmd.force); } + + // Guard Logic Tests (requires_force) + + #[test] + fn test_requires_force_partial_reset_not_blocked() { + // Naming a file is explicit consent — never blocked, even when the + // tree has changes. This is the core bug fix. + let cmd = Reset::new().with_files(vec!["file.txt".to_string()]); + assert!(!cmd.requires_force(true)); + } + + #[test] + fn test_requires_force_whole_tree_blocked() { + let cmd = Reset::new(); + assert!(cmd.requires_force(true)); + } + + #[test] + fn test_requires_force_whole_tree_with_force_passes() { + let cmd = Reset::new().with_force(true); + assert!(!cmd.requires_force(true)); + } + + #[test] + fn test_requires_force_clean_tree_passes() { + let cmd = Reset::new(); + assert!(!cmd.requires_force(false)); + } + + #[test] + fn test_requires_force_dry_run_passes() { + let cmd = Reset::new().with_dry_run(true); + assert!(!cmd.requires_force(true)); + } + + #[test] + fn test_reset_view_is_rejected_before_touching_repo() { + // `--view` is rejected up front (before any filesystem access), with a + // message pointing at `atomic view switch`. + let cmd = Reset::new().with_view("feature"); + match cmd.run() { + Err(CliError::InvalidArgument { message }) => { + assert!(message.contains("view switch")); + assert!(message.contains("feature")); + } + other => panic!("expected InvalidArgument for --view, got {other:?}"), + } + } + + // Empty-result Message Tests + + #[test] + fn test_nothing_to_reset_message_partial() { + let cmd = Reset::new().with_files(vec!["a.txt".to_string()]); + assert_eq!( + cmd.nothing_to_reset_message(), + "Nothing to reset for the specified path(s)" + ); + } + + #[test] + fn test_nothing_to_reset_message_whole_tree() { + let cmd = Reset::new(); + assert_eq!( + cmd.nothing_to_reset_message(), + "Nothing to reset - working copy is clean" + ); + } + + // End-to-end Behavior Tests (real repository) + + use std::fs; + use tempfile::TempDir; + + /// Initialize a repository in a temp dir. Returns the guard, repo, and root. + fn test_repo() -> (TempDir, Repository, PathBuf) { + let dir = TempDir::new().expect("create tempdir"); + let root = dir.path().to_path_buf(); + let repo = Repository::init(&root).expect("init repository"); + (dir, repo, root) + } + + #[test] + fn test_reset_modified_restores_pristine_content() { + let (_dir, repo, root) = test_repo(); + let path = Path::new("file.txt"); + fs::write(root.join(path), b"recorded\n").unwrap(); + repo.add(path, TrackingOptions::default()).unwrap(); + repo.record_all("init").unwrap(); + + // Local edit that we want to discard. + fs::write(root.join(path), b"local edit\n").unwrap(); + + let cmd = Reset::new(); + let outcome = cmd + .reset_file(&repo, &root, path, FileStatus::Modified) + .unwrap(); + + assert_eq!(outcome, ResetOutcome::Restored); + assert_eq!(fs::read(root.join(path)).unwrap(), b"recorded\n"); + } + + #[test] + fn test_reset_deleted_restores_file_from_pristine() { + let (_dir, repo, root) = test_repo(); + let path = Path::new("file.txt"); + fs::write(root.join(path), b"recorded\n").unwrap(); + repo.add(path, TrackingOptions::default()).unwrap(); + repo.record_all("init").unwrap(); + + // Delete it on disk; reset should bring it back. + fs::remove_file(root.join(path)).unwrap(); + assert!(!root.join(path).exists()); + + let cmd = Reset::new(); + let outcome = cmd + .reset_file(&repo, &root, path, FileStatus::Deleted) + .unwrap(); + + assert_eq!(outcome, ResetOutcome::Restored); + assert!(root.join(path).exists()); + assert_eq!(fs::read(root.join(path)).unwrap(), b"recorded\n"); + } + + #[test] + fn test_reset_added_untracks_but_keeps_file_on_disk() { + let (_dir, repo, root) = test_repo(); + let path = Path::new("new.txt"); + fs::write(root.join(path), b"brand new\n").unwrap(); + repo.add(path, TrackingOptions::default()).unwrap(); + // Deliberately NOT recorded → status is `Added`. + + let cmd = Reset::new().with_files(vec!["new.txt".to_string()]); + + // Before: status reports it as a pending Added change. + let before = repo.status(Reset::status_options()).unwrap(); + let listed = cmd.get_files_to_reset(&before); + assert!(listed + .iter() + .any(|(p, s)| p.as_path() == path && *s == FileStatus::Added)); + + let outcome = cmd + .reset_file(&repo, &root, path, FileStatus::Added) + .unwrap(); + assert_eq!(outcome, ResetOutcome::Untracked); + + // File is kept on disk (we never destroy user-created content)... + assert!(root.join(path).exists()); + assert_eq!(fs::read(root.join(path)).unwrap(), b"brand new\n"); + + // ...and status no longer reports a pending change for it, so the + // status hint is no longer lying. + let after = repo.status(Reset::status_options()).unwrap(); + let still_listed = cmd.get_files_to_reset(&after); + assert!(!still_listed.iter().any(|(p, _)| p.as_path() == path)); + } } diff --git a/atomic-cli/src/error.rs b/atomic-cli/src/error.rs index da41f115..6f4baec4 100644 --- a/atomic-cli/src/error.rs +++ b/atomic-cli/src/error.rs @@ -294,6 +294,17 @@ pub enum CliError { message: String, }, + /// A destructive operation was blocked because it would discard + /// uncommitted changes and `--force` was not supplied. + /// + /// This is an expected, user-fixable condition (not a bug): the user + /// asked for a whole-working-copy operation that would throw away work. + #[error("Cannot {operation}: this would discard all uncommitted changes")] + RequiresForce { + /// The operation that was blocked, e.g. "reset". + operation: String, + }, + // Internal Errors /// An unexpected internal error occurred. /// @@ -440,6 +451,7 @@ impl CliError { | Self::RemoteNotFound { .. } | Self::AuthenticationFailed { .. } | Self::InvalidArgument { .. } + | Self::RequiresForce { .. } | Self::InvalidRepository { .. } | Self::InvalidPath { .. } ) @@ -530,6 +542,9 @@ impl CliError { Self::InvalidArgument { .. } => { Some("Run 'atomic --help' for usage information.") } + Self::RequiresForce { .. } => Some( + "Reset specific files with 'atomic reset ...', or use 'atomic reset --force' to discard everything.", + ), Self::Internal(_) => { Some("This appears to be a bug. Please report it at: https://github.com/atomicdotdev/atomic/issues") } @@ -557,6 +572,7 @@ impl CliError { Self::NothingToRecord | Self::Cancelled | Self::FileAlreadyTracked { .. } + | Self::RequiresForce { .. } | Self::ViewAlreadyExists { .. } => 1, // Command-line usage errors @@ -751,6 +767,17 @@ mod tests { ); } + #[test] + fn test_requires_force_is_user_fixable_not_internal() { + let err = CliError::RequiresForce { + operation: "reset".to_string(), + }; + assert!(err.is_user_fixable()); + assert!(!err.is_internal()); + assert_eq!(err.exit_code(), 1); + assert!(err.suggestion().is_some()); + } + #[test] fn test_is_internal() { let err = CliError::Internal(anyhow::anyhow!("something broke")); diff --git a/atomic-cli/src/main.rs b/atomic-cli/src/main.rs index 6b33f564..af1f10b0 100644 --- a/atomic-cli/src/main.rs +++ b/atomic-cli/src/main.rs @@ -231,9 +231,6 @@ enum Commands { /// # Reset specific files /// atomic reset src/main.rs /// - /// # Switch to a different view - /// atomic reset --view main - /// /// # Preview what would be reset /// atomic reset --dry-run /// ``` diff --git a/atomic-cli/tests/reset_integration_test.rs b/atomic-cli/tests/reset_integration_test.rs new file mode 100644 index 00000000..893ff0f5 --- /dev/null +++ b/atomic-cli/tests/reset_integration_test.rs @@ -0,0 +1,179 @@ +//! Integration tests for `atomic reset`, driving the real CLI binary +//! end-to-end (`Reset::run()`), against a temporary repository. +//! +//! These complement the unit tests in `commands/reset.rs` by exercising the +//! full command path: argument parsing, the safety guard, `--view` rejection, +//! and the actual filesystem effects. + +use std::path::Path; +use std::process::{Command, Output}; + +use tempfile::TempDir; + +/// Path to the compiled `atomic` binary (provided by Cargo to integration tests). +const ATOMIC_BIN: &str = env!("CARGO_BIN_EXE_atomic"); + +/// Run `atomic ` inside `dir`. +fn atomic(dir: &Path, args: &[&str]) -> Output { + Command::new(ATOMIC_BIN) + .args(args) + .current_dir(dir) + .output() + .expect("run atomic") +} + +/// Initialize a repo with a single recorded file `file.txt` = "v1\n". +fn repo_with_recorded_file() -> TempDir { + let dir = TempDir::new().expect("tempdir"); + let root = dir.path(); + assert!(atomic(root, &["init"]).status.success()); + std::fs::write(root.join("file.txt"), b"v1\n").unwrap(); + assert!(atomic(root, &["add", "file.txt"]).status.success()); + assert!(atomic(root, &["record", "-m", "rec"]).status.success()); + dir +} + +#[test] +fn reset_named_modified_file_restores_without_force() { + let dir = repo_with_recorded_file(); + let root = dir.path(); + + std::fs::write(root.join("file.txt"), b"local edit\n").unwrap(); + + let out = atomic(root, &["reset", "file.txt"]); + assert!(out.status.success(), "reset should succeed"); + assert_eq!(std::fs::read(root.join("file.txt")).unwrap(), b"v1\n"); +} + +#[test] +fn reset_named_file_not_blocked_by_unrelated_dirty_file() { + let dir = repo_with_recorded_file(); + let root = dir.path(); + std::fs::write(root.join("other.txt"), b"o1\n").unwrap(); + assert!(atomic(root, &["add", "other.txt"]).status.success()); + assert!(atomic(root, &["record", "-m", "two"]).status.success()); + + // Both files dirty; reset only file.txt. + std::fs::write(root.join("file.txt"), b"edit-a\n").unwrap(); + std::fs::write(root.join("other.txt"), b"edit-b\n").unwrap(); + + let out = atomic(root, &["reset", "file.txt"]); + assert!(out.status.success()); + assert_eq!(std::fs::read(root.join("file.txt")).unwrap(), b"v1\n"); + // The unrelated dirty file is untouched. + assert_eq!(std::fs::read(root.join("other.txt")).unwrap(), b"edit-b\n"); +} + +#[test] +fn whole_tree_reset_without_force_is_user_error_not_internal() { + let dir = repo_with_recorded_file(); + let root = dir.path(); + std::fs::write(root.join("file.txt"), b"dirty\n").unwrap(); + + let out = atomic(root, &["reset"]); + assert!(!out.status.success(), "whole-tree reset needs --force"); + assert_eq!(out.status.code(), Some(1), "user-level exit code"); + + let stderr = String::from_utf8_lossy(&out.stderr); + let combined = format!("{}{}", String::from_utf8_lossy(&out.stdout), stderr); + assert!( + combined.contains("Cannot reset"), + "should explain the guard, got: {combined}" + ); + assert!( + !combined.contains("Internal error"), + "must not surface as an internal bug, got: {combined}" + ); + // The file is left untouched when the guard fires. + assert_eq!(std::fs::read(root.join("file.txt")).unwrap(), b"dirty\n"); +} + +#[test] +fn reset_added_file_untracks_and_keeps_it_on_disk() { + let dir = repo_with_recorded_file(); + let root = dir.path(); + + std::fs::write(root.join("new.txt"), b"brand new\n").unwrap(); + assert!(atomic(root, &["add", "new.txt"]).status.success()); + + let out = atomic(root, &["reset", "new.txt"]); + assert!(out.status.success()); + // Kept on disk... + assert!(root.join("new.txt").exists()); + assert_eq!(std::fs::read(root.join("new.txt")).unwrap(), b"brand new\n"); + // ...and no longer a pending change. + let status = atomic(root, &["status"]); + let text = String::from_utf8_lossy(&status.stdout); + assert!( + !text.contains("new file:"), + "added file should no longer be reported as a pending change: {text}" + ); +} + +#[test] +fn dry_run_added_file_reports_untrack_without_erroring() { + let dir = repo_with_recorded_file(); + let root = dir.path(); + + std::fs::write(root.join("new.txt"), b"brand new\n").unwrap(); + assert!(atomic(root, &["add", "new.txt"]).status.success()); + + let out = atomic(root, &["reset", "--dry-run", "new.txt"]); + assert!( + out.status.success(), + "dry-run on an added file must not error" + ); + let combined = format!( + "{}{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ); + assert!( + combined.contains("Would untrack"), + "dry-run should preview an untrack, got: {combined}" + ); + assert!( + !combined.contains("File not found"), + "dry-run must not try to read pristine content for an added file: {combined}" + ); + // Dry run leaves everything as-is. + assert!(root.join("new.txt").exists()); +} + +#[test] +fn reset_view_fails_fast_and_points_to_view_switch() { + // `reset --view` must not silently half-switch views (it used to leave + // stale working-copy content while printing "working copy already clean"). + // It now fails fast and directs the user to `atomic view switch`. + let dir = repo_with_recorded_file(); + let root = dir.path(); + assert!(atomic(root, &["view", "create", "feature"]) + .status + .success()); + + std::fs::write(root.join("file.txt"), b"DIRTY-EDIT\n").unwrap(); + + let out = atomic(root, &["reset", "--force", "--view", "feature"]); + assert!(!out.status.success(), "reset --view should be rejected"); + + let combined = format!( + "{}{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ); + assert!( + combined.contains("view switch"), + "should point users to 'atomic view switch', got: {combined}" + ); + // It must not have touched the working copy or switched the view. + assert_eq!( + std::fs::read(root.join("file.txt")).unwrap(), + b"DIRTY-EDIT\n" + ); + let views = atomic(root, &["view", "list"]); + let views_text = String::from_utf8_lossy(&views.stdout); + assert!( + views_text.contains("* dev"), + "current view must be unchanged (still dev), got: {views_text}" + ); +} From 8db9590f4f52c54f34ae77847e2f8d6a4f127558 Mon Sep 17 00:00:00 2001 From: Vincent Date: Thu, 21 May 2026 02:26:54 -0400 Subject: [PATCH 2/3] refactor: rename reset to restore (keep reset alias), remove --view --- atomic-cli/src/commands/mod.rs | 4 +- .../src/commands/{reset.rs => restore.rs} | 486 +++++++----------- atomic-cli/src/commands/status.rs | 4 +- atomic-cli/src/error.rs | 4 +- atomic-cli/src/main.rs | 24 +- ...on_test.rs => restore_integration_test.rs} | 92 ++-- 6 files changed, 255 insertions(+), 359 deletions(-) rename atomic-cli/src/commands/{reset.rs => restore.rs} (54%) rename atomic-cli/tests/{reset_integration_test.rs => restore_integration_test.rs} (66%) diff --git a/atomic-cli/src/commands/mod.rs b/atomic-cli/src/commands/mod.rs index d257b4c9..435ba299 100644 --- a/atomic-cli/src/commands/mod.rs +++ b/atomic-cli/src/commands/mod.rs @@ -77,7 +77,7 @@ pub mod log; pub mod mv; pub mod record; pub mod remove; -pub mod reset; +pub mod restore; pub mod revise; pub mod split; pub mod stash; @@ -138,7 +138,7 @@ pub use query::Query; pub use record::Record; pub use remote::Remote; pub use remove::Remove; -pub use reset::Reset; +pub use restore::Restore; pub use revise::Revise; pub use split::Split; pub use stash::Stash; diff --git a/atomic-cli/src/commands/reset.rs b/atomic-cli/src/commands/restore.rs similarity index 54% rename from atomic-cli/src/commands/reset.rs rename to atomic-cli/src/commands/restore.rs index 10d48e1c..2c52ab19 100644 --- a/atomic-cli/src/commands/reset.rs +++ b/atomic-cli/src/commands/restore.rs @@ -1,55 +1,58 @@ -//! The `reset` command for restoring working copy to pristine state. +//! The `restore` command for restoring the working copy to pristine state. //! -//! This module implements the `atomic reset` command, which restores the working -//! copy to match the pristine state (last recorded state in the view). +//! This module implements `atomic restore` (the working-copy counterpart of +//! `git restore`), which restores tracked files to match the pristine state +//! (the last recorded state in the current view). It discards unrecorded +//! edits to the named files. +//! +//! The legacy name `atomic reset` is kept as a hidden alias. //! //! # Usage //! //! ```text -//! atomic reset [OPTIONS] [FILES]... +//! atomic restore [OPTIONS] [FILES]... //! //! Arguments: -//! [FILES]... Optional files/directories to reset (default: all) +//! [FILES]... Optional files/directories to restore (default: all) //! //! Options: -//! -n, --dry-run Preview what would be reset without changes -//! -f, --force Force reset even with uncommitted changes +//! -n, --dry-run Preview what would be restored without changes +//! -f, --force Force a whole-tree restore with uncommitted changes //! -h, --help Print help information //! ``` //! //! # Behavior //! -//! The `reset` command: -//! 1. Compares working copy with pristine state +//! The `restore` command: +//! 1. Compares the working copy with the pristine state //! 2. Restores files to match the last recorded state //! 3. Discards any unrecorded modifications //! //! Switching views is a separate concern handled by `atomic view switch`. //! -//! **Warning**: Reset discards uncommitted changes permanently. +//! **Warning**: Restore discards uncommitted changes permanently. //! //! # Examples //! -//! Discard all uncommitted changes: +//! Restore specific files: //! ```text -//! $ atomic reset --force -//! Resetting working copy... -//! ✓ Reset 3 files +//! $ atomic restore src/main.rs +//! Restoring working copy... +//! ✓ Restored 1 file //! ``` //! -//! Reset specific files: +//! Discard all uncommitted changes: //! ```text -//! $ atomic reset src/main.rs -//! Resetting: src/main.rs -//! ✓ Reset 1 file +//! $ atomic restore --force +//! Restoring working copy... +//! ✓ Restored 3 files //! ``` //! //! Dry run (preview): //! ```text -//! $ atomic reset --dry-run src/ -//! Would reset: src/main.rs -//! Would reset: src/lib.rs -//! (dry run - no changes made) +//! $ atomic restore --dry-run src/ +//! Would restore: src/main.rs +//! Would restore: src/lib.rs //! ``` use std::path::{Path, PathBuf}; @@ -62,11 +65,11 @@ use crate::commands::{find_repository_root, Command}; use crate::error::{CliError, CliResult}; use crate::output::{print_hint, print_success, print_warning}; -// Reset Command +// Restore Command -/// The result of resetting a single path. +/// The result of restoring a single path. #[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum ResetOutcome { +enum RestoreOutcome { /// Content was restored from the pristine state. Restored, /// An added-but-unrecorded file was untracked (kept on disk). @@ -75,65 +78,56 @@ enum ResetOutcome { Skipped, } -/// Reset the working copy to the last recorded state. +/// Restore the working copy to the last recorded state. /// -/// The `reset` command restores the working copy to match the pristine state -/// (the last recorded state in the view). This discards any uncommitted -/// changes. +/// The `restore` command restores the working copy to match the pristine +/// state (the last recorded state in the current view). This discards any +/// uncommitted changes to the named files. /// /// # Behavior /// -/// - Without arguments: Resets entire working copy (requires `--force`) -/// - With file arguments: Resets only the specified files +/// - Without arguments: restores the entire working copy (requires `--force`) +/// - With file arguments: restores only the specified files /// /// # Warning /// -/// Reset is destructive - uncommitted changes cannot be recovered. +/// Restore is destructive - uncommitted changes cannot be recovered. /// Use `--dry-run` to preview changes first. #[derive(Parser, Debug, Clone)] -#[command(name = "reset")] -pub struct Reset { - /// Files or directories to reset. +#[command(name = "restore")] +pub struct Restore { + /// Files or directories to restore. /// - /// If not specified, resets the entire working copy. + /// If not specified, restores the entire working copy. #[arg(value_name = "FILES")] pub files: Vec, - /// Deprecated: switching views is no longer done via reset. - /// - /// Use `atomic view switch ` instead. Passing `--view` here returns - /// an error pointing to the correct command. This flag is kept only to - /// give a clear migration message and will be removed in a later release. - #[arg(long, hide = true)] - pub view: Option, - - /// Dry run - show what would be reset without doing it. + /// Dry run - show what would be restored without doing it. /// /// For a single file, outputs the pristine content to stdout. - /// For multiple files, lists what would be reset. + /// For multiple files, lists what would be restored. #[arg(short = 'n', long = "dry-run")] pub dry_run: bool, - /// Force reset even if there are uncommitted changes. + /// Force a whole-tree restore even if there are uncommitted changes. /// - /// Without this flag, reset will warn and abort if there are - /// uncommitted changes (safety measure). + /// Only required when no files are named. Naming files is itself explicit + /// consent to discard their changes. #[arg(short = 'f', long = "force")] pub force: bool, } -impl Reset { - /// Create a new Reset command with default settings. +impl Restore { + /// Create a new Restore command with default settings. pub fn new() -> Self { Self { files: Vec::new(), - view: None, dry_run: false, force: false, } } - /// Builder: set files to reset. + /// Builder: set files to restore. pub fn with_files(mut self, files: I) -> Self where I: IntoIterator, @@ -143,12 +137,6 @@ impl Reset { self } - /// Builder: set the view to reset to. - pub fn with_view(mut self, view: impl Into) -> Self { - self.view = Some(view.into()); - self - } - /// Builder: set the dry-run flag. pub fn with_dry_run(mut self, dry_run: bool) -> Self { self.dry_run = dry_run; @@ -161,77 +149,37 @@ impl Reset { self } - /// Check if this is a partial reset (specific files, not whole working copy). - pub fn is_partial_reset(&self) -> bool { + /// Check if this is a partial restore (specific files, not the whole copy). + pub fn is_partial(&self) -> bool { !self.files.is_empty() } /// Whether this invocation must be blocked until `--force` is supplied. /// - /// Only a whole-working-copy reset (no paths named) is guarded, because it - /// would discard *all* uncommitted work. Naming specific files is explicit - /// consent (like `git restore `), and `--force` / `--dry-run` always - /// bypass the guard. + /// Only a whole-working-copy restore (no paths named) is guarded, because + /// it would discard *all* uncommitted work. Naming specific files is + /// explicit consent (like `git restore `), and `--force` / + /// `--dry-run` always bypass the guard. fn requires_force(&self, has_changes: bool) -> bool { - !self.is_partial_reset() && has_changes && !self.force && !self.dry_run + !self.is_partial() && has_changes && !self.force && !self.dry_run } - /// Message shown when there is nothing to reset. + /// Message shown when there is nothing to restore. /// - /// For a partial reset we must not claim the whole working copy is clean + /// For a partial restore we must not claim the whole working copy is clean /// (other paths may still be dirty) — only that the named paths had - /// nothing to reset. - fn nothing_to_reset_message(&self) -> &'static str { - if self.is_partial_reset() { - "Nothing to reset for the specified path(s)" + /// nothing to restore. + fn nothing_to_restore_message(&self) -> &'static str { + if self.is_partial() { + "Nothing to restore for the specified path(s)" } else { - "Nothing to reset - working copy is clean" + "Nothing to restore - working copy is clean" } } - /// Normalize a path relative to the repository root. + /// Status options used by restore. /// - /// If the path is absolute and under the repo root, strips the prefix. - /// Otherwise returns the path as-is. - pub fn normalize_path(&self, repo_root: &std::path::Path, path: &str) -> CliResult { - let p = std::path::Path::new(path); - // On Windows, Path::is_absolute() returns false for Unix-style "/foo" - // paths (they're drive-relative). Treat a leading '/' as absolute on - // all platforms so cross-platform behaviour is consistent. - let looks_absolute = p.is_absolute() || path.starts_with('/'); - if looks_absolute { - match p.strip_prefix(repo_root) { - Ok(rel) => Ok(rel.to_string_lossy().to_string()), - Err(_) => Err(CliError::PathOutsideRepository { - path: std::path::PathBuf::from(path), - }), - } - } else { - Ok(path.to_string()) - } - } - - /// Check if a path matches any of the specified file filters. - fn matches_filter(&self, path: &str) -> bool { - if self.files.is_empty() { - return true; - } - - for filter in &self.files { - let filter_normalized = filter.trim_end_matches('/'); - if path == filter_normalized - || path.starts_with(&format!("{}/", filter_normalized)) - || filter_normalized.ends_with('/') && path.starts_with(filter_normalized) - { - return true; - } - } - false - } - - /// Status options used by reset. - /// - /// Reset only ever touches *tracked* dirty files (Modified / Deleted / + /// Restore only ever touches *tracked* dirty files (Modified / Deleted / /// Added), so we skip the (potentially expensive) untracked-file scan. fn status_options() -> StatusOptions { StatusOptions { @@ -240,17 +188,17 @@ impl Reset { } } - /// Get the files that need to be reset, paired with their status. + /// Get the files that need to be restored, paired with their status. /// /// Derives the list from a status that was already computed by the - /// caller (so reset doesn't walk the tree twice). Only tracked, dirty + /// caller (so restore doesn't walk the tree twice). Only tracked, dirty /// states are considered; untracked files are never touched. /// /// - `Modified` / `Deleted`: content will be restored from pristine. /// - `Added`: tracking will be undone (file kept on disk as untracked), /// so that `status` stops reporting a pending "new file" change. - fn get_files_to_reset(&self, status: &RepositoryStatus) -> Vec<(PathBuf, FileStatus)> { - let mut files_to_reset = Vec::new(); + fn files_to_restore(&self, status: &RepositoryStatus) -> Vec<(PathBuf, FileStatus)> { + let mut out = Vec::new(); for entry in status.entries() { let file_status = entry.status(); @@ -258,14 +206,14 @@ impl Reset { FileStatus::Modified | FileStatus::Deleted | FileStatus::Added => { let path_str = entry.path().to_string_lossy(); if self.matches_filter(&path_str) { - files_to_reset.push((entry.path().to_path_buf(), file_status)); + out.push((entry.path().to_path_buf(), file_status)); } } _ => {} } } - files_to_reset + out } /// Execute dry-run for a single file - output pristine content to stdout. @@ -290,28 +238,28 @@ impl Reset { } } - /// Reset a single file according to its status. + /// Restore a single file according to its status. /// /// - `Added` (tracked but not recorded): undo tracking. The file stays /// on disk and becomes untracked, so we never destroy content the user - /// created. This is what makes `reset ` honest about the + /// created. This is what makes `restore ` honest about the /// "new file" change reported by `status`. /// - Otherwise (`Modified` / `Deleted`): restore the file's content from /// the pristine state. /// /// Returns the outcome so the caller can report it accurately. - fn reset_file( + fn restore_file( &self, repo: &Repository, repo_root: &Path, path: &Path, status: FileStatus, - ) -> CliResult { + ) -> CliResult { if status == FileStatus::Added { // Undo the `add`: stop tracking, but keep the file on disk. repo.remove(path, TrackingOptions::default().with_recursive(false)) .map_err(CliError::Repository)?; - return Ok(ResetOutcome::Untracked); + return Ok(RestoreOutcome::Untracked); } // Restore content from pristine. @@ -336,52 +284,56 @@ impl Reset { CliError::Internal(anyhow::anyhow!("Failed to write file: {}", e)) })?; - Ok(ResetOutcome::Restored) + Ok(RestoreOutcome::Restored) } None => { // No pristine content available; nothing safe to do. - Ok(ResetOutcome::Skipped) + Ok(RestoreOutcome::Skipped) } } } + + /// Check if a path matches any of the specified file filters. + fn matches_filter(&self, path: &str) -> bool { + if self.files.is_empty() { + return true; + } + + for filter in &self.files { + let filter_normalized = filter.trim_end_matches('/'); + if path == filter_normalized + || path.starts_with(&format!("{}/", filter_normalized)) + || filter_normalized.ends_with('/') && path.starts_with(filter_normalized) + { + return true; + } + } + false + } } -impl Default for Reset { +impl Default for Restore { fn default() -> Self { Self::new() } } -impl Command for Reset { - /// Execute the reset command. +impl Command for Restore { + /// Execute the restore command. /// /// # Process /// - /// 1. Reject `--view` (use `atomic view switch` instead) - /// 2. Find and open the repository - /// 3. Guard a whole-tree reset behind `--force` - /// 4. Determine files to reset - /// 5. If `--dry-run`, preview changes - /// 6. Otherwise, reset files to pristine state + /// 1. Find and open the repository + /// 2. Guard a whole-tree restore behind `--force` + /// 3. Determine files to restore + /// 4. If `--dry-run`, preview changes + /// 5. Otherwise, restore files to pristine state fn run(&self) -> CliResult<()> { - // `reset` is for discarding working-copy changes only. Switching views - // is a separate concern owned by `atomic view switch`, which performs a - // proper materialization. Reset must not reimplement that, so reject - // `--view` with a clear migration message rather than half-doing it. - if let Some(view_name) = &self.view { - return Err(CliError::InvalidArgument { - message: format!( - "'atomic reset --view' is no longer supported. \ - Use 'atomic view switch {view_name}' to switch views." - ), - }); - } - // Find repository let repo_root = find_repository_root()?; let repo = Repository::open(&repo_root).map_err(CliError::Repository)?; - // Compute status once. Reset only touches tracked files, so we skip + // Compute status once. Restore only touches tracked files, so we skip // the untracked scan, and we reuse this single status for both the // safety guard and the file list (no second tree walk). let status = repo @@ -390,81 +342,81 @@ impl Command for Reset { let has_changes = !status.is_clean(); - // Safety guard: only a whole-working-copy reset (no paths named) + // Safety guard: only a whole-working-copy restore (no paths named) // requires --force. Naming specific files is explicit consent to // discard them, exactly like `git restore `. if self.requires_force(has_changes) { return Err(CliError::RequiresForce { - operation: "reset".to_string(), + operation: "restore".to_string(), }); } - // Determine files to reset, paired with their status. - let files_to_reset = self.get_files_to_reset(&status); + // Determine files to restore, paired with their status. + let files_to_restore = self.files_to_restore(&status); // Handle dry-run for a single file by printing its pristine content to // stdout (useful for piping). This only makes sense for files that // have pristine content; an Added file would be untracked, not // restored, so fall through to the listing branch below. - let single_added = files_to_reset + let single_added = files_to_restore .first() .map(|(_, s)| *s == FileStatus::Added) .unwrap_or(false); - if self.dry_run && self.files.len() == 1 && files_to_reset.len() <= 1 && !single_added { + if self.dry_run && self.files.len() == 1 && files_to_restore.len() <= 1 && !single_added { let path = &self.files[0]; return self.dry_run_single_file(&repo, path); } // Dry run mode - just show what would happen if self.dry_run { - if files_to_reset.is_empty() { - println!("{}", self.nothing_to_reset_message()); + if files_to_restore.is_empty() { + println!("{}", self.nothing_to_restore_message()); } else { - for (path, file_status) in &files_to_reset { + for (path, file_status) in &files_to_restore { if *file_status == FileStatus::Added { println!("Would untrack: {} (kept on disk)", path.display()); } else { - println!("Would reset: {}", path.display()); + println!("Would restore: {}", path.display()); } } println!(); print_hint(&format!( - "(dry run - {} would be reset)", - format_count(files_to_reset.len(), "file") + "(dry run - {} would be restored)", + format_count(files_to_restore.len(), "file") )); } return Ok(()); } - // Check if there's anything to reset - if files_to_reset.is_empty() { - println!("{}", self.nothing_to_reset_message()); + // Check if there's anything to restore + if files_to_restore.is_empty() { + println!("{}", self.nothing_to_restore_message()); return Ok(()); } - // Perform reset - println!("Resetting working copy..."); + // Perform restore + println!("Restoring working copy..."); - let mut reset_count = 0; + let mut restored_count = 0; let mut error_count = 0; - for (path, file_status) in &files_to_reset { + for (path, file_status) in &files_to_restore { let path_display = path.display(); - match self.reset_file(&repo, &repo_root, path, *file_status) { - Ok(ResetOutcome::Restored) => { - println!(" Reset: {}", path_display); - reset_count += 1; + match self.restore_file(&repo, &repo_root, path, *file_status) { + Ok(RestoreOutcome::Restored) => { + println!(" Restored: {}", path_display); + restored_count += 1; } - Ok(ResetOutcome::Untracked) => { + Ok(RestoreOutcome::Untracked) => { println!(" Untracked: {} (kept on disk)", path_display); - reset_count += 1; + restored_count += 1; } - Ok(ResetOutcome::Skipped) => { + Ok(RestoreOutcome::Skipped) => { // No pristine content to restore; nothing to do. } Err(e) => { - print_warning(&format!("Failed to reset '{}': {}", path_display, e)); + print_warning(&format!("Failed to restore '{}': {}", path_display, e)); error_count += 1; } } @@ -472,13 +424,16 @@ impl Command for Reset { // Summary println!(); - if reset_count > 0 { - print_success(&format!("Reset {}", format_count(reset_count, "file"))); + if restored_count > 0 { + print_success(&format!( + "Restored {}", + format_count(restored_count, "file") + )); } if error_count > 0 { print_warning(&format!( - "{} could not be reset", + "{} could not be restored", format_count(error_count, "file") )); } @@ -505,95 +460,85 @@ mod tests { // Builder Tests #[test] - fn test_reset_new() { - let cmd = Reset::new(); + fn test_restore_new() { + let cmd = Restore::new(); assert!(cmd.files.is_empty()); - assert!(cmd.view.is_none()); assert!(!cmd.dry_run); assert!(!cmd.force); } #[test] - fn test_reset_default() { - let cmd = Reset::default(); + fn test_restore_default() { + let cmd = Restore::default(); assert!(cmd.files.is_empty()); - assert!(cmd.view.is_none()); assert!(!cmd.dry_run); assert!(!cmd.force); } #[test] - fn test_reset_with_files() { - let cmd = Reset::new().with_files(vec!["file.txt".to_string(), "src/".to_string()]); + fn test_restore_with_files() { + let cmd = Restore::new().with_files(vec!["file.txt".to_string(), "src/".to_string()]); assert_eq!(cmd.files.len(), 2); assert_eq!(cmd.files[0], "file.txt"); assert_eq!(cmd.files[1], "src/"); } #[test] - fn test_reset_with_view() { - let cmd = Reset::new().with_view("main"); - assert_eq!(cmd.view, Some("main".to_string())); - } - - #[test] - fn test_reset_with_dry_run() { - let cmd = Reset::new().with_dry_run(true); + fn test_restore_with_dry_run() { + let cmd = Restore::new().with_dry_run(true); assert!(cmd.dry_run); } #[test] - fn test_reset_with_force() { - let cmd = Reset::new().with_force(true); + fn test_restore_with_force() { + let cmd = Restore::new().with_force(true); assert!(cmd.force); } #[test] - fn test_reset_builder_chain() { - let cmd = Reset::new() + fn test_restore_builder_chain() { + let cmd = Restore::new() .with_files(vec!["src/main.rs".to_string()]) - .with_view("feature") .with_dry_run(true) .with_force(true); assert_eq!(cmd.files, vec!["src/main.rs"]); - assert_eq!(cmd.view, Some("feature".to_string())); assert!(cmd.dry_run); assert!(cmd.force); } - // Partial Reset Tests + // Partial Restore Tests #[test] - fn test_is_partial_reset_empty() { - let cmd = Reset::new(); - assert!(!cmd.is_partial_reset()); + fn test_is_partial_empty() { + let cmd = Restore::new(); + assert!(!cmd.is_partial()); } #[test] - fn test_is_partial_reset_with_files() { - let cmd = Reset::new().with_files(vec!["file.txt".to_string()]); - assert!(cmd.is_partial_reset()); + fn test_is_partial_with_files() { + let cmd = Restore::new().with_files(vec!["file.txt".to_string()]); + assert!(cmd.is_partial()); } // Filter Tests #[test] fn test_matches_filter_empty() { - let cmd = Reset::new(); + let cmd = Restore::new(); assert!(cmd.matches_filter("any/path.rs")); } #[test] fn test_matches_filter_exact() { - let cmd = Reset::new().with_files(vec!["src/main.rs".to_string()]); + let cmd = Restore::new().with_files(vec!["src/main.rs".to_string()]); assert!(cmd.matches_filter("src/main.rs")); assert!(!cmd.matches_filter("src/lib.rs")); } #[test] fn test_matches_filter_directory() { - let cmd = Reset::new().with_files(vec!["src/".to_string()]); + let cmd = Restore::new().with_files(vec!["src/".to_string()]); assert!(cmd.matches_filter("src/main.rs")); assert!(cmd.matches_filter("src/utils/helpers.rs")); assert!(!cmd.matches_filter("tests/test.rs")); @@ -601,7 +546,7 @@ mod tests { #[test] fn test_matches_filter_directory_without_slash() { - let cmd = Reset::new().with_files(vec!["src".to_string()]); + let cmd = Restore::new().with_files(vec!["src".to_string()]); assert!(cmd.matches_filter("src")); assert!(cmd.matches_filter("src/main.rs")); assert!(!cmd.matches_filter("srcfile.rs")); @@ -609,41 +554,12 @@ mod tests { #[test] fn test_matches_filter_multiple() { - let cmd = Reset::new().with_files(vec!["src/".to_string(), "README.md".to_string()]); + let cmd = Restore::new().with_files(vec!["src/".to_string(), "README.md".to_string()]); assert!(cmd.matches_filter("src/main.rs")); assert!(cmd.matches_filter("README.md")); assert!(!cmd.matches_filter("Cargo.toml")); } - // Normalize Path Tests - - #[test] - fn test_normalize_relative_path() { - let cmd = Reset::new(); - let temp = tempfile::tempdir().unwrap(); - let result = cmd.normalize_path(temp.path(), "src/file.rs").unwrap(); - assert_eq!(result, "src/file.rs"); - } - - #[test] - fn test_normalize_absolute_path_inside_repo() { - let cmd = Reset::new(); - let temp = tempfile::tempdir().unwrap(); - let abs = temp.path().join("src/file.rs"); - let result = cmd - .normalize_path(temp.path(), abs.to_str().unwrap()) - .unwrap(); - assert_eq!(result, "src/file.rs"); - } - - #[test] - fn test_normalize_absolute_path_outside_repo() { - let cmd = Reset::new(); - let temp = tempfile::tempdir().unwrap(); - let result = cmd.normalize_path(temp.path(), "/other/path/file.rs"); - assert!(result.is_err()); - } - // Format Tests #[test] @@ -664,83 +580,67 @@ mod tests { // Clone Tests #[test] - fn test_reset_clone() { - let cmd = Reset::new() + fn test_restore_clone() { + let cmd = Restore::new() .with_files(vec!["file.txt".to_string()]) - .with_view("main") .with_force(true); let cloned = cmd.clone(); assert_eq!(cloned.files, cmd.files); - assert_eq!(cloned.view, cmd.view); assert_eq!(cloned.force, cmd.force); } // Guard Logic Tests (requires_force) #[test] - fn test_requires_force_partial_reset_not_blocked() { + fn test_requires_force_partial_not_blocked() { // Naming a file is explicit consent — never blocked, even when the // tree has changes. This is the core bug fix. - let cmd = Reset::new().with_files(vec!["file.txt".to_string()]); + let cmd = Restore::new().with_files(vec!["file.txt".to_string()]); assert!(!cmd.requires_force(true)); } #[test] fn test_requires_force_whole_tree_blocked() { - let cmd = Reset::new(); + let cmd = Restore::new(); assert!(cmd.requires_force(true)); } #[test] fn test_requires_force_whole_tree_with_force_passes() { - let cmd = Reset::new().with_force(true); + let cmd = Restore::new().with_force(true); assert!(!cmd.requires_force(true)); } #[test] fn test_requires_force_clean_tree_passes() { - let cmd = Reset::new(); + let cmd = Restore::new(); assert!(!cmd.requires_force(false)); } #[test] fn test_requires_force_dry_run_passes() { - let cmd = Reset::new().with_dry_run(true); + let cmd = Restore::new().with_dry_run(true); assert!(!cmd.requires_force(true)); } - #[test] - fn test_reset_view_is_rejected_before_touching_repo() { - // `--view` is rejected up front (before any filesystem access), with a - // message pointing at `atomic view switch`. - let cmd = Reset::new().with_view("feature"); - match cmd.run() { - Err(CliError::InvalidArgument { message }) => { - assert!(message.contains("view switch")); - assert!(message.contains("feature")); - } - other => panic!("expected InvalidArgument for --view, got {other:?}"), - } - } - // Empty-result Message Tests #[test] - fn test_nothing_to_reset_message_partial() { - let cmd = Reset::new().with_files(vec!["a.txt".to_string()]); + fn test_nothing_to_restore_message_partial() { + let cmd = Restore::new().with_files(vec!["a.txt".to_string()]); assert_eq!( - cmd.nothing_to_reset_message(), - "Nothing to reset for the specified path(s)" + cmd.nothing_to_restore_message(), + "Nothing to restore for the specified path(s)" ); } #[test] - fn test_nothing_to_reset_message_whole_tree() { - let cmd = Reset::new(); + fn test_nothing_to_restore_message_whole_tree() { + let cmd = Restore::new(); assert_eq!( - cmd.nothing_to_reset_message(), - "Nothing to reset - working copy is clean" + cmd.nothing_to_restore_message(), + "Nothing to restore - working copy is clean" ); } @@ -758,7 +658,7 @@ mod tests { } #[test] - fn test_reset_modified_restores_pristine_content() { + fn test_restore_modified_restores_pristine_content() { let (_dir, repo, root) = test_repo(); let path = Path::new("file.txt"); fs::write(root.join(path), b"recorded\n").unwrap(); @@ -768,58 +668,58 @@ mod tests { // Local edit that we want to discard. fs::write(root.join(path), b"local edit\n").unwrap(); - let cmd = Reset::new(); + let cmd = Restore::new(); let outcome = cmd - .reset_file(&repo, &root, path, FileStatus::Modified) + .restore_file(&repo, &root, path, FileStatus::Modified) .unwrap(); - assert_eq!(outcome, ResetOutcome::Restored); + assert_eq!(outcome, RestoreOutcome::Restored); assert_eq!(fs::read(root.join(path)).unwrap(), b"recorded\n"); } #[test] - fn test_reset_deleted_restores_file_from_pristine() { + fn test_restore_deleted_restores_file_from_pristine() { let (_dir, repo, root) = test_repo(); let path = Path::new("file.txt"); fs::write(root.join(path), b"recorded\n").unwrap(); repo.add(path, TrackingOptions::default()).unwrap(); repo.record_all("init").unwrap(); - // Delete it on disk; reset should bring it back. + // Delete it on disk; restore should bring it back. fs::remove_file(root.join(path)).unwrap(); assert!(!root.join(path).exists()); - let cmd = Reset::new(); + let cmd = Restore::new(); let outcome = cmd - .reset_file(&repo, &root, path, FileStatus::Deleted) + .restore_file(&repo, &root, path, FileStatus::Deleted) .unwrap(); - assert_eq!(outcome, ResetOutcome::Restored); + assert_eq!(outcome, RestoreOutcome::Restored); assert!(root.join(path).exists()); assert_eq!(fs::read(root.join(path)).unwrap(), b"recorded\n"); } #[test] - fn test_reset_added_untracks_but_keeps_file_on_disk() { + fn test_restore_added_untracks_but_keeps_file_on_disk() { let (_dir, repo, root) = test_repo(); let path = Path::new("new.txt"); fs::write(root.join(path), b"brand new\n").unwrap(); repo.add(path, TrackingOptions::default()).unwrap(); // Deliberately NOT recorded → status is `Added`. - let cmd = Reset::new().with_files(vec!["new.txt".to_string()]); + let cmd = Restore::new().with_files(vec!["new.txt".to_string()]); // Before: status reports it as a pending Added change. - let before = repo.status(Reset::status_options()).unwrap(); - let listed = cmd.get_files_to_reset(&before); + let before = repo.status(Restore::status_options()).unwrap(); + let listed = cmd.files_to_restore(&before); assert!(listed .iter() .any(|(p, s)| p.as_path() == path && *s == FileStatus::Added)); let outcome = cmd - .reset_file(&repo, &root, path, FileStatus::Added) + .restore_file(&repo, &root, path, FileStatus::Added) .unwrap(); - assert_eq!(outcome, ResetOutcome::Untracked); + assert_eq!(outcome, RestoreOutcome::Untracked); // File is kept on disk (we never destroy user-created content)... assert!(root.join(path).exists()); @@ -827,8 +727,8 @@ mod tests { // ...and status no longer reports a pending change for it, so the // status hint is no longer lying. - let after = repo.status(Reset::status_options()).unwrap(); - let still_listed = cmd.get_files_to_reset(&after); + let after = repo.status(Restore::status_options()).unwrap(); + let still_listed = cmd.files_to_restore(&after); assert!(!still_listed.iter().any(|(p, _)| p.as_path() == path)); } } diff --git a/atomic-cli/src/commands/status.rs b/atomic-cli/src/commands/status.rs index 46c8c6d2..5014fefa 100644 --- a/atomic-cli/src/commands/status.rs +++ b/atomic-cli/src/commands/status.rs @@ -30,7 +30,7 @@ //! State: ABCDEF123456 //! //! Changes to be recorded: -//! (use "atomic reset ..." to discard changes) +//! (use "atomic restore ..." to discard changes) //! //! new file: src/new_feature.rs //! modified: src/main.rs @@ -281,7 +281,7 @@ impl Status { print_section("Changes to be recorded:"); println!( " {}", - hint("(use \"atomic reset ...\" to discard changes)") + hint("(use \"atomic restore ...\" to discard changes)") ); print_blank(); diff --git a/atomic-cli/src/error.rs b/atomic-cli/src/error.rs index 6f4baec4..9042ad42 100644 --- a/atomic-cli/src/error.rs +++ b/atomic-cli/src/error.rs @@ -543,7 +543,7 @@ impl CliError { Some("Run 'atomic --help' for usage information.") } Self::RequiresForce { .. } => Some( - "Reset specific files with 'atomic reset ...', or use 'atomic reset --force' to discard everything.", + "Restore specific files with 'atomic restore ...', or use 'atomic restore --force' to discard everything.", ), Self::Internal(_) => { Some("This appears to be a bug. Please report it at: https://github.com/atomicdotdev/atomic/issues") @@ -770,7 +770,7 @@ mod tests { #[test] fn test_requires_force_is_user_fixable_not_internal() { let err = CliError::RequiresForce { - operation: "reset".to_string(), + operation: "restore".to_string(), }; assert!(err.is_user_fixable()); assert!(!err.is_internal()); diff --git a/atomic-cli/src/main.rs b/atomic-cli/src/main.rs index af1f10b0..27f50abd 100644 --- a/atomic-cli/src/main.rs +++ b/atomic-cli/src/main.rs @@ -75,7 +75,7 @@ use commands::{ Record, Remote, Remove, - Reset, + Restore, Revise, Split, Stash, @@ -217,24 +217,26 @@ enum Commands { #[command(visible_alias = "mv")] Move(Move), - /// Reset the working copy to the last recorded state. + /// Restore the working copy to the last recorded state. /// /// Restores the working copy to match the pristine state (last recorded - /// state in the view). This discards any uncommitted changes. + /// state in the view). This discards any uncommitted changes. Equivalent + /// to `git restore`. The legacy name `reset` is kept as an alias. /// /// # Examples /// /// ```text - /// # Discard all uncommitted changes - /// atomic reset --force + /// # Restore specific files + /// atomic restore src/main.rs /// - /// # Reset specific files - /// atomic reset src/main.rs + /// # Discard all uncommitted changes + /// atomic restore --force /// - /// # Preview what would be reset - /// atomic reset --dry-run + /// # Preview what would be restored + /// atomic restore --dry-run /// ``` - Reset(Reset), + #[command(alias = "reset")] + Restore(Restore), /// Split a view (create a new view from an existing one). /// @@ -714,7 +716,7 @@ fn main() { Commands::Move(mv) => mv.run(), - Commands::Reset(reset) => reset.run(), + Commands::Restore(restore) => restore.run(), Commands::Split(split) => split.run(), diff --git a/atomic-cli/tests/reset_integration_test.rs b/atomic-cli/tests/restore_integration_test.rs similarity index 66% rename from atomic-cli/tests/reset_integration_test.rs rename to atomic-cli/tests/restore_integration_test.rs index 893ff0f5..a864fdf8 100644 --- a/atomic-cli/tests/reset_integration_test.rs +++ b/atomic-cli/tests/restore_integration_test.rs @@ -1,9 +1,9 @@ -//! Integration tests for `atomic reset`, driving the real CLI binary -//! end-to-end (`Reset::run()`), against a temporary repository. +//! Integration tests for `atomic restore`, driving the real CLI binary +//! end-to-end (`Restore::run()`), against a temporary repository. //! -//! These complement the unit tests in `commands/reset.rs` by exercising the -//! full command path: argument parsing, the safety guard, `--view` rejection, -//! and the actual filesystem effects. +//! These complement the unit tests in `commands/restore.rs` by exercising the +//! full command path: argument parsing, the safety guard, the `reset` alias, +//! `--view` removal, and the actual filesystem effects. use std::path::Path; use std::process::{Command, Output}; @@ -34,30 +34,43 @@ fn repo_with_recorded_file() -> TempDir { } #[test] -fn reset_named_modified_file_restores_without_force() { +fn restore_named_modified_file_without_force() { + let dir = repo_with_recorded_file(); + let root = dir.path(); + + std::fs::write(root.join("file.txt"), b"local edit\n").unwrap(); + + let out = atomic(root, &["restore", "file.txt"]); + assert!(out.status.success(), "restore should succeed"); + assert_eq!(std::fs::read(root.join("file.txt")).unwrap(), b"v1\n"); +} + +#[test] +fn reset_alias_still_works() { + // The legacy `reset` name is kept as an alias for `restore`. let dir = repo_with_recorded_file(); let root = dir.path(); std::fs::write(root.join("file.txt"), b"local edit\n").unwrap(); let out = atomic(root, &["reset", "file.txt"]); - assert!(out.status.success(), "reset should succeed"); + assert!(out.status.success(), "reset alias should still work"); assert_eq!(std::fs::read(root.join("file.txt")).unwrap(), b"v1\n"); } #[test] -fn reset_named_file_not_blocked_by_unrelated_dirty_file() { +fn restore_named_file_not_blocked_by_unrelated_dirty_file() { let dir = repo_with_recorded_file(); let root = dir.path(); std::fs::write(root.join("other.txt"), b"o1\n").unwrap(); assert!(atomic(root, &["add", "other.txt"]).status.success()); assert!(atomic(root, &["record", "-m", "two"]).status.success()); - // Both files dirty; reset only file.txt. + // Both files dirty; restore only file.txt. std::fs::write(root.join("file.txt"), b"edit-a\n").unwrap(); std::fs::write(root.join("other.txt"), b"edit-b\n").unwrap(); - let out = atomic(root, &["reset", "file.txt"]); + let out = atomic(root, &["restore", "file.txt"]); assert!(out.status.success()); assert_eq!(std::fs::read(root.join("file.txt")).unwrap(), b"v1\n"); // The unrelated dirty file is untouched. @@ -65,19 +78,22 @@ fn reset_named_file_not_blocked_by_unrelated_dirty_file() { } #[test] -fn whole_tree_reset_without_force_is_user_error_not_internal() { +fn whole_tree_restore_without_force_is_user_error_not_internal() { let dir = repo_with_recorded_file(); let root = dir.path(); std::fs::write(root.join("file.txt"), b"dirty\n").unwrap(); - let out = atomic(root, &["reset"]); - assert!(!out.status.success(), "whole-tree reset needs --force"); + let out = atomic(root, &["restore"]); + assert!(!out.status.success(), "whole-tree restore needs --force"); assert_eq!(out.status.code(), Some(1), "user-level exit code"); - let stderr = String::from_utf8_lossy(&out.stderr); - let combined = format!("{}{}", String::from_utf8_lossy(&out.stdout), stderr); + let combined = format!( + "{}{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ); assert!( - combined.contains("Cannot reset"), + combined.contains("Cannot restore"), "should explain the guard, got: {combined}" ); assert!( @@ -89,14 +105,14 @@ fn whole_tree_reset_without_force_is_user_error_not_internal() { } #[test] -fn reset_added_file_untracks_and_keeps_it_on_disk() { +fn restore_added_file_untracks_and_keeps_it_on_disk() { let dir = repo_with_recorded_file(); let root = dir.path(); std::fs::write(root.join("new.txt"), b"brand new\n").unwrap(); assert!(atomic(root, &["add", "new.txt"]).status.success()); - let out = atomic(root, &["reset", "new.txt"]); + let out = atomic(root, &["restore", "new.txt"]); assert!(out.status.success()); // Kept on disk... assert!(root.join("new.txt").exists()); @@ -118,7 +134,7 @@ fn dry_run_added_file_reports_untrack_without_erroring() { std::fs::write(root.join("new.txt"), b"brand new\n").unwrap(); assert!(atomic(root, &["add", "new.txt"]).status.success()); - let out = atomic(root, &["reset", "--dry-run", "new.txt"]); + let out = atomic(root, &["restore", "--dry-run", "new.txt"]); assert!( out.status.success(), "dry-run on an added file must not error" @@ -141,39 +157,17 @@ fn dry_run_added_file_reports_untrack_without_erroring() { } #[test] -fn reset_view_fails_fast_and_points_to_view_switch() { - // `reset --view` must not silently half-switch views (it used to leave - // stale working-copy content while printing "working copy already clean"). - // It now fails fast and directs the user to `atomic view switch`. +fn view_flag_is_removed() { + // `--view` was removed; switching views is `atomic view switch`. clap + // should reject the unknown flag before any work happens. let dir = repo_with_recorded_file(); let root = dir.path(); - assert!(atomic(root, &["view", "create", "feature"]) - .status - .success()); - - std::fs::write(root.join("file.txt"), b"DIRTY-EDIT\n").unwrap(); - - let out = atomic(root, &["reset", "--force", "--view", "feature"]); - assert!(!out.status.success(), "reset --view should be rejected"); - let combined = format!( - "{}{}", - String::from_utf8_lossy(&out.stdout), - String::from_utf8_lossy(&out.stderr) - ); - assert!( - combined.contains("view switch"), - "should point users to 'atomic view switch', got: {combined}" - ); - // It must not have touched the working copy or switched the view. - assert_eq!( - std::fs::read(root.join("file.txt")).unwrap(), - b"DIRTY-EDIT\n" - ); - let views = atomic(root, &["view", "list"]); - let views_text = String::from_utf8_lossy(&views.stdout); + let out = atomic(root, &["restore", "--view", "feature", "--force"]); + assert!(!out.status.success(), "--view should no longer be accepted"); + let stderr = String::from_utf8_lossy(&out.stderr); assert!( - views_text.contains("* dev"), - "current view must be unchanged (still dev), got: {views_text}" + stderr.contains("unexpected argument") || stderr.contains("--view"), + "clap should reject --view, got: {stderr}" ); } From 259eb148af15d9be6712c7124bf926542e42df9f Mon Sep 17 00:00:00 2001 From: Vincent Date: Thu, 21 May 2026 02:43:42 -0400 Subject: [PATCH 3/3] fix: restore --dry-run on a directory lists instead of erroring; update README + reset-alias tests --- atomic-cli/README.md | 26 +++++----- atomic-cli/src/commands/restore.rs | 16 +++--- atomic-cli/tests/restore_integration_test.rs | 52 ++++++++++++++++++++ 3 files changed, 75 insertions(+), 19 deletions(-) diff --git a/atomic-cli/README.md b/atomic-cli/README.md index f7ea8c74..ccabd05e 100644 --- a/atomic-cli/README.md +++ b/atomic-cli/README.md @@ -137,29 +137,29 @@ atomic move config.toml src/config.toml **Alias:** `atomic mv` -#### `atomic reset` +#### `atomic restore` -Reset the working copy to the last recorded state, discarding uncommitted changes. +Restore the working copy to the last recorded state, discarding uncommitted +changes (the working-copy counterpart of `git restore`). The legacy name +`atomic reset` is kept as an alias. ```bash -# Preview what would be reset -atomic reset --dry-run +# Restore specific files (no --force needed) +atomic restore src/main.rs -# Reset everything (requires --force) -atomic reset --force +# Restore everything (requires --force) +atomic restore --force -# Reset specific files -atomic reset src/main.rs - -# Reset to a different stack's state -atomic reset --stack main +# Preview a single file's pristine content +atomic restore --dry-run src/main.rs ``` | Option | Description | |--------|-------------| -| `--force` | Required to confirm destructive reset | +| `--force` | Required only for a whole-tree restore | | `--dry-run` | Preview without making changes | -| `--stack ` | Reset to a specific stack's state | + +To switch views, use `atomic view switch `. --- diff --git a/atomic-cli/src/commands/restore.rs b/atomic-cli/src/commands/restore.rs index 2c52ab19..00b41d9c 100644 --- a/atomic-cli/src/commands/restore.rs +++ b/atomic-cli/src/commands/restore.rs @@ -355,16 +355,20 @@ impl Command for Restore { let files_to_restore = self.files_to_restore(&status); // Handle dry-run for a single file by printing its pristine content to - // stdout (useful for piping). This only makes sense for files that - // have pristine content; an Added file would be untracked, not - // restored, so fall through to the listing branch below. + // stdout (useful for piping). This only makes sense when the argument + // is exactly one concrete file: + // - a directory or prefix filter (e.g. `src/`) has no pristine content + // of its own and must fall through to the listing branch; + // - an Added file would be untracked, not restored, so it lists too. let single_added = files_to_restore .first() .map(|(_, s)| *s == FileStatus::Added) .unwrap_or(false); - if self.dry_run && self.files.len() == 1 && files_to_restore.len() <= 1 && !single_added { - let path = &self.files[0]; - return self.dry_run_single_file(&repo, path); + let single_file_arg = self.files.len() == 1 + && !self.files[0].ends_with('/') + && !repo_root.join(&self.files[0]).is_dir(); + if self.dry_run && single_file_arg && !single_added { + return self.dry_run_single_file(&repo, &self.files[0]); } // Dry run mode - just show what would happen diff --git a/atomic-cli/tests/restore_integration_test.rs b/atomic-cli/tests/restore_integration_test.rs index a864fdf8..ddcf28bd 100644 --- a/atomic-cli/tests/restore_integration_test.rs +++ b/atomic-cli/tests/restore_integration_test.rs @@ -156,6 +156,40 @@ fn dry_run_added_file_reports_untrack_without_erroring() { assert!(root.join("new.txt").exists()); } +#[test] +fn dry_run_directory_lists_instead_of_reading_pristine() { + // `restore --dry-run src/` must list what would be restored, not try to + // read pristine content for the directory itself (which 404s). + let dir = repo_with_recorded_file(); + let root = dir.path(); + std::fs::create_dir(root.join("src")).unwrap(); + std::fs::write(root.join("src/main.rs"), b"v1\n").unwrap(); + assert!(atomic(root, &["add", "src/main.rs"]).status.success()); + assert!(atomic(root, &["record", "-m", "src"]).status.success()); + + // One modified file under src/. + std::fs::write(root.join("src/main.rs"), b"edited\n").unwrap(); + + let out = atomic(root, &["restore", "--dry-run", "src/"]); + assert!( + out.status.success(), + "dry-run on a directory must not error" + ); + let combined = format!( + "{}{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ); + assert!( + combined.contains("Would restore: src/main.rs"), + "should list the matched file, got: {combined}" + ); + assert!( + !combined.contains("File not found"), + "must not read pristine for the directory itself: {combined}" + ); +} + #[test] fn view_flag_is_removed() { // `--view` was removed; switching views is `atomic view switch`. clap @@ -171,3 +205,21 @@ fn view_flag_is_removed() { "clap should reject --view, got: {stderr}" ); } + +#[test] +fn view_flag_is_removed_for_reset_alias_too() { + // The `reset` alias must also reject `--view`, not silently accept it. + let dir = repo_with_recorded_file(); + let root = dir.path(); + + let out = atomic(root, &["reset", "--view", "feature", "--force"]); + assert!( + !out.status.success(), + "--view should be rejected via the reset alias too" + ); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + stderr.contains("unexpected argument") || stderr.contains("--view"), + "clap should reject --view on the reset alias, got: {stderr}" + ); +}