Example #1
0
 def load(self):
     try:
         from ujson import loads
         from uos import stat, mkdir
         try:
             stat('/etc')
         except Exception as e:
             if e.args[0] == 2:
                 mkdir('/etc')
             else:
                 raise
         finally:
             try:
                 del stat, mkdir
             except:
                 pass
         with open(self.filename) as fp:
             self.json = loads(''.join(fp.readlines()))
     except Exception as e:
         prexc(e)
         self.load_defaults()
     finally:
         try:
             del loads
         except:
             pass
Example #2
0
def ensure_folder(path: str):
    "Create nested folders if needed"
    i = start = 0
    while i != -1:
        i = path.find("/", start)
        if i != -1:
            if i == 0:
                p = path[0]
            else:
                p = path[0:i]
            # p = partial folder
            try:
                _ = os.stat(p)
            except OSError as e:
                # folder does not exist
                if e.args[0] == ENOENT:
                    try:
                        os.mkdir(p)
                    except OSError as e2:
                        # self._log.error("failed to create folder {}".format(p))
                        raise e2
                else:
                    # self._log.error("failed to create folder {}".format(p))
                    raise e
        # next level deep
        start = i + 1
Example #3
0
def test(bdev, vfs_class):
    print("test", vfs_class)

    # mkfs
    vfs_class.mkfs(bdev)

    # construction
    vfs = vfs_class(bdev)

    # mount
    uos.mount(vfs, "/lfs")

    # import
    with open("/lfs/lfsmod.py", "w") as f:
        f.write('print("hello from lfs")\n')
    import lfsmod

    # import package
    uos.mkdir("/lfs/lfspkg")
    with open("/lfs/lfspkg/__init__.py", "w") as f:
        f.write('print("package")\n')
    import lfspkg

    # chdir and import module from current directory (needs "" in sys.path)
    uos.mkdir("/lfs/subdir")
    uos.chdir("/lfs/subdir")
    uos.rename("/lfs/lfsmod.py", "/lfs/subdir/lfsmod2.py")
    import lfsmod2

    # umount
    uos.umount("/lfs")

    # clear imported modules
    sys.modules.clear()
Example #4
0
 def save_rk(self, rkid, user_id, key_handle):
     try:
         stat = statvfs('/flash')
         if stat[0] * stat[3] < 100000:  # bsize * bfree
             # if actual number of free bytes too low exit
             return False
         dir = listdir()
         if KS_CTAP2.RK_DIR not in dir:
             mkdir(KS_CTAP2.RK_DIR)
         dir = listdir(KS_CTAP2.RK_DIR)
         fn = hexlify(user_id).decode('utf-8')
         with open(KS_CTAP2.RK_DIR + '/' + fn, 'wb') as fout:
             fout.write(key_handle)
         if rkid in self.RKS:
             if fn in self.RKS[rkid]:
                 self.RKS[rkid].remove(fn)
             self.RKS[rkid].append(fn)  # most recent ones at the end
         else:
             self.RKS[rkid] = [fn]
         self.save_keystore()
     except OSError:
         return False
     except ValueError:
         return False
     return True
Example #5
0
def test(bdev, vfs_class):
    print('test', vfs_class)

    # mkfs
    vfs_class.mkfs(bdev)

    # construction
    vfs = vfs_class(bdev)

    # mount
    uos.mount(vfs, '/lfs')

    # import
    with open('/lfs/lfsmod.py', 'w') as f:
        f.write('print("hello from lfs")\n')
    import lfsmod

    # import package
    uos.mkdir('/lfs/lfspkg')
    with open('/lfs/lfspkg/__init__.py', 'w') as f:
        f.write('print("package")\n')
    import lfspkg

    # umount
    uos.umount('/lfs')

    # clear imported modules
    sys.modules.clear()
 async def MKD(self, stream, argument):
     try:
         os.mkdir(argument)
         await stream.awrite("257 Okey.\r\n")
     except OSError as e:
         await stream.awrite("550 {}.\r\n".format(e))
     return True
