Skip to content

Commit

Permalink
Merge d299060 into a210d03
Browse files Browse the repository at this point in the history
  • Loading branch information
jsiirola committed Jun 13, 2019
2 parents a210d03 + d299060 commit c2ba9d8
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 16 deletions.
32 changes: 22 additions & 10 deletions pyutilib/misc/indent_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,25 +17,37 @@ class StreamIndenter(object):
def __init__(self, ostream, indent=" "):
self.os = ostream
self.indent = indent
self.stripped_indent = indent.rstrip()
self.newline = True

def __getattr__(self, name):
return getattr(self.os, name)

def write(self, str):
if not len(str):
def write(self, data):
if not len(data):
return
lines = data.split('\n')
if self.newline:
self.os.write(self.indent)
if lines[0]:
self.os.write(self.indent+lines[0])
else:
self.os.write(self.stripped_indent)
else:
self.os.write(lines[0])
if len(lines) < 2:
self.newline = False
frag = str.rsplit('\n', 1)
self.os.write(frag[0].replace('\n', '\n' + self.indent))
if len(frag) > 1:
self.os.write('\n')
if len(frag[1]):
self.os.write(self.indent + frag[1])
return
for line in lines[1:-1]:
if line:
self.os.write("\n"+self.indent+line)
else:
self.newline = True
self.os.write("\n"+self.stripped_indent)
if lines[-1]:
self.os.write("\n"+self.indent+lines[-1])
self.newline = False
else:
self.os.write("\n")
self.newline = True

def writelines(self, sequence):
for x in sequence:
Expand Down
17 changes: 11 additions & 6 deletions pyutilib/misc/tests/test_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,17 +145,22 @@ def test_format_float_err1(self):

def test_indenter_write(self):
output = six.StringIO()
indenter = pyutilib.misc.StreamIndenter(output, "X")
indenter = pyutilib.misc.StreamIndenter(output, "X ")
indenter.write("foo")
self.assertEqual(output.getvalue(), "Xfoo")
self.assertEqual(output.getvalue(), "X foo")
indenter.write("\n")
self.assertEqual(output.getvalue(), "Xfoo\n")
self.assertEqual(output.getvalue(), "X foo\n")
indenter.write("foo\n")
self.assertEqual(output.getvalue(), "Xfoo\nXfoo\n")
self.assertEqual(output.getvalue(), "X foo\nX foo\n")
indenter.write("")
self.assertEqual(output.getvalue(), "Xfoo\nXfoo\n")
self.assertEqual(output.getvalue(), "X foo\nX foo\n")
indenter.write("\n")
self.assertEqual(output.getvalue(), "X foo\nX foo\nX\n")
indenter.write("baz\nbin")
self.assertEqual(output.getvalue(), "Xfoo\nXfoo\nXbaz\nXbin")
self.assertEqual(output.getvalue(), "X foo\nX foo\nX\nX baz\nX bin")
indenter.write("a\nb\n\nc\n")
self.assertEqual(output.getvalue(),
"X foo\nX foo\nX\nX baz\nX bina\nX b\nX\nX c\n")

self.assertEqual(indenter.closed, False)
indenter.close()
Expand Down

0 comments on commit c2ba9d8

Please sign in to comment.