1""" Make links in HTML pages relative to a root """ 2 3import os 4import fileinput 5 6from ext.html5_petsc import PETSC_DOC_OUT_ROOT_PLACEHOLDER 7 8def make_links_relative(root, placeholder=PETSC_DOC_OUT_ROOT_PLACEHOLDER): 9 """ For all generated .html files in directory root and descendants replace placeholder with a relative path back up to root 10 Exclude a specific set of subdirectories. 11 """ 12 excludes = ["_static", "_sources", "_images"] 13 root_level = os.fspath(root).count(os.path.sep) 14 for dirpath, dirnames, filenames in os.walk(root, topdown=True): 15 dirnames[:] = [dirname for dirname in dirnames if dirname not in excludes] 16 level = os.fspath(dirpath).count(os.path.sep) - root_level 17 if level == 0: relpath = "." 18 else: relpath = os.path.sep.join([".."] * level) 19 for filename in filenames: 20 if filename.endswith(".html"): 21 filename_from_root = os.path.join(dirpath, filename) 22 with fileinput.FileInput(filename_from_root, inplace=True) as file: 23 for line in file: 24 print(line.replace(placeholder, relpath), end='') # prints to file 25