core file updated for python 3

main
Fabien Benureau 12 years ago
parent 50e7d1bdab
commit e9cb26f2e0

@ -15,9 +15,12 @@
# included in all copies or substantial portions of the Software. # included in all copies or substantial portions of the Software.
import locale #import locale
import sys import sys
from ConfigParser import NoOptionError
from . import p3
from p3 import input
from p3 import configparser
from . import configs from . import configs
@ -34,7 +37,7 @@ def _encoding(config):
# Configured override? # Configured override?
try: try:
return config.get(configs.MAIN_SECTION, 'terminal-encoding') return config.get(configs.MAIN_SECTION, 'terminal-encoding')
except NoOptionError: except configparser.NoOptionError:
# Determine from locale settings. # Determine from locale settings.
try: try:
return locale.getdefaultlocale()[1] or 'utf8' return locale.getdefaultlocale()[1] or 'utf8'
@ -54,7 +57,7 @@ def input_():
# use print() explicitly to display prompts. # use print() explicitly to display prompts.
# http://bugs.python.org/issue1927 # http://bugs.python.org/issue1927
try: try:
resp = raw_input() resp = input()
except EOFError: except EOFError:
raise UserError('stdin stream ended while input required') raise UserError('stdin stream ended while input required')
return resp.decode(sys.stdin.encoding or 'utf8', 'ignore') return resp.decode(sys.stdin.encoding or 'utf8', 'ignore')

@ -1,6 +1,6 @@
import os import os
import copy import copy
from p3 import configparser from .p3 import configparser
# constant stuff (DFT = DEFAULT) # constant stuff (DFT = DEFAULT)
@ -33,7 +33,7 @@ BOOLEANS = {'import_copy', 'import_move', 'color'}
_config = None _config = None
def config(section = MAIN_SECTION): def config(section = MAIN_SECTION):
if _config is None: if _config is None:
raise ValueError, 'not config instanciated yet' raise ValueError('not config instanciated yet')
_config._section = section _config._section = section
return _config return _config

@ -2,12 +2,13 @@
This module can't depend on configs. This module can't depend on configs.
If you feel the need to import configs, you are not in the right place. If you feel the need to import configs, you are not in the right place.
""" """
from __future__ import print_function
import os import os
import subprocess import subprocess
import tempfile import tempfile
from cStringIO import StringIO from .p3 import io
from io import StringIO
import yaml import yaml
@ -65,9 +66,9 @@ def name_from_path(fullpdfpath, verbose=False):
def check_file(path, fail=False): def check_file(path, fail=False):
if fail: if fail:
if not os.path.exists(path): if not os.path.exists(path):
raise(IOError, "File does not exist: %s." % path) raise IOError("File does not exist: {}.".format(path))
if not os.path.isfile(path): if not os.path.isfile(path):
raise(IOError, "%s is not a file." % path) raise IOError("{} is not a file.".format(path))
return True return True
else: else:
return os.path.exists(path) and os.path.isfile(path) return os.path.exists(path) and os.path.isfile(path)
@ -129,7 +130,7 @@ def load_meta(filepath):
def load_externalbibfile(fullbibpath): def load_externalbibfile(fullbibpath):
check_file(fullbibpath, fail=True) check_file(fullbibpath, fail=True)
filename, ext = os.path.splitext(os.path.split(fullbibpath)[1]) filename, ext = os.path.splitext(os.path.split(fullbibpath)[1])
if ext[1:] in FORMATS_INPUT.keys(): if ext[1:] in list(FORMATS_INPUT.keys()):
with open(fullbibpath) as f: with open(fullbibpath) as f:
return _parse_bibdata_formated_stream(f, ext[1:]) return _parse_bibdata_formated_stream(f, ext[1:])
else: else:
@ -144,11 +145,11 @@ def _parse_bibdata_formated_stream(stream, fmt):
try: try:
parser = FORMATS_INPUT[fmt].Parser() parser = FORMATS_INPUT[fmt].Parser()
data = parser.parse_stream(stream) data = parser.parse_stream(stream)
if data.entries.keys() > 0: if len(list(data.entries.keys())) > 0:
return data return data
except Exception: except Exception:
pass pass
raise ValueError, 'content format is not recognized.' raise ValueError('content format is not recognized.')
def parse_bibdata(content, format_ = None): def parse_bibdata(content, format_ = None):
"""Parse bib data from string or stream. """Parse bib data from string or stream.
@ -170,7 +171,7 @@ def parse_bibdata(content, format_ = None):
except Exception: except Exception:
pass pass
raise ValueError, 'content format is not recognized.' raise ValueError('content format is not recognized.')
def editor_input(editor, initial="", suffix=None): def editor_input(editor, initial="", suffix=None):

@ -7,3 +7,7 @@ if sys.version_info[0] == 2:
else: else:
import configparser import configparser
import io import io
configparser = configparser
io = io
input = input

