py3 porting cleanup: drop os.getenv/getcwd proxies

The stdlib getenv/getcwd is suitable everywhere now, so that is all that
is used.
This commit is contained in:
Eli Schwartz 2021-10-17 17:24:59 -04:00
parent e592d895ea
commit 34f3033444
No known key found for this signature in database
GPG Key ID: CEB167EFB5722BD6
43 changed files with 130 additions and 134 deletions

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8 # vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net>
from polyglot.builtins import unicode_type, environ_item, hasenv, getenv from polyglot.builtins import unicode_type, environ_item, hasenv
import sys, locale, codecs, os, collections, collections.abc import sys, locale, codecs, os, collections, collections.abc
__appname__ = 'calibre' __appname__ = 'calibre'
@ -123,7 +123,7 @@ def _get_cache_dir():
raise raise
if isportable: if isportable:
return confcache return confcache
ccd = getenv('CALIBRE_CACHE_DIRECTORY') ccd = os.getenv('CALIBRE_CACHE_DIRECTORY')
if ccd is not None: if ccd is not None:
ans = os.path.abspath(ccd) ans = os.path.abspath(ccd)
try: try:
@ -141,7 +141,7 @@ def _get_cache_dir():
elif ismacos: elif ismacos:
candidate = os.path.join(os.path.expanduser('~/Library/Caches'), __appname__) candidate = os.path.join(os.path.expanduser('~/Library/Caches'), __appname__)
else: else:
candidate = getenv('XDG_CACHE_HOME', '~/.cache') candidate = os.getenv('XDG_CACHE_HOME', '~/.cache')
candidate = os.path.join(os.path.expanduser(candidate), candidate = os.path.join(os.path.expanduser(candidate),
__appname__) __appname__)
if isinstance(candidate, bytes): if isinstance(candidate, bytes):
@ -340,7 +340,7 @@ if plugins is None:
CONFIG_DIR_MODE = 0o700 CONFIG_DIR_MODE = 0o700
cconfd = getenv('CALIBRE_CONFIG_DIRECTORY') cconfd = os.getenv('CALIBRE_CONFIG_DIRECTORY')
if cconfd is not None: if cconfd is not None:
config_dir = os.path.abspath(cconfd) config_dir = os.path.abspath(cconfd)
elif iswindows: elif iswindows:
@ -354,7 +354,7 @@ elif iswindows:
elif ismacos: elif ismacos:
config_dir = os.path.expanduser('~/Library/Preferences/calibre') config_dir = os.path.expanduser('~/Library/Preferences/calibre')
else: else:
bdir = os.path.abspath(os.path.expanduser(getenv('XDG_CONFIG_HOME', '~/.config'))) bdir = os.path.abspath(os.path.expanduser(os.getenv('XDG_CONFIG_HOME', '~/.config')))
config_dir = os.path.join(bdir, 'calibre') config_dir = os.path.join(bdir, 'calibre')
try: try:
os.makedirs(config_dir, mode=CONFIG_DIR_MODE) os.makedirs(config_dir, mode=CONFIG_DIR_MODE)
@ -386,7 +386,7 @@ if getattr(sys, 'frozen', False):
else: else:
is_running_from_develop = running_in_develop_mode() is_running_from_develop = running_in_develop_mode()
in_develop_mode = getenv('CALIBRE_ENABLE_DEVELOP_MODE') == '1' in_develop_mode = os.getenv('CALIBRE_ENABLE_DEVELOP_MODE') == '1'
def get_version(): def get_version():
@ -415,7 +415,7 @@ def get_appname_for_display():
def get_portable_base(): def get_portable_base():
'Return path to the directory that contains calibre-portable.exe or None' 'Return path to the directory that contains calibre-portable.exe or None'
if isportable: if isportable:
return os.path.dirname(os.path.dirname(getenv('CALIBRE_PORTABLE_BUILD'))) return os.path.dirname(os.path.dirname(os.getenv('CALIBRE_PORTABLE_BUILD')))
def get_windows_username(): def get_windows_username():

View File

@ -10,7 +10,7 @@ from calibre.ebooks.metadata.book.base import field_from_string
from calibre.ebooks.metadata.book.serialize import read_cover from calibre.ebooks.metadata.book.serialize import read_cover
from calibre.ebooks.metadata.opf import get_metadata from calibre.ebooks.metadata.opf import get_metadata
from calibre.srv.changes import metadata from calibre.srv.changes import metadata
from polyglot.builtins import iteritems, unicode_type, getcwd from polyglot.builtins import iteritems, unicode_type
readonly = False readonly = False
version = 0 # change this if you change signature of implementation() version = 0 # change this if you change signature of implementation()
@ -147,7 +147,7 @@ def main(opts, args, dbctx):
with lopen(opf, 'rb') as stream: with lopen(opf, 'rb') as stream:
mi = get_metadata(stream)[0] mi = get_metadata(stream)[0]
if mi.cover: if mi.cover:
mi.cover = os.path.join(os.path.dirname(opf), os.path.relpath(mi.cover, getcwd())) mi.cover = os.path.join(os.path.dirname(opf), os.path.relpath(mi.cover, os.getcwd()))
final_mi = dbctx.run('set_metadata', 'opf', book_id, read_cover(mi)) final_mi = dbctx.run('set_metadata', 'opf', book_id, read_cover(mi))
if not final_mi: if not final_mi:
raise SystemExit(_('No book with id: %s in the database') % book_id) raise SystemExit(_('No book with id: %s in the database') % book_id)

View File

@ -3,11 +3,12 @@
# License: GPLv3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
import os
import sys import sys
from calibre import prints from calibre import prints
from calibre.ebooks.metadata.opf2 import OPFCreator from calibre.ebooks.metadata.opf2 import OPFCreator
from polyglot.builtins import unicode_type, getcwd from polyglot.builtins import unicode_type
readonly = True readonly = True
version = 0 # change this if you change signature of implementation() version = 0 # change this if you change signature of implementation()
@ -49,7 +50,7 @@ def main(opts, args, dbctx):
raise SystemExit('Id #%d is not present in database.' % id) raise SystemExit('Id #%d is not present in database.' % id)
if opts.as_opf: if opts.as_opf:
stdout = getattr(sys.stdout, 'buffer', sys.stdout) stdout = getattr(sys.stdout, 'buffer', sys.stdout)
mi = OPFCreator(getcwd(), mi) mi = OPFCreator(os.getcwd(), mi)
mi.render(stdout) mi.render(stdout)
else: else:
prints(unicode_type(mi)) prints(unicode_type(mi))

View File

@ -12,7 +12,7 @@ from calibre.utils.config import OptionParser
from calibre.constants import iswindows from calibre.constants import iswindows
from calibre import prints from calibre import prints
from calibre.startup import get_debug_executable from calibre.startup import get_debug_executable
from polyglot.builtins import exec_path, unicode_type, getcwd from polyglot.builtins import exec_path, unicode_type
def run_calibre_debug(*args, **kw): def run_calibre_debug(*args, **kw):
@ -164,7 +164,7 @@ def add_simple_plugin(path_to_plugin):
tdir = tempfile.mkdtemp() tdir = tempfile.mkdtemp()
open(os.path.join(tdir, 'custom_plugin.py'), open(os.path.join(tdir, 'custom_plugin.py'),
'wb').write(open(path_to_plugin, 'rb').read()) 'wb').write(open(path_to_plugin, 'rb').read())
odir = getcwd() odir = os.getcwd()
os.chdir(tdir) os.chdir(tdir)
zf = zipfile.ZipFile('plugin.zip', 'w') zf = zipfile.ZipFile('plugin.zip', 'w')
zf.write('custom_plugin.py') zf.write('custom_plugin.py')

View File

@ -16,7 +16,6 @@ import os
import re import re
from calibre.ebooks.pdb.formatreader import FormatReader from calibre.ebooks.pdb.formatreader import FormatReader
from polyglot.builtins import getcwd
def unwrap(stream, output_path): def unwrap(stream, output_path):
@ -46,7 +45,7 @@ class Reader(FormatReader):
if mo: if mo:
data = mo.group() data = mo.group()
pdf_n = os.path.join(getcwd(), 'tmp.pdf') pdf_n = os.path.join(os.getcwd(), 'tmp.pdf')
with open(pdf_n, 'wb') as pdf: with open(pdf_n, 'wb') as pdf:
pdf.write(data) pdf.write(data)
from calibre.customize.ui import plugin_for_input_format from calibre.customize.ui import plugin_for_input_format

