Commit b7df3e54 authored by Damien George's avatar Damien George
Browse files

extmod/vfs_fat: Implement POSIX behaviour of rename, allow to overwrite.

If the destination of os.rename() exists then it will be overwritten if it
is a file.  This is the POSIX behaviour, which is also the CPython
behaviour, and so we follow suit.

See issue #2598 for discussion.
parent 08bd7d1d
...@@ -121,6 +121,12 @@ STATIC mp_obj_t fat_vfs_rename(mp_obj_t vfs_in, mp_obj_t path_in, mp_obj_t path_ ...@@ -121,6 +121,12 @@ STATIC mp_obj_t fat_vfs_rename(mp_obj_t vfs_in, mp_obj_t path_in, mp_obj_t path_
const char *old_path = mp_obj_str_get_str(path_in); const char *old_path = mp_obj_str_get_str(path_in);
const char *new_path = mp_obj_str_get_str(path_out); const char *new_path = mp_obj_str_get_str(path_out);
FRESULT res = f_rename(old_path, new_path); FRESULT res = f_rename(old_path, new_path);
if (res == FR_EXIST) {
// if new_path exists then try removing it (but only if it's a file)
fat_vfs_remove_internal(path_out, 0); // 0 == file attribute
// try to rename again
res = f_rename(old_path, new_path);
}
if (res == FR_OK) { if (res == FR_OK) {
return mp_const_none; return mp_const_none;
} else { } else {
......
...@@ -140,6 +140,14 @@ print(vfs.listdir("foo_dir")) ...@@ -140,6 +140,14 @@ print(vfs.listdir("foo_dir"))
vfs.rename("foo_dir/file.txt", "moved-to-root.txt") vfs.rename("foo_dir/file.txt", "moved-to-root.txt")
print(vfs.listdir()) print(vfs.listdir())
# check that renaming to existing file will overwrite it
with vfs.open("temp", "w") as f:
f.write("new text")
vfs.rename("temp", "moved-to-root.txt")
print(vfs.listdir())
with vfs.open("moved-to-root.txt") as f:
print(f.read())
# valid removes # valid removes
vfs.remove("foo_dir/sub_file.txt") vfs.remove("foo_dir/sub_file.txt")
vfs.remove("foo_file.txt") vfs.remove("foo_file.txt")
......
...@@ -18,5 +18,7 @@ b'data in file' ...@@ -18,5 +18,7 @@ b'data in file'
True True
['sub_file.txt', 'file.txt'] ['sub_file.txt', 'file.txt']
['foo_file.txt', 'foo_dir', 'moved-to-root.txt'] ['foo_file.txt', 'foo_dir', 'moved-to-root.txt']
['foo_file.txt', 'foo_dir', 'moved-to-root.txt']
new text
['moved-to-root.txt'] ['moved-to-root.txt']
ENOSPC: True ENOSPC: True
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment