Simple in-memory file system

class Dir:

    def __init__(self, parent, name):
        self.parent = parent
        self.name = name
        self.children = dict()

    def mkdir_path(self, path):
        sub_dirs = path.split('/')
        current_dir = self
        for child_dir_name in sub_dirs:
            current_dir = current_dir.mkdir(child_dir_name)

    def mkdir(self, name):
        dir = Dir(self, name)
        self.children[name] = dir
        return dir

    def get_child_dir(self, name):
        return self.children[name]

    def get_child_dir_path(self, path):
        sub_dirs = path.split('/')
        current_dir = self
        for sub_dir in sub_dirs:
            current_dir = current_dir.children[sub_dir]
        return current_dir

    def write_file(self, name, contents):
        self.children[name] = contents

    def write_file_path(self, path, contents):
        sub_dirs = path.split('/')
        file_name = sub_dirs[-1]
        current_dir = self
        for sub_dir in sub_dirs[:-1]:
            current_dir = current_dir.children[sub_dir]
        current_dir.write_file(file_name, contents)

    def read_file(self, name):
        return self.children[name]

    def read_file_path(self, path):
        sub_dirs = path.split('/')
        file_name = sub_dirs[-1]
        current_dir = self
        for sub_dir in sub_dirs[:-1]:
            current_dir = current_dir.children[sub_dir]
        return current_dir.read_file(file_name)

    def __repr__(self):
        return f'{self.name} {self.children}'


if __name__ == "__main__":
    fs = Dir(None, '/')
    fs.mkdir('tmp').mkdir('1')
    fs.get_child_dir('tmp').get_child_dir('1').write_file('test', 'data')
    contents = fs.get_child_dir('tmp').get_child_dir('1').read_file('test')
    assert contents == 'data', "contents of the file don't match"

    fs.mkdir_path('tmp/1/2/3/4')
    fs.write_file_path('tmp/1/2/3/4/4.dat', '4')
    contents = fs.read_file_path('tmp/1/2/3/4/4.dat')
    assert contents == '4', 'Correct content not found'

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s