Skip to content

Commit fa8d9fd

Browse files
pjbullspdjudd
andauthored
Prevent file loss/exceptions when renaming: (#278) (#279)
* Prevent file loss/exceptions when renaming: (#278) Do nothing if renaming to the same path Explicit exception when attempting to rename a dir * Update HISTORY.md Co-authored-by: Simon Judd <simon@3ai.co>
1 parent b7f6010 commit fa8d9fd

3 files changed

Lines changed: 20 additions & 2 deletions

File tree

HISTORY.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22

33
## v0.11.0 (UNRELEASED)
44

5-
- API change: Add `ignore` parameter to `CloudPath.copytree` in order to match `shutil` API. ([Issue #145](https://github.com/drivendataorg/cloudpathlib/issues/234), [PR #272](https://github.com/drivendataorg/cloudpathlib/pull/250))
5+
- API change: Add `ignore` parameter to `CloudPath.copytree` in order to match `shutil` API. ([Issue #145](https://github.com/drivendataorg/cloudpathlib/issues/145), [PR #272](https://github.com/drivendataorg/cloudpathlib/pull/272))
6+
- Prevent data loss when renaming by skipping files that would be renamed to the same thing. ([Issue #277](https://github.com/drivendataorg/cloudpathlib/issues/277), [PR #278](https://github.com/drivendataorg/cloudpathlib/pull/278))
67

78

89
## v0.10.0 (2022-08-18)

cloudpathlib/cloudpath.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -453,6 +453,15 @@ def replace(self, target: "CloudPath") -> "CloudPath":
453453
f"The target based to rename must be an instantiated class of type: {type(self)}"
454454
)
455455

456+
if self.is_dir():
457+
raise CloudPathIsADirectoryError(
458+
f"Path {self} is a directory; rename/replace the files recursively."
459+
)
460+
461+
if target == self:
462+
# Request is to replace/rename this with the same path - nothing to do
463+
return self
464+
456465
if target.exists():
457466
target.unlink()
458467

tests/test_cloudpath_file_io.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,9 @@ def test_file_discovery(rig):
3838
with pytest.raises(CloudPathIsADirectoryError):
3939
p3.unlink()
4040

41+
with pytest.raises(CloudPathIsADirectoryError):
42+
p3.rename(rig.create_cloud_path("dir_2/"))
43+
4144
with pytest.raises(DirectoryNotEmptyError):
4245
p3.rmdir()
4346
p3.rmtree()
@@ -275,8 +278,13 @@ def test_file_read_writes(rig, tmp_path):
275278
assert not dest.exists()
276279
p.rename(dest)
277280
assert dest.exists()
278-
279281
assert not p.exists()
282+
283+
dest_duplicate = rig.create_cloud_path("dir2/new_file0_0.txt")
284+
assert dest == dest_duplicate
285+
dest.rename(dest_duplicate)
286+
assert dest.exists()
287+
280288
p.touch()
281289
dest.replace(p)
282290
assert p.exists()

0 commit comments

Comments
 (0)