Micro-optimization

This commit is contained in:
Kovid Goyal 2022-08-21 08:28:07 +05:30
parent fd8fa7420e
commit 3bae760705
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C
2 changed files with 26 additions and 14 deletions

View File

@ -8,7 +8,6 @@ __docformat__ = 'restructuredtext en'
# Imports {{{
import apsw
import errno
import glob
import hashlib
import json
import os
@ -1435,17 +1434,24 @@ class DB:
fmt_path = os.path.join(path, fname+fmt)
if os.path.exists(fmt_path):
return fmt_path
if not fmt:
return
candidates = ()
with suppress(OSError):
candidates = os.listdir(path)
q = fmt.lower()
for x in candidates:
if x.lower().endswith(q):
x = os.path.join(path, x)
with suppress(OSError):
atomic_rename(x, fmt_path)
return fmt_path
try:
candidates = glob.glob(os.path.join(path, '*'+fmt))
except: # If path contains strange characters this throws an exc
candidates = []
if fmt and candidates and os.path.exists(candidates[0]):
try:
shutil.copyfile(candidates[0], fmt_path)
except shutil.SameFileError:
shutil.move(x, fmt_path)
except (shutil.SameFileError, OSError):
# some other process synced in the file since the last
# os.path.exists()
return candidates[0]
return x
return fmt_path
def cover_abspath(self, book_id, path):

View File

@ -5,7 +5,7 @@ __license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import datetime
import datetime, os
from io import BytesIO
from time import time
@ -455,6 +455,12 @@ class ReadingTest(BaseTest):
buf = BytesIO()
self.assertRaises(NoSuchFormat, cache.copy_format_to, 99999, 'X', buf, 'copy_format_to() failed to raise an exception for non-existent book')
self.assertRaises(NoSuchFormat, cache.copy_format_to, 1, 'X', buf, 'copy_format_to() failed to raise an exception for non-existent format')
fmt = cache.formats(1)[0]
path = cache.format_abspath(1, fmt)
changed_path = os.path.join(os.path.dirname(path), 'x' + os.path.basename(path))
os.rename(path, changed_path)
self.assertEqual(cache.format_abspath(1, fmt), path)
self.assertFalse(os.path.exists(changed_path))
# }}}