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 = 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 = dirpath.count(os.path.sep) - root_level 17 relpath = os.path.sep.join([".."] * level) 18 for filename in filenames: 19 if filename.endswith(".html"): 20 filename_from_root = os.path.join(dirpath, filename) 21 with fileinput.FileInput(filename_from_root, inplace=True) as file: 22 for line in file: 23 print(line.replace(placeholder, relpath), end='') # prints to file 24