[mpy/os] listdir

This commit is contained in:
M4x1m3
2020-07-21 22:17:33 +02:00
parent 18ccc0c771
commit 14a3ea51c4
6 changed files with 54 additions and 0 deletions

View File

@@ -122,6 +122,10 @@ public:
// Useful
static bool FullNameCompliant(const char * name);
// User by Python OS module
int numberOfRecords();
Record recordAtIndex(int index);
private:
constexpr static uint32_t Magic = 0xEE0BDDBA;

View File

@@ -208,6 +208,37 @@ int Storage::numberOfRecordsWithExtension(const char * extension) {
return count;
}
int Storage::numberOfRecords() {
int count = 0;
for (char * p : *this) {
const char * name = fullNameOfRecordStarting(p);
count++;
}
return count;
}
Storage::Record Storage::recordAtIndex(int index) {
int currentIndex = -1;
const char * name = nullptr;
char * recordAddress = nullptr;
for (char * p : *this) {
const char * currentName = fullNameOfRecordStarting(p);
currentIndex++;
if (currentIndex == index) {
recordAddress = p;
name = currentName;
break;
}
}
if (name == nullptr) {
return Record();
}
Record r = Record(name);
m_lastRecordRetrieved = r;
m_lastRecordRetrievedPointer = recordAddress;
return Record(name);
}
Storage::Record Storage::recordWithExtensionAtIndex(const char * extension, int index) {
int currentIndex = -1;
const char * name = nullptr;

View File

@@ -535,4 +535,5 @@ Q(release)
Q(version)
Q(machine)
Q(rename)
Q(listdir)

View File

@@ -1,5 +1,6 @@
extern "C" {
#include "modos.h"
#include <string.h>
#include <py/obj.h>
#include <py/runtime.h>
#include <py/objstr.h>
@@ -98,3 +99,17 @@ mp_obj_t modos_rename(mp_obj_t o_old_name, mp_obj_t o_new_name) {
return mp_const_none;
}
mp_obj_t modos_listdir(void) {
mp_obj_t list = mp_obj_new_list(0, NULL);
for(size_t i = 0; i < (size_t)Ion::Storage::sharedStorage()->numberOfRecords(); i++) {
Ion::Storage::Record record = Ion::Storage::sharedStorage()->recordAtIndex(i);
size_t file_name_length = strlen(record.fullName());
mp_obj_t file_name = mp_obj_new_str(record.fullName(), file_name_length);
mp_obj_list_append(list, file_name);
}
return list;
}

View File

@@ -3,3 +3,4 @@
mp_obj_t modos_uname();
mp_obj_t modos_remove(mp_obj_t o_file_name);
mp_obj_t modos_rename(mp_obj_t o_old_name, mp_obj_t o_new_name);
mp_obj_t modos_listdir();

View File

@@ -3,12 +3,14 @@
MP_DEFINE_CONST_FUN_OBJ_0(modos_uname_obj, modos_uname);
MP_DEFINE_CONST_FUN_OBJ_1(modos_remove_obj, modos_remove);
MP_DEFINE_CONST_FUN_OBJ_2(modos_rename_obj, modos_rename);
MP_DEFINE_CONST_FUN_OBJ_0(modos_listdir_obj, modos_listdir);
STATIC const mp_rom_map_elem_t modos_module_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_os) },
{ MP_ROM_QSTR(MP_QSTR_uname), &modos_uname_obj},
{ MP_ROM_QSTR(MP_QSTR_remove), &modos_remove_obj},
{ MP_ROM_QSTR(MP_QSTR_rename), &modos_rename_obj},
{ MP_ROM_QSTR(MP_QSTR_listdir), &modos_listdir_obj},
};
STATIC MP_DEFINE_CONST_DICT(modos_module_globals, modos_module_globals_table);