Debian Codegraph @

sphinxext/opengraph/_description_parser.py

raw
1 from __future__ import annotations
2
3 import html
4 import string
5 from typing import TYPE_CHECKING
6
7 from docutils import nodes
8
9 if TYPE_CHECKING:
10 from collections.abc import Set
11
12
13 def get_description(
14 doctree: nodes.document,
15 description_length: int,
16 known_titles: Set[str] = frozenset(),
17 ) -> str:
18 mcv = DescriptionParser(
19 doctree, desc_len=description_length, known_titles=known_titles
20 )
21 doctree.walkabout(mcv)
22 return mcv.description
23
24
25 class DescriptionParser(nodes.NodeVisitor):
26 """Finds the title and creates a description from a doctree."""
27
28 def __init__(
29 self,
30 document: nodes.document,
31 *,
32 desc_len: int,
33 known_titles: Set[str] = frozenset(),
34 ) -> None:
35 super().__init__(document)
36 self.description = ''
37 self.desc_len = desc_len
38 self.list_level = 0
39 self.known_titles = known_titles
40 self.first_title_found = False
41
42 # Exceptions can't be raised from dispatch_departure()
43 # This is used to loop the stop call back to the next dispatch_visit()
44 self.stop = False
45
46 def dispatch_visit(self, node: nodes.Element) -> None:
47 if self.stop:
48 raise nodes.StopTraversal
49
50 # Skip comments & all admonitions
51 if isinstance(node, (nodes.Admonition, nodes.Invisible)):
52 raise nodes.SkipNode
53
54 # Mark start of nested lists
55 if isinstance(node, nodes.Sequential):
56 self.list_level += 1
57 if self.list_level > 1:
58 self.description += '-'
59
60 # Skip the first title if it's the title of the page
61 if not self.first_title_found and isinstance(node, nodes.title):
62 self.first_title_found = True
63 if node.astext() in self.known_titles:
64 raise nodes.SkipNode
65
66 if isinstance(node, nodes.raw) or isinstance(node.parent, nodes.literal_block):
67 raise nodes.SkipNode
68
69 # Only include leaf nodes in the description
70 if len(node.children) == 0:
71 text = node.astext().replace('\r', '').replace('\n', ' ').strip()
72
73 # Ensure string contains HTML-safe characters
74 text = html.escape(text, quote=True)
75
76 # Remove double spaces
77 while text.find(' ') != -1:
78 text = text.replace(' ', ' ')
79
80 # Put a space between elements if one does not already exist.
81 if (
82 len(self.description) > 0
83 and len(text) > 0
84 and self.description[-1] not in string.whitespace
85 and text[0] not in string.whitespace + string.punctuation
86 ):
87 self.description += ' '
88
89 self.description += text
90
91 def dispatch_departure(self, node: nodes.Element) -> None:
92 # Separate title from text
93 if isinstance(node, nodes.title):
94 self.description += ':'
95
96 # Separate list elements
97 if isinstance(node, nodes.Part):
98 self.description += ','
99
100 # Separate end of list from text
101 if isinstance(node, nodes.Sequential):
102 if self.description and self.description[-1] == ',':
103 self.description = self.description[:-1]
104 self.description += '.'
105 self.list_level -= 1
106
107 # Check for length
108 if len(self.description) > self.desc_len:
109 self.description = self.description[: self.desc_len]
110 if self.desc_len >= 3:
111 self.description = self.description[:-3] + '...'
112
113 self.stop = True