from os import PathLike
from pathlib import Path
from typing import Dict, List, Set, Tuple
from dataclasses import dataclass
import re
DOCS_PATH = "../lammps_docs/"
MODIFIED_PATH = Path("../lammps_docs_cleaned/")
INDEX_REGEX = re.compile(r".. index::\s+(.+)")
DOCS_REGEX = re.compile(
r":doc:`(?P<text>.+)\s+<(?P<link_dest>.+)>`"
)
LINK_REGEX_MULTI = re.compile(
r"`(?P<text>[^`]+)\s+<(?P<link_dest>[^`]+)>`"
)
DOCS_SIMPLE_REGEX = re.compile(r":doc:") REF_REGEX = re.compile(r":ref:")
def get_file_indices(file_name: PathLike) -> List[str]:
with open(file_name, "r", encoding="utf-8") as file:
file_text = file.read()
indices = []
for match in re.finditer(INDEX_REGEX, file_text):
indices.append(match.groups()[0])
return indices
type IndexMap = Dict[str, str]
@dataclass
class Styles:
fixes: Set[str]
computes: Set[str]
pair_styles: Set[str]
def create_index_file_map(docs_path: Path) -> Tuple[IndexMap, Styles]:
index_lookup = {}
fixes = set()
computes = set()
pair_styles = set()
for file in docs_path.glob("*.rst"):
for index in get_file_indices(file):
index_lookup[index] = file.name.removesuffix(".rst")
words = index.split()
if len(words) != 2:
continue
style = trim_accelerator(words[1])
match words[0]:
case "fix":
fixes.add(style)
case "compute":
print(style)
computes.add(style)
case "pair_style":
pair_styles.add(style)
return index_lookup, Styles(fixes, computes, pair_styles)
def trim_accelerator(s: str) -> str:
accel_variants = ["/gpu", "/intel", "/kk", "/opt", "/omp"]
n = len(s)
for accel in accel_variants:
s = s.removesuffix(accel)
if len(s) != n:
break
return s
def tidy_file(file_contents: str) -> str:
modified = INDEX_REGEX.sub("", file_contents)
def replace_link(match: re.Match) -> str:
text = match.group("text")
link = match.group("link_dest")
return rf"`{text} <{link}>`__"
modified = DOCS_SIMPLE_REGEX.sub("", modified)
modified = REF_REGEX.sub("", modified)
modified = LINK_REGEX_MULTI.sub(replace_link, modified)
modified = modified.replace(r".. parsed-literal::", r"::")
return modified
def main():
docs_path = Path(DOCS_PATH)
index_map, styles = create_index_file_map(docs_path)
with open("index_map.txt", "w") as stream:
for k, v in index_map.items():
stream.write(f"{k},{v}")
stream.write("\n")
with open("fixes.txt", "w") as stream:
for v in styles.fixes:
stream.write(f"{v}")
stream.write("\n")
with open("computes.txt", "w") as stream:
for v in styles.computes:
stream.write(f"{v}")
stream.write("\n")
with open("pair_styles.txt", "w") as stream:
for v in styles.pair_styles:
stream.write(f"{v}")
stream.write("\n")
for file in Path(DOCS_PATH).glob("*.rst"):
with open(file, "r", encoding="utf-8") as stream:
original_source = stream.read()
modified = tidy_file(original_source)
with open(MODIFIED_PATH.joinpath(file.name), "w") as stream:
stream.write(modified)
if __name__ == "__main__":
main()