Commit 8c57291a authored by Ryan Herbert's avatar Ryan Herbert Committed by Mikaël Salson

vidjilparser.py refactor writer class

split VidjilWriter into VidjilWriter and VidjilFileWriter
parent 71cf75ec
...@@ -9,30 +9,23 @@ class MatchingEvent(Enum): ...@@ -9,30 +9,23 @@ class MatchingEvent(Enum):
class VidjilWriter(object): class VidjilWriter(object):
def __init__(self, filepath=None, pretty=False): def __init__(self, pretty=False):
self._filepath = filepath
self.pretty = pretty self.pretty = pretty
self.buffer = [] self.buffer = []
self.buffering = False self.buffering = False
self.conserveBuffer = False self.conserveBuffer = False
self.file = None
def __enter__(self): def __enter__(self):
if self._filepath:
self.file = open(self._filepath, 'wb')
return self return self
def __exit__(self, exc_type, exc_value, traceback): def __exit__(self, exc_type, exc_value, traceback):
if self.file: pass
self.file.close()
def write(self, prefix, event, value, previous): def write(self, prefix, event, value, previous):
res = self._write(prefix, event, value, previous) res = self._write(prefix, event, value, previous)
if self.buffering: if self.buffering:
self.buffer.append(res) self.buffer.append(res)
return "" return ""
elif self.file:
self.file.write(res)
return res return res
def _write(self, prefix, event, value, previous): def _write(self, prefix, event, value, previous):
...@@ -75,8 +68,6 @@ class VidjilWriter(object): ...@@ -75,8 +68,6 @@ class VidjilWriter(object):
def writeBuffer(self): def writeBuffer(self):
try: try:
if self.file:
self.file.write(self.buffer)
return ''.join(self.buffer) return ''.join(self.buffer)
finally: finally:
self.purgeBuffer() self.purgeBuffer()
...@@ -94,6 +85,30 @@ class VidjilWriter(object): ...@@ -94,6 +85,30 @@ class VidjilWriter(object):
self.purgeBuffer() self.purgeBuffer()
return "" return ""
class VidjilFileWriter(VidjilWriter):
def __init__(self, filepath=None, pretty=False):
super(VidjilWriter, self).__init__()
self._filepath = filepath
self.file = None
def __enter__(self):
self.file = open(self._filepath, 'wb')
return self
def __exit__(self, exc_type, exc_value, traceback):
self.file.close()
def write(self, prefix, event, value, previous):
res = super(VidjilWriter, self).write(prefix, event, value, previous)
self.file.write(res)
return res
def writeBuffer(self):
res = super(VidjilWriter, self).writeBuffer()
self.file.write(res)
return res
class Predicate(object): class Predicate(object):
def __init__(self, field, comparator, value): def __init__(self, field, comparator, value):
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment