| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import json |
| 4 |
import logging |
| 5 |
import os |
| 6 |
import re |
| 7 |
import subprocess |
| 8 |
from html.parser import HTMLParser |
| 9 |
from typing import TYPE_CHECKING |
| 10 |
|
| 11 |
if TYPE_CHECKING: |
| 12 |
from mkdocs.structure.pages import Page |
| 13 |
from mkdocs.structure.toc import AnchorLink, TableOfContents |
| 14 |
|
| 15 |
try: |
| 16 |
from lunr import lunr # type: ignore |
| 17 |
|
| 18 |
haslunrpy = True |
| 19 |
except ImportError: |
| 20 |
haslunrpy = False |
| 21 |
|
| 22 |
log = logging.getLogger(__name__) |
| 23 |
|
| 24 |
|
| 25 |
class SearchIndex: |
| 26 |
""" |
| 27 |
Search index is a collection of pages and sections (heading |
| 28 |
tags and their following content are sections). |
| 29 |
""" |
| 30 |
|
| 31 |
def __init__(self, **config) -> None: |
| 32 |
self._entries: list[dict] = [] |
| 33 |
self.config = config |
| 34 |
|
| 35 |
def _find_toc_by_id(self, toc, id_: str | None) -> AnchorLink | None: |
| 36 |
""" |
| 37 |
Given a table of contents and HTML ID, iterate through |
| 38 |
and return the matched item in the TOC. |
| 39 |
""" |
| 40 |
for toc_item in toc: |
| 41 |
if toc_item.id == id_: |
| 42 |
return toc_item |
| 43 |
toc_item_r = self._find_toc_by_id(toc_item.children, id_) |
| 44 |
if toc_item_r is not None: |
| 45 |
return toc_item_r |
| 46 |
return None |
| 47 |
|
| 48 |
def _add_entry(self, title: str | None, text: str, loc: str) -> None: |
| 49 |
"""A simple wrapper to add an entry, dropping bad characters.""" |
| 50 |
text = text.replace('\u00a0', ' ') |
| 51 |
text = re.sub(r'[ \t\n\r\f\v]+', ' ', text.strip()) |
| 52 |
|
| 53 |
self._entries.append({'title': title, 'text': text, 'location': loc}) |
| 54 |
|
| 55 |
def add_entry_from_context(self, page: Page) -> None: |
| 56 |
""" |
| 57 |
Create a set of entries in the index for a page. One for |
| 58 |
the page itself and then one for each of its' heading |
| 59 |
tags. |
| 60 |
""" |
| 61 |
# Create the content parser and feed in the HTML for the |
| 62 |
# full page. This handles all the parsing and prepares |
| 63 |
# us to iterate through it. |
| 64 |
parser = ContentParser() |
| 65 |
assert page.content is not None |
| 66 |
parser.feed(page.content) |
| 67 |
parser.close() |
| 68 |
|
| 69 |
# Get the absolute URL for the page, this is then |
| 70 |
# prepended to the urls of the sections |
| 71 |
url = page.url |
| 72 |
|
| 73 |
# Create an entry for the full page. |
| 74 |
text = parser.stripped_html.rstrip('\n') if self.config['indexing'] == 'full' else '' |
| 75 |
self._add_entry(title=page.title, text=text, loc=url) |
| 76 |
|
| 77 |
if self.config['indexing'] in ['full', 'sections']: |
| 78 |
for section in parser.data: |
| 79 |
self.create_entry_for_section(section, page.toc, url) |
| 80 |
|
| 81 |
def create_entry_for_section( |
| 82 |
self, section: ContentSection, toc: TableOfContents, abs_url: str |
| 83 |
) -> None: |
| 84 |
""" |
| 85 |
Given a section on the page, the table of contents and |
| 86 |
the absolute url for the page create an entry in the |
| 87 |
index. |
| 88 |
""" |
| 89 |
toc_item = self._find_toc_by_id(toc, section.id) |
| 90 |
|
| 91 |
text = ' '.join(section.text) if self.config['indexing'] == 'full' else '' |
| 92 |
if toc_item is not None: |
| 93 |
self._add_entry(title=toc_item.title, text=text, loc=abs_url + toc_item.url) |
| 94 |
|
| 95 |
def generate_search_index(self) -> str: |
| 96 |
"""Python to json conversion.""" |
| 97 |
page_dicts = {'docs': self._entries, 'config': self.config} |
| 98 |
data = json.dumps(page_dicts, sort_keys=True, separators=(',', ':'), default=str) |
| 99 |
|
| 100 |
if self.config['prebuild_index'] in (True, 'node'): |
| 101 |
try: |
| 102 |
script_path = os.path.join( |
| 103 |
os.path.dirname(os.path.abspath(__file__)), 'prebuild-index.js' |
| 104 |
) |
| 105 |
p = subprocess.Popen( |
| 106 |
['node', script_path], |
| 107 |
stdin=subprocess.PIPE, |
| 108 |
stdout=subprocess.PIPE, |
| 109 |
stderr=subprocess.PIPE, |
| 110 |
encoding='utf-8', |
| 111 |
) |
| 112 |
idx, err = p.communicate(data) |
| 113 |
if not err: |
| 114 |
page_dicts['index'] = json.loads(idx) |
| 115 |
data = json.dumps(page_dicts, sort_keys=True, separators=(',', ':')) |
| 116 |
log.debug('Pre-built search index created successfully.') |
| 117 |
else: |
| 118 |
log.warning(f'Failed to pre-build search index. Error: {err}') |
| 119 |
except (OSError, ValueError) as e: |
| 120 |
log.warning(f'Failed to pre-build search index. Error: {e}') |
| 121 |
elif self.config['prebuild_index'] == 'python': |
| 122 |
if haslunrpy: |
| 123 |
lunr_idx = lunr( |
| 124 |
ref='location', |
| 125 |
fields=('title', 'text'), |
| 126 |
documents=self._entries, |
| 127 |
languages=self.config['lang'], |
| 128 |
) |
| 129 |
page_dicts['index'] = lunr_idx.serialize() |
| 130 |
data = json.dumps(page_dicts, sort_keys=True, separators=(',', ':')) |
| 131 |
else: |
| 132 |
log.warning( |
| 133 |
"Failed to pre-build search index. The 'python' method was specified; " |
| 134 |
"however, the 'lunr.py' library does not appear to be installed. Try " |
| 135 |
"installing it with 'pip install lunr'. If you are using any language " |
| 136 |
"other than English you will also need to install 'lunr[languages]'." |
| 137 |
) |
| 138 |
|
| 139 |
return data |
| 140 |
|
| 141 |
|
| 142 |
class ContentSection: |
| 143 |
""" |
| 144 |
Used by the ContentParser class to capture the information we |
| 145 |
need when it is parsing the HTML. |
| 146 |
""" |
| 147 |
|
| 148 |
def __init__( |
| 149 |
self, |
| 150 |
text: list[str] | None = None, |
| 151 |
id_: str | None = None, |
| 152 |
title: str | None = None, |
| 153 |
) -> None: |
| 154 |
self.text = text or [] |
| 155 |
self.id = id_ |
| 156 |
self.title = title |
| 157 |
|
| 158 |
def __eq__(self, other): |
| 159 |
return self.text == other.text and self.id == other.id and self.title == other.title |
| 160 |
|
| 161 |
|
| 162 |
_HEADER_TAGS = tuple(f"h{x}" for x in range(1, 7)) |
| 163 |
|
| 164 |
|
| 165 |
class ContentParser(HTMLParser): |
| 166 |
""" |
| 167 |
Given a block of HTML, group the content under the preceding |
| 168 |
heading tags which can then be used for creating an index |
| 169 |
for that section. |
| 170 |
""" |
| 171 |
|
| 172 |
def __init__(self, *args, **kwargs) -> None: |
| 173 |
super().__init__(*args, **kwargs) |
| 174 |
|
| 175 |
self.data: list[ContentSection] = [] |
| 176 |
self.section: ContentSection | None = None |
| 177 |
self.is_header_tag = False |
| 178 |
self._stripped_html: list[str] = [] |
| 179 |
|
| 180 |
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: |
| 181 |
"""Called at the start of every HTML tag.""" |
| 182 |
# We only care about the opening tag for headings. |
| 183 |
if tag not in _HEADER_TAGS: |
| 184 |
return |
| 185 |
|
| 186 |
# We are dealing with a new header, create a new section |
| 187 |
# for it and assign the ID if it has one. |
| 188 |
self.is_header_tag = True |
| 189 |
self.section = ContentSection() |
| 190 |
self.data.append(self.section) |
| 191 |
|
| 192 |
for attr in attrs: |
| 193 |
if attr[0] == "id": |
| 194 |
self.section.id = attr[1] |
| 195 |
|
| 196 |
def handle_endtag(self, tag: str) -> None: |
| 197 |
"""Called at the end of every HTML tag.""" |
| 198 |
# We only care about the opening tag for headings. |
| 199 |
if tag not in _HEADER_TAGS: |
| 200 |
return |
| 201 |
|
| 202 |
self.is_header_tag = False |
| 203 |
|
| 204 |
def handle_data(self, data: str) -> None: |
| 205 |
"""Called for the text contents of each tag.""" |
| 206 |
self._stripped_html.append(data) |
| 207 |
|
| 208 |
if self.section is None: |
| 209 |
# This means we have some content at the start of the |
| 210 |
# HTML before we reach a heading tag. We don't actually |
| 211 |
# care about that content as it will be added to the |
| 212 |
# overall page entry in the search. So just skip it. |
| 213 |
return |
| 214 |
|
| 215 |
# If this is a header, then the data is the title. |
| 216 |
# Otherwise it is content of something under that header |
| 217 |
# section. |
| 218 |
if self.is_header_tag: |
| 219 |
self.section.title = data |
| 220 |
else: |
| 221 |
self.section.text.append(data.rstrip('\n')) |
| 222 |
|
| 223 |
@property |
| 224 |
def stripped_html(self) -> str: |
| 225 |
return '\n'.join(self._stripped_html) |