Милка обнови решението на 30.04.2015 15:08 (преди над 9 години)
+class FileSystemError(Exception):
+ def __init__(self):
+ self.message = 'FileSystemError'
+
+
+class DestinationNodeExistsError(FileSystemError):
+ def __init__(self):
+ super(DestinationNodeExistsError, self).__init__()
+ self.message = 'DestinationNodeExistsError'
+
+
+class NotEnoughSpaceError(FileSystemError):
+ def __init__(self):
+ super(NotEnoughSpaceError, self).__init__()
+ self.message = 'NotEnoughSpaceError'
+
+
+class DestinationNodeDoesNotExistError(FileSystemError):
+ def __init__(self):
+ super(DestinationNodeDoesNotExistError, self).__init__()
+ self.message = 'NotEnoughSpaceError'
+
+
+class NodeDoesNotExistError(FileSystemError):
+ def __init__(self):
+ super(NodeDoesNotExistError, self).__init__()
+ self.message = 'NodeDoesNotExistError'
+
+
+class File:
+ def __init__(self, name, content=''):
+ self.content = str(content)
+ self.size = len(self.content) + 1
+ self.name = name
+
+ @property
+ def is_directory(self):
+ return False
+
+ def append(self, text):
+ self.content += text
+ self.size += len(text)
+
+ def truncate(self, text):
+ self.content = text
+ self.size = len(text) + 1
+
+ def __str__(self):
+ return self.content
+
+
+class Directory:
+ def __init__(self, name):
+ self.name = name
+ self.size = 1
+ self.files = []
+ self.directories = []
+ self.nodes = []
+
+ def __str__(self):
+ return self.name
+
+ @property
+ def is_directory(self):
+ return True
+
+ def add(self, obj):
+ self.nodes.append(obj)
+ if type(obj) is File:
+ self.files.append(obj)
+ else:
+ self.directories.append(obj)
+ self.size = len(self.directories) + sum(
+ [file.size for file in self.files]) + 1
+
+
+class FileSystem:
+ def __init__(self, size):
+ self.size = size
+ self.available_size = size - 1
+ self._directories = {'/': Directory('/')}
+
+ def get_node(self, path):
+ if path in self._directories:
+ return self._directories[path]
+ raise NodeDoesNotExistError
+
+ def create(self, path, directory=False, content=''):
+ path = path[:-1] if path[-1] == '/' else path
+ if self.available_size < 2 or self.available_size < len(content) + 1:
+ raise NotEnoughSpaceError
+ elif path in self._directories:
+ raise DestinationNodeExistsError
+ else:
+ filename = path.split('/')[-1]
+ old_path = '/'.join(
+ [x for x in path.split('/') if x != filename])
+ if old_path == '':
+ old_path = '/'
+ if old_path not in self._directories:
+ raise DestinationNodeDoesNotExistError
+ else:
+ obj = self._directories[old_path]
+
+ new_obj = (
+ Directory(filename)
+ if directory else File(filename, content)
+ )
+
+ self._directories[path] = new_obj
+ obj.add(new_obj)
+ self.available_size -= new_obj.size