2 # Copyright 2012-2015 Bronto Software, Inc. and contributors
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
8 # http://www.apache.org/licenses/LICENSE-2.0
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
17 from __future__ import unicode_literals
18 from builtins import str
24 class StringBuilder(list):
31 class Directive(object):
33 def __init__(self, type, argument=''):
35 self.argument = argument
40 def add_option(self, name, value=''):
41 self.options.append((name, value))
43 def add_content(self, o):
45 self.content.append(o)
49 doc.add_line('.. %s:: %s' % (self.type, self.argument))
51 for name, value in self.options:
52 doc.add_line(' :%s: %s\n' % (name, value))
56 for obj in self.content:
57 content.add_object(obj)
60 for line in content.build().splitlines():
61 doc.add_line(' ' + line)
66 class Document(object):
67 remove_trailing_whitespace_re = re.compile('[ \t]+$', re.MULTILINE)
68 collapse_empty_lines_re = re.compile('\n' + '{3,}', re.DOTALL)
73 def add_object(self, o):
76 self.content.append(o)
81 def add_line(self, s):
85 def add_heading(self, s, t='-'):
87 self.add_line(t * len(s))
93 output = StringBuilder()
95 for obj in self.content:
96 if isinstance(obj, Directive):
98 output.append(obj.build())
100 elif isinstance(obj, Document):
101 output.append(obj.build())
103 output.append(str(obj))
105 output.append('\n\n')
108 output = self.remove_trailing_whitespace_re.sub('', output)
109 output = self.collapse_empty_lines_re.sub('\n\n', output)
113 def error(s, *args, **kwargs):
114 logging.error(s, *args, **kwargs)
117 def unexpected(s, *args, **kwargs):
118 logging.exception(s, *args, **kwargs)