Skip to content

Commit bdd6b7c

Browse files
author
Saiteja Kura
committed
Add FileLock::rename method to update path after filesystem rename
The existing FileLock struct tracks a file path but doesn't provide a way to update that path when the underlying file is moved. This causes issues when code renames a locked file and then tries to access it through the FileLock, as the internal path becomes stale. Add a rename() method that performs both the filesystem rename operation and updates the internal path, ensuring the FileLock remains valid after the file is moved.
1 parent 35775fa commit bdd6b7c

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

src/cargo/util/flock.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,29 @@ impl FileLock {
7676
}
7777
Ok(())
7878
}
79+
80+
/// Renames the file and updates the internal path.
81+
///
82+
/// This method performs a filesystem rename operation using [`std::fs::rename`]
83+
/// while keeping the FileLock's internal path synchronized with the actual
84+
/// file location.
85+
///
86+
/// ## Difference from `std::fs::rename`
87+
///
88+
/// - `std::fs::rename(old, new)` only moves the file on the filesystem
89+
/// - `FileLock::rename(new)` moves the file AND updates `self.path` to point to the new location
90+
pub fn rename<P: AsRef<Path>>(&mut self, new_path: P) -> CargoResult<()> {
91+
let new_path = new_path.as_ref();
92+
std::fs::rename(&self.path, new_path).with_context(|| {
93+
format!(
94+
"failed to rename {} to {}",
95+
self.path.display(),
96+
new_path.display()
97+
)
98+
})?;
99+
self.path = new_path.to_path_buf();
100+
Ok(())
101+
}
79102
}
80103

81104
impl Read for FileLock {

0 commit comments

Comments
 (0)