15100 - Lunix File System   

Description

You've decided to write your own operating system from scratch. The bootloader works, and the kernel prints "Hello, world!" without crashing (most of the time).

But there's one problem: you can't save anything.

Your OS has no file system. No folders, no files, not even somewhere to store your unfinished homework.

Time to build one.

File System Rules

Your file system is made up of nodes. Every node has a name, and there are two types:

Node
Description
Size
File
Stores text content
Number of characters in its content
Directory
Contains files and other directories
Total size of all files inside it, including nested directories

 

Both File and Directory inherit from FileSystemNode and override get_size().

All paths are absolute (starting with /). For example, /home/user/notes.txt represents a file inside two nested directories. The file system starts with an empty root directory, /.

Empty path components are ignored, so /home//user/ is equivalent to /home/user.

The following rules apply:

  • Creating directories: MKDIR creates all missing directories along the path. Existing directories remain unchanged.

  • Adding files: ADD creates a new file or appends content to an existing one. Missing parent directories are created automatically.

  • Reading: READ returns a file's content.

  • Listing: LS returns directory contents in alphabetical order. Listing a file returns its name, while an empty directory prints EMPTY.

  • Size: SIZE returns the number of characters in a file or the combined size of a directory's contents.

  • Deleting: DELETE removes a file or an entire directory, including everything inside it. The root directory cannot be deleted.

  • Moving: MOVE relocates or renames a file or directory, preserving its contents. The destination's parent must already exist, and the destination must not exist.

Additional rules for MOVE:

  1. The root directory cannot be moved.

  2. The source must exist.

  3. A directory cannot be moved into itself or one of its descendants.

  4. The destination's parent must exist and must be a directory.

  5. The destination must not already exist.

  6. If any check fails, the file system must remain unchanged.

When checking whether a directory is moved into itself, compare complete path components. For example, moving /homeinto /home/projects is invalid, but moving it to /homework/old is allowed if /homework exists.

 

Error Handling

When a command fails, print the appropriate error message and return without changing the file system. 

Situation
Error message
Path is not absolute
Error: path must be absolute: <path>
Path does not exist
Error: no such file or directory: <path>
Path passes through a file
Error: not a directory: <path>
READ or ADD targets a directory
Error: is a directory: <path>
Child already exists in Directory.add()
Error: '<name>' already exists
Deleting root
Error: cannot delete root
Moving root
Error: cannot move root
Moving directory into itself
Error: cannot move a directory into itself: <destination>
Destination already exists
Error: destination exists: <destination>

 

Your Mission

Complete all methods marked with TODO in the provided starter code.

Sample Code


class FileSystemNode:
    def __init__(self, name):
        self.name = name

    def get_size(self):
        raise NotImplementedError


class File(FileSystemNode):
    def __init__(self, name, content=""):
        # TODO: Initialize the name and store the content.
        raise NotImplementedError

    def append(self, text):
        # TODO: Append text to the file.
        raise NotImplementedError

    def read(self):
        # TODO: Return the file's content.
        raise NotImplementedError

    def get_size(self):
        # TODO: Return the content's length.
        raise NotImplementedError


class Directory(FileSystemNode):
    def __init__(self, name):
        # TODO: Initialize the name and an empty dictionary of children.
        raise NotImplementedError

    def add(self, node):
        # TODO: Add a child by name, or print an error if it already exists.
        raise NotImplementedError

    def get(self, name):
        # TODO: Return the matching child, or None.
        raise NotImplementedError

    def remove(self, name):
        # TODO: Remove and return a child, or None.
        raise NotImplementedError

    def list_contents(self):
        # TODO: Return sorted child names.
        raise NotImplementedError

    def get_size(self):
        # TODO: Return total size of all children.
        raise NotImplementedError