Example #7
0
    def save_certificates(config_dict: dict) -> None:
        """
        Save AWS certificates to files.
        :param config_dict: dict with credentials.
        :return: None
        """
        global cfg
        logging.debug("save_certificates()")
        try:
            mkdir(CERTIFICATES_DIR)
        except:
            pass

        if 'cert_pem' in config_dict.keys():
            certificate_string = config_dict['cert_pem']
            cfg.cert_pem = config_dict['cert_pem']
            with open(CERTIFICATE_PATH, "w", encoding="utf8") as infile:
                infile.write(certificate_string)

        if 'priv_key' in config_dict.keys():
            private_key_string = config_dict['priv_key']
            cfg.private_key = config_dict['priv_key']
            logging.info(private_key_string)
            with open(KEY_PATH, "w", encoding="utf8") as infile:
                infile.write(private_key_string)

        if 'cert_ca' in config_dict.keys():
            ca_certificate_string = config_dict['cert_ca']
            cfg.cert_ca = config_dict['cert_ca']
            with open(CA_CERTIFICATE_PATH, "w", encoding="utf8") as infile:
                infile.write(ca_certificate_string)
Example #8
0
 def _download_file(self, f):
     content = urequests.get(f["download_url"])
     if content.status_code == 200:
         if "next" not in uos.listdir():
             uos.mkdir("next")
         with open("next/" + f["name"], "w") as f:
             f.write(content.content)
Example #9
0
    def check_path(self, file_path):
        """ checks if the folder leaving to the given file path exist/creates them """
        # split the path into its parts
        # the last element is the file name; all before are folders
        path_parts = file_path.split("/")[:-1]

        # string to store the path of existent dirs
        current_path = "/"

        # go trough the parts
        for part in path_parts:
            # ignore potential empty parts originating from splitting up paths like
            #  /flash/... (leading /)
            #  /flash//lib (double /)
            if part.strip() == "":
                continue

            # assemble the new path
            new_path = current_path + part

            # check if the part (dir) is not found in the current directory
            # remove the trailing / if the path does consist of more than just the /
            # os.listdir("/flash/lib/") will cause an EINVAL error
            if not part in os.listdir(current_path[:-1] if (
                    len(current_path) > 1 and current_path[-1] == "/"
            ) else current_path):
                # create it
                os.mkdir(new_path)

            # set the current_path and add a / for the next part
            current_path = new_path + "/"
Example #10
0
def add_directory(directory, sock=None):
    try:
        uos.mkdir(directory)
    except:
        out = "could not create %s" % directory
        print(out)
        send_output(sock, out)
Example #11
0
def __process_next_file_entry(dio, verbose=False):
    header = dio.read(6)
    if len(header) < 6:
        return False
    file_name_length = int.from_bytes(header[:2], "big")
    file_type = header[2]
    file_content_length = int.from_bytes(header[3:6], "big")
    file_name = dio.read(file_name_length).decode("utf8")
    if file_type == TYPE_DIR:
        if verbose:
            print("DIR: {}".format(file_name))
            console.log("DIR: {}".format(file_name))
        try:
            uos.mkdir(file_name)
        except:
            pass
    else:
        if verbose:
            print("FILE: {} SIZE: {}".format(file_name, file_content_length))
            console.log("FILE: {} SIZE: {}".format(file_name,
                                                   file_content_length))
        with open(file_name, "wb") as f:
            count = 0
            buffer = bytearray(BUFFER_SIZE)
            while count + BUFFER_SIZE <= file_content_length:
                size = dio.readinto(buffer)
                f.write(buffer)
                f.flush()
                count += size
            count = file_content_length % BUFFER_SIZE
            if count > 0:
                size = dio.readinto(buffer, count)
                f.write(buffer[:count])
                f.flush()
    return True
Example #12
0
 def __init__(self, path="/woezel_packages"):
     self.path = path
     self.categories = []
     self.lastUpdate = 0
     try:
         uos.mkdir(self.path)
     except:
         pass
Example #13
0
 def save(self):
     # Create config_dir if do not exists
     try:
         uos.stat(self.config_dir)
     except OSError:
         uos.mkdir(self.config_dir)
     with open('{}/{}.json'.format(self.config_dir, self.name), 'w') as fp:
         json.dump(self.data, fp)
Example #14
0
 def create_dir(cls, name):
     try:
         uos.mkdir(name)
     except OSError as e:
         log.debug("MKDIR: {}, {}".format(e, name))
         return False
     log.info("MKDIR: {}".format(name))
     return True
