File: mdwriter.py

package info (click to toggle)
python-changelog 0.6.1-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 216 kB
  • sloc: python: 994; makefile: 2
file content (289 lines) | stat: -rw-r--r-- 9,238 bytes parent folder | download | duplicates (3)
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
import io

from docutils import nodes
from docutils import writers
from docutils.core import publish_file
from docutils.core import publish_string

from .docutils import setup_docutils
from .environment import DefaultEnvironment
from .environment import Environment


class Writer(writers.Writer):

    supported = ("markdown",)

    def __init__(self, limit_version=None, receive_sections=None):
        super(Writer, self).__init__()
        self.limit_version = limit_version
        self.receive_sections = receive_sections

    def translate(self):
        translator = MarkdownTranslator(
            self.document, self.limit_version, self.receive_sections
        )
        self.document.walkabout(translator)
        self.output = translator.output_buf.getvalue()


class MarkdownTranslator(nodes.NodeVisitor):
    def __init__(self, document, limit_version, receive_sections):
        super(MarkdownTranslator, self).__init__(document)
        self.buf = self.output_buf = io.StringIO()
        self.limit_version = limit_version
        self.receive_sections = receive_sections
        self.section_level = 1
        self.stack = []

        self._standalone_section_display = (
            self.limit_version or self.receive_sections
        )
        if self._standalone_section_display:
            self.disable_writing()

    def enable_writing(self):
        self.buf = self.output_buf

    def disable_writing(self):
        self.buf = io.StringIO()

    def _detect_section_was_squashed_into_subtitle(self, document_node):
        # docutils converts a single section we generated into a "subtitle"
        # and squashes the section object
        # http://docutils.sourceforge.net/FAQ.html\
        # #how-can-i-indicate-the-document-title-subtitle
        for subnode in document_node:
            if "version_string" in subnode.attributes:
                if isinstance(subnode, nodes.subtitle):
                    return subnode
                elif isinstance(subnode, nodes.section):
                    return False
                else:
                    raise NotImplementedError(
                        "detected version_string in unexpected node type: %s"
                        % subnode
                    )

    def visit_document(self, node):
        self.document = node
        self.env = Environment.from_document_settings(self.document.settings)

        subtitle_node = self._detect_section_was_squashed_into_subtitle(node)
        if subtitle_node:
            version = subtitle_node.attributes["version_string"]
            rebuild_our_lost_section = nodes.section(
                "",
                nodes.title(version, version, classes=["release-version"]),
                **subtitle_node.attributes
            )

            # note we are taking the nodes from the document and moving them
            # into the new section.   nodes have a "parent" which means that
            # parent changes, which means we are mutating the internal
            # state of the document node.  so use deepcopy() to avoid this
            # side effect; deepcopy() for these nodes seems to not be a
            # performance problem.
            rebuild_our_lost_section.extend([n.deepcopy() for n in node[2:]])
            rebuild_our_lost_section.walkabout(self)
            raise nodes.SkipNode()

    def visit_standalone_version_node(self, node, version_string):
        """visit a section or document that has a changelog version string
        at the top"""

        if self.limit_version and self.limit_version != version_string:
            return

        self.section_level = 1
        self.enable_writing()
        if self.receive_sections:
            self.buf = io.StringIO()

    def depart_standalone_version_node(self, node, version_string):
        """depart a section or document that has a changelog version string
        at the top"""

        if self.limit_version and self.limit_version != version_string:
            return

        if self.receive_sections:
            self.receive_sections(version_string, self.buf.getvalue())
        self.disable_writing()

    def visit_section(self, node):
        if (
            "version_string" in node.attributes
            and self._standalone_section_display
        ):
            self.visit_standalone_version_node(
                node, node.attributes["version_string"]
            )
        else:
            self.section_level += 1

    def depart_section(self, node):
        if (
            "version_string" in node.attributes
            and self._standalone_section_display
        ):
            self.depart_standalone_version_node(
                node, node.attributes["version_string"]
            )
        else:
            self.section_level -= 1

    def visit_strong(self, node):
        self.buf.write("**")

    def depart_strong(self, node):
        self.buf.write("**")

    def visit_emphasis(self, node):
        self.buf.write("*")

    def depart_emphasis(self, node):
        self.buf.write("*")

    def visit_literal(self, node):
        self.buf.write("`")

    def visit_Text(self, node):
        self.buf.write(node.astext())

    def depart_Text(self, node):
        pass

    def depart_paragraph(self, node):
        self.buf.write("\n\n")

    def depart_literal(self, node):
        self.buf.write("`")

    def visit_title(self, node):
        self.buf.write(
            "\n%s %s\n\n" % ("#" * self.section_level, node.astext())
        )
        raise nodes.SkipNode()

    def visit_changeset_link(self, node):
        # it would be nice to have an absolutely link to the HTML
        # hosted changelog but this requires being able to generate
        # the absolute link from the document filename and all that.
        # it can perhaps be sent on the commandline
        raise nodes.SkipNode()

    def depart_changeset_link(self, node):
        pass

    def visit_reference(self, node):
        if "changelog-reference" in node.attributes["classes"]:
            self.visit_changeset_link(node)
        else:
            self.buf.write("[")

    def depart_reference(self, node):
        if "changelog-reference" in node.attributes["classes"]:
            self.depart_changeset_link(node)
        else:
            self.buf.write("](%s)" % node.attributes["refuri"])

    def visit_admonition(self, node):
        # "seealsos" typically have internal sphinx references so at the
        # moment we're not prepared to look those up, future version can
        # perhaps use sphinx object lookup
        raise nodes.SkipNode()

    def visit_list_item(self, node):
        self.stack.append(self.buf)
        self.buf = io.StringIO()

    def depart_list_item(self, node):
        popped = self.buf
        self.buf = self.stack.pop(-1)

        indent_level = len(self.stack)
        indent_string = " " * 4 * indent_level

        value = popped.getvalue().strip()

        lines = value.split("\n")
        self.buf.write("\n" + indent_string + "-   ")
        line = lines.pop(0)
        self.buf.write(line + "\n")
        for line in lines:
            self.buf.write(indent_string + "    " + line + "\n")

    def _visit_generic_node(self, node):
        pass

    def __getattr__(self, name):
        if not name.startswith("_"):
            return self._visit_generic_node
        else:
            raise AttributeError(name)