@ -36,7 +36,7 @@ def get_bibentry_from_file(bibfile):
"""Extract first entry (supposed to be the only one) from given file. """Extract first entry (supposed to be the only one) from given file.
""" """
bib_data = files.load_externalbibfile(bibfile) bib_data = files.load_externalbibfile(bibfile)
first_key = bib_data.entries.keys()[0] first_key = list(bib_data.entries.keys())[0]
first_entry = bib_data.entries[first_key] first_entry = bib_data.entries[first_key]
return first_key, first_entry return first_key, first_entry
@ -45,7 +45,7 @@ def get_bibentry_from_string(content):
"""Extract first entry (supposed to be the only one) from given file. """Extract first entry (supposed to be the only one) from given file.
""" """
bib_data = files.parse_bibdata(StringIO(content)) bib_data = files.parse_bibdata(StringIO(content))
first_key = bib_data.entries.keys()[0] first_key = list(bib_data.entries.keys())[0]
first_entry = bib_data.entries[first_key] first_entry = bib_data.entries[first_key]
return first_key, first_entry return first_key, first_entry
@ -88,7 +88,7 @@ def get_safe_metadata_from_path(metapath):
def check_citekey(citekey): def check_citekey(citekey):
# TODO This is not the right way to test that (17/12/2012) # TODO This is not the right way to test that (17/12/2012)
if unicode(citekey) != str2citekey(citekey): if unicode(citekey) != str2citekey(citekey):
raise(ValueError("Invalid citekey: %s" % citekey)) raise ValueError("Invalid citekey: %s" % citekey)
class NoDocumentFile(Exception): class NoDocumentFile(Exception):
@ -157,8 +157,8 @@ class Paper(object):
try: try:
first_author = self.bibentry.persons[author_key][0] first_author = self.bibentry.persons[author_key][0]
except KeyError: except KeyError:
raise(ValueError( raise ValueError(
'No author or editor defined: cannot generate a citekey.')) 'No author or editor defined: cannot generate a citekey.')
try: try:
year = self.bibentry.fields['year'] year = self.bibentry.fields['year']
except KeyError: except KeyError:
@ -171,8 +171,8 @@ class Paper(object):
saves it to disc. saves it to disc.
""" """
if self.citekey is None: if self.citekey is None:
raise(ValueError( raise ValueError(
'No valid citekey initialized. Cannot save paper')) 'No valid citekey initialized. Cannot save paper')
bibdata = BibliographyData(entries={self.citekey: self.bibentry}) bibdata = BibliographyData(entries={self.citekey: self.bibentry})
files.save_bibdata(bibdata, bib_filepath) files.save_bibdata(bibdata, bib_filepath)
files.save_meta(self.metadata, meta_filepath) files.save_meta(self.metadata, meta_filepath)
@ -208,7 +208,7 @@ class Paper(object):
f = '/' + f f = '/' + f
return f return f
except (KeyError, IndexError): except (KeyError, IndexError):
raise(NoDocumentFile('No file found in bib data.')) raise NoDocumentFile('No file found in bib data.')
def copy(self): def copy(self):
return Paper(bibentry=copy_bibentry(self.bibentry), return Paper(bibentry=copy_bibentry(self.bibentry),
@ -247,7 +247,7 @@ class Paper(object):
try: try:
papers.append(Paper(bibentry=b.entries[k], citekey=k)) papers.append(Paper(bibentry=b.entries[k], citekey=k))
except ValueError, e: except ValueError, e:
print "Warning, skipping paper (%s)." % e print('Warning, skipping paper ({}).'.format(e))
return papers return papers
@ -260,7 +260,7 @@ class Paper(object):
@tags.setter @tags.setter
def tags(self, value): def tags(self, value):
if not hasattr(value, '__iter__'): if not hasattr(value, '__iter__'):
raise ValueError, 'tags must be iterables' raise ValueError('tags must be iterables')
self.metadata['tags'] = set(value) self.metadata['tags'] = set(value)
def add_tag(self, tag): def add_tag(self, tag):

@ -37,7 +37,7 @@ class PapersPlugin(object):
This is a basic example This is a basic example
""" """
for s in strings: for s in strings:
print s print(s)
@classmethod @classmethod
def get_instance(cls): def get_instance(cls):

@ -97,7 +97,7 @@ class Repository(object):
try: try:
return self.citekeys[int(ref)] return self.citekeys[int(ref)]
except (IndexError, ValueError): except (IndexError, ValueError):
raise(InvalidReference) raise InvalidReference
# papers # papers
@ -116,7 +116,7 @@ class Repository(object):
def add_paper(self, p, overwrite = False): def add_paper(self, p, overwrite = False):
if p.citekey is None: # TODO also test if citekey is valid if p.citekey is None: # TODO also test if citekey is valid
raise(ValueError("Invalid citekey: %s." % p.citekey)) raise ValueError("Invalid citekey: {}.".format(p.citekey))
if not overwrite and p.citekey in self: if not overwrite and p.citekey in self:
raise CiteKeyCollision('citekey {} already in use'.format( raise CiteKeyCollision('citekey {} already in use'.format(
p.citekey)) p.citekey))
@ -178,7 +178,7 @@ class Repository(object):
def save_paper(self, paper): def save_paper(self, paper):
if not paper.citekey in self: if not paper.citekey in self:
raise(ValueError('Paper not in repository, first add it.')) raise ValueError('Paper not in repository, first add it.')
paper.save(self._bibfile(paper.citekey), paper.save(self._bibfile(paper.citekey),
self._metafile(paper.citekey)) self._metafile(paper.citekey))
@ -199,7 +199,7 @@ class Repository(object):
def import_document(self, citekey, doc_file): def import_document(self, citekey, doc_file):
if citekey not in self.citekeys: if citekey not in self.citekeys:
raise(ValueError, "Unknown citekey: %s." % citekey) raise ValueError("Unknown citekey: {}.".format(citekey))
else: else:
if not os.path.isfile(doc_file): if not os.path.isfile(doc_file):
raise ValueError("No file {} found.".format(doc_file)) raise ValueError("No file {} found.".format(doc_file))

@ -1,3 +1,5 @@
from __future__ import print_function
import sys import sys
from .beets_ui import _encoding, input_ from .beets_ui import _encoding, input_

Loading…
Cancel
Save