View File

@ -13,7 +13,7 @@ from calibre.ebooks.BeautifulSoup import BeautifulSoup, NavigableString
from calibre.ebooks.chardet import xml_to_unicode from calibre.ebooks.chardet import xml_to_unicode
from calibre.ebooks.metadata.toc import TOC from calibre.ebooks.metadata.toc import TOC
from chm.chm import CHMFile, chmlib from chm.chm import CHMFile, chmlib
from polyglot.builtins import as_unicode, getcwd, unicode_type from polyglot.builtins import as_unicode, unicode_type
def match_string(s1, s2_already_lowered): def match_string(s1, s2_already_lowered):
@ -113,7 +113,7 @@ class CHMReader(CHMFile):
def get_encoding(self): def get_encoding(self):
return self.encoding_from_system_file or self.encoding_from_lcid or 'cp1252' return self.encoding_from_system_file or self.encoding_from_lcid or 'cp1252'
def _parse_toc(self, ul, basedir=getcwd()): def _parse_toc(self, ul, basedir=os.getcwd()):
toc = TOC(play_order=self._playorder, base_path=basedir, text='') toc = TOC(play_order=self._playorder, base_path=basedir, text='')
self._playorder += 1 self._playorder += 1
for li in ul('li', recursive=False): for li in ul('li', recursive=False):
@ -157,7 +157,7 @@ class CHMReader(CHMFile):
def get_home(self): def get_home(self):
return self.GetFile(self.home) return self.GetFile(self.home)
def ExtractFiles(self, output_dir=getcwd(), debug_dump=False): def ExtractFiles(self, output_dir=os.getcwd(), debug_dump=False):
html_files = set() html_files = set()
for path in self.Contents(): for path in self.Contents():
fpath = path fpath = path
@ -336,5 +336,5 @@ class CHMReader(CHMFile):
if not os.path.isdir(dir): if not os.path.isdir(dir):
os.makedirs(dir) os.makedirs(dir)
def extract_content(self, output_dir=getcwd(), debug_dump=False): def extract_content(self, output_dir=os.getcwd(), debug_dump=False):
self.ExtractFiles(output_dir=output_dir, debug_dump=debug_dump) self.ExtractFiles(output_dir=output_dir, debug_dump=debug_dump)

View File

@ -5,8 +5,9 @@ __license__ = 'GPL v3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>' __copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
import os
from calibre.customize.conversion import InputFormatPlugin from calibre.customize.conversion import InputFormatPlugin
from polyglot.builtins import getcwd
class AZW4Input(InputFormatPlugin): class AZW4Input(InputFormatPlugin):
@ -24,6 +25,6 @@ class AZW4Input(InputFormatPlugin):
header = PdbHeaderReader(stream) header = PdbHeaderReader(stream)
reader = Reader(header, stream, log, options) reader = Reader(header, stream, log, options)
opf = reader.extract_content(getcwd()) opf = reader.extract_content(os.getcwd())
return opf return opf

View File

@ -13,7 +13,6 @@ import shutil, textwrap, codecs, os
from calibre.customize.conversion import InputFormatPlugin, OptionRecommendation from calibre.customize.conversion import InputFormatPlugin, OptionRecommendation
from calibre import CurrentDir from calibre import CurrentDir
from calibre.ptempfile import PersistentTemporaryDirectory from calibre.ptempfile import PersistentTemporaryDirectory
from polyglot.builtins import getcwd
class ComicInput(InputFormatPlugin): class ComicInput(InputFormatPlugin):
@ -198,7 +197,7 @@ class ComicInput(InputFormatPlugin):
mi = MetaInformation(os.path.basename(stream.name).rpartition('.')[0], mi = MetaInformation(os.path.basename(stream.name).rpartition('.')[0],
[_('Unknown')]) [_('Unknown')])
opf = OPFCreator(getcwd(), mi) opf = OPFCreator(os.getcwd(), mi)
entries = [] entries = []
def href(x): def href(x):

View File

@ -9,7 +9,6 @@ import os
from io import BytesIO from io import BytesIO
from calibre.customize.conversion import InputFormatPlugin from calibre.customize.conversion import InputFormatPlugin
from polyglot.builtins import getcwd
class DJVUInput(InputFormatPlugin): class DJVUInput(InputFormatPlugin):
@ -40,7 +39,7 @@ class DJVUInput(InputFormatPlugin):
for opt in html_input.options: for opt in html_input.options:
setattr(options, opt.option.name, opt.recommended_value) setattr(options, opt.option.name, opt.recommended_value)
options.input_encoding = 'utf-8' options.input_encoding = 'utf-8'
base = getcwd() base = os.getcwd()
htmlfile = os.path.join(base, 'index.html') htmlfile = os.path.join(base, 'index.html')
c = 0 c = 0
while os.path.exists(htmlfile): while os.path.exists(htmlfile):

View File

@ -8,7 +8,6 @@ import os, re, posixpath
from itertools import cycle from itertools import cycle
from calibre.customize.conversion import InputFormatPlugin, OptionRecommendation from calibre.customize.conversion import InputFormatPlugin, OptionRecommendation
from polyglot.builtins import getcwd
ADOBE_OBFUSCATION = 'http://ns.adobe.com/pdf/enc#RC' ADOBE_OBFUSCATION = 'http://ns.adobe.com/pdf/enc#RC'
IDPF_OBFUSCATION = 'http://www.idpf.org/2008/embedding' IDPF_OBFUSCATION = 'http://www.idpf.org/2008/embedding'
@ -246,7 +245,7 @@ class EPUBInput(InputFormatPlugin):
path = attr(r, 'full-path') path = attr(r, 'full-path')
if not path: if not path:
continue continue
path = os.path.join(getcwd(), *path.split('/')) path = os.path.join(os.getcwd(), *path.split('/'))
if os.path.exists(path): if os.path.exists(path):
return path return path
except Exception: except Exception:
@ -260,7 +259,7 @@ class EPUBInput(InputFormatPlugin):
from calibre.ebooks.metadata.opf2 import OPF from calibre.ebooks.metadata.opf2 import OPF
try: try:
zf = ZipFile(stream) zf = ZipFile(stream)
zf.extractall(getcwd()) zf.extractall(os.getcwd())
except: except:
log.exception('EPUB appears to be invalid ZIP file, trying a' log.exception('EPUB appears to be invalid ZIP file, trying a'
' more forgiving ZIP parser') ' more forgiving ZIP parser')
@ -280,7 +279,7 @@ class EPUBInput(InputFormatPlugin):
if opf is None: if opf is None:
raise ValueError('%s is not a valid EPUB file (could not find opf)'%path) raise ValueError('%s is not a valid EPUB file (could not find opf)'%path)
opf = os.path.relpath(opf, getcwd()) opf = os.path.relpath(opf, os.getcwd())
parts = os.path.split(opf) parts = os.path.split(opf)
opf = OPF(opf, os.path.dirname(os.path.abspath(opf))) opf = OPF(opf, os.path.dirname(os.path.abspath(opf)))
@ -405,7 +404,7 @@ class EPUBInput(InputFormatPlugin):
with NamedTemporaryFile(suffix='.ncx', dir=os.path.dirname(nav_path), delete=False) as f: with NamedTemporaryFile(suffix='.ncx', dir=os.path.dirname(nav_path), delete=False) as f:
f.write(etree.tostring(ncx, encoding='utf-8')) f.write(etree.tostring(ncx, encoding='utf-8'))
ncx_href = os.path.relpath(f.name, getcwd()).replace(os.sep, '/') ncx_href = os.path.relpath(f.name, os.getcwd()).replace(os.sep, '/')
ncx_id = opf.create_manifest_item(ncx_href, NCX_MIME, append=True).get('id') ncx_id = opf.create_manifest_item(ncx_href, NCX_MIME, append=True).get('id')
for spine in opf.root.xpath('//*[local-name()="spine"]'): for spine in opf.root.xpath('//*[local-name()="spine"]'):
spine.set('toc', ncx_id) spine.set('toc', ncx_id)

View File

