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

View File

@ -5,7 +5,7 @@ __license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>' __copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
import datetime import datetime, os
from io import BytesIO from io import BytesIO
from time import time from time import time
@ -455,6 +455,12 @@ class ReadingTest(BaseTest):
buf = BytesIO() 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, 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') 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))
# }}} # }}}