99import os .path as path
1010import json
1111import re
12+ import subprocess
1213import sys
1314import warnings
1415from contextlib import contextmanager
1516from functools import lru_cache
1617from http .server import BaseHTTPRequestHandler , HTTPServer
18+ from pathlib import Path
1719from typing import Dict , List , Sequence
1820from warnings import warn
1921
@@ -397,6 +399,7 @@ def recursive_add_to_index(dobj):
397399 info ['doc' ] = trim_docstring (dobj .docstring )
398400 if isinstance (dobj , pdoc .Function ):
399401 info ['func' ] = 1
402+ nonlocal index
400403 index .append (info )
401404 for member_dobj in getattr (dobj , 'doc' , {}).values ():
402405 recursive_add_to_index (member_dobj )
@@ -414,12 +417,27 @@ def to_url_id(module):
414417 recursive_add_to_index (top_module )
415418 urls = sorted (url_cache .keys (), key = url_cache .__getitem__ )
416419
420+ json_values = [dict (obj , url = urls [obj ['url' ]]) for obj in index ]
421+ cmd = ['node' , str (Path (__file__ ).with_name ('build-index.js' ))]
422+ proc = subprocess .Popen (cmd , text = True , stdin = subprocess .PIPE , stdout = subprocess .PIPE )
417423 main_path = args .output_dir
418- with _open_write_file (path .join (main_path , 'index.js' )) as f :
419- f .write ("URLS=" )
420- json .dump (urls , f , indent = 0 , separators = (',' , ':' ))
421- f .write (";\n INDEX=" )
422- json .dump (index , f , indent = 0 , separators = (',' , ':' ))
424+ if proc .poll () is None :
425+ stdout , stderr = proc .communicate (json .dumps (json_values ))
426+ assert proc .poll () == 0 , proc .poll ()
427+ if proc .returncode == 0 :
428+ stdout = 'INDEX=' + stdout
429+ else :
430+ warn (f'Prebuilding Lunr index with command `{ " " .join (cmd )} ` failed: '
431+ f'{ proc .stderr and proc .stderr .read () or "" !r} . '
432+ f'The search feature will still work, '
433+ f'but may be slower (with the index rebuilt just before use). '
434+ f'To prebuild an index in advance, ensure `node` is executable in the '
435+ f'pdoc environment.' , category = RuntimeWarning )
436+ stdout = ('URLS=' + json .dumps (urls , indent = 0 , separators = (',' , ':' )) +
437+ ';\n INDEX=' + json .dumps (index , indent = 0 , separators = (',' , ':' )))
438+ index_path = Path (main_path ).joinpath ('index.js' )
439+ index_path .write_text (stdout )
440+ print (str (index_path ))
423441
424442 # Generate search.html
425443 with _open_write_file (path .join (main_path , 'doc-search.html' )) as f :
0 commit comments