Skip to content
Snippets Groups Projects
Commit e05463a9 authored by Martin Schroschk's avatar Martin Schroschk
Browse files

Merge branch 'mibo604c--tu-dresden.de-preview-patch-96732' into 'preview'

Created a new check-TOC.py without importing pd, and yaml

See merge request !799
parents d60d006d cd5f7037
No related branches found
No related tags found
2 merge requests!811Automated merge from preview to main,!799Created a new check-TOC.py without importing pd, and yaml
""" #!/usr/bin/env python
Check for consistency between TOC and page headings.
Provide as an command line argument the path to the mkdocs.yml file.
Author: Taras Lazariv
"""
import os
import sys
import yaml
import pandas as pd
def list_and_read_files(path):
"List files in a directory recursively and read the first line of each file"
files = []
firstline = []
for root, _, filenames in os.walk(path):
for filename in filenames:
if filename.endswith('.md'):
files.append(os.path.join(root.split('/')[-1], filename))
firstline.append(open(os.path.join(root, filename)).readline().strip().replace('# ',''))
df = pd.DataFrame({'file': files, 'firstline': firstline})
return df
def main():
"Main function"
path = os.getcwd()
df = list_and_read_files(path)
nav_section = dict()
with open(sys.argv[1], 'r') as file:
for line in file:
line = line.rstrip()
if line.endswith('.md'):
nav_section.update(yaml.safe_load(line)[0])
nav_df = pd.DataFrame(nav_section.items(), columns=['title', 'file'])
with pd.option_context('display.max_rows', None): # more options can be specified also
complete_nav_df = pd.merge(df, nav_df, on='file', how='outer')
print(complete_nav_df.loc[~(complete_nav_df['firstline'] == complete_nav_df['title'])])
if __name__ == '__main__':
main()
\ No newline at end of file
""" #!/usr/bin/env python
Check for consistency between TOC and page headings.
Provide as an command line argument the path to the mkdocs.yml file.
Author: Michael Bommhardt-Richter
"""
import argparse
import sys
from pathlib import Path
# {path/filename.md: [toc_heading, file_heading], ... }
TOCData = dict()
whitelist = ["index.md"] # ["archive"]
def get_heading_in_file(filename, docs_path):
# Read until first level one heading is found
f = Path.joinpath(docs_path, filename)
with open(f, "r") as file:
for line in file:
if line.startswith("#"):
# TODO Make sure it is really a level one heading!
# Will be empty if there is more than one "#".
return line.split("#")[1].strip()
def main():
scriptpath = Path(__file__).resolve().parent
mkdocsyaml = Path.joinpath(scriptpath, "../", "mkdocs.yml")
if Path.exists(mkdocsyaml):
docs_path = Path.joinpath(scriptpath, "../", "docs")
with open(mkdocsyaml, "r") as file:
c = file.readlines()
for line in c:
line = line.rstrip()
# "headline: path/file.md" -> "Headline" = "path/file.md"
if line.endswith(".md"):
line = line.split(" - ")[1]
line = line.split(": ")
key = line[1]
file_heading = get_heading_in_file(line[1], docs_path)
TOCData[line[1]] = [line[0], file_heading]
# Check TOC vs heading in corresponding md-file
cnt = 0
for key, value in TOCData.items():
if key in whitelist:
continue
if value[0] == "Overview":
continue
if value[0] != value[1]:
cnt += 1
print(f"{key:<40}{value[0]:<30} != {value[1]}")
sys.exit(cnt)
else:
print("Error: Could not find mkdocs.yml file.")
sys.exit(-1)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Find differences in TOC and top level headings of md-files."
)
args = parser.parse_args()
main()
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment