xref: /petsc/doc/make_links_relative.py (revision 2fa40bb9206b96114faa7cb222621ec184d31cd2)
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 root, 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())
17    root_level = root.count(os.path.sep)
18    for dirpath, dirnames, filenames in os.walk(root, topdown=True):
19        dirnames[:] = [dirname for dirname in dirnames if dirname not in excludes]
20        level = dirpath.count(os.path.sep) - root_level
21        relpath = os.path.sep.join([".."] * level)
22        for filename in filenames:
23            if filename.endswith(".html"):
24                filename_from_root = os.path.join(dirpath, filename)
25                with fileinput.FileInput(filename_from_root, inplace=True) as file:
26                    for line in file:
27                        print(line.replace(placeholder, relpath), end='')  # prints to file
28