import json
import sys
def add_part(current_part, json_structure):
if current_part:
json_structure["sections"].append(current_part)
current_part = None
return current_part
def add_subsection(current_subsection, current_section):
if current_subsection:
current_section["Chapter"]["sub_items"].append(current_subsection)
current_section["Chapter"]["content"] += f"- [{current_subsection['Chapter']['name']}]({current_subsection['Chapter']['path']}.md)\n"
current_subsection = None
return current_subsection
def add_section(current_section, json_structure):
if current_section:
json_structure["sections"].append(current_section)
current_section = None
return current_section
def parse_markdown(content):
lines = content.split("\n")
json_structure = {"sections": [], "__non_exhaustive": None}
current_part = None
current_section = None
current_subsection = None
section_count = 0
subsection_count = 0
for line in lines:
if line.startswith("# "):
# New part
current_part = {
"PartTitle": line[2:],
}
elif line.startswith("## "):
# New section
section_count += 1
subsection_count = 0
current_subsection = add_subsection(current_subsection, current_section)
current_section = add_section(current_section, json_structure)
current_part = add_part(current_part, json_structure)
current_section = {
"Chapter": {
"name": line[3:],
"content": f"# {line[3:]}\n",
"number": [section_count],
"sub_items": [],
"path": str(section_count),
"parent_names": [],
}
}
elif line.startswith("### "):
# New subsection
subsection_count += 1
current_subsection = add_subsection(current_subsection, current_section)
current_subsection = {
"Chapter": {
"name": line[4:],
"content": f"# {line[4:]}\n",
"number": [section_count, subsection_count],
"sub_items": [],
"parent_names": [current_section["Chapter"]["name"]],
"path": f"{section_count}-{subsection_count}",
}
}
else:
# Content line
if line.startswith("#### "):
line = f"## {line[5:]}"
if current_subsection is not None:
current_subsection["Chapter"]["content"] += f"{line}\n"
elif current_section is not None:
current_section["Chapter"]["content"] += f"{line}\n"
add_subsection(current_subsection, current_section)
add_section(current_section, json_structure)
return json_structure
if __name__ == "__main__":
if len(sys.argv) > 1:
if sys.argv[1] == "supports":
sys.exit(0)
context, book = json.load(sys.stdin)
content = book["sections"][0]["Chapter"]["content"]
splited_content = parse_markdown(content)
print(json.dumps(splited_content))