Finish getting rid of getcwdu()

This commit is contained in:
Kovid Goyal 2019-05-15 16:53:39 +05:30
parent a08bdbeb4e
commit 2896bb3571
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C
30 changed files with 93 additions and 89 deletions

View File

@ -15,6 +15,7 @@ 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):
@ -44,7 +45,7 @@ class Reader(FormatReader):
if mo: if mo:
data = mo.group() data = mo.group()
pdf_n = os.path.join(os.getcwdu(), 'tmp.pdf') pdf_n = os.path.join(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

@ -14,7 +14,7 @@ from calibre.utils.chm.chm import CHMFile
from calibre.constants import plugins from calibre.constants import plugins
from calibre.ebooks.metadata.toc import TOC from calibre.ebooks.metadata.toc import TOC
from calibre.ebooks.chardet import xml_to_unicode from calibre.ebooks.chardet import xml_to_unicode
from polyglot.builtins import unicode_type from polyglot.builtins import unicode_type, getcwd
chmlib, chmlib_err = plugins['chmlib'] chmlib, chmlib_err = plugins['chmlib']
@ -70,7 +70,7 @@ class CHMReader(CHMFile):
self.root, ext = os.path.splitext(self.topics.lstrip('/')) self.root, ext = os.path.splitext(self.topics.lstrip('/'))
self.hhc_path = self.root + ".hhc" self.hhc_path = self.root + ".hhc"
def _parse_toc(self, ul, basedir=os.getcwdu()): def _parse_toc(self, ul, basedir=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):
@ -104,7 +104,7 @@ class CHMReader(CHMFile):
raise CHMError("'%s' is zero bytes in length!"%(path,)) raise CHMError("'%s' is zero bytes in length!"%(path,))
return data return data
def ExtractFiles(self, output_dir=os.getcwdu(), debug_dump=False): def ExtractFiles(self, output_dir=getcwd(), debug_dump=False):
html_files = set([]) html_files = set([])
try: try:
x = self.get_encoding() x = self.get_encoding()
@ -288,5 +288,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=os.getcwdu(), debug_dump=False): def extract_content(self, output_dir=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

@ -4,9 +4,8 @@ __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 +23,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(os.getcwdu()) opf = reader.extract_content(getcwd())
return opf return opf

View File

@ -12,6 +12,7 @@ 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):
@ -190,7 +191,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(os.getcwdu(), mi) opf = OPFCreator(getcwd(), mi)
entries = [] entries = []
def href(x): def href(x):

View File

@ -11,6 +11,7 @@ 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):
@ -37,7 +38,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 = os.getcwdu() base = getcwd()
fname = os.path.join(base, 'index.html') fname = os.path.join(base, 'index.html')
c = 0 c = 0
while os.path.exists(fname): while os.path.exists(fname):

View File