@ -9,7 +9,7 @@ import os, re
from calibre.customize.conversion import InputFormatPlugin, OptionRecommendation from calibre.customize.conversion import InputFormatPlugin, OptionRecommendation
from calibre import guess_type from calibre import guess_type
from polyglot.builtins import iteritems, getcwd from polyglot.builtins import iteritems
FB2NS = 'http://www.gribuser.ru/xml/fictionbook/2.0' FB2NS = 'http://www.gribuser.ru/xml/fictionbook/2.0'
FB21NS = 'http://www.gribuser.ru/xml/fictionbook/2.1' FB21NS = 'http://www.gribuser.ru/xml/fictionbook/2.1'
@ -145,7 +145,7 @@ class FB2Input(InputFormatPlugin):
cpath = os.path.abspath(href) cpath = os.path.abspath(href)
break break
opf = OPFCreator(getcwd(), mi) opf = OPFCreator(os.getcwd(), mi)
entries = [(f2, guess_type(f2)[0]) for f2 in os.listdir(u'.')] entries = [(f2, guess_type(f2)[0]) for f2 in os.listdir(u'.')]
opf.create_manifest(entries) opf.create_manifest(entries)
opf.create_spine(['index.xhtml']) opf.create_spine(['index.xhtml'])
@ -153,7 +153,7 @@ class FB2Input(InputFormatPlugin):
opf.guide.set_cover(cpath) opf.guide.set_cover(cpath)
with open('metadata.opf', 'wb') as f: with open('metadata.opf', 'wb') as f:
opf.render(f) opf.render(f)
return os.path.join(getcwd(), 'metadata.opf') return os.path.join(os.getcwd(), 'metadata.opf')
def extract_embedded_content(self, doc): def extract_embedded_content(self, doc):
from calibre.ebooks.fb2 import base64_decode from calibre.ebooks.fb2 import base64_decode

View File

@ -17,7 +17,7 @@ from calibre.customize.conversion import InputFormatPlugin, OptionRecommendation
from calibre.utils.filenames import ascii_filename from calibre.utils.filenames import ascii_filename
from calibre.utils.imghdr import what from calibre.utils.imghdr import what
from calibre.utils.localization import get_lang from calibre.utils.localization import get_lang
from polyglot.builtins import as_unicode, getcwd, unicode_type from polyglot.builtins import as_unicode, unicode_type
def sanitize_file_name(x): def sanitize_file_name(x):
@ -70,7 +70,7 @@ class HTMLInput(InputFormatPlugin):
def convert(self, stream, opts, file_ext, log, def convert(self, stream, opts, file_ext, log,
accelerators): accelerators):
self._is_case_sensitive = None self._is_case_sensitive = None
basedir = getcwd() basedir = os.getcwd()
self.opts = opts self.opts = opts
fname = None fname = None
@ -228,7 +228,7 @@ class HTMLInput(InputFormatPlugin):
continue continue
toc.add(title, item.href) toc.add(title, item.href)
oeb.container = DirContainer(getcwd(), oeb.log, ignore_opf=True) oeb.container = DirContainer(os.getcwd(), oeb.log, ignore_opf=True)
return oeb return oeb
def link_to_local_path(self, link_, base=None): def link_to_local_path(self, link_, base=None):
@ -240,7 +240,7 @@ class HTMLInput(InputFormatPlugin):
self.log.warn('Failed to decode link %r. Ignoring'%link_) self.log.warn('Failed to decode link %r. Ignoring'%link_)
return None, None return None, None
try: try:
l = Link(link_, base if base else getcwd()) l = Link(link_, base if base else os.getcwd())
except: except:
self.log.exception('Failed to process link: %r'%link_) self.log.exception('Failed to process link: %r'%link_)
return None, None return None, None

View File

@ -9,7 +9,6 @@ import os
from calibre import guess_type from calibre import guess_type
from calibre.customize.conversion import InputFormatPlugin from calibre.customize.conversion import InputFormatPlugin
from polyglot.builtins import getcwd
class HTMLZInput(InputFormatPlugin): class HTMLZInput(InputFormatPlugin):
@ -86,7 +85,7 @@ class HTMLZInput(InputFormatPlugin):
for opt in html_input.options: for opt in html_input.options:
setattr(options, opt.option.name, opt.recommended_value) setattr(options, opt.option.name, opt.recommended_value)
options.input_encoding = 'utf-8' options.input_encoding = 'utf-8'
base = getcwd() base = os.getcwd()
htmlfile = os.path.join(base, u'index.html') htmlfile = os.path.join(base, u'index.html')
c = 0 c = 0
while os.path.exists(htmlfile): while os.path.exists(htmlfile):
@ -117,12 +116,12 @@ class HTMLZInput(InputFormatPlugin):
opf = x opf = x
break break
if opf: if opf:
opf = OPF(opf, basedir=getcwd()) opf = OPF(opf, basedir=os.getcwd())
cover_path = opf.raster_cover or opf.cover cover_path = opf.raster_cover or opf.cover
# Set the cover. # Set the cover.
if cover_path: if cover_path:
cdata = None cdata = None
with open(os.path.join(getcwd(), cover_path), 'rb') as cf: with open(os.path.join(os.getcwd(), cover_path), 'rb') as cf:
cdata = cf.read() cdata = cf.read()
cover_name = os.path.basename(cover_path) cover_name = os.path.basename(cover_path)
id, href = oeb.manifest.generate('cover', cover_name) id, href = oeb.manifest.generate('cover', cover_name)

View File

@ -5,8 +5,9 @@ __license__ = 'GPL v3'
__copyright__ = '2009, John Schember <john@nachtimwald.com>' __copyright__ = '2009, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
import os
from calibre.customize.conversion import InputFormatPlugin from calibre.customize.conversion import InputFormatPlugin
from polyglot.builtins import getcwd
class PDBInput(InputFormatPlugin): class PDBInput(InputFormatPlugin):
@ -32,6 +33,6 @@ class PDBInput(InputFormatPlugin):
log.debug('Detected ebook format as: %s with identity: %s' % (IDENTITY_TO_NAME[header.ident], header.ident)) log.debug('Detected ebook format as: %s with identity: %s' % (IDENTITY_TO_NAME[header.ident], header.ident))
reader = Reader(header, stream, log, options) reader = Reader(header, stream, log, options)
opf = reader.extract_content(getcwd()) opf = reader.extract_content(os.getcwd())
return opf return opf

View File

@ -8,7 +8,7 @@ __docformat__ = 'restructuredtext en'
import os import os
from calibre.customize.conversion import InputFormatPlugin, OptionRecommendation from calibre.customize.conversion import InputFormatPlugin, OptionRecommendation
from polyglot.builtins import as_bytes, getcwd from polyglot.builtins import as_bytes
class PDFInput(InputFormatPlugin): class PDFInput(InputFormatPlugin):
@ -35,11 +35,11 @@ class PDFInput(InputFormatPlugin):
from calibre.utils.cleantext import clean_ascii_chars from calibre.utils.cleantext import clean_ascii_chars
from calibre.ebooks.pdf.reflow import PDFDocument from calibre.ebooks.pdf.reflow import PDFDocument
pdftohtml(getcwd(), stream.name, self.opts.no_images, as_xml=True) pdftohtml(os.getcwd(), stream.name, self.opts.no_images, as_xml=True)
with lopen('index.xml', 'rb') as f: with lopen('index.xml', 'rb') as f:
xml = clean_ascii_chars(f.read()) xml = clean_ascii_chars(f.read())
PDFDocument(xml, self.opts, self.log) PDFDocument(xml, self.opts, self.log)
return os.path.join(getcwd(), 'metadata.opf') return os.path.join(os.getcwd(), 'metadata.opf')
def convert(self, stream, options, file_ext, log, def convert(self, stream, options, file_ext, log,
accelerators): accelerators):
@ -51,16 +51,16 @@ class PDFInput(InputFormatPlugin):
self.opts, self.log = options, log self.opts, self.log = options, log
if options.new_pdf_engine: if options.new_pdf_engine:
return self.convert_new(stream, accelerators) return self.convert_new(stream, accelerators)
pdftohtml(getcwd(), stream.name, options.no_images) pdftohtml(os.getcwd(), stream.name, options.no_images)
from calibre.ebooks.metadata.meta import get_metadata from calibre.ebooks.metadata.meta import get_metadata
log.debug('Retrieving document metadata...') log.debug('Retrieving document metadata...')
mi = get_metadata(stream, 'pdf') mi = get_metadata(stream, 'pdf')
opf = OPFCreator(getcwd(), mi) opf = OPFCreator(os.getcwd(), mi)
manifest = [('index.html', None)] manifest = [('index.html', None)]
images = os.listdir(getcwd()) images = os.listdir(os.getcwd())
images.remove('index.html') images.remove('index.html')
for i in images: for i in images:
manifest.append((i, None)) manifest.append((i, None))
@ -79,4 +79,4 @@ class PDFInput(InputFormatPlugin):
f.seek(0) f.seek(0)
f.write(raw) f.write(raw)
return os.path.join(getcwd(), 'metadata.opf') return os.path.join(os.getcwd(), 'metadata.opf')

