diff --git a/CHANGELOG.md b/CHANGELOG.md index 2bed1e1..f968916 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,12 @@ All notable changes to this project are documented here. The format follows folder of another case, as on FAT, exFAT or SMB drives on Linux. Changing only the case of a folder's name (`Photos` to `photos`) deleted every file in it, and renaming `a` to `b` merged it into an existing `B`. +- Rename a file to a change of case only (`notes.txt` to `Notes.txt`) where + rclone knows the filesystem ignores case, as on macOS, which was refused as + a name already in use. Where rclone does not know, as on FAT, exFAT or SMB + drives on Linux (reported case-sensitive however they behave), the move + would delete the file: the refusal now explains that and suggests renaming + through another name, which works. ## [0.1.1] - 2026-11-15 diff --git a/src/backend/rc.rs b/src/backend/rc.rs index c4ddb65..2fe8211 100644 --- a/src/backend/rc.rs +++ b/src/backend/rc.rs @@ -14,7 +14,8 @@ use super::{ }; use crate::location::{Location, Remote}; use crate::rc::types::{ - RcAbout, RcConfigOut, RcJobId, RcJobStatus, RcList, RcListItem, RcOption, RcProviders, RcStats, RcVersion, + RcAbout, RcConfigOut, RcFsInfo, RcJobId, RcJobStatus, RcList, RcListItem, RcOption, RcProviders, RcStats, + RcVersion, }; use crate::rc::{RcError, UnixRc}; use crate::transfer::spec::{FileProgress, TransferKind, TransferProgress, TransferSpec, aggregate}; @@ -69,6 +70,18 @@ impl RcBackend { } } + /// Whether rclone knows the filesystem of `loc` ignores case. It then moves a + /// file whose name changes only its case through a temporary name; where it + /// does not, as on FAT, exFAT or SMB drives on Linux (reported case-sensitive + /// whatever the filesystem really is), the move deletes the file instead. + async fn fs_ignores_case(&self, loc: &Location) -> Result { + let info: RcFsInfo = self + .rc + .call_typed("operations/fsinfo", json!({ "fs": loc.fs() })) + .await?; + Ok(info.features.case_insensitive) + } + /// Write `names` (one per line, relative to the source folder) for `--files-from-raw`. fn write_list(&self, group: &str, names: &[&str]) -> Result { let io = |e: std::io::Error| BackendError::Other(format!("could not write file list: {e}")); @@ -311,15 +324,39 @@ impl Backend for RcBackend { // rclone moves onto whatever has the new name: a file is overwritten, a folder // merged into. The pane refuses names it shows, but its listing may be old, // and some services (Dropbox, OneDrive) find `photo.jpg` when asked for - // `Photo.JPG`. Look right before moving. The entry itself answering to the - // new name is a change of case only, which is fine. + // `Photo.JPG`. Look right before moving. if let Some(taken) = self.stat(&to).await? && taken.name != from.name() { - return Err(BackendError::Other(format!( - "“{}” already exists here", - taken.name - ))); + // Where the filesystem ignores case the entry itself answers to the new + // name, and the local backend of macOS answers with the name it was + // asked for, so `Notes.txt` looks like another entry while it is + // `notes.txt` itself. The folder's real names tell the two apart: only + // another entry matching the new name, in whatever case, is a file to + // keep away from. + let wanted = new_name.to_lowercase(); + let case_only = !is_dir + && wanted == from.name().to_lowercase() + && !self + .list(&parent) + .await? + .iter() + .any(|e| e.name != from.name() && e.name.to_lowercase() == wanted); + if !case_only { + return Err(BackendError::Other(format!( + "“{}” already exists here", + taken.name + ))); + } + // rclone renames through a temporary name only where it knows the + // filesystem ignores case; anywhere else the move deletes the file. + if !self.fs_ignores_case(from).await? { + return Err(BackendError::Other(format!( + "this filesystem ignores case: “{new_name}” is “{}” itself; \ + rename it to another name first", + from.name() + ))); + } } // `stat` finds a folder only by its exact name. Where the filesystem ignores // case (FAT, exFAT or SMB on Linux), `photos` still opens `Photos`, and moving diff --git a/src/rc/types.rs b/src/rc/types.rs index 6a74769..b99e49a 100644 --- a/src/rc/types.rs +++ b/src/rc/types.rs @@ -81,6 +81,23 @@ pub struct RcAbout { pub objects: Option, } +/// `operations/fsinfo`: what rclone can do on a filesystem, as it sees it. Only +/// the one feature a rename depends on is read; the rest is ignored. +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(rename_all = "PascalCase", default)] +pub struct RcFsInfo { + pub features: RcFeatures, +} + +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(rename_all = "PascalCase", default)] +pub struct RcFeatures { + /// Whether rclone itself takes care of a change of case, moving the file + /// through a temporary name. The local backend reports every filesystem on + /// Linux as case-sensitive, however it really behaves. + pub case_insensitive: bool, +} + #[derive(Debug, Clone, Default, Deserialize)] #[serde(rename_all = "camelCase", default)] pub struct RcStats { diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 2b7f384..544ebdd 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -40,6 +40,10 @@ pub fn rclone_bin() -> Option { /// Keep test daemons independent of environment-defined remotes and credentials. /// The wrapper execs rclone, preserving its PID and the caller's fake-browser PATH. +/// +/// It also turns off cloning: on macOS (APFS) rclone clones a local-to-local copy, +/// which ends at once whatever the bandwidth limit, and the tests that need a copy +/// still running throttle one. Older rclones ignore the unknown variable. pub fn isolated_rclone(binary: &Path, directory: &Path) -> PathBuf { use std::os::unix::fs::PermissionsExt; let quote = |path: &Path| format!("'{}'", path.to_str().unwrap().replace('\'', "'\\''")); @@ -47,7 +51,7 @@ pub fn isolated_rclone(binary: &Path, directory: &Path) -> PathBuf { std::fs::write( &wrapper, format!( - "#!/bin/sh\nexec /usr/bin/env -i PATH=\"$PATH\" HOME={} XDG_CONFIG_HOME={} XDG_CACHE_HOME={} {} \"$@\"\n", + "#!/bin/sh\nexec /usr/bin/env -i PATH=\"$PATH\" HOME={} XDG_CONFIG_HOME={} XDG_CACHE_HOME={} RCLONE_LOCAL_NO_CLONE=true {} \"$@\"\n", quote(directory), quote(&directory.join("config")), quote(&directory.join("cache")), diff --git a/tests/rc_backend.rs b/tests/rc_backend.rs index 4674160..10bf38d 100644 --- a/tests/rc_backend.rs +++ b/tests/rc_backend.rs @@ -109,7 +109,30 @@ async fn rename_never_lands_on_another_entry() { assert!(!root.join("d2/x.txt").exists()); // A change of case only is a rename like any other. backend.rename(&tst("b.txt"), "B.txt", false).await.unwrap(); - assert!(root.join("B.txt").exists()); + // The real names: on a filesystem that ignores case (macOS) `exists()` answers + // for `b.txt` whatever was renamed. + let names: Vec<_> = std::fs::read_dir(root) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + assert!(names.contains(&"B.txt".to_string()), "{names:?}"); + assert!(!names.contains(&"b.txt".to_string()), "{names:?}"); +} + +#[tokio::test] +async fn a_change_of_case_never_lands_on_another_entry() { + let Some((f, backend)) = setup() else { return }; + let root = &f.root; + std::fs::write(root.join("b.txt"), "b").unwrap(); + std::fs::write(root.join("B.txt"), "keep me").unwrap(); + // On a filesystem that ignores case (macOS) the second write replaced the first. + if std::fs::read_to_string(root.join("b.txt")).unwrap() != "b" { + return; + } + let e = backend.rename(&tst("b.txt"), "B.txt", false).await.unwrap_err(); + assert!(e.to_string().contains("already exists"), "{e}"); + assert_eq!(std::fs::read_to_string(root.join("b.txt")).unwrap(), "b"); + assert_eq!(std::fs::read_to_string(root.join("B.txt")).unwrap(), "keep me"); } // rclone moves a folder into whatever folder the new name finds. Where the @@ -186,6 +209,63 @@ async fn a_folder_changes_case_where_the_filesystem_keeps_case() { assert!(!root.join("Photos").exists()); } +// Where the filesystem ignores case, a file's own name answers to the new one, +// so `stat` alone cannot tell the file from another entry. What rclone knows +// about the filesystem decides between a safe rename and a clear refusal. + +#[tokio::test] +async fn a_file_changes_case_only_where_rclone_knows_it_can() { + let Some((f, backend)) = setup() else { return }; + let Some(ci) = CaseInsensitiveDir::over(&f) else { + return; + }; + std::fs::write(ci.path.join("notes.txt"), "keep me").unwrap(); + let notes = Location::new(Remote::Local, &ci.path.join("notes.txt").display().to_string()); + let names = || { + std::fs::read_dir(&ci.backing) + .unwrap() + .map(|e| e.unwrap().file_name()) + .collect::>() + }; + // On macOS rclone knows the filesystem ignores case and moves the file + // through a temporary name; on Linux it reports FAT, exFAT and SMB as + // case-sensitive, and the move would delete the file. + let info: ratclone::rc::types::RcFsInfo = + f.rc.call_typed("operations/fsinfo", serde_json::json!({ "fs": "/" })) + .await + .unwrap(); + let result = backend.rename(¬es, "Notes.txt", false).await; + if info.features.case_insensitive { + result.unwrap(); + assert_eq!(names(), ["Notes.txt"]); + assert_eq!( + std::fs::read_to_string(ci.backing.join("Notes.txt")).unwrap(), + "keep me" + ); + } else { + let e = result.unwrap_err(); + assert!(e.to_string().contains("ignores case"), "{e}"); + assert_eq!(names(), ["notes.txt"]); + assert_eq!( + std::fs::read_to_string(ci.backing.join("notes.txt")).unwrap(), + "keep me" + ); + } + // The way the message suggests: through another name, then to the wanted + // case. Another file: the refused lookups above still ring in the test + // mount's cache, and answer for a file that is no longer there. + std::fs::write(ci.path.join("other.txt"), "keep me too").unwrap(); + let other = Location::new(Remote::Local, &ci.path.join("other.txt").display().to_string()); + backend.rename(&other, "other.tmp", false).await.unwrap(); + let tmp = Location::new(Remote::Local, &ci.path.join("other.tmp").display().to_string()); + backend.rename(&tmp, "Other.txt", false).await.unwrap(); + assert_eq!( + std::fs::read_to_string(ci.backing.join("Other.txt")).unwrap(), + "keep me too" + ); + assert!(names().iter().any(|n| *n == "Other.txt")); +} + #[tokio::test] async fn a_folder_renames_on_a_bucket_based_remote() { let Some((f, backend)) = setup() else { return }; diff --git a/tests/rc_client.rs b/tests/rc_client.rs index 79c45b8..d0a21e2 100644 --- a/tests/rc_client.rs +++ b/tests/rc_client.rs @@ -13,15 +13,18 @@ fn daemon_wrapper_excludes_inherited_credentials_and_remotes() { .tempdir() .unwrap(); let wrapper = common::isolated_rclone(std::path::Path::new("/usr/bin/env"), dir.path()); - let output = std::process::Command::new(wrapper) - .env_clear() + let mut cmd = std::process::Command::new(&wrapper); + cmd.env_clear() .env("RCLONE_CONFIG_TST_REMOTE", "/personal/files") .env("RCLONE_CONFIG_PASS", "private-password") .env("AWS_SECRET_ACCESS_KEY", "private-key") .env("HOME", "/personal/home") .env("PATH", "/fake/browser/path") - .output() - .unwrap(); + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()); + // Tests run in parallel: a wrapper just written can still be open for + // writing in a child another test forked but not yet exec'd. + let output = common::spawn(&mut cmd).wait_with_output().unwrap(); assert!(output.status.success()); let env = String::from_utf8(output.stdout).unwrap(); assert!(!env.contains("private-") && !env.contains("/personal/"), "{env}");