From 3bae76070592c8057df3ffbd9119b77f7f9c72f6 Mon Sep 17 00:00:00 2001 From: Kovid Goyal Date: Sun, 21 Aug 2022 08:28:07 +0530 Subject: [PATCH] Micro-optimization --- src/calibre/db/backend.py | 32 +++++++++++++++++++------------- src/calibre/db/tests/reading.py | 8 +++++++- 2 files changed, 26 insertions(+), 14 deletions(-) diff --git a/src/calibre/db/backend.py b/src/calibre/db/backend.py index ae421b0080..4115740583 100644 --- a/src/calibre/db/backend.py +++ b/src/calibre/db/backend.py @@ -8,7 +8,6 @@ __docformat__ = 'restructuredtext en' # Imports {{{ import apsw import errno -import glob import hashlib import json import os @@ -1435,18 +1434,25 @@ class DB: fmt_path = os.path.join(path, fname+fmt) if os.path.exists(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: - # some other process synced in the file since the last - # os.path.exists() - return candidates[0] - 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: + 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): path = os.path.join(self.library_path, path) diff --git a/src/calibre/db/tests/reading.py b/src/calibre/db/tests/reading.py index fc0fd88955..5a46bcca4e 100644 --- a/src/calibre/db/tests/reading.py +++ b/src/calibre/db/tests/reading.py @@ -5,7 +5,7 @@ __license__ = 'GPL v3' __copyright__ = '2011, Kovid Goyal ' __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)) # }}}