View File

@ -11,7 +11,6 @@ import shutil
from calibre.customize.conversion import InputFormatPlugin from calibre.customize.conversion import InputFormatPlugin
from calibre.ptempfile import TemporaryDirectory from calibre.ptempfile import TemporaryDirectory
from polyglot.builtins import getcwd
class PMLInput(InputFormatPlugin): class PMLInput(InputFormatPlugin):
@ -76,10 +75,10 @@ class PMLInput(InputFormatPlugin):
if not imgs: if not imgs:
imgs = glob.glob(os.path.join(os.path.join(tdir, 'images'), '*.png')) imgs = glob.glob(os.path.join(os.path.join(tdir, 'images'), '*.png'))
if imgs: if imgs:
os.makedirs(os.path.join(getcwd(), 'images')) os.makedirs(os.path.join(os.getcwd(), 'images'))
for img in imgs: for img in imgs:
pimg_name = os.path.basename(img) pimg_name = os.path.basename(img)
pimg_path = os.path.join(getcwd(), 'images', pimg_name) pimg_path = os.path.join(os.getcwd(), 'images', pimg_name)
images.append('images/' + pimg_name) images.append('images/' + pimg_name)
@ -107,7 +106,7 @@ class PMLInput(InputFormatPlugin):
pmls = glob.glob(os.path.join(tdir, '*.pml')) pmls = glob.glob(os.path.join(tdir, '*.pml'))
for pml in pmls: for pml in pmls:
html_name = os.path.splitext(os.path.basename(pml))[0]+'.html' html_name = os.path.splitext(os.path.basename(pml))[0]+'.html'
html_path = os.path.join(getcwd(), html_name) html_path = os.path.join(os.getcwd(), html_name)
pages.append(html_name) pages.append(html_name)
log.debug('Processing PML item %s...' % pml) log.debug('Processing PML item %s...' % pml)
@ -133,7 +132,7 @@ class PMLInput(InputFormatPlugin):
mi = get_metadata(stream, 'pml') mi = get_metadata(stream, 'pml')
if 'images/cover.png' in images: if 'images/cover.png' in images:
mi.cover = 'images/cover.png' mi.cover = 'images/cover.png'
opf = OPFCreator(getcwd(), mi) opf = OPFCreator(os.getcwd(), mi)
log.debug('Generating manifest...') log.debug('Generating manifest...')
opf.create_manifest(manifest_items) opf.create_manifest(manifest_items)
opf.create_spine(pages) opf.create_spine(pages)
@ -142,7 +141,7 @@ class PMLInput(InputFormatPlugin):
with lopen('toc.ncx', 'wb') as tocfile: with lopen('toc.ncx', 'wb') as tocfile:
opf.render(opffile, tocfile, 'toc.ncx') opf.render(opffile, tocfile, 'toc.ncx')
return os.path.join(getcwd(), 'metadata.opf') return os.path.join(os.getcwd(), 'metadata.opf')
def postprocess_book(self, oeb, opts, log): def postprocess_book(self, oeb, opts, log):
from calibre.ebooks.oeb.base import XHTML, barename from calibre.ebooks.oeb.base import XHTML, barename

View File

@ -6,8 +6,9 @@ __copyright__ = '2009, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
import os
from calibre.customize.conversion import InputFormatPlugin from calibre.customize.conversion import InputFormatPlugin
from polyglot.builtins import getcwd
class RBInput(InputFormatPlugin): class RBInput(InputFormatPlugin):
@ -23,6 +24,6 @@ class RBInput(InputFormatPlugin):
from calibre.ebooks.rb.reader import Reader from calibre.ebooks.rb.reader import Reader
reader = Reader(stream, log, options.input_encoding) reader = Reader(stream, log, options.input_encoding)
opf = reader.extract_content(getcwd()) opf = reader.extract_content(os.getcwd())
return opf return opf

View File

