aboutsummaryrefslogtreecommitdiff
blob: ce6799e3feb258b5560cb3f204f15651522578ed (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# Copyright 2015 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
#
# This is a minimalistic derivation of Python's deprecated formatter module,
# supporting only the methods related to style, literal data, and line breaks.

import sys


class AbstractFormatter(object):
	"""The standard formatter."""

	def __init__(self, writer):
		self.writer = writer            # Output device
		self.style_stack = []           # Other state, e.g. color
		self.hard_break = True          # Have a hard break

	def add_line_break(self):
		if not self.hard_break:
			self.writer.send_line_break()
		self.hard_break = True

	def add_literal_data(self, data):
		if not data: return
		self.hard_break = data[-1:] == '\n'
		self.writer.send_literal_data(data)

	def push_style(self, *styles):
		for style in styles:
			self.style_stack.append(style)
		self.writer.new_styles(tuple(self.style_stack))

	def pop_style(self, n=1):
		del self.style_stack[-n:]
		self.writer.new_styles(tuple(self.style_stack))


class NullWriter(object):
	"""Minimal writer interface to use in testing & inheritance.

	A writer which only provides the interface definition; no actions are
	taken on any methods.  This should be the base class for all writers
	which do not need to inherit any implementation methods.
	"""
	def __init__(self): pass
	def flush(self): pass
	def new_styles(self, styles): pass
	def send_line_break(self): pass
	def send_literal_data(self, data): pass


class DumbWriter(NullWriter):
	"""Simple writer class which writes output on the file object passed in
	as the file parameter or, if file is omitted, on standard output.
	"""

	def __init__(self, file=None, maxcol=None):
		NullWriter.__init__(self)
		self.file = file or sys.stdout

	def flush(self):
		self.file.flush()

	def send_line_break(self):
		self.file.write('\n')

	def send_literal_data(self, data):
		self.file.write(data)