Example #15
0
def setup():
    check_bootsec()
    print("Performing initial setup")
    uos.VfsFat.mkfs(bdev)
    vfs = uos.VfsFat(bdev)
    uos.mount(vfs, '/')

    # Make dobby config dir
    uos.mkdir('/conf')
    # make lib dir
    uos.mkdir('/lib')

    with open("boot.py", "w") as f:
        f.write("""\
# Print to clear serial on boot
print("")
print("")
# Disable os debugging
import esp
esp.osdebug(None)
""")

    with open("main.py", "w") as f:
        f.write("""\
# Import and run loader to check modules
import loader
# Run loader
Loader = loader.Run()
# get log queue from loader
Log_Queue = Loader.Log_Queue
# Delete the Loader and loader to free memory
del Loader
del loader

# Import base system to get wifi up and download modules if needed
import base
# run base with loader.Run() as arguments, it will return a loader log to be published when connected
Base = base.Run(Log_Queue)
# delete the log queue
del Log_Queue
# Run base loop
Base.Loop()

# If we get to here something went wrong so lets reboot
print()
print()
print()
print()
print()
print("End of loop rebooting - we should not get to here")
print()
print()
print()
print()
print()
""")

    return vfs
Example #16
0
    def restore_backup(dir_to_restore='firmware'):
        target = 'backup'
        try:
            uos.rmdir(dir_to_restore)
        except OSError:
            pass

        uos.mkdir(dir_to_restore)
        move_f(target, dir_to_restore)
Example #17
0
 def init(cls, fail_silently=False):
     cls.__fields__ = list(cls.__schema__.keys())
     cls.Row = namedtuple(cls.__table__, cls.__fields__)
     for d in (cls.__db__.name, "%s/%s" % (cls.__db__.name, cls.__table__)):
         try:
             uos.mkdir(d)
         except OSError as e:
             if fail_silently:
                 print(e)
Example #18
0
def ensure_dirs(path):
    split_path = path.split('/')
    if len(split_path) > 1:
        for i, fragment in enumerate(split_path):
            parent = '/'.join(split_path[:-i])
            try:
                os.mkdir(parent)
            except OSError:
                pass
Example #19
0
def SyncPathPrepare(path, root="/"):
    ps = path.split("/")
    ps = [ps[i] for i in range(len(ps)) if len(ps[i]) > 0]
    for i in range(len(ps)):
        path = "/".join(ps[:i + 1])
        if ps[i] not in listdir(root):
            mkdir(path)
        root = path
    return path
Example #20
0
 def makedirs(self):
     import gc
     try:
         self.log.debug("Config: Create directory")
         uos.mkdir(self.dir + "config")
     except OSError as e:
         self.log.error("Config: Create directory config exception: " +
                        repr(e))
     gc.collect()
def mkdir_p(dir: str) -> None:
    if dir:
        mkdir_p(get_parent_path(dir))
        try:
            os.mkdir(dir)
        except OSError:
            pass
    else:
        return
Example #22
0
def setPath(newPath="/woezel_packages"):
    global path
    path = newPath
    categories = []
    lastUpdate = 0
    try:
        uos.mkdir(path)
    except:
        pass
Example #23
0
    def backup(dir_to_backup='firmware'):
        target = 'backup'
        try:
            uos.rmdir(target)
        except OSError:
            pass

        uos.mkdir(target)

        move_f(dir_to_backup, target)
Example #24
0
    def __download_latest(self):
        target = 'firmware'
        try:
            uos.rmdir(target)
        except OSError:
            pass

        uos.mkdir(target)

        self.__download_from_git(git_dir=self.conf['remote'].get('root_dir', ''), target_dir=target)
Example #25
0
    def create_table(cls):
        cls.__fields__ = list(cls.__schema__.keys())

        for d in (cls.__db__.name, cls.path_to_dir()):
            if not cls.list_dir(d):
                try:
                    uos.mkdir(d)
                except OSError as e:
                    log.debug("MKDIR: {}, {}".format(e, d))
                    pass
Example #26
0
def ensure_file_path(path):
    split_path = path.split('/')
    if len(split_path) > 1:
        for i, fragment in enumerate(split_path):
            if i > 0:
                parent = '/'.join(split_path[:i])
                try:
                    uos.mkdir(parent)
                except OSError as exc:
                    LOG.exc(exc, 'Error creating folder: %s' % parent)