@ -5,7 +5,7 @@ __copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
import os, glob, re, textwrap import os, glob, re, textwrap
from calibre.customize.conversion import InputFormatPlugin, OptionRecommendation from calibre.customize.conversion import InputFormatPlugin, OptionRecommendation
from polyglot.builtins import iteritems, getcwd, as_bytes from polyglot.builtins import iteritems, as_bytes
border_style_map = { border_style_map = {
'single' : 'solid', 'single' : 'solid',
@ -304,7 +304,7 @@ class RTFInput(InputFormatPlugin):
mi.title = _('Unknown') mi.title = _('Unknown')
if not mi.authors: if not mi.authors:
mi.authors = [_('Unknown')] mi.authors = [_('Unknown')]
opf = OPFCreator(getcwd(), mi) opf = OPFCreator(os.getcwd(), mi)
opf.create_manifest([(u'index.xhtml', None)]) opf.create_manifest([(u'index.xhtml', None)])
opf.create_spine([u'index.xhtml']) opf.create_spine([u'index.xhtml'])
opf.render(open(u'metadata.opf', 'wb')) opf.render(open(u'metadata.opf', 'wb'))

View File

@ -9,7 +9,6 @@ import os
from calibre import _ent_pat, walk, xml_entity_to_unicode from calibre import _ent_pat, walk, xml_entity_to_unicode
from calibre.customize.conversion import InputFormatPlugin, OptionRecommendation from calibre.customize.conversion import InputFormatPlugin, OptionRecommendation
from polyglot.builtins import getcwd
MD_EXTENSIONS = { MD_EXTENSIONS = {
'abbr': _('Abbreviations'), 'abbr': _('Abbreviations'),
@ -143,7 +142,7 @@ class TXTInput(InputFormatPlugin):
txt = b'' txt = b''
log.debug('Reading text from file...') log.debug('Reading text from file...')
length = 0 length = 0
base_dir = self.output_dir = getcwd() base_dir = self.output_dir = os.getcwd()
# Extract content from zip archive. # Extract content from zip archive.
if file_ext == 'txtz': if file_ext == 'txtz':

View File

@ -28,7 +28,7 @@ from calibre.ebooks.docx.fields import Fields
from calibre.ebooks.docx.settings import Settings from calibre.ebooks.docx.settings import Settings
from calibre.ebooks.metadata.opf2 import OPFCreator from calibre.ebooks.metadata.opf2 import OPFCreator
from calibre.utils.localization import canonicalize_lang, lang_as_iso639_1 from calibre.utils.localization import canonicalize_lang, lang_as_iso639_1
from polyglot.builtins import iteritems, itervalues, getcwd, unicode_type from polyglot.builtins import iteritems, itervalues, unicode_type
NBSP = '\xa0' NBSP = '\xa0'
@ -69,7 +69,7 @@ class Convert:
self.notes_text = notes_text or _('Notes') self.notes_text = notes_text or _('Notes')
self.notes_nopb = notes_nopb self.notes_nopb = notes_nopb
self.nosupsub = nosupsub self.nosupsub = nosupsub
self.dest_dir = dest_dir or getcwd() self.dest_dir = dest_dir or os.getcwd()
self.mi = self.docx.metadata self.mi = self.docx.metadata
self.body = BODY() self.body = BODY()
self.theme = Theme(self.namespace) self.theme = Theme(self.namespace)
@ -842,7 +842,7 @@ if __name__ == '__main__':
import shutil import shutil
from calibre.utils.logging import default_log from calibre.utils.logging import default_log
default_log.filter_level = default_log.DEBUG default_log.filter_level = default_log.DEBUG
dest_dir = os.path.join(getcwd(), 'docx_input') dest_dir = os.path.join(os.getcwd(), 'docx_input')
if os.path.exists(dest_dir): if os.path.exists(dest_dir):
shutil.rmtree(dest_dir) shutil.rmtree(dest_dir)
os.mkdir(dest_dir) os.mkdir(dest_dir)

View File

@ -32,7 +32,7 @@ from calibre.ebooks.lrf.pylrs.pylrs import (
RuledLine, Span, Sub, Sup, TextBlock RuledLine, Span, Sub, Sup, TextBlock
) )
from calibre.ptempfile import PersistentTemporaryFile from calibre.ptempfile import PersistentTemporaryFile
from polyglot.builtins import getcwd, itervalues, string_or_bytes, unicode_type from polyglot.builtins import itervalues, string_or_bytes, unicode_type
from polyglot.urllib import unquote, urlparse from polyglot.urllib import unquote, urlparse
""" """
@ -1889,7 +1889,7 @@ def process_file(path, options, logger):
if not oname: if not oname:
suffix = '.lrs' if options.lrs else '.lrf' suffix = '.lrs' if options.lrs else '.lrf'
name = os.path.splitext(os.path.basename(path))[0] + suffix name = os.path.splitext(os.path.basename(path))[0] + suffix
oname = os.path.join(getcwd(), name) oname = os.path.join(os.getcwd(), name)
oname = os.path.abspath(os.path.expanduser(oname)) oname = os.path.abspath(os.path.expanduser(oname))
conv.writeto(oname, lrs=options.lrs) conv.writeto(oname, lrs=options.lrs)
conv.cleanup() conv.cleanup()

View File

@ -14,7 +14,7 @@ from contextlib import suppress
from calibre import relpath, guess_type, prints, force_unicode from calibre import relpath, guess_type, prints, force_unicode
from calibre.utils.config_base import tweaks from calibre.utils.config_base import tweaks
from polyglot.builtins import codepoint_to_chr, unicode_type, getcwd, iteritems, as_unicode from polyglot.builtins import codepoint_to_chr, unicode_type, iteritems, as_unicode
from polyglot.urllib import quote, unquote, urlparse from polyglot.urllib import quote, unquote, urlparse
@ -242,7 +242,7 @@ class Resource:
''' '''
def __init__(self, href_or_path, basedir=getcwd(), is_path=True): def __init__(self, href_or_path, basedir=os.getcwd(), is_path=True):
self._href = None self._href = None
self._basedir = basedir self._basedir = basedir
self.path = None self.path = None
@ -284,7 +284,7 @@ class Resource:
if self._basedir: if self._basedir:
basedir = self._basedir basedir = self._basedir
else: else:
basedir = getcwd() basedir = os.getcwd()
if self.path is None: if self.path is None:
return self._href return self._href
f = self.fragment.encode('utf-8') if isinstance(self.fragment, unicode_type) else self.fragment f = self.fragment.encode('utf-8') if isinstance(self.fragment, unicode_type) else self.fragment

View File

@ -17,7 +17,7 @@ from calibre.ebooks.metadata import string_to_authors, authors_to_sort_string, \
from calibre.ebooks.lrf.meta import LRFMetaFile from calibre.ebooks.lrf.meta import LRFMetaFile
from calibre import prints from calibre import prints
from calibre.utils.date import parse_date from calibre.utils.date import parse_date
from polyglot.builtins import iteritems, unicode_type, getcwd from polyglot.builtins import iteritems, unicode_type
USAGE=_('%prog ebook_file [options]\n') + \ USAGE=_('%prog ebook_file [options]\n') + \
_(''' _('''
@ -208,7 +208,7 @@ def main(args=sys.argv):
if opts.to_opf is not None: if opts.to_opf is not None:
from calibre.ebooks.metadata.opf2 import OPFCreator from calibre.ebooks.metadata.opf2 import OPFCreator
opf = OPFCreator(getcwd(), mi) opf = OPFCreator(os.getcwd(), mi)
with open(opts.to_opf, 'wb') as f: with open(opts.to_opf, 'wb') as f:
opf.render(f) opf.render(f)
prints(_('OPF created in'), opts.to_opf) prints(_('OPF created in'), opts.to_opf)

View File

@ -21,7 +21,6 @@ from calibre.utils.xml_parse import safe_xml_fromstring
from calibre.ptempfile import TemporaryDirectory from calibre.ptempfile import TemporaryDirectory
from calibre.utils.localunzip import LocalZipFile from calibre.utils.localunzip import LocalZipFile
from calibre.utils.zipfile import BadZipfile, ZipFile, safe_replace from calibre.utils.zipfile import BadZipfile, ZipFile, safe_replace
from polyglot.builtins import getcwd
class EPubException(Exception): class EPubException(Exception):
@ -144,7 +143,7 @@ class OCFZipReader(OCFReader):
if name: if name:
self.root = os.path.abspath(os.path.dirname(name)) self.root = os.path.abspath(os.path.dirname(name))
else: else:
self.root = getcwd() self.root = os.getcwd()
super(OCFZipReader, self).__init__() super(OCFZipReader, self).__init__()
def open(self, name): def open(self, name):
@ -245,7 +244,7 @@ def serialize_cover_data(new_cdata, cpath):
def set_metadata(stream, mi, apply_null=False, update_timestamp=False, force_identifiers=False, add_missing_cover=True): def set_metadata(stream, mi, apply_null=False, update_timestamp=False, force_identifiers=False, add_missing_cover=True):
stream.seek(0) stream.seek(0)
reader = get_zip_reader(stream, root=getcwd()) reader = get_zip_reader(stream, root=os.getcwd())
new_cdata = None new_cdata = None
try: try:
new_cdata = mi.cover_data[1] new_cdata = mi.cover_data[1]

View File

@ -7,9 +7,9 @@ Support for reading the metadata from a LIT file.
''' '''
import io import io
import os
from calibre.ebooks.metadata.opf2 import OPF from calibre.ebooks.metadata.opf2 import OPF
from polyglot.builtins import getcwd
def get_metadata(stream): def get_metadata(stream):
@ -18,7 +18,7 @@ def get_metadata(stream):
litfile = LitContainer(stream, Log()) litfile = LitContainer(stream, Log())
src = litfile.get_metadata().encode('utf-8') src = litfile.get_metadata().encode('utf-8')
litfile = litfile._litfile litfile = litfile._litfile
opf = OPF(io.BytesIO(src), getcwd()) opf = OPF(io.BytesIO(src), os.getcwd())
mi = opf.to_book_metadata() mi = opf.to_book_metadata()
covers = [] covers = []
for item in opf.iterguide(): for item in opf.iterguide():

View File

@ -11,7 +11,7 @@ from calibre.ebooks.metadata.opf2 import OPF
from calibre import isbytestring from calibre import isbytestring
from calibre.customize.ui import get_file_type_metadata, set_file_type_metadata from calibre.customize.ui import get_file_type_metadata, set_file_type_metadata
from calibre.ebooks.metadata import MetaInformation, string_to_authors from calibre.ebooks.metadata import MetaInformation, string_to_authors
from polyglot.builtins import getcwd, unicode_type from polyglot.builtins import unicode_type
# The priorities for loading metadata from different file types # The priorities for loading metadata from different file types
# Higher values should be used to update metadata from lower values # Higher values should be used to update metadata from lower values
@ -209,7 +209,7 @@ def metadata_from_filename(name, pat=None, fallback_pat=None):
def opf_metadata(opfpath): def opf_metadata(opfpath):
if hasattr(opfpath, 'read'): if hasattr(opfpath, 'read'):
f = opfpath f = opfpath
opfpath = getattr(f, 'name', getcwd()) opfpath = getattr(f, 'name', os.getcwd())
else: else:
f = open(opfpath, 'rb') f = open(opfpath, 'rb')
try: try:

View File

@ -24,7 +24,7 @@ from calibre import prints, guess_type
from calibre.utils.cleantext import clean_ascii_chars, clean_xml_chars from calibre.utils.cleantext import clean_ascii_chars, clean_xml_chars
from calibre.utils.config import tweaks from calibre.utils.config import tweaks
from calibre.utils.xml_parse import safe_xml_fromstring from calibre.utils.xml_parse import safe_xml_fromstring
from polyglot.builtins import iteritems, unicode_type, getcwd from polyglot.builtins import iteritems, unicode_type
from polyglot.urllib import unquote, urlparse from polyglot.urllib import unquote, urlparse
pretty_print_opf = False pretty_print_opf = False
@ -57,7 +57,7 @@ class Resource: # {{{
:method:`href` :method:`href`
''' '''
def __init__(self, href_or_path, basedir=getcwd(), is_path=True): def __init__(self, href_or_path, basedir=os.getcwd(), is_path=True):
self.orig = href_or_path self.orig = href_or_path
self._href = None self._href = None
self._basedir = basedir self._basedir = basedir
@ -101,7 +101,7 @@ class Resource: # {{{
if self._basedir: if self._basedir:
basedir = self._basedir basedir = self._basedir
else: else:
basedir = getcwd() basedir = os.getcwd()
if self.path is None: if self.path is None:
return self._href return self._href
frag = ('#' + self.fragment) if self.fragment else '' frag = ('#' + self.fragment) if self.fragment else ''
@ -386,7 +386,7 @@ class Guide(ResourceCollection): # {{{
return ans + '/>' return ans + '/>'
@staticmethod @staticmethod
def from_opf_guide(references, base_dir=getcwd()): def from_opf_guide(references, base_dir=os.getcwd()):
coll = Guide() coll = Guide()
for ref in references: for ref in references:
try: try:
@ -587,7 +587,7 @@ class OPF: # {{{
author_link_map = MetadataField('author_link_map', is_dc=False, author_link_map = MetadataField('author_link_map', is_dc=False,
formatter=json.loads, renderer=dump_dict) formatter=json.loads, renderer=dump_dict)
def __init__(self, stream, basedir=getcwd(), unquote_urls=True, def __init__(self, stream, basedir=os.getcwd(), unquote_urls=True,
populate_spine=True, try_to_guess_cover=True, preparsed_opf=None, read_toc=True): populate_spine=True, try_to_guess_cover=True, preparsed_opf=None, read_toc=True):
self.try_to_guess_cover = try_to_guess_cover self.try_to_guess_cover = try_to_guess_cover
self.basedir = self.base_dir = basedir self.basedir = self.base_dir = basedir
@ -1780,7 +1780,7 @@ def suite():
</package> </package>
''' '''
) )
self.opf = OPF(self.stream, getcwd()) self.opf = OPF(self.stream, os.getcwd())
def testReading(self, opf=None): def testReading(self, opf=None):
if opf is None: if opf is None:
@ -1811,11 +1811,11 @@ def suite():
self.opf.render() self.opf.render()
def testCreator(self): def testCreator(self):
opf = OPFCreator(getcwd(), self.opf) opf = OPFCreator(os.getcwd(), self.opf)
buf = io.BytesIO() buf = io.BytesIO()
opf.render(buf) opf.render(buf)
raw = buf.getvalue() raw = buf.getvalue()
self.testReading(opf=OPF(io.BytesIO(raw), getcwd())) self.testReading(opf=OPF(io.BytesIO(raw), os.getcwd()))
def testSmartUpdate(self): def testSmartUpdate(self):
self.opf.smart_update(MetaInformation(self.opf)) self.opf.smart_update(MetaInformation(self.opf))
@ -1841,7 +1841,7 @@ def test_user_metadata():
} }
mi.set_all_user_metadata(um) mi.set_all_user_metadata(um)
raw = metadata_to_opf(mi) raw = metadata_to_opf(mi)
opfc = OPFCreator(getcwd(), other=mi) opfc = OPFCreator(os.getcwd(), other=mi)
out = io.BytesIO() out = io.BytesIO()
opfc.render(out) opfc.render(out)
raw2 = out.getvalue() raw2 = out.getvalue()

