1import sys
2
3import click
4import six
5
6
7class Printer(object):
8    """Wrap click.echo_via_pager() so it accepts binary data."""
9
10    def write(self, data):
11        if isinstance(data, six.binary_type):
12            data = data.decode('utf-8')
13
14        # echo_via_pager() already appends a '\n' at the end of text,
15        # so we use rstrip() to remove extra newlines (#89)
16        click.echo_via_pager(data.rstrip())
17
18    def flush(self):
19        pass
20
21    def close(self):
22        pass
23
24    def isatty(self):
25        return True
26
27    def fileno(self):
28        return sys.stdout.fileno()
29
30    def clear(self):
31        click.clear()
32
33
34class TextWriter(object):
35    """Wrap a file-like object, opened with 'wb' or 'ab', so it accepts text
36    data.
37    """
38    def __init__(self, fp):
39        self.fp = fp
40
41    def write(self, data):
42        if isinstance(data, six.text_type):
43            data = data.encode('utf-8')
44        self.fp.write(data)
45
46    def flush(self):
47        self.fp.flush()
48
49    def close(self):
50        self.fp.close()
51
52    def isatty(self):
53        return self.fp.isatty()
54
55    def fileno(self):
56        return self.fp.fileno()
57