class FileSystem:
    def __init__(self):
        self.root = Directory("")

    def _parts(self, path):
        # TODO: Validate and split an absolute path, skipping empty parts. Then return a list of parts.
        raise NotImplementedError

    def _traverse(self, path):
        # TODO: Find and return a node, or print an error and return None.

        # HINT: If a child does not exist, print:
        # Error: no such file or directory: <path>
        # If the path passes through a File, print:
        # Error: not a directory: <path>
        # Return None on error.
        # You can reuse _parts().
        raise NotImplementedError

    def mkdir(self, path):
        # TODO: Create missing directories and return the final directory.
        # If the path passes through a File, print:
        # Error: not a directory: <path>
        raise NotImplementedError

    def add_file(self, path, content):
        # TODO:
        # Create a file if it does not exist.
        # If it already exists, append the new content.
        # Create any missing parent directories automatically.
        #
        # If the path refers to a directory, print:
        # Error: is a directory: <path>
        raise NotImplementedError

    def read_file(self, path):
        # TODO:
        # Create a file if it does not exist.
        # If it already exists, append the new content.
        # Create any missing parent directories automatically.
        #
        # If the path refers to a directory, print:
        # Error: is a directory: <path>
        #
        # Hint: mkdir() can help create the parent directory.

        raise NotImplementedError

    def ls(self, path):
        # TODO:
        # If the node is a Directory, return its sorted child names.
        # If the node is a File, return [node.name].
        # Return None on error.
        raise NotImplementedError

    def get_size(self, path):
        # TODO:
        # Find the node and return its size.
        # Return None on error.
        #
        # Hint: Every node implements get_size().
        raise NotImplementedError

    def delete(self, path):
        # TODO:
        # Remove a file or an entire directory.
        #
        # Rules:
        # 1. The path must be absolute.
        # 2. The root directory "/" cannot be deleted.
        # 3. The target must exist.
        #
        # Hint: Find the target's parent directory.
        # Removing a directory also removes its entire subtree.
        raise NotImplementedError

    def move(self, source, destination):
        # TODO: 
        # Move or rename a file or directory.
        # Preserve the node and everything inside it.
        # Hints:
        # - Compare path components to detect invalid moves.
        # - The destination does not create missing directories.
        # - Update the node's name if it changes.
        # - If any check fails, the file system must remain unchanged.
        raise NotImplementedError


# MAIN PROGRAM — DO NOT MODIFY

if __name__ == "__main__":
    fs = FileSystem()

    q = int(input())

    for _ in range(q):
        line = input()
        parts = line.split(maxsplit=2)

        if not parts:
            continue

        command = parts[0]
        path = parts[1] if len(parts) > 1 else "/"

        if command == "MKDIR":
            fs.mkdir(path)

        elif command == "ADD":
            # Take everything after "ADD <path> " verbatim, keeping inner/leading spaces.
            rest = line.lstrip()[len(command):].lstrip()
            content = rest[len(path) + 1:] if len(rest) > len(path) else ""
            fs.add_file(path, content)

        elif command == "READ":
            text = fs.read_file(path)
            if text is not None:
                print(text)

        elif command == "LS":
            names = fs.ls(path)

            if names is not None:
                print(" ".join(names) if names else "EMPTY")

        elif command == "SIZE":
            size = fs.get_size(path)
            if size is not None:
                print(size)

        elif command == "DELETE":
            fs.delete(path)

        elif command == "MOVE":
            destination = parts[2] if len(parts) > 2 else ""
            fs.move(path, destination

Input

The first line contains an integer Q, representing the number of commands.

The following Q lines each contain one of seven commands:

Command
Description
MKDIR path
Create directories
ADD path content
Create or append to a file
READ path
Read a file
LS path
List contents
SIZE path
Get a node's size
DELETE path
Delete a file or directory
MOVE source destination
Move or rename a node

Output

For each command, print the corresponding result:

  • MKDIR, ADD, DELETE, MOVE: No output on success.

  • READ: Print the file's content.

  • LS: Print names separated by spaces, or EMPTY.

  • SIZE: Print the file or directory's size.

  • Errors: Print exactly one matching error message. Do not print an additional result.

Sample Input  Download

Sample Output  Download




Discuss