xref: /petsc/doc/make_links_relative.py (revision fbf9dbe564678ed6eff1806adbc4c4f01b9743f4)
1""" Helper to 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
7from build_classic_docs import classic_docs_subdirs
8
9
10def make_links_relative(root, placeholder=PETSC_DOC_OUT_ROOT_PLACEHOLDER):
11    """ For .html files in directory root and all its descendants replace placeholder with a relative path back up to root
12
13        Exclude a specific set of subdirectories.
14    """
15    excludes = ["_static", "_sources", "_images"]
16    #excludes.extend(classic_docs_subdirs("pre"))
17    #excludes.extend(classic_docs_subdirs("post"))
18    root_level = root.count(os.path.sep)
19    for dirpath, dirnames, filenames in os.walk(root, topdown=True):
20        dirnames[:] = [dirname for dirname in dirnames if dirname not in excludes]
21        level = dirpath.count(os.path.sep) - root_level
22        relpath = os.path.sep.join([".."] * level)
23        for filename in filenames:
24            if filename.endswith(".html"):
25                filename_from_root = os.path.join(dirpath, filename)
26                with fileinput.FileInput(filename_from_root, inplace=True) as file:
27                    for line in file:
28                        print(line.replace(placeholder, relpath), end='')  # prints to file
29