Change find_available_file_name into a method

This commit is contained in:
Guillaume Ayoub 2016-08-02 11:16:24 +02:00
parent 880744ada7
commit a7f078eb54

View File

@ -347,6 +347,14 @@ class Collection(BaseCollection):
path, self.storage_encoding, mode).open() as fd: path, self.storage_encoding, mode).open() as fd:
yield fd yield fd
def find_available_file_name(self):
# Prevent infinite loop
for _ in range(10000):
file_name = hex(getrandbits(32))[2:]
if not self.has(file_name):
return file_name
raise FileExistsError(errno.EEXIST, "No usable file name found")
@classmethod @classmethod
def discover(cls, path, depth="1"): def discover(cls, path, depth="1"):
# path == None means wrong URL # path == None means wrong URL
@ -394,14 +402,6 @@ class Collection(BaseCollection):
@classmethod @classmethod
def create_collection(cls, href, collection=None, tag=None): def create_collection(cls, href, collection=None, tag=None):
def find_available_file_name(exists_fn):
# Prevent infinite loop
for _ in range(10000):
file_name = hex(getrandbits(32))[2:]
if not exists_fn(file_name):
return file_name
raise FileExistsError(errno.EEXIST, "No usable file name found")
folder = os.path.expanduser( folder = os.path.expanduser(
cls.configuration.get("storage", "filesystem_folder")) cls.configuration.get("storage", "filesystem_folder"))
path = path_to_filesystem(folder, href) path = path_to_filesystem(folder, href)
@ -429,14 +429,14 @@ class Collection(BaseCollection):
new_collection = vobject.iCalendar() new_collection = vobject.iCalendar()
for item in items: for item in items:
new_collection.add(item) new_collection.add(item)
self.upload(find_available_file_name(self.has), self.upload(
new_collection) self.find_available_file_name(), new_collection)
elif tag == "VCARD": elif tag == "VCARD":
self.set_meta("tag", "VADDRESSBOOK") self.set_meta("tag", "VADDRESSBOOK")
if collection: if collection:
for card in collection: for card in collection:
self.upload(find_available_file_name(self.has), card) self.upload(self.find_available_file_name(), card)
return self return self