Skip to content
Open
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
10 changes: 7 additions & 3 deletions src/uu/mv/src/hardlink.rs
Original file line number Diff line number Diff line change
Expand Up @@ -262,10 +262,13 @@ pub fn create_hardlink_context() -> (HardlinkTracker, HardlinkGroupScanner) {
(HardlinkTracker::new(), HardlinkGroupScanner::new())
}

/// Convenient function to execute operations with proper hardlink context handling
/// Run `operation` with the caller's hardlink context, or, if there is none,
/// with a new one built by scanning `source`.
pub fn with_optional_hardlink_context<F, R>(
tracker: Option<&mut HardlinkTracker>,
scanner: Option<&HardlinkGroupScanner>,
source: &Path,
options: &HardlinkOptions,
operation: F,
) -> R
where
Expand All @@ -274,8 +277,9 @@ where
if let (Some(tracker), Some(scanner)) = (tracker, scanner) {
operation(tracker, scanner)
} else {
let (mut dummy_tracker, dummy_scanner) = create_hardlink_context();
operation(&mut dummy_tracker, &dummy_scanner)
let (mut tracker, mut scanner) = create_hardlink_context();
scanner.scan_files(&[source.to_path_buf()], options);
operation(&mut tracker, &scanner)
}
}

Expand Down
65 changes: 20 additions & 45 deletions src/uu/mv/src/mv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,18 @@ fn determine_overwrite_mode(matches: &ArgMatches) -> OverwriteMode {
}
}