View File

@ -14,7 +14,7 @@ from calibre.constants import __appname__, __version__
from calibre.ebooks.chardet import xml_to_unicode from calibre.ebooks.chardet import xml_to_unicode
from calibre.utils.xml_parse import safe_xml_fromstring from calibre.utils.xml_parse import safe_xml_fromstring
from calibre.utils.cleantext import clean_xml_chars from calibre.utils.cleantext import clean_xml_chars
from polyglot.builtins import unicode_type, getcwd from polyglot.builtins import unicode_type
from polyglot.urllib import unquote, urlparse from polyglot.urllib import unquote, urlparse
NCX_NS = "http://www.daisy.org/z3986/2005/ncx/" NCX_NS = "http://www.daisy.org/z3986/2005/ncx/"
@ -47,7 +47,7 @@ def parse_html_toc(data):
class TOC(list): class TOC(list):
def __init__(self, href=None, fragment=None, text=None, parent=None, def __init__(self, href=None, fragment=None, text=None, parent=None,
play_order=0, base_path=getcwd(), type='unknown', author=None, play_order=0, base_path=os.getcwd(), type='unknown', author=None,
description=None, toc_thumbnail=None): description=None, toc_thumbnail=None):
self.href = href self.href = href
self.fragment = fragment self.fragment = fragment

View File

@ -8,7 +8,6 @@ import os
from calibre.utils.zipfile import ZipFile from calibre.utils.zipfile import ZipFile
from calibre.ptempfile import TemporaryDirectory from calibre.ptempfile import TemporaryDirectory
from calibre import CurrentDir from calibre import CurrentDir
from polyglot.builtins import getcwd
def get_metadata(stream): def get_metadata(stream):
@ -49,7 +48,7 @@ def zip_opf_metadata(opfpath, zf):
from calibre.ebooks.metadata.opf2 import OPF from calibre.ebooks.metadata.opf2 import OPF
if hasattr(opfpath, 'read'): if hasattr(opfpath, 'read'):
f = opfpath f = opfpath
opfpath = getattr(f, 'name', getcwd()) opfpath = getattr(f, 'name', os.getcwd())
else: else:
f = open(opfpath, 'rb') f = open(opfpath, 'rb')
opf = OPF(f, os.path.dirname(opfpath)) opf = OPF(f, os.path.dirname(opfpath))

View File