def stream_changelog_sections(
    target_filename, config_filename, receive_sections, version=None
):
    """Send individual changelog sections to a callable, one per version.

    The callable accepts two arguments, the string version number of the
    changelog section, and the markdown-formatted content of the changelog
    section.

    Used for APIs that receive changelog sections per version.

    """
    Environment.register(DefaultEnvironment)

    setup_docutils()
    with open(target_filename, encoding="utf-8") as handle:
        publish_string(
            handle.read(),
            source_path=target_filename,
            writer=Writer(
                limit_version=version, receive_sections=receive_sections
            ),
            settings_overrides={
                "changelog_env": DefaultEnvironment(config_filename),
                "report_level": 3,
            },
        )


def render_changelog_as_md(
    target_filename, config_filename, version, sections_only
):

    Environment.register(DefaultEnvironment)

    setup_docutils()

    if sections_only:

        def receive_sections(version_string, text):
            print(text)

    else:
        receive_sections = None

    writer = Writer(limit_version=version, receive_sections=receive_sections)
    settings_overrides = {
        "changelog_env": DefaultEnvironment(config_filename),
        "report_level": 3,
    }

    with open(target_filename, encoding="utf-8") as handle:
        if receive_sections:
            publish_string(
                handle.read(),
                source_path=target_filename,
                writer=writer,
                settings_overrides=settings_overrides,
            )
        else:
            publish_file(
                handle, writer=writer, settings_overrides=settings_overrides
            )