#[cfg(unix)]
fn scan_hardlinks(files: &[PathBuf], options: &Options) -> (HardlinkTracker, HardlinkGroupScanner) {
let hardlink_options = HardlinkOptions {
verbose: options.verbose || options.debug,
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it's only used once now, do we still need this function?
if we keep it, these two comments don't add much

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In my mind, the fn looks good. It does little but specifics and it helps to "document" the code without writing extra document IMO. I'll remove the comments though


let (tracker, mut scanner) = create_hardlink_context();

scanner.scan_files(files, &hardlink_options);
(tracker, scanner)
}

fn parse_paths(files: &[OsString], opts: &Options) -> Vec<PathBuf> {
let paths = files.iter().map(Path::new);

Expand Down Expand Up @@ -431,22 +443,8 @@ fn handle_two_paths(source: &Path, target: &Path, opts: &Options) -> UResult<()>
if target_is_dir {
if opts.no_target_dir {
if source.is_dir() {
#[cfg(unix)]
let (mut hardlink_tracker, hardlink_scanner) = create_hardlink_context();
#[cfg(unix)]
let hardlink_params = (Some(&mut hardlink_tracker), Some(&hardlink_scanner));
#[cfg(not(unix))]
let hardlink_params = (None, None);

rename(
source,
target,
opts,
None,
hardlink_params.0,
hardlink_params.1,
)
.map_err(|e| cannot_move_error(e, source, target))
rename(source, target, opts, None, None, None)
.map_err(|e| cannot_move_error(e, source, target))
} else {
Err(MvError::DirectoryToNonDirectory(
target.quote().to_string(),
Expand Down Expand Up @@ -475,22 +473,7 @@ fn handle_two_paths(source: &Path, target: &Path, opts: &Options) -> UResult<()>
)
.into())
} else {
#[cfg(unix)]
let (mut hardlink_tracker, hardlink_scanner) = create_hardlink_context();
#[cfg(unix)]
let hardlink_params = (Some(&mut hardlink_tracker), Some(&hardlink_scanner));
#[cfg(not(unix))]
let hardlink_params = (None, None);

rename(
source,
target,
opts,
None,
hardlink_params.0,
hardlink_params.1,
)
.map_err(|e| -> Box<dyn UError> {
rename(source, target, opts, None, None, None).map_err(|e| -> Box<dyn UError> {
// OS errors get the same "cannot move" context as GNU; our own
// messages (e.g. "not replacing") are already complete.
if e.raw_os_error().is_some() {
Expand Down Expand Up @@ -695,19 +678,7 @@ fn move_files_into_dir(files: &[PathBuf], target_dir: &Path, options: &Options)
FxHashSet::with_capacity_and_hasher(files.len(), rustc_hash::FxBuildHasher);
// Create hardlink tracking context
#[cfg(unix)]
let (mut hardlink_tracker, hardlink_scanner) = {
let (tracker, mut scanner) = create_hardlink_context();

// Use hardlink options
let hardlink_options = HardlinkOptions {
verbose: options.verbose || options.debug,
};

// Pre-scan files if needed
scanner.scan_files(files, &hardlink_options);

(tracker, scanner)
};
let (mut hardlink_tracker, hardlink_scanner) = scan_hardlinks(files, options);

if !target_dir.is_dir() {
return Err(MvError::NotADirectory(target_dir.quote().to_string()).into());
Expand Down Expand Up @@ -1003,6 +974,8 @@ fn rename_with_fallback(
with_optional_hardlink_context(
hardlink_tracker,
hardlink_scanner,
from,
&HardlinkOptions { verbose },
|tracker, scanner| {
rename_dir_fallback(
from,
Expand All @@ -1027,6 +1000,8 @@ fn rename_with_fallback(
with_optional_hardlink_context(
hardlink_tracker,
hardlink_scanner,
from,
&HardlinkOptions { verbose },
|tracker, scanner| rename_file_fallback(from, to, Some(tracker), Some(scanner)),
)
}
Expand Down
95 changes: 80 additions & 15 deletions tests/by-util/test_mv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2012,6 +2012,7 @@ fn test_mv_dir_with_symlink_cycles_terminates() {

#[cfg(target_os = "linux")]
mod inter_partition_copying {
use rstest::rstest;
use std::fs::{self, set_permissions, write};
use std::os::unix::fs::{PermissionsExt, symlink};
use tempfile::TempDir;
Expand All @@ -2024,7 +2025,7 @@ mod inter_partition_copying {
// that needs a second uid, so it is exercised out of band rather than here.
#[uutests::wasi_ignore(HostPathsNotVisible)]
#[test]
pub(crate) fn test_mv_inter_partition_keeps_setuid_when_ownership_preserved() {
fn test_mv_inter_partition_keeps_setuid_when_ownership_preserved() {
let scene = TestScenario::new(util_name!());
let at = &scene.fixtures;

Expand Down Expand Up @@ -2167,7 +2168,7 @@ mod inter_partition_copying {
// Ensure that the copying code used in an inter-partition move unlinks the destination symlink.
#[uutests::wasi_ignore(HostPathsNotVisible)]
#[test]
pub(crate) fn test_mv_unlinks_dest_symlink() {
fn test_mv_unlinks_dest_symlink() {
let scene = TestScenario::new(util_name!());
let at = &scene.fixtures;

Expand Down Expand Up @@ -2217,7 +2218,7 @@ mod inter_partition_copying {
// that it would output the proper error message.
#[uutests::wasi_ignore(HostPathsNotVisible)]
#[test]
pub(crate) fn test_mv_unlinks_dest_symlink_error_message() {
fn test_mv_unlinks_dest_symlink_error_message() {
use uutests::util::TestScenario;
let scene = TestScenario::new(util_name!());
let at = &scene.fixtures;
Expand Down Expand Up @@ -2249,8 +2250,7 @@ mod inter_partition_copying {
// Test that hardlinks are preserved when moving files across partitions
#[uutests::wasi_ignore(HostPathsNotVisible)]
#[test]
#[cfg(unix)]
pub(crate) fn test_mv_preserves_hardlinks_across_partitions() {
fn test_mv_preserves_hardlinks_across_partitions() {
use std::fs;
use std::os::unix::fs::MetadataExt;
use tempfile::TempDir;
Expand Down Expand Up @@ -2324,10 +2324,9 @@ mod inter_partition_copying {
// Test that hardlinks are preserved even with multiple sets of hardlinked files
#[uutests::wasi_ignore(HostPathsNotVisible)]
#[test]
#[cfg(unix)]
#[allow(clippy::too_many_lines)]
#[allow(clippy::similar_names)]
pub(crate) fn test_mv_preserves_multiple_hardlink_groups_across_partitions() {
fn test_mv_preserves_multiple_hardlink_groups_across_partitions() {
use std::fs::metadata;
use std::os::unix::fs::MetadataExt;
use tempfile::TempDir;
Expand Down Expand Up @@ -2437,11 +2436,80 @@ mod inter_partition_copying {
);
}

// Test hardlinks within directories being moved, including a case with -T onto an
// existing empty directory
#[rstest]
#[case::with_minus_t(true)]
#[case::without_minus_t(false)]
#[uutests::wasi_ignore(HostPathsNotVisible)]
fn test_mv_preserves_hardlinks_in_directories_to_files_across_partitions(
#[case] with_minus_t: bool,
) {
use std::fs::metadata;
use std::os::unix::fs::MetadataExt;

let scene = TestScenario::new(util_name!());
let at = &scene.fixtures;
let basedir: &str = "somedir";
let file_name = "the_file";
let link_name = "hard_link";

let file = format!("{basedir}/{file_name}");
let link = format!("{basedir}/{link_name}");

at.mkdir(basedir);
at.write(&file, "directory file content");
at.hard_link(&file, &link);

let f1_meta = metadata(at.plus(&file)).unwrap();
let f2_meta = metadata(at.plus(&link)).unwrap();

assert_eq!(
f1_meta.ino(),
f2_meta.ino(),
"Both files should have same inode before move"
);
assert_eq!(
f1_meta.nlink(),
2,
"'{file}' should have nlink=2 before move"
);

let other_fs_tempdir =
TempDir::new_in("/dev/shm/").expect("Unable to create temp directory in /dev/shm");

let mut ucmd = scene.ucmd();

let new_dest = other_fs_tempdir.path().join("random");
if with_minus_t {
fs::create_dir(&new_dest).unwrap();
assert!(
new_dest.is_dir(),
"dest must be an existing empty dir so mv -T replaces it"
);
ucmd.arg("-T");
} else {
assert!(
!new_dest.exists(),
"dest must not exist so mv renames instead of moving into it"
);
}

ucmd.arg(basedir).arg(new_dest.to_str().unwrap()).succeeds();

let f1_meta = metadata(new_dest.as_path().join(file_name)).unwrap();
let f2_meta = metadata(new_dest.as_path().join(link_name)).unwrap();
assert_eq!(
f1_meta.ino(),
f2_meta.ino(),
"Both files should've had same inodes because there was a hard link"
);
}

// Test hardlinks within directories being moved
#[uutests::wasi_ignore(HostPathsNotVisible)]
#[test]
#[cfg(unix)]
pub(crate) fn test_mv_preserves_hardlinks_in_directories_across_partitions() {
fn test_mv_preserves_hardlinks_in_directories_across_partitions() {
use std::fs::metadata;
use std::os::unix::fs::MetadataExt;
use tempfile::TempDir;
Expand Down Expand Up @@ -2541,10 +2609,9 @@ mod inter_partition_copying {
// Test complex scenario with multiple hardlink groups across nested directories
#[uutests::wasi_ignore(HostPathsNotVisible)]
#[test]
#[cfg(unix)]
#[allow(clippy::too_many_lines)]
#[allow(clippy::similar_names)]
pub(crate) fn test_mv_preserves_complex_hardlinks_across_nested_directories() {
fn test_mv_preserves_complex_hardlinks_across_nested_directories() {
use std::fs::metadata;
use std::os::unix::fs::MetadataExt;
use tempfile::TempDir;
Expand Down Expand Up @@ -2690,8 +2757,7 @@ mod inter_partition_copying {

#[uutests::wasi_ignore(HostPathsNotVisible)]
#[test]
#[cfg(unix)]
pub(crate) fn test_mv_dir_with_fifo_across_partitions() {
fn test_mv_dir_with_fifo_across_partitions() {
use std::os::unix::fs::FileTypeExt;
use tempfile::TempDir;
use uutests::util::TestScenario;
Expand Down Expand Up @@ -2724,8 +2790,7 @@ mod inter_partition_copying {
// self-referential symlinks and destroying the content.
#[uutests::wasi_ignore(HostPathsNotVisible)]
#[test]
#[cfg(unix)]
pub(crate) fn test_mv_symlink_to_hardlinked_sibling_across_partitions() {
fn test_mv_symlink_to_hardlinked_sibling_across_partitions() {
use std::os::unix::fs::MetadataExt;

let scene = TestScenario::new(util_name!());
Expand Down
Loading