Bug 1382697 - Clean up I/O related code for jar.mn processing; r?glandium
Let's introduce some context managers so this is slightly easier to
read.
While we're here, we also introduce an intermediary buffer for
preprocessed output. The reason for this will become apparent in
a subsequent commit.
MozReview-Commit-ID: AmK9xVnyXaz
--- a/python/mozbuild/mozbuild/jar.py
+++ b/python/mozbuild/mozbuild/jar.py
@@ -5,16 +5,17 @@
'''jarmaker.py provides a python class to package up chrome content by
processing jar.mn files.
See the documentation for jar.mn on MDC for further details on the format.
'''
from __future__ import absolute_import
+import io
import sys
import os
import errno
import re
import logging
from time import localtime
from mozbuild.preprocessor import Preprocessor
@@ -401,42 +402,41 @@ class JarMaker(object):
raise RuntimeError('File "{0}" not found in {1}'.format(src,
', '.join(src_base)))
if out in self._seen_output:
raise RuntimeError('%s already added' % out)
self._seen_output.add(out)
if e.preprocess:
- outf = outHelper.getOutput(out)
- inf = open(realsrc)
- pp = self.pp.clone()
- if src[-4:] == '.css':
- pp.setMarker('%')
- pp.out = outf
- pp.do_include(inf)
- pp.failUnused(realsrc)
- outf.close()
- inf.close()
+ content = io.BytesIO()
+
+ with open(realsrc) as fh:
+ pp = self.pp.clone()
+ if src[-4:] == '.css':
+ pp.setMarker('%')
+ pp.out = content
+ pp.do_include(fh)
+ pp.failUnused(realsrc)
+
+ with outHelper.getOutput(out) as fh:
+ fh.write(content.getvalue())
+
return
# copy or symlink if newer
if getModTime(realsrc) > outHelper.getDestModTime(e.output):
if self.outputFormat == 'symlink':
outHelper.symlink(realsrc, out)
return
- outf = outHelper.getOutput(out)
- # open in binary mode, this can be images etc
-
- inf = open(realsrc, 'rb')
- outf.write(inf.read())
- outf.close()
- inf.close()
+ with outHelper.getOutput(out) as ofh:
+ with open(realsrc, 'rb') as ifh:
+ ofh.write(ifh.read())
class OutputHelper_flat(object):
'''Provide getDestModTime and getOutput for a given flat
output directory. The helper method ensureDirFor is used by
the symlink subclass.
'''
def __init__(self, basepath):