"""customize events for logo management.we use one event to copy over custom logo images to _staticand another even to link them in the html context"""fromfunctoolsimportpartialfrompathlibimportPathfromdocutils.nodesimportNodefromsphinx.applicationimportSphinxfromsphinx.errorsimportExtensionErrorfromsphinx.utilimportisurlfromsphinx.util.fileutilimportcopy_asset_filefrom.utilsimportget_theme_options_dict,maybe_warn
[文档]defsetup_logo_path(app:Sphinx,pagename:str,templatename:str,context:dict,doctree:Node)->None:"""Set up relative paths to logos in our HTML templates. In Sphinx, the context["logo"] is a path to the `html_logo` image now in the output `_static` folder. If logo["image_light"] and logo["image_dark"] are given, we must modify them to follow the same pattern. They have already been copied to the output folder in the `update_config` event. """# get information from the context "logo_url" for sphinx>=6, "logo" sphinx<6pathto=context.get("pathto")logo=context.get("logo_url")orcontext.get("logo")theme_logo=context.get("theme_logo",{})# Define the final path to logo images in the HTML contexttheme_logo["image_relative"]={}forkindin["light","dark"]:image_kind_logo=theme_logo.get(f"image_{kind}")# If it's a URL the "relative" path is just the URL# else we need to calculate the relative path to a local fileifimage_kind_logo:ifnotisurl(image_kind_logo):image_kind_name=Path(image_kind_logo).nameimage_kind_logo=pathto(f"_static/{image_kind_name}",resource=True)theme_logo["image_relative"][kind]=image_kind_logo# If there's no custom logo for this kind, just use `html_logo`# If `logo` is also None, then do not add this key to context.elifisinstance(logo,str)andlen(logo)>0:theme_logo["image_relative"][kind]=logo# Update our context logo variables with the new image pathscontext["theme_logo"]=theme_logo
[文档]defcopy_logo_images(app:Sphinx,exception=None)->None:""" Copy logo image to the _static directory. If logo image paths are given, copy them to the `_static` folder. Then we can link to them directly in an html_page_context event. """warning=partial(maybe_warn,app)logo=get_theme_options_dict(app).get("logo",{})staticdir=Path(app.builder.outdir)/"_static"assertstaticdir.is_absolute()forkindin["light","dark"]:path_image=logo.get(f"image_{kind}")ifnotpath_imageorisurl(path_image):continueif(staticdir/Path(path_image).name).exists():# file already exists in static dir e.g. because a theme has# bundled the logo and installed it therecontinuefull_logo_path=Path(app.srcdir)/path_imageassertfull_logo_path.is_absolute()ifnotfull_logo_path.exists():warning(f"Path to {kind} image logo does not exist: {path_image}")# Ensure templates cannot be passed for logo path to avoid security# vulnerabilityifpath_image.lower().endswith("_t"):raiseExtensionError(f"The {kind} logo path '{path_image}' looks like a Sphinx template; ""please provide a static logo image.")copy_asset_file(str(full_logo_path),staticdir)