@ -23,7 +23,7 @@ from calibre.ebooks.metadata.toc import TOC
from calibre.ebooks.mobi.utils import read_font_record from calibre.ebooks.mobi.utils import read_font_record
from calibre.ebooks.oeb.parse_utils import parse_html from calibre.ebooks.oeb.parse_utils import parse_html
from calibre.ebooks.oeb.base import XPath, XHTML, xml2text from calibre.ebooks.oeb.base import XPath, XHTML, xml2text
from polyglot.builtins import unicode_type, getcwd, as_unicode from polyglot.builtins import unicode_type, as_unicode
from polyglot.urllib import urldefrag from polyglot.urllib import urldefrag
Part = namedtuple('Part', Part = namedtuple('Part',
@ -357,7 +357,7 @@ class Mobi8Reader:
if isinstance(idtext, bytes): if isinstance(idtext, bytes):
idtext = idtext.decode(self.header.codec) idtext = idtext.decode(self.header.codec)
linktgt += '#' + idtext linktgt += '#' + idtext
g = Guide.Reference(linktgt, getcwd()) g = Guide.Reference(linktgt, os.getcwd())
g.title, g.type = ref_title, ref_type g.title, g.type = ref_title, ref_type
if g.title == 'start' or g.type == 'text': if g.title == 'start' or g.type == 'text':
has_start = True has_start = True
@ -371,7 +371,7 @@ class Mobi8Reader:
linktgt = fi.filename linktgt = fi.filename
if idtext: if idtext:
linktgt += '#' + idtext linktgt += '#' + idtext
g = Guide.Reference('%s/%s'%(fi.type, linktgt), getcwd()) g = Guide.Reference('%s/%s'%(fi.type, linktgt), os.getcwd())
g.title, g.type = 'start', 'text' g.title, g.type = 'start', 'text'
guide.append(g) guide.append(g)
@ -485,7 +485,7 @@ class Mobi8Reader:
except: except:
self.log.exception('Failed to read inline ToC') self.log.exception('Failed to read inline ToC')
opf = OPFCreator(getcwd(), mi) opf = OPFCreator(os.getcwd(), mi)
opf.guide = guide opf.guide = guide
def exclude(path): def exclude(path):
@ -505,7 +505,7 @@ class Mobi8Reader:
except: except:
pass pass
opf.create_manifest_from_files_in([getcwd()], exclude=exclude) opf.create_manifest_from_files_in([os.getcwd()], exclude=exclude)
for entry in opf.manifest: for entry in opf.manifest:
if entry.mime_type == 'text/html': if entry.mime_type == 'text/html':
entry.mime_type = 'application/xhtml+xml' entry.mime_type = 'application/xhtml+xml'

View File

@ -6,11 +6,13 @@ __license__ = 'GPL v3'
__copyright__ = '2012, Kovid Goyal <kovid@kovidgoyal.net>' __copyright__ = '2012, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
import os
from calibre import replace_entities from calibre import replace_entities
from calibre.ebooks.metadata.toc import TOC from calibre.ebooks.metadata.toc import TOC
from calibre.ebooks.mobi.reader.headers import NULL_INDEX from calibre.ebooks.mobi.reader.headers import NULL_INDEX
from calibre.ebooks.mobi.reader.index import read_index from calibre.ebooks.mobi.reader.index import read_index
from polyglot.builtins import iteritems, getcwd from polyglot.builtins import iteritems
tag_fieldname_map = { tag_fieldname_map = {
1: ['pos',0], 1: ['pos',0],
@ -81,7 +83,7 @@ def read_ncx(sections, index, codec):
def build_toc(index_entries): def build_toc(index_entries):
ans = TOC(base_path=getcwd()) ans = TOC(base_path=os.getcwd())
levels = {x['hlvl'] for x in index_entries} levels = {x['hlvl'] for x in index_entries}
num_map = {-1: ans} num_map = {-1: ans}
level_map = {l:[x for x in index_entries if x['hlvl'] == l] for l in level_map = {l:[x for x in index_entries if x['hlvl'] == l] for l in

View File

@ -20,7 +20,7 @@ from odf.namespaces import TEXTNS as odTEXTNS
from calibre import CurrentDir, walk from calibre import CurrentDir, walk
from calibre.ebooks.oeb.base import _css_logger from calibre.ebooks.oeb.base import _css_logger
from calibre.utils.xml_parse import safe_xml_fromstring from calibre.utils.xml_parse import safe_xml_fromstring
from polyglot.builtins import unicode_type, string_or_bytes, getcwd, as_bytes from polyglot.builtins import unicode_type, string_or_bytes, as_bytes
class Extract(ODF2XHTML): class Extract(ODF2XHTML):
@ -296,9 +296,9 @@ class Extract(ODF2XHTML):
f.write(as_bytes(html)) f.write(as_bytes(html))
zf = ZipFile(stream, 'r') zf = ZipFile(stream, 'r')
self.extract_pictures(zf) self.extract_pictures(zf)
opf = OPFCreator(os.path.abspath(getcwd()), mi) opf = OPFCreator(os.path.abspath(os.getcwd()), mi)
opf.create_manifest([(os.path.abspath(f2), None) for f2 in opf.create_manifest([(os.path.abspath(f2), None) for f2 in
walk(getcwd())]) walk(os.getcwd())])
opf.create_spine([os.path.abspath('index.xhtml')]) opf.create_spine([os.path.abspath('index.xhtml')])
with open('metadata.opf', 'wb') as f: with open('metadata.opf', 'wb') as f:
opf.render(f) opf.render(f)

View File

@ -14,7 +14,7 @@ from qt.core import QEventLoop
from calibre import force_unicode from calibre import force_unicode
from calibre.constants import DEBUG, filesystem_encoding, preferred_encoding from calibre.constants import DEBUG, filesystem_encoding, preferred_encoding
from calibre.utils.config import dynamic from calibre.utils.config import dynamic
from polyglot.builtins import getenv, reraise, string_or_bytes, unicode_type from polyglot.builtins import reraise, string_or_bytes, unicode_type
def dialog_name(name, title): def dialog_name(name, title):
@ -27,20 +27,20 @@ def get_winid(widget=None):
def detect_desktop_environment(): def detect_desktop_environment():
de = getenv('XDG_CURRENT_DESKTOP') de = os.getenv('XDG_CURRENT_DESKTOP')
if de: if de:
return de.upper().split(':', 1)[0] return de.upper().split(':', 1)[0]
if getenv('KDE_FULL_SESSION') == 'true': if os.getenv('KDE_FULL_SESSION') == 'true':
return 'KDE' return 'KDE'
if getenv('GNOME_DESKTOP_SESSION_ID'): if os.getenv('GNOME_DESKTOP_SESSION_ID'):
return 'GNOME' return 'GNOME'
ds = getenv('DESKTOP_SESSION') ds = os.getenv('DESKTOP_SESSION')
if ds and ds.upper() in {'GNOME', 'XFCE'}: if ds and ds.upper() in {'GNOME', 'XFCE'}:
return ds.upper() return ds.upper()
def is_executable_present(name): def is_executable_present(name):
PATH = getenv('PATH') or '' PATH = os.getenv('PATH') or ''
for path in PATH.split(os.pathsep): for path in PATH.split(os.pathsep):
if os.access(os.path.join(path, name), os.X_OK): if os.access(os.path.join(path, name), os.X_OK):
return True return True

View File

@ -37,7 +37,7 @@ from calibre.library.comments import comments_to_html
from calibre import force_unicode from calibre import force_unicode
from calibre.utils.ipc.simple_worker import fork_job, WorkerError from calibre.utils.ipc.simple_worker import fork_job, WorkerError
from calibre.ptempfile import TemporaryDirectory from calibre.ptempfile import TemporaryDirectory
from polyglot.builtins import iteritems, itervalues, unicode_type, getcwd from polyglot.builtins import iteritems, itervalues, unicode_type
from polyglot.queue import Queue, Empty from polyglot.queue import Queue, Empty
# }}} # }}}
@ -408,7 +408,7 @@ class IdentifyWorker(Thread): # {{{
'single_identify', (self.title, self.authors, 'single_identify', (self.title, self.authors,
self.identifiers), no_output=True, abort=self.abort) self.identifiers), no_output=True, abort=self.abort)
self.results, covers, caches, log_dump = res['result'] self.results, covers, caches, log_dump = res['result']
self.results = [OPF(BytesIO(r), basedir=getcwd(), self.results = [OPF(BytesIO(r), basedir=os.getcwd(),
populate_spine=False).to_book_metadata() for r in self.results] populate_spine=False).to_book_metadata() for r in self.results]
for r, cov in zip(self.results, covers): for r, cov in zip(self.results, covers):
r.has_cached_cover_url = cov r.has_cached_cover_url = cov

View File

@ -26,7 +26,7 @@ from calibre.gui2.widgets2 import Dialog as BaseDialog, HistoryComboBox, to_plai
from calibre.utils.icu import primary_sort_key, sort_key, primary_contains, numeric_sort_key from calibre.utils.icu import primary_sort_key, sort_key, primary_contains, numeric_sort_key
from calibre.utils.matcher import get_char, Matcher, DEFAULT_LEVEL1, DEFAULT_LEVEL2, DEFAULT_LEVEL3 from calibre.utils.matcher import get_char, Matcher, DEFAULT_LEVEL1, DEFAULT_LEVEL2, DEFAULT_LEVEL3
from calibre.gui2.complete2 import EditWithComplete from calibre.gui2.complete2 import EditWithComplete
from polyglot.builtins import iteritems, unicode_type, getcwd from polyglot.builtins import iteritems, unicode_type
ROOT = QModelIndex() ROOT = QModelIndex()
@ -478,7 +478,7 @@ class QuickOpen(Dialog):
@classmethod @classmethod
def test(cls): def test(cls):
from calibre.utils.matcher import get_items_from_dir from calibre.utils.matcher import get_items_from_dir
items = get_items_from_dir(getcwd(), lambda x:not x.endswith('.pyc')) items = get_items_from_dir(os.getcwd(), lambda x:not x.endswith('.pyc'))
d = cls(items) d = cls(items)
d.exec_() d.exec_()
print(d.selected_result) print(d.selected_result)

View File

@ -6,7 +6,6 @@ Provides platform independent temporary files that persist even after
being closed. being closed.
""" """
import tempfile, os, atexit import tempfile, os, atexit
from polyglot.builtins import getenv
from calibre.constants import (__version__, __appname__, filesystem_encoding, from calibre.constants import (__version__, __appname__, filesystem_encoding,
iswindows, get_windows_temp_path, ismacos) iswindows, get_windows_temp_path, ismacos)
@ -102,7 +101,7 @@ def base_dir():
else: else:
base = os.environ.get('CALIBRE_TEMP_DIR', None) base = os.environ.get('CALIBRE_TEMP_DIR', None)
if base is not None and iswindows: if base is not None and iswindows:
base = getenv('CALIBRE_TEMP_DIR') base = os.getenv('CALIBRE_TEMP_DIR')
prefix = app_prefix('tmp_') prefix = app_prefix('tmp_')
if base is None: if base is None:
if iswindows: if iswindows:

View File

@ -13,7 +13,7 @@ Test a binary calibre build to ensure that all needed binary images/libraries ha
import os, ctypes, sys, unittest, time, shutil import os, ctypes, sys, unittest, time, shutil
from calibre.constants import iswindows, islinux, ismacos, plugins_loc from calibre.constants import iswindows, islinux, ismacos, plugins_loc
from polyglot.builtins import iteritems, unicode_type, getenv from polyglot.builtins import iteritems, unicode_type
is_ci = os.environ.get('CI', '').lower() == 'true' is_ci = os.environ.get('CI', '').lower() == 'true'
is_sanitized = 'libasan' in os.environ.get('LD_PRELOAD', '') is_sanitized = 'libasan' in os.environ.get('LD_PRELOAD', '')
@ -178,11 +178,11 @@ class BuildTest(unittest.TestCase):
for k, v in iteritems(d): for k, v in iteritems(d):
au(v, k) au(v, k)
os.environ['XXXTEST'] = 'YYY' os.environ['XXXTEST'] = 'YYY'
self.assertEqual(getenv('XXXTEST'), 'YYY') self.assertEqual(os.getenv('XXXTEST'), 'YYY')
del os.environ['XXXTEST'] del os.environ['XXXTEST']
self.assertIsNone(getenv('XXXTEST')) self.assertIsNone(os.getenv('XXXTEST'))
for k in os.environ: for k in os.environ:
v = getenv(k) v = os.getenv(k)
if v is not None: if v is not None:
au(v, 'getenv-' + k) au(v, 'getenv-' + k)
t = time.localtime() t = time.localtime()

View File

@ -11,7 +11,7 @@ from calibre.constants import iswindows, ismacos, isfrozen
from calibre.utils.config import prefs from calibre.utils.config import prefs
from calibre.ptempfile import PersistentTemporaryFile, base_dir from calibre.ptempfile import PersistentTemporaryFile, base_dir
from calibre.utils.serialize import msgpack_dumps from calibre.utils.serialize import msgpack_dumps
from polyglot.builtins import string_or_bytes, environ_item, native_string_type, getcwd from polyglot.builtins import string_or_bytes, environ_item, native_string_type
from polyglot.binary import as_hex_unicode from polyglot.binary import as_hex_unicode
if iswindows: if iswindows:
@ -152,7 +152,7 @@ class Worker:
exe = self.gui_executable if self.gui else self.executable exe = self.gui_executable if self.gui else self.executable
env = self.env env = self.env
try: try:
origwd = cwd or os.path.abspath(getcwd()) origwd = cwd or os.path.abspath(os.getcwd())
except EnvironmentError: except EnvironmentError:
# cwd no longer exists # cwd no longer exists
origwd = cwd or os.path.expanduser('~') origwd = cwd or os.path.expanduser('~')

View File

@ -18,7 +18,7 @@ from struct import calcsize, unpack, pack
from collections import namedtuple, OrderedDict from collections import namedtuple, OrderedDict
from calibre.ptempfile import SpooledTemporaryFile from calibre.ptempfile import SpooledTemporaryFile
from polyglot.builtins import itervalues, getcwd from polyglot.builtins import itervalues
HEADER_SIG = 0x04034b50 HEADER_SIG = 0x04034b50
HEADER_BYTE_SIG = pack(b'<L', HEADER_SIG) HEADER_BYTE_SIG = pack(b'<L', HEADER_SIG)
@ -247,7 +247,7 @@ def extractall(path_or_stream, path=None):
f = open(f, 'rb') f = open(f, 'rb')
close_at_end = True close_at_end = True
if path is None: if path is None:
path = getcwd() path = os.getcwd()
pos = f.tell() pos = f.tell()
try: try:
_extractall(f, path) _extractall(f, path)
@ -294,7 +294,7 @@ class LocalZipFile:
def extractall(self, path=None): def extractall(self, path=None):
self.stream.seek(0) self.stream.seek(0)
_extractall(self.stream, path=(path or getcwd())) _extractall(self.stream, path=(path or os.getcwd()))
def close(self): def close(self):
pass pass

View File

@ -16,7 +16,7 @@ from itertools import islice
from calibre import detect_ncpus as cpu_count, as_unicode from calibre import detect_ncpus as cpu_count, as_unicode
from calibre.constants import filesystem_encoding from calibre.constants import filesystem_encoding
from calibre.utils.icu import primary_sort_key, primary_find, primary_collator from calibre.utils.icu import primary_sort_key, primary_find, primary_collator
from polyglot.builtins import iteritems, itervalues, unicode_type, getcwd from polyglot.builtins import iteritems, itervalues, unicode_type
from polyglot.queue import Queue from polyglot.queue import Queue
DEFAULT_LEVEL1 = '/' DEFAULT_LEVEL1 = '/'
@ -339,8 +339,8 @@ def main(basedir=None, query=None):
from calibre.utils.terminal import ColoredStream from calibre.utils.terminal import ColoredStream
if basedir is None: if basedir is None:
try: try:
basedir = input_unicode('Enter directory to scan [%s]: ' % getcwd() basedir = input_unicode('Enter directory to scan [%s]: ' % os.getcwd()
).strip() or getcwd() ).strip() or os.getcwd()
except (EOFError, KeyboardInterrupt): except (EOFError, KeyboardInterrupt):
return return
m = FilesystemMatcher(basedir) m = FilesystemMatcher(basedir)

View File

@ -18,7 +18,7 @@ from calibre.utils.tdir_in_cache import (
clean_tdirs_in, is_tdir_locked, retry_lock_tdir, tdir_in_cache, tdirs_in, clean_tdirs_in, is_tdir_locked, retry_lock_tdir, tdir_in_cache, tdirs_in,
unlock_file unlock_file
) )
from polyglot.builtins import iteritems, getcwd, native_string_type from polyglot.builtins import iteritems, native_string_type
def FastFailEF(name): def FastFailEF(name):
@ -186,13 +186,13 @@ def other3():
def other4(): def other4():
cache_dir.ans = getcwd() cache_dir.ans = os.getcwd()
tdir_in_cache('t') tdir_in_cache('t')
time.sleep(30) time.sleep(30)
def other5(): def other5():
cache_dir.ans = getcwd() cache_dir.ans = os.getcwd()
if not os.path.isdir(tdir_in_cache('t')): if not os.path.isdir(tdir_in_cache('t')):
raise SystemExit(1) raise SystemExit(1)

View File

@ -18,7 +18,7 @@ from calibre import sanitize_file_name
from calibre.constants import filesystem_encoding from calibre.constants import filesystem_encoding
from calibre.ebooks.chardet import detect from calibre.ebooks.chardet import detect
from calibre.ptempfile import SpooledTemporaryFile from calibre.ptempfile import SpooledTemporaryFile
from polyglot.builtins import getcwd, string_or_bytes, unicode_type, as_bytes from polyglot.builtins import string_or_bytes, unicode_type, as_bytes
try: try:
import zlib # We may need its compression method import zlib # We may need its compression method
@ -1093,7 +1093,7 @@ class ZipFile:
member = self.getinfo(member) member = self.getinfo(member)
if path is None: if path is None:
path = getcwd() path = os.getcwd()
return self._extract_member(member, path, pwd) return self._extract_member(member, path, pwd)

View File

@ -38,7 +38,7 @@ from calibre.web.fetch.simple import (
AbortArticle, RecursiveFetcher, option_parser as web2disk_option_parser AbortArticle, RecursiveFetcher, option_parser as web2disk_option_parser
) )
from calibre.web.fetch.utils import prepare_masthead_image from calibre.web.fetch.utils import prepare_masthead_image
from polyglot.builtins import getcwd, string_or_bytes, unicode_type from polyglot.builtins import string_or_bytes, unicode_type
def classes(classes): def classes(classes):
@ -902,7 +902,7 @@ class BasicNewsRecipe(Recipe):
self.title = unicode_type(self.title, 'utf-8', 'replace') self.title = unicode_type(self.title, 'utf-8', 'replace')
self.debug = options.verbose > 1 self.debug = options.verbose > 1
self.output_dir = os.path.abspath(getcwd()) self.output_dir = os.path.abspath(os.getcwd())
self.verbose = options.verbose self.verbose = options.verbose
self.test = options.test self.test = options.test
if self.test and not isinstance(self.test, tuple): if self.test and not isinstance(self.test, tuple):
@ -1495,7 +1495,7 @@ class BasicNewsRecipe(Recipe):
mp = getattr(self, 'masthead_path', None) mp = getattr(self, 'masthead_path', None)
if mp is not None and os.access(mp, os.R_OK): if mp is not None and os.access(mp, os.R_OK):
from calibre.ebooks.metadata.opf2 import Guide from calibre.ebooks.metadata.opf2 import Guide
ref = Guide.Reference(os.path.basename(self.masthead_path), getcwd()) ref = Guide.Reference(os.path.basename(self.masthead_path), os.getcwd())
ref.type = 'masthead' ref.type = 'masthead'
ref.title = 'Masthead Image' ref.title = 'Masthead Image'
opf.guide.append(ref) opf.guide.append(ref)