|
| 1 | +importhashlib |
1 | 2 | importos
|
| 3 | +fromfunctoolsimportlru_cache |
| 4 | +frompathlibimportPath |
| 5 | +fromtypingimportAny,Dict,List |
| 6 | + |
| 7 | +importsphinx.application |
| 8 | +fromsphinx.builders.htmlimportStandaloneHTMLBuilder |
| 9 | + |
| 10 | +THEME_PATH=Path(__file__).parent.resolve() |
| 11 | + |
| 12 | + |
| 13 | +@lru_cache(maxsize=None) |
| 14 | +def_asset_hash(path:str)->str: |
| 15 | +"""Append a `?digest=` to an url based on the file content.""" |
| 16 | +full_path=THEME_PATH/path.replace("_static/","static/") |
| 17 | +digest=hashlib.sha1(full_path.read_bytes()).hexdigest() |
| 18 | + |
| 19 | +returnf"{path}?digest={digest}" |
| 20 | + |
| 21 | + |
| 22 | +def_add_asset_hashes(static:List[str],add_digest_to:List[str])->None: |
| 23 | +forassetinadd_digest_to: |
| 24 | +index=static.index(asset) |
| 25 | +static[index].filename=_asset_hash(asset)# type: ignore |
| 26 | + |
| 27 | + |
| 28 | +def_html_page_context( |
| 29 | +app:sphinx.application.Sphinx, |
| 30 | +pagename:str, |
| 31 | +templatename:str, |
| 32 | +context:Dict[str,Any], |
| 33 | +doctree:Any, |
| 34 | +)->None: |
| 35 | +ifapp.config.html_theme!="python_docs_theme": |
| 36 | +return |
| 37 | + |
| 38 | +assertisinstance(app.builder,StandaloneHTMLBuilder) |
| 39 | + |
| 40 | +if"css_files"incontext: |
| 41 | +if"_static/pydoctheme.css"notincontext["css_files"]: |
| 42 | +raiseValueError( |
| 43 | +"This documentation is not using `pydoctheme.css` as the stylesheet. " |
| 44 | +"If you have set `html_style` in your conf.py file, remove it." |
| 45 | + ) |
| 46 | + |
| 47 | +_add_asset_hashes( |
| 48 | +context["css_files"], |
| 49 | + ["_static/pydoctheme.css"], |
| 50 | + ) |
2 | 51 |
|
3 | 52 |
|
4 | 53 | defsetup(app):
|
5 | 54 | current_dir=os.path.abspath(os.path.dirname(__file__))
|
6 | 55 | app.add_html_theme(
|
7 | 56 | 'python_docs_theme',current_dir)
|
8 | 57 |
|
| 58 | +app.connect("html-page-context",_html_page_context) |
| 59 | + |
9 | 60 | return {
|
10 | 61 | 'parallel_read_safe':True,
|
11 | 62 | 'parallel_write_safe':True,
|
|