Debian Codegraph @

docutils/transforms/peps.py

raw symbols SCIP
1 # $Id: peps.py 10136 2025-05-20 15:48:27Z milde $
2 # Author: David Goodger <[email protected]>
3 # Copyright: This module has been placed in the public domain.
4
5 """
6 Transforms for PEP processing.
7
8 - `Headers`: Used to transform a PEP's initial RFC-2822 header. It remains a
9 field list, but some entries get processed.
10 - `Contents`: Auto-inserts a table of contents.
11 - `PEPZero`: Special processing for PEP 0.
12 """
13
14 from __future__ import annotations
15
16 __docformat__ = 'reStructuredText'
17
18 import os
19 import re
20 import time
21 from docutils import nodes, utils, languages
22 from docutils import DataError
23 from docutils.transforms import Transform
24 from docutils.transforms import parts, references, misc
25
26
27 class Headers(Transform):
28
29 """
30 Process fields in a PEP's initial RFC-2822 header.
31 """
32
33 default_priority = 360
34
35 pep_url = 'pep-%04d'
36 pep_cvs_url = ('http://hg.python.org'
37 '/peps/file/default/pep-%04d.txt')
38 rcs_keyword_substitutions = (
39 (re.compile(r'\$' r'RCSfile: (.+),v \$$', # NoQA: ISC001
40 re.IGNORECASE), r'\1'),
41 (re.compile(r'\$[a-zA-Z]+: (.+) \$$'), r'\1'),
42 )
43
44 def apply(self):
45 if not len(self.document):
46 # @@@ replace these DataErrors with proper system messages
47 raise DataError('Document tree is empty.')
48 header = self.document[0]
49 if (not isinstance(header, nodes.field_list)
50 or 'rfc2822' not in header['classes']):
51 raise DataError('Document does not begin with an RFC-2822 '
52 'header; it is not a PEP.')
53 pep = None
54 for field in header:
55 if field[0].astext().lower() == 'pep': # should be the first field
56 value = field[1].astext()
57 try:
58 pep = int(value)
59 cvs_url = self.pep_cvs_url % pep
60 except ValueError:
61 pep = value
62 cvs_url = None
63 msg = self.document.reporter.warning(
64 '"PEP" header must contain an integer; "%s" is an '
65 'invalid value.' % pep, base_node=field)
66 msgid = self.document.set_id(msg)
67 prb = nodes.problematic(value, value or '(none)',
68 refid=msgid)
69 prbid = self.document.set_id(prb)
70 msg.add_backref(prbid)
71 if len(field[1]):
72 field[1][0][:] = [prb]
73 else:
74 field[1] += nodes.paragraph('', '', prb)
75 break
76 if pep is None:
77 raise DataError('Document does not contain an RFC-2822 "PEP" '
78 'header.')
79 if pep == 0:
80 # Special processing for PEP 0.
81 pending = nodes.pending(PEPZero)
82 self.document.insert(1, pending)
83 self.document.note_pending(pending)
84 if len(header) < 2 or header[1][0].astext().lower() != 'title':
85 raise DataError('No title!')
86 for field in header:
87 name = field[0].astext().lower()
88 body = field[1]
89 if len(body) > 1:
90 raise DataError('PEP header field body contains multiple '
91 'elements:\n%s' % field.pformat(level=1))
92 elif len(body) == 1:
93 if not isinstance(body[0], nodes.paragraph):
94 raise DataError('PEP header field body may only contain '
95 'a single paragraph:\n%s'
96 % field.pformat(level=1))
97 elif name == 'last-modified':
98 try:
99 date = time.strftime(
100 '%d-%b-%Y',
101 time.localtime(os.stat(self.document['source'])[8]))
102 except OSError:
103 date = 'unknown'
104 if cvs_url:
105 body += nodes.paragraph(
106 '', '', nodes.reference('', date, refuri=cvs_url))
107 else:
108 # empty
109 continue
110 para = body[0]
111 if name == 'author':
112 for node in para:
113 if isinstance(node, nodes.reference):
114 node.replace_self(mask_email(node))
115 elif name == 'discussions-to':
116 for node in para:
117 if isinstance(node, nodes.reference):
118 node.replace_self(mask_email(node, pep))
119 elif name in ('replaces', 'replaced-by', 'requires'):
120 newbody = []
121 space = nodes.Text(' ')
122 for refpep in re.split(r',?\s+', body.astext()):
123 pepno = int(refpep)
124 newbody.extend((
125 nodes.reference(
126 refpep, refpep,
127 refuri=(self.document.settings.pep_base_url
128 + self.pep_url % pepno)
129 ),
130 space,
131 ))
132 para[:] = newbody[:-1] # drop trailing space
133 elif name == 'last-modified':
134 utils.clean_rcs_keywords(para, self.rcs_keyword_substitutions)
135 if cvs_url:
136 date = para.astext()
137 para[:] = [nodes.reference('', date, refuri=cvs_url)]
138 elif name == 'content-type':
139 pep_type = para.astext()
140 uri = self.document.settings.pep_base_url + self.pep_url % 12
141 para[:] = [nodes.reference('', pep_type, refuri=uri)]
142 elif name == 'version' and len(body):
143 utils.clean_rcs_keywords(para, self.rcs_keyword_substitutions)
144
145
146 class Contents(Transform):
147
148 """
149 Insert an empty table of contents topic and a transform placeholder into
150 the document after the RFC 2822 header.
151 """
152
153 default_priority = 380
154
155 def apply(self) -> None:
156 language = languages.get_language(self.document.settings.language_code,
157 self.document.reporter)
158 name = language.labels['contents']
159 title = nodes.title('', name)
160 topic = nodes.topic('', title, classes=['contents'])
161 name = nodes.fully_normalize_name(name)
162 if not self.document.has_name(name):
163 topic['names'].append(name)
164 self.document.note_implicit_target(topic)
165 pending = nodes.pending(parts.Contents)
166 topic += pending
167 self.document.insert(1, topic)
168 self.document.note_pending(pending)
169
170
171 class TargetNotes(Transform):
172
173 """
174 Locate the "References" section, insert a placeholder for an external
175 target footnote insertion transform at the end, and schedule the
176 transform to run immediately.
177 """
178
179 default_priority = 520
180
181 def apply(self) -> None:
182 doc = self.document
183 i = len(doc) - 1
184 refsect = copyright_ = None
185 while i >= 0 and isinstance(doc[i], nodes.section):
186 title_words = doc[i][0].astext().lower().split()
187 if 'references' in title_words:
188 refsect = doc[i]
189 break
190 elif 'copyright' in title_words:
191 copyright_ = i
192 i -= 1
193 if not refsect:
194 refsect = nodes.section()
195 refsect += nodes.title('', 'References')
196 doc.set_id(refsect)
197 if copyright_:
198 # Put the new "References" section before "Copyright":
199 doc.insert(copyright_, refsect)
200 else:
201 # Put the new "References" section at end of doc:
202 doc.append(refsect)
203 pending = nodes.pending(references.TargetNotes)
204 refsect.append(pending)
205 self.document.note_pending(pending, 0)
206 pending = nodes.pending(misc.CallBack,
207 details={'callback': self.cleanup_callback})
208 refsect.append(pending)
209 self.document.note_pending(pending, 1)
210
211 def cleanup_callback(self, pending) -> None:
212 """
213 Remove an empty "References" section.
214
215 Called after the `references.TargetNotes` transform is complete.
216 """
217 if len(pending.parent) == 2: # <title> and <pending>
218 pending.parent.parent.remove(pending.parent)
219
220
221 class PEPZero(Transform):
222
223 """
224 Special processing for PEP 0.
225 """
226
227 default_priority = 760
228
229 def apply(self) -> None:
230 visitor = PEPZeroSpecial(self.document)
231 self.document.walk(visitor)
232 self.startnode.parent.remove(self.startnode)
233
234
235 class PEPZeroSpecial(nodes.SparseNodeVisitor):
236
237 """
238 Perform the special processing needed by PEP 0:
239
240 - Mask email addresses.
241
242 - Link PEP numbers in the second column of 4-column tables to the PEPs
243 themselves.
244 """
245
246 pep_url = Headers.pep_url
247
248 def unknown_visit(self, node) -> None:
249 pass
250
251 def visit_reference(self, node) -> None:
252 node.replace_self(mask_email(node))
253
254 def visit_field_list(self, node):
255 if 'rfc2822' in node['classes']:
256 raise nodes.SkipNode
257
258 def visit_tgroup(self, node) -> None:
259 self.pep_table = node['cols'] == 4
260 self.entry = 0
261
262 def visit_colspec(self, node) -> None:
263 self.entry += 1
264 if self.pep_table and self.entry == 2:
265 node['classes'].append('num')
266
267 def visit_row(self, node) -> None:
268 self.entry = 0
269
270 def visit_entry(self, node) -> None:
271 self.entry += 1
272 if self.pep_table and self.entry == 2 and len(node) == 1:
273 node['classes'].append('num')
274 p = node[0]
275 if isinstance(p, nodes.paragraph) and len(p) == 1:
276 text = p.astext()
277 try:
278 pep = int(text)
279 ref = (self.document.settings.pep_base_url
280 + self.pep_url % pep)
281 p[0] = nodes.reference(text, text, refuri=ref)
282 except ValueError:
283 pass
284
285
286 non_masked_addresses = ('[email protected]',
287 '[email protected]',
288 '[email protected]')
289
290
291 def mask_email(ref, pepno=None):
292 """
293 Mask the email address in `ref` and return a replacement node.
294
295 `ref` is returned unchanged if it contains no email address.
296
297 For email addresses such as "user@host", mask the address as "user at
298 host" (text) to thwart simple email address harvesters (except for those
299 listed in `non_masked_addresses`). If a PEP number (`pepno`) is given,
300 return a reference including a default email subject.
301 """
302 if ref.hasattr('refuri') and ref['refuri'].startswith('mailto:'):
303 if ref['refuri'][8:] in non_masked_addresses:
304 replacement = ref[0]
305 else:
306 replacement_text = ref.astext().replace('@', '&#32;&#97;t&#32;')
307 replacement = nodes.raw('', replacement_text, format='html')
308 if pepno is None:
309 return replacement
310 else:
311 ref['refuri'] += '?subject=PEP%%20%s' % pepno
312 ref[:] = [replacement]
313 return ref
314 else:
315 return ref