Better fix for decoding external plugin source code

Use the python stdlib function for doing it, so it works exactly the same
as a regular python import.
This commit is contained in:
Kovid Goyal 2020-11-04 08:41:14 +05:30
parent 6ba70b06aa
commit d81a1fdc91
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C

View File

@ -6,16 +6,23 @@ __license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>' __copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
import os, zipfile, posixpath, importlib, threading, re, sys import importlib
import os
import posixpath
import re
import sys
import threading
import zipfile
from collections import OrderedDict from collections import OrderedDict
from functools import partial from functools import partial
from importlib.machinery import ModuleSpec from importlib.machinery import ModuleSpec
from importlib.util import decode_source
from calibre import as_unicode from calibre import as_unicode
from calibre.customize import (Plugin, numeric_version, platform, from calibre.customize import (
InvalidPlugin, PluginNotFound) InvalidPlugin, Plugin, PluginNotFound, numeric_version, platform
from polyglot.builtins import (itervalues, map, string_or_bytes, )
unicode_type, reload) from polyglot.builtins import itervalues, map, reload, string_or_bytes, unicode_type
# PEP 302 based plugin loading mechanism, works around the bug in zipimport in # PEP 302 based plugin loading mechanism, works around the bug in zipimport in
# python 2.x that prevents importing from zip files in locations whose paths # python 2.x that prevents importing from zip files in locations whose paths
@ -165,10 +172,7 @@ class CalibrePluginLoader:
def get_source(self, fullname=None): def get_source(self, fullname=None):
raw = self.get_source_as_bytes(fullname) raw = self.get_source_as_bytes(fullname)
try: return decode_source(raw)
return raw.decode('utf-8-sig', 'replace').replace('\r\n', '\n')
except Exception:
return ''
def get_filename(self, fullname): def get_filename(self, fullname):
return self.filename return self.filename
@ -388,8 +392,9 @@ sys.meta_path.append(loader)
if __name__ == '__main__': if __name__ == '__main__':
from tempfile import NamedTemporaryFile from tempfile import NamedTemporaryFile
from calibre.customize.ui import add_plugin
from calibre import CurrentDir from calibre import CurrentDir
from calibre.customize.ui import add_plugin
path = sys.argv[-1] path = sys.argv[-1]
with NamedTemporaryFile(suffix='.zip') as f: with NamedTemporaryFile(suffix='.zip') as f:
with zipfile.ZipFile(f, 'w') as zf: with zipfile.ZipFile(f, 'w') as zf: