Browse Source

Transformation de encoding.open_read en un 'context manager'

pull/69/head
Louis 10 years ago
parent
commit
607e064bfb
  1. 7
      patacrep/content/include.py
  2. 8
      patacrep/encoding.py
  3. 6
      patacrep/index.py
  4. 3
      patacrep/latex/__init__.py
  5. 8
      patacrep/songbook.py
  6. 41
      patacrep/templates.py

7
patacrep/content/include.py

@ -48,15 +48,12 @@ def parse(keyword, config, argument, contentlist):
filepath = load_from_datadirs(path, config) filepath = load_from_datadirs(path, config)
content_file = None content_file = None
try: try:
content_file = encoding.open_read(filepath, 'r') with encoding.open_read(filepath, 'r') as content_file:
new_content = json.load(content_file) new_content = json.load(content_file)
except Exception as error: # pylint: disable=broad-except except Exception as error: # pylint: disable=broad-except
LOGGER.error(error) LOGGER.error(error)
LOGGER.error("Error while loading file '{}'.".format(filepath)) LOGGER.error("Error while loading file '{}'.".format(filepath))
sys.exit(1) sys.exit(1)
finally:
if content_file:
content_file.close()
config["datadir"].append(os.path.abspath(os.path.dirname(filepath))) config["datadir"].append(os.path.abspath(os.path.dirname(filepath)))
new_contentlist += process_content(new_content, config) new_contentlist += process_content(new_content, config)

8
patacrep/encoding.py

@ -5,17 +5,21 @@
import codecs import codecs
import chardet import chardet
import logging import logging
import contextlib
LOGGER = logging.getLogger(__name__) LOGGER = logging.getLogger(__name__)
@contextlib.contextmanager
def open_read(filename, mode='r'): def open_read(filename, mode='r'):
"""Open a file for reading, guessing the right encoding. """Open a file for reading, guessing the right encoding.
Return a fileobject, reading unicode strings. Return a fileobject, reading unicode strings.
""" """
return codecs.open( with codecs.open(
filename, filename,
mode=mode, mode=mode,
encoding=chardet.detect(open(filename, 'rb').read())['encoding'], encoding=chardet.detect(open(filename, 'rb').read())['encoding'],
errors='replace', errors='replace',
) ) as fileobject:
yield fileobject

6
patacrep/index.py

@ -29,13 +29,9 @@ def process_sxd(filename):
""" """
data = [] data = []
index_file = None index_file = None
try: with encoding.open_read(filename, 'r') as index_file:
index_file = encoding.open_read(filename, 'r')
for line in index_file: for line in index_file:
data.append(line.strip()) data.append(line.strip())
finally:
if index_file:
index_file.close()
i = 1 i = 1
idx = Index(data[0]) idx = Index(data[0])

3
patacrep/latex/__init__.py

@ -15,6 +15,7 @@ def parsesong(path):
"""Return a dictonary of data read from the latex file `path`. """Return a dictonary of data read from the latex file `path`.
""" """
data = syntax_parsesong(encoding.open_read(path).read(), path) with encoding.open_read(path) as songfile:
data = syntax_parsesong(songfile.read(), path)
data['@path'] = path data['@path'] = path
return data return data

8
patacrep/songbook.py

@ -100,17 +100,13 @@ def main():
basename = os.path.basename(songbook_path)[:-3] basename = os.path.basename(songbook_path)[:-3]
songbook_file = None
try: try:
songbook_file = encoding.open_read(songbook_path) with encoding.open_read(songbook_path) as songbook_file:
songbook = json.load(songbook_file) songbook = json.load(songbook_file)
except Exception as error: # pylint: disable=broad-except except Exception as error: # pylint: disable=broad-except
LOGGER.error(error) LOGGER.error(error)
LOGGER.error("Error while loading file '{}'.".format(songbook_path)) LOGGER.error("Error while loading file '{}'.".format(songbook_path))
sys.exit(1) sys.exit(1)
finally:
if songbook_file:
songbook_file.close()
# Gathering datadirs # Gathering datadirs
datadirs = [] datadirs = []

41
patacrep/templates.py

@ -186,32 +186,27 @@ class TexRenderer(object):
""" """
subvariables = {} subvariables = {}
template_file = None
templatename = self.texenv.get_template(template).filename templatename = self.texenv.get_template(template).filename
try: with encoding.open_read(templatename, 'r') as template_file:
template_file = encoding.open_read(templatename, 'r')
content = template_file.read() content = template_file.read()
subtemplates = list(find_templates(self.texenv.parse(content))) subtemplates = list(find_templates(self.texenv.parse(content)))
match = re.findall(_VARIABLE_REGEXP, content) match = re.findall(_VARIABLE_REGEXP, content)
if match: if match:
for var in match: for var in match:
try: try:
subvariables.update(json.loads(var)) subvariables.update(json.loads(var))
except ValueError as exception: except ValueError as exception:
raise errors.TemplateError( raise errors.TemplateError(
exception, exception,
( (
"Error while parsing json in file " "Error while parsing json in file "
"{filename}. The json string was:" "{filename}. The json string was:"
"\n'''\n{jsonstring}\n'''" "\n'''\n{jsonstring}\n'''"
).format( ).format(
filename=templatename, filename=templatename,
jsonstring=var, jsonstring=var,
)
) )
finally: )
if template_file:
template_file.close()
return (subvariables, subtemplates) return (subvariables, subtemplates)

Loading…
Cancel
Save