Skip to content

Commit 0a3ac07

Browse files
committed
extmod/vfs: Rewrite path lookup algo to support relative paths from root.
For example, if the current directory is the root dir then this patch allows one to do uos.listdir('mnt'), where 'mnt' is a valid mount point. Previous to this patch such a thing would not work, on needed to do uos.listdir('/mnt') instead.
1 parent a7a2344 commit 0a3ac07

1 file changed

Lines changed: 27 additions & 22 deletions

File tree

extmod/vfs.c

Lines changed: 27 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -43,33 +43,38 @@
4343
// Returns MP_VFS_ROOT for root dir (and then path_out is undefined) and
4444
// MP_VFS_NONE for path not found.
4545
mp_vfs_mount_t *mp_vfs_lookup_path(const char *path, const char **path_out) {
46-
if (path[0] == '/' && path[1] == 0) {
47-
return MP_VFS_ROOT;
48-
} else if (MP_STATE_VM(vfs_cur) == MP_VFS_ROOT) {
49-
// in root dir
50-
if (path[0] == 0) {
51-
return MP_VFS_ROOT;
46+
if (*path == '/' || MP_STATE_VM(vfs_cur) == MP_VFS_ROOT) {
47+
// an absolute path, or the current volume is root, so search root dir
48+
bool is_abs = 0;
49+
if (*path == '/') {
50+
++path;
51+
is_abs = 1;
5252
}
53-
} else if (*path != '/') {
54-
// a relative path within a mounted device
55-
*path_out = path;
56-
return MP_STATE_VM(vfs_cur);
57-
}
58-
59-
for (mp_vfs_mount_t *vfs = MP_STATE_VM(vfs_mount_table); vfs != NULL; vfs = vfs->next) {
60-
if (strncmp(path, vfs->str, vfs->len) == 0) {
61-
if (path[vfs->len] == '/') {
62-
*path_out = path + vfs->len;
63-
return vfs;
64-
} else if (path[vfs->len] == '\0') {
65-
*path_out = "/";
66-
return vfs;
53+
for (mp_vfs_mount_t *vfs = MP_STATE_VM(vfs_mount_table); vfs != NULL; vfs = vfs->next) {
54+
size_t len = vfs->len - 1;
55+
if (strncmp(path, vfs->str + 1, len) == 0) {
56+
if (path[len] == '/') {
57+
*path_out = path + len;
58+
return vfs;
59+
} else if (path[len] == '\0') {
60+
*path_out = "/";
61+
return vfs;
62+
}
6763
}
6864
}
65+
if (*path == '\0') {
66+
// path was "" or "/" so return virtual root
67+
return MP_VFS_ROOT;
68+
}
69+
if (is_abs) {
70+
// path began with / and was not found
71+
return MP_VFS_NONE;
72+
}
6973
}
7074

71-
// mount point not found
72-
return MP_VFS_NONE;
75+
// a relative path within a mounted device
76+
*path_out = path;
77+
return MP_STATE_VM(vfs_cur);
7378
}
7479

7580
// Version of mp_vfs_lookup_path that takes and returns uPy string objects.

0 commit comments

Comments
 (0)