Example #27
0
 def write_cache(self, data):
     try:
         mkdir(cachedir)
     except OSError as e:
         if e.args[
                 0] != errno.EEXIST:  # MicroPython OSError objects don't have .errno
             raise
     with open(cachefile, "w") as outfile:
         ujson.dump(data, outfile)
     print("Written config cache.")
def install():
    try:
        uos.mkdir('/media')
    except:
        pass
    media = uos.listdir('/media')
    for i in range(len(names)):
        if not names[i] + ".png" in media:
            f = open("/media/" + names[i] + ".png", 'wb')
            f.write(data[i])
            f.close()
Example #29
0
    async def MKD(self, stream, argument):

        try:
            uos.mkdir(self.get_path(argument))
            await _awrite(stream, "257 Okey.\r\n")
        except OSError as e:
            if e.args[0] == uerrno.EEXIST:
                await _awrite(stream, "257 Okey.\r\n")
            else:
                await _awrite(stream, "550 {}.\r\n".format(e))
        return True
Example #30
0
def _makedirs(name, mode=0o777):
    ret = False
    s = ""
    for c in name.rstrip("/").split("/"):
        s += c + "/"
        try:
            os.mkdir(s)
            ret = True
        except OSError as e:
            if e.args[0] != errno.EEXIST and e.args[0] != errno.EISDIR:
                raise
            ret = False
    return ret
Example #31
0
def _makedirs(name, mode=0o777):
    ret = False
    s = ""
    for c in name.rstrip("/").split("/"):
        s += c + "/"
        try:
            os.mkdir(s)
            ret = True
        except OSError as e:
            if e.args[0] != errno.EEXIST and e.args[0] != errno.EISDIR:
                raise
            ret = False
    return ret
Example #32
0
def makedirs(name, mode=0o777, exist_ok=False):
    s = ""
    comps = name.split("/")
    if comps[-1] == "":
        comps.pop()
    for i, c in enumerate(comps):
        s += c + "/"
        try:
            uos.mkdir(s)
        except OSError as e:
            if e.args[0] != errno_.EEXIST:
                raise
            if i == len(comps) - 1:
                if exist_ok:
                    return
                raise e
Example #33
0
def _makedirs(name, mode=0o777):
    ret = False
    s = ""
    comps = name.rstrip("/").split("/")[:-1]
    if comps[0] == "":
        s = "/"
    for c in comps:
        if s and s[-1] != "/":
            s += "/"
        s += c
        try:
            os.mkdir(s)
            ret = True
        except OSError as e:
            if e.args[0] != errno.EEXIST and e.args[0] != errno.EISDIR:
                raise
            ret = False
    return ret
Example #34
0
print(uos.listdir('/test_mnt'))

# mounting another filesystem
uos.mount(Filesystem(2), '/test_mnt2', readonly=True)
print(uos.listdir())
print(uos.listdir('/test_mnt2'))

# mounting over an existing mount point
try:
    uos.mount(Filesystem(3), '/test_mnt2')
except OSError:
    print('OSError')

# mkdir of a mount point
try:
    uos.mkdir('/test_mnt')
except OSError:
    print('OSError')

# rename across a filesystem
try:
    uos.rename('/test_mnt/a', '/test_mnt2/b')
except OSError:
    print('OSError')

# delegating to mounted filesystem
uos.chdir('test_mnt')
print(uos.listdir())
print(uos.getcwd())
uos.mkdir('test_dir')
uos.remove('test_file')
print(uos.stat('/test.txt')[:-3])

f = open('/test.txt')
print(f.read())
f.close()

uos.rename('test.txt', 'test2.txt')
print(uos.listdir())
uos.rename('test2.txt', '/test3.txt')
print(uos.listdir())
uos.rename('/test3.txt', 'test4.txt')
print(uos.listdir())
uos.rename('/test4.txt', '/test5.txt')
print(uos.listdir())

uos.mkdir('dir')
print(uos.listdir())
uos.mkdir('/dir2')
print(uos.listdir())
uos.mkdir('dir/subdir')
print(uos.listdir('dir'))
for exist in ('', '/', 'dir', '/dir', 'dir/subdir'):
    try:
        uos.mkdir(exist)
    except OSError as er:
        print('mkdir OSError', er.args[0] == 17) # EEXIST

uos.chdir('/')
print(uos.stat('test5.txt')[:-3])

uos.VfsFat.mkfs(bdev2)