Иван обнови решението на 30.04.2015 08:04 (преди над 9 години)
+import os
+import shutil
+
+
+class FileSystemError(Exception):
+ pass
+
+
+class NodeDoesNotExistError(FileSystemError):
+ pass
+
+
+class DestinationNodeExistsError(NodeDoesNotExistError):
+ pass
+
+
+class DestinationNodeDoesNotExistError(NodeDoesNotExistError):
+ pass
+
+
+class NotEnoughSpaceError(FileSystemError):
+ pass
+
+
+class NonExplicitDirectoryDeletionError(FileSystemError):
+ pass
+
+
+class NonEmptyDirectoryDeletionError(FileSystemError):
+ pass
+
+
+class SourceNodeDoesNotExistError(FileSystemError):
+ pass
+
+
+class DestinationNotADirectoryError(FileSystemError):
+ pass
+
+
+class GetNode:
+ def __init__(self, value, is_directory):
+ self.is_directory = is_directory
+ self.value = value
+ if not is_directory:
+ with open(value) as infile:
+ self.content = infile.read()
+
+
+def get_size(start_path='.'):
+ total_size = 0
+ for dirpath, dirnames, filenames in os.walk(start_path):
+ for f in filenames:
+ fp = os.path.join(dirpath, f)
+ total_size += os.path.getsize(fp)
+ return total_size
+
+
+class FileSystem:
+ def __init__(self, size):
+ self.size = size
+ self.available_size = size - 1
+
+ def get_node(self, path):
+ path = path[1:]
+ if not os.access(path, os.F_OK):
+ raise NodeDoesNotExistError
+ else:
+ return GetNode(os.path.abspath(path), os.path.isdir(path))
+
+ def create(self, path, directory=False, content=''):
+ path = path[1:]
+ if directory:
+ if os.path.exists(path):
+ raise DestinationNodeExistsError
+ elif os.path.exists(path[:path.rfind('/')]):
+ raise DestinationNodeDoesNotExistError
+ else:
+ os.mkdir(path)
+ elif len(content) > self.available_size:
+ raise NotEnoughSpaceError
+ else:
+ if os.path.exists(path):
+ raise DestinationNodeExistsError
+ elif os.path.exists(path[:path.rfind('/')]):
+ raise DestinationNodeDoesNotExistError
+ else:
+ with open(path, 'w') as infile:
+ infile.write(content)
+ self.available_size = self.available_size - len(content)
+
+ def remove(self, path, directory=False, force=True):
+ path = path[1:]
+ if os.path.exists == False:
+ raise NodeDoesNotExistError
+ elif directory == False and os.path.isdir(path):
+ raise NonExplicitDirectoryDeletionError
+ elif os.listdir(path): # differs from zero
+ if force:
+ self.available_size += get_size(path)
+ shutil.rmtree(path)
+ else:
+ raise NonEmptyDirectoryDeletionError
+ else:
+ self.available_size += os.path.getsize(path)
+ os.remove(path)
+
+ def move(source, destination):
+ source = source[1:]
+ destination = destination[1:]
+ if os.path.exists(source) is False:
+ raise SourceNodeDoesNotExistError
+ elif os.path.exists(destination) is False:
+ raise DestinationNodeDoesNotExistError
+ elif os.path.isdir(destination) is False:
+ raise DestinationNotADirectoryError
+ else:
+ shutil.move(source, destination)