@ -7,7 +7,7 @@ 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 unicode_type, as_bytes from polyglot.builtins import unicode_type, as_bytes, 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'
@ -245,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(os.getcwdu(), *path.split('/')) path = os.path.join(getcwd(), *path.split('/'))
if os.path.exists(path): if os.path.exists(path):
return path return path
except Exception: except Exception:
@ -259,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(os.getcwdu()) zf.extractall(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')
@ -279,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, os.getcwdu()) opf = os.path.relpath(opf, 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)))
@ -403,7 +403,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, os.getcwdu()).replace(os.sep, '/') ncx_href = os.path.relpath(f.name, 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

@ -8,7 +8,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, unicode_type from polyglot.builtins import iteritems, unicode_type, getcwd
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'
@ -146,7 +146,7 @@ class FB2Input(InputFormatPlugin):
cpath = os.path.abspath(href) cpath = os.path.abspath(href)
break break
opf = OPFCreator(os.getcwdu(), mi) opf = OPFCreator(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([u'index.xhtml']) opf.create_spine([u'index.xhtml'])
@ -154,7 +154,7 @@ class FB2Input(InputFormatPlugin):
opf.guide.set_cover(cpath) opf.guide.set_cover(cpath)
with open(u'metadata.opf', 'wb') as f: with open(u'metadata.opf', 'wb') as f:
opf.render(f) opf.render(f)
return os.path.join(os.getcwdu(), u'metadata.opf') return os.path.join(getcwd(), u'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

@ -16,7 +16,7 @@ from calibre.customize.conversion import (InputFormatPlugin,
from calibre.utils.localization import get_lang from calibre.utils.localization import get_lang
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 polyglot.builtins import unicode_type, zip from polyglot.builtins import unicode_type, zip, getcwd
def sanitize_file_name(x): def sanitize_file_name(x):
@ -64,7 +64,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 = os.getcwdu() basedir = getcwd()
self.opts = opts self.opts = opts
fname = None fname = None
@ -220,7 +220,7 @@ class HTMLInput(InputFormatPlugin):
continue continue
toc.add(title, item.href) toc.add(title, item.href)
oeb.container = DirContainer(os.getcwdu(), oeb.log, ignore_opf=True) oeb.container = DirContainer(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):
@ -232,7 +232,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 os.getcwdu()) l = Link(link_, base if base else 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

@ -10,6 +10,7 @@ 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 +87,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 = os.getcwdu() base = getcwd()
fname = os.path.join(base, u'index.html') fname = os.path.join(base, u'index.html')
c = 0 c = 0
while os.path.exists(fname): while os.path.exists(fname):
@ -117,12 +118,12 @@ class HTMLZInput(InputFormatPlugin):
opf = x opf = x
break break
if opf: if opf:
opf = OPF(opf, basedir=os.getcwdu()) opf = OPF(opf, basedir=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(os.getcwdu(), cover_path), 'rb') as cf: with open(os.path.join(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

@ -4,9 +4,8 @@ __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 +31,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(os.getcwdu()) opf = reader.extract_content(getcwd())
return opf return opf

View File

@ -7,7 +7,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 from polyglot.builtins import as_bytes, getcwd
class PDFInput(InputFormatPlugin): class PDFInput(InputFormatPlugin):
@ -34,11 +34,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(os.getcwdu(), stream.name, self.opts.no_images, as_xml=True) pdftohtml(getcwd(), stream.name, self.opts.no_images, as_xml=True)
with open(u'index.xml', 'rb') as f: with open(u'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(os.getcwdu(), u'metadata.opf') return os.path.join(getcwd(), u'metadata.opf')
def convert(self, stream, options, file_ext, log, def convert(self, stream, options, file_ext, log,
accelerators): accelerators):
@ -50,16 +50,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(os.getcwdu(), stream.name, options.no_images) pdftohtml(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(os.getcwdu(), mi) opf = OPFCreator(getcwd(), mi)
manifest = [(u'index.html', None)] manifest = [(u'index.html', None)]
images = os.listdir(os.getcwdu()) images = os.listdir(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))
@ -78,4 +78,4 @@ class PDFInput(InputFormatPlugin):
f.seek(0) f.seek(0)
f.write(raw) f.write(raw)
return os.path.join(os.getcwdu(), u'metadata.opf') return os.path.join(getcwd(), u'metadata.opf')

View File

@ -10,6 +10,7 @@ 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):
@ -72,10 +73,10 @@ class PMLInput(InputFormatPlugin):
if not imgs: if not imgs:
imgs = glob.glob(os.path.join(os.path.join(tdir, u'images'), u'*.png')) imgs = glob.glob(os.path.join(os.path.join(tdir, u'images'), u'*.png'))
if imgs: if imgs:
os.makedirs(os.path.join(os.getcwdu(), u'images')) os.makedirs(os.path.join(getcwd(), u'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(os.getcwdu(), 'images', pimg_name) pimg_path = os.path.join(getcwd(), 'images', pimg_name)
images.append('images/' + pimg_name) images.append('images/' + pimg_name)
@ -103,7 +104,7 @@ class PMLInput(InputFormatPlugin):
pmls = glob.glob(os.path.join(tdir, u'*.pml')) pmls = glob.glob(os.path.join(tdir, u'*.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(os.getcwdu(), html_name) html_path = os.path.join(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)
@ -129,7 +130,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 = u'images/cover.png' mi.cover = u'images/cover.png'
opf = OPFCreator(os.getcwdu(), mi) opf = OPFCreator(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)
@ -138,4 +139,4 @@ class PMLInput(InputFormatPlugin):
with open(u'toc.ncx', 'wb') as tocfile: with open(u'toc.ncx', 'wb') as tocfile:
opf.render(opffile, tocfile, u'toc.ncx') opf.render(opffile, tocfile, u'toc.ncx')
return os.path.join(os.getcwdu(), u'metadata.opf') return os.path.join(getcwd(), u'metadata.opf')

View File

@ -4,9 +4,9 @@ __license__ = 'GPL 3'
__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 RBInput(InputFormatPlugin): class RBInput(InputFormatPlugin):
@ -22,6 +22,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(os.getcwdu()) opf = reader.extract_content(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, filter from polyglot.builtins import iteritems, filter, getcwd
border_style_map = { border_style_map = {
'single' : 'solid', 'single' : 'solid',
@ -303,7 +303,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(os.getcwdu(), mi) opf = OPFCreator(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,6 +9,7 @@ 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'),
@ -140,7 +141,7 @@ class TXTInput(InputFormatPlugin):
txt = '' txt = ''
log.debug('Reading text from file...') log.debug('Reading text from file...')
length = 0 length = 0
base_dir = os.getcwdu() base_dir = getcwd()
# Extract content from zip archive. # Extract content from zip archive.
if file_ext == 'txtz': if file_ext == 'txtz':

View File

@ -11,7 +11,7 @@ import os, re, sys, copy, glob, tempfile
from collections import deque from collections import deque
from math import ceil, floor from math import ceil, floor
from functools import partial from functools import partial
from polyglot.builtins import string_or_bytes, itervalues from polyglot.builtins import string_or_bytes, itervalues, getcwd
from itertools import chain from itertools import chain
try: try:
@ -1911,7 +1911,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(os.getcwdu(), name) oname = os.path.join(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

@ -11,7 +11,7 @@ import os, sys, re
from calibre import relpath, guess_type, remove_bracketed_text, prints, force_unicode from calibre import relpath, guess_type, remove_bracketed_text, 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, range, map, zip from polyglot.builtins import codepoint_to_chr, unicode_type, range, map, zip, getcwd
from polyglot.urllib import quote, unquote, urlparse from polyglot.urllib import quote, unquote, urlparse
@ -202,7 +202,7 @@ class Resource(object):
''' '''
def __init__(self, href_or_path, basedir=os.getcwdu(), is_path=True): def __init__(self, href_or_path, basedir=getcwd(), is_path=True):
self._href = None self._href = None
self._basedir = basedir self._basedir = basedir
self.path = None self.path = None
@ -244,7 +244,7 @@ class Resource(object):
if self._basedir: if self._basedir:
basedir = self._basedir basedir = self._basedir
else: else:
basedir = os.getcwdu() basedir = 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

@ -16,7 +16,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 from polyglot.builtins import iteritems, unicode_type, getcwd
USAGE=_('%prog ebook_file [options]\n') + \ USAGE=_('%prog ebook_file [options]\n') + \
_(''' _('''
@ -207,7 +207,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(os.getcwdu(), mi) opf = OPFCreator(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

@ -24,6 +24,7 @@ from calibre.ebooks.metadata.opf2 import OPF
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):
@ -148,7 +149,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 = os.getcwdu() self.root = getcwd()
super(OCFZipReader, self).__init__() super(OCFZipReader, self).__init__()
def open(self, name, mode='r'): def open(self, name, mode='r'):
@ -284,7 +285,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=os.getcwdu()) reader = get_zip_reader(stream, root=getcwd())
new_cdata = None new_cdata = None
try: try:
new_cdata = mi.cover_data[1] new_cdata = mi.cover_data[1]

View File

@ -4,9 +4,10 @@ __copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
Support for reading the metadata from a LIT file. Support for reading the metadata from a LIT file.
''' '''
import io, os import io
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):
@ -15,7 +16,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), os.getcwdu()) opf = OPF(io.BytesIO(src), 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

@ -10,6 +10,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
_METADATA_PRIORITIES = [ _METADATA_PRIORITIES = [
'html', 'htm', 'xhtml', 'xhtm', 'html', 'htm', 'xhtml', 'xhtm',
@ -202,7 +203,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', os.getcwdu()) opfpath = getattr(f, 'name', getcwd())
else: else:
f = open(opfpath, 'rb') f = open(opfpath, 'rb')
try: try:

View File

@ -23,7 +23,7 @@ from calibre.utils.localization import get_lang, canonicalize_lang
from calibre import prints, guess_type 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 polyglot.builtins import iteritems, unicode_type from polyglot.builtins import iteritems, unicode_type, getcwd
from polyglot.urllib import unquote, urlparse from polyglot.urllib import unquote, urlparse
pretty_print_opf = False pretty_print_opf = False
@ -56,7 +56,7 @@ class Resource(object): # {{{
:method:`href` :method:`href`
''' '''
def __init__(self, href_or_path, basedir=os.getcwdu(), is_path=True): def __init__(self, href_or_path, basedir=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
@ -100,7 +100,7 @@ class Resource(object): # {{{
if self._basedir: if self._basedir:
basedir = self._basedir basedir = self._basedir
else: else:
basedir = os.getcwdu() basedir = 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
@ -392,7 +392,7 @@ class Guide(ResourceCollection): # {{{
return ans + '/>' return ans + '/>'
@staticmethod @staticmethod
def from_opf_guide(references, base_dir=os.getcwdu()): def from_opf_guide(references, base_dir=getcwd()):
coll = Guide() coll = Guide()
for ref in references: for ref in references:
try: try:
@ -579,7 +579,7 @@ class OPF(object): # {{{
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=os.getcwdu(), unquote_urls=True, def __init__(self, stream, basedir=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 @@ b'''\
</package> </package>
''' '''
) )
self.opf = OPF(self.stream, os.getcwdu()) self.opf = OPF(self.stream, getcwd())
def testReading(self, opf=None): def testReading(self, opf=None):
if opf is None: if opf is None:
@ -1811,11 +1811,11 @@ b'''\
self.opf.render() self.opf.render()
def testCreator(self): def testCreator(self):
opf = OPFCreator(os.getcwdu(), self.opf) opf = OPFCreator(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), os.getcwdu())) self.testReading(opf=OPF(io.BytesIO(raw), getcwd()))
def testSmartUpdate(self): def testSmartUpdate(self):
self.opf.smart_update(MetaInformation(self.opf)) self.opf.smart_update(MetaInformation(self.opf))
@ -1842,7 +1842,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(os.getcwdu(), other=mi) opfc = OPFCreator(getcwd(), other=mi)
out = io.BytesIO() out = io.BytesIO()
opfc.render(out) opfc.render(out)
raw2 = out.getvalue() raw2 = out.getvalue()

View File

@ -12,7 +12,7 @@ from lxml.builder import ElementMaker
from calibre.constants import __appname__, __version__ 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.cleantext import clean_xml_chars from calibre.utils.cleantext import clean_xml_chars
from polyglot.builtins import unicode_type from polyglot.builtins import unicode_type, getcwd
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/"
@ -51,7 +51,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=os.getcwdu(), type='unknown', author=None, play_order=0, base_path=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

@ -7,6 +7,7 @@ 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):
@ -47,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', os.getcwdu()) opfpath = getattr(f, 'name', 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))
@ -65,4 +66,3 @@ def zip_opf_metadata(opfpath, zf):
data = zf.read(covername) data = zf.read(covername)
mi.cover_data = (fmt, data) mi.cover_data = (fmt, data)
return mi return mi

View File

@ -24,7 +24,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 range, zip, unicode_type from polyglot.builtins import range, zip, unicode_type, getcwd
from polyglot.urllib import urldefrag from polyglot.urllib import urldefrag
Part = namedtuple('Part', Part = namedtuple('Part',
@ -358,7 +358,7 @@ class Mobi8Reader(object):
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, os.getcwdu()) g = Guide.Reference(linktgt, 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
@ -372,7 +372,7 @@ class Mobi8Reader(object):
linktgt = fi.filename linktgt = fi.filename
if idtext: if idtext:
linktgt += '#' + idtext linktgt += '#' + idtext
g = Guide.Reference('%s/%s'%(fi.type, linktgt), os.getcwdu()) g = Guide.Reference('%s/%s'%(fi.type, linktgt), getcwd())
g.title, g.type = 'start', 'text' g.title, g.type = 'start', 'text'
guide.append(g) guide.append(g)
@ -486,7 +486,7 @@ class Mobi8Reader(object):
except: except:
self.log.exception('Failed to read inline ToC') self.log.exception('Failed to read inline ToC')
opf = OPFCreator(os.getcwdu(), mi) opf = OPFCreator(getcwd(), mi)
opf.guide = guide opf.guide = guide
def exclude(path): def exclude(path):
@ -506,7 +506,7 @@ class Mobi8Reader(object):
except: except:
pass pass
opf.create_manifest_from_files_in([os.getcwdu()], exclude=exclude) opf.create_manifest_from_files_in([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

@ -7,13 +7,11 @@ __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 from polyglot.builtins import iteritems, getcwd
tag_fieldname_map = { tag_fieldname_map = {
1: ['pos',0], 1: ['pos',0],
@ -84,7 +82,7 @@ def read_ncx(sections, index, codec):
def build_toc(index_entries): def build_toc(index_entries):
ans = TOC(base_path=os.getcwdu()) ans = TOC(base_path=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

@ -19,7 +19,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 polyglot.builtins import unicode_type, string_or_bytes, filter from polyglot.builtins import unicode_type, string_or_bytes, filter, getcwd
class Extract(ODF2XHTML): class Extract(ODF2XHTML):
@ -295,9 +295,9 @@ class Extract(ODF2XHTML):
f.write(html.encode('utf-8')) f.write(html.encode('utf-8'))
zf = ZipFile(stream, 'r') zf = ZipFile(stream, 'r')
self.extract_pictures(zf) self.extract_pictures(zf)
opf = OPFCreator(os.path.abspath(os.getcwdu()), mi) opf = OPFCreator(os.path.abspath(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(os.getcwdu())]) walk(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

@ -39,7 +39,7 @@ from calibre import force_unicode
from calibre.utils.config import tweaks from calibre.utils.config import tweaks
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, range from polyglot.builtins import iteritems, itervalues, unicode_type, range, getcwd
from polyglot.queue import Queue, Empty from polyglot.queue import Queue, Empty
# }}} # }}}
@ -424,7 +424,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=os.getcwdu(), self.results = [OPF(BytesIO(r), basedir=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

@ -27,7 +27,7 @@ from calibre.gui2.widgets2 import Dialog as BaseDialog, HistoryComboBox
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 from calibre.utils.matcher import get_char, Matcher
from calibre.gui2.complete2 import EditWithComplete from calibre.gui2.complete2 import EditWithComplete
from polyglot.builtins import iteritems, unicode_type, zip from polyglot.builtins import iteritems, unicode_type, zip, getcwd
ROOT = QModelIndex() ROOT = QModelIndex()
PARAGRAPH_SEPARATOR = '\u2029' PARAGRAPH_SEPARATOR = '\u2029'
@ -470,9 +470,8 @@ class QuickOpen(Dialog):
@classmethod @classmethod
def test(cls): def test(cls):
import os
from calibre.utils.matcher import get_items_from_dir from calibre.utils.matcher import get_items_from_dir
items = get_items_from_dir(os.getcwdu(), lambda x:not x.endswith('.pyc')) items = get_items_from_dir(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

@ -13,7 +13,7 @@ from calibre.constants import iswindows, isosx, isfrozen, filesystem_encoding, i
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 iteritems, unicode_type, string_or_bytes, environ_item, native_string_type from polyglot.builtins import iteritems, unicode_type, string_or_bytes, environ_item, native_string_type, getcwd
from polyglot.binary import as_hex_unicode from polyglot.binary import as_hex_unicode
if iswindows: if iswindows:
@ -186,7 +186,7 @@ class Worker(object):
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(os.getcwdu()) origwd = cwd or os.path.abspath(getcwd())
except EnvironmentError: except EnvironmentError:
# cwd no longer exists # cwd no longer exists
origwd = cwd or os.path.expanduser(u'~') origwd = cwd or os.path.expanduser(u'~')