Skip to content

Commit d02f3a5

Browse files
Alex Marchdpgeorge
authored andcommitted
extmod/vfs_fat: Add file and directory checks for remove and rmdir.
1 parent eaef6b5 commit d02f3a5

1 file changed

Lines changed: 29 additions & 10 deletions

File tree

extmod/vfs_fat.c

Lines changed: 29 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
#include <string.h>
3232
#include "py/nlr.h"
3333
#include "py/runtime.h"
34+
#include "py/mperrno.h"
3435
#include "lib/fatfs/ff.h"
3536
#include "lib/fatfs/diskio.h"
3637
#include "extmod/vfs_fat_file.h"
@@ -76,24 +77,42 @@ STATIC mp_obj_t fat_vfs_listdir_func(size_t n_args, const mp_obj_t *args) {
7677
}
7778
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(fat_vfs_listdir_obj, 1, 2, fat_vfs_listdir_func);
7879

79-
STATIC mp_obj_t fat_vfs_remove(mp_obj_t vfs_in, mp_obj_t path_in) {
80-
(void)vfs_in;
80+
STATIC mp_obj_t fat_vfs_remove_internal(mp_obj_t path_in, mp_int_t attr) {
8181
const char *path = mp_obj_str_get_str(path_in);
82-
// TODO check that path is actually a file before trying to unlink it
83-
FRESULT res = f_unlink(path);
84-
if (res == FR_OK) {
82+
83+
FILINFO fno;
84+
#if _USE_LFN
85+
fno.lfname = NULL;
86+
fno.lfsize = 0;
87+
#endif
88+
FRESULT res = f_stat(path, &fno);
89+
90+
if (res != FR_OK) {
91+
mp_raise_OSError(fresult_to_errno_table[res]);
92+
}
93+
94+
// check if path is a file or directory
95+
if ((fno.fattrib & AM_DIR) == attr) {
96+
res = f_unlink(path);
97+
98+
if (res != FR_OK) {
99+
mp_raise_OSError(fresult_to_errno_table[res]);
100+
}
85101
return mp_const_none;
86102
} else {
87-
mp_raise_OSError(fresult_to_errno_table[res]);
103+
mp_raise_OSError(attr ? MP_ENOTDIR : MP_EISDIR);
88104
}
89105
}
106+
107+
STATIC mp_obj_t fat_vfs_remove(mp_obj_t vfs_in, mp_obj_t path_in) {
108+
(void)vfs_in;
109+
return fat_vfs_remove_internal(path_in, 0); // 0 == file attribute
110+
}
90111
STATIC MP_DEFINE_CONST_FUN_OBJ_2(fat_vfs_remove_obj, fat_vfs_remove);
91112

92113
STATIC mp_obj_t fat_vfs_rmdir(mp_obj_t vfs_in, mp_obj_t path_in) {
93-
// TODO: Currently just redirects to fat_vfs_remove(), which are
94-
// backed by the same underlying FatFs function. Should at least
95-
// check that path is actually a dir.
96-
return fat_vfs_remove(vfs_in, path_in);
114+
(void) vfs_in;
115+
return fat_vfs_remove_internal(path_in, AM_DIR);
97116
}
98117
STATIC MP_DEFINE_CONST_FUN_OBJ_2(fat_vfs_rmdir_obj, fat_vfs_rmdir);
99118

0 commit comments

Comments
 (0)