add_cmd automatically recognize the format when using the editor

main
Fabien Benureau 12 years ago
parent 2981d6d9cc
commit 467e9f4713

@ -1,6 +1,7 @@
import os import os
import subprocess import subprocess
import tempfile import tempfile
from cStringIO import StringIO
import yaml import yaml
@ -122,7 +123,7 @@ def load_externalbibfile(fullbibpath):
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 FORMATS_INPUT.keys():
with open(fullbibpath) as f: with open(fullbibpath) as f:
return parse_bibdata(f, ext[1:]) return _parse_bibdata_formated_stream(f, ext[1:])
else: else:
print('{}: {} not recognized format for bibliography'.format( print('{}: {} not recognized format for bibliography'.format(
color.dye('error', color.error), color.dye('error', color.error),
@ -130,14 +131,38 @@ def load_externalbibfile(fullbibpath):
exit(-1) exit(-1)
def parse_bibdata(content, format_): def _parse_bibdata_formated_stream(stream, fmt):
"""Parse bib data from string. """Parse a stream for bibdata, using the supplied format."""
try:
parser = FORMATS_INPUT[fmt].Parser()
data = parser.parse_stream(stream)
if data.entries.keys() > 0:
return data
except Exception:
pass
raise ValueError, 'content format is not recognized.'
def parse_bibdata(content, format_ = None):
"""Parse bib data from string or stream.
Raise ValueError if no bibdata is present.
:content: stream :content: stream
:param format_: (bib|xml|yml) :param format_: (bib|xml|yml) if format is None, tries to recognize the
format automatically.
""" """
parser = FORMATS_INPUT[format_].Parser() fmts = [format_]
return parser.parse_stream(content) if format_ is None:
fmts = FORMATS_INPUT.keys()
# we need to reuse the content
content = content if type(content) == str else str(content.read())
for fmt in fmts:
try:
return _parse_bibdata_formated_stream(StringIO(content), fmt)
except Exception:
pass
raise ValueError, 'content format is not recognized.'
def editor_input(config, initial="", suffix=None): def editor_input(config, initial="", suffix=None):

@ -44,7 +44,7 @@ def get_bibentry_from_file(bibfile):
def get_bibentry_from_string(content): 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), 'yml') bib_data = files.parse_bibdata(StringIO(content))
first_key = bib_data.entries.keys()[0] first_key = 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

Loading…
Cancel
Save