You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

177 lines
5.9 KiB

  1. import json
  2. import os
  3. import re
  4. import requests
  5. import toml
  6. from shutil import copytree, rmtree
  7. def parse_for_toc(content):
  8. # TODO: ADD .TableofContent directly to the page (see hugo theme ?)
  9. content = content.replace("[TOC]", "")
  10. return content
  11. def parse_for_notice(content):
  12. result = re.findall(":::warning.*?:::", content, re.MULTILINE | re.DOTALL)
  13. for notice in result:
  14. old = notice
  15. content = content.replace(
  16. old,
  17. notice.replace(":::warning", '{{% alert context="warning" %}}').replace(
  18. ":::", "{{% /alert %}}"
  19. ),
  20. )
  21. result = re.findall(":::info.*?:::", content, re.MULTILINE | re.DOTALL)
  22. for notice in result:
  23. old = notice
  24. content = content.replace(
  25. old,
  26. notice.replace(":::info", '{{% alert context="info" %}}').replace(
  27. ":::", "{{% /alert %}}"
  28. ),
  29. )
  30. result = re.findall(":::success.*?:::", content, re.MULTILINE | re.DOTALL)
  31. for notice in result:
  32. old = notice
  33. content = content.replace(
  34. old,
  35. notice.replace(":::success", '{{% alert context="success" %}}').replace(
  36. ":::", "{{% /alert %}}"
  37. ),
  38. )
  39. result = re.findall(":::danger.*?:::", content, re.MULTILINE | re.DOTALL)
  40. for notice in result:
  41. old = notice
  42. content = content.replace(
  43. old,
  44. notice.replace(":::danger", '{{% alert context="danger" %}}').replace(
  45. ":::", "{{% /alert %}}"
  46. ),
  47. )
  48. # print(content)
  49. return content
  50. def create_index_file(dir_path, dir_name):
  51. #add _index.md for page organization
  52. with open(dir_path + "/_index.md", "wb") as f:
  53. print("Created", dir_path + "/_index.md")
  54. index = """
  55. +++
  56. title = "{dir_name}"
  57. chapter = true
  58. weight = 5
  59. +++
  60. # {dir_name}
  61. Discover what this Hugo theme is all about and the core-concepts behind it.
  62. """.format(
  63. dir_name=dir_name
  64. )
  65. f.write(b"%s" % index.encode("utf-8"))
  66. def generate_directory_structure_and_files(node, parent_path="./content/"):
  67. if "children" in node:
  68. # If the node has children, it's a directory
  69. dir_path = os.path.join(parent_path, node["technical_name"])
  70. os.makedirs(dir_path, exist_ok=True) # Create directory
  71. create_index_file(dir_path, node["name"])
  72. for child in node["children"]:
  73. generate_directory_structure_and_files(child, parent_path=dir_path)
  74. elif "url" in node:
  75. # If the node has a URL, it's a document
  76. file_path = os.path.join(parent_path, node["technical_name"] + ".md")
  77. link_url = node["url"]
  78. if link_url:
  79. with open(file_path, "wb") as f:
  80. doc_link = link_url + "/download"
  81. response = requests.get(doc_link)
  82. hugo_header = '---\ntitle: "' + node["name"] + '"\n---\n\n'
  83. content = parse_for_notice(
  84. response.content.decode("utf-8")
  85. ).encode("utf-8")
  86. content = parse_for_toc(content.decode("utf-8")).encode("utf-8")
  87. f.write(hugo_header.encode("utf-8"))
  88. f.write(content.replace(b"---", b""))
  89. print("Downloaded", doc_link, "to", file_path)
  90. def generate_book_layout(node):
  91. """Copy the defaults layout repository 'docs' for the new/other books"""
  92. layout_dir = "./themes/lotusdocs/layouts/"
  93. layout_docs_dir = os.path.join(layout_dir, "docs")
  94. layout_book_dir = os.path.join(layout_dir, node["technical_name"])
  95. # copy book layout folder from "layouts/docs" if it doesn't exist
  96. if not os.path.exists(layout_book_dir):
  97. # create the layout for the book
  98. copytree(layout_docs_dir, layout_book_dir)
  99. def generate_book_menu(node, weight):
  100. """Generate the menu displayed in the home page"""
  101. book_config = {
  102. "name": node["name"],
  103. "url": node["technical_name"] + "/",
  104. "identifier": node["technical_name"],
  105. "weight": weight,
  106. }
  107. return book_config
  108. def generate_book_config(node):
  109. """Generate configuration for each book"""
  110. book_config = {
  111. "title": node["name"],
  112. "darkMode": True
  113. }
  114. return book_config
  115. def parse_json_file(json_file_path):
  116. content_dir = "./content/"
  117. config_path ="./hugo.toml"
  118. # new_config_path = "./config_new.toml" # TO DELETE WHEN SCRIPT FINISHED
  119. config_data_dict = toml.load(config_path)
  120. # Retrieve the init json data
  121. with open(json_file_path, 'r') as json_file:
  122. json_data = json.load(json_file)
  123. if not os.path.exists(content_dir):
  124. # Create content directory if it doesn't exist
  125. os.makedirs(content_dir)
  126. else:
  127. # Delete the content directories files and sub-directories
  128. rmtree(content_dir)
  129. nb_books = 0
  130. primary_menu = []
  131. books_config = []
  132. config_data_dict.update({"params": {}})
  133. # Loop on the json structure to build repositories and files
  134. for book_node in json_data["books"]:
  135. nb_books +=1
  136. generate_directory_structure_and_files(book_node)
  137. generate_book_layout(book_node)
  138. primary_menu.append(generate_book_menu(book_node, nb_books))
  139. # books_config.append(generate_book_config(book_node))
  140. config_data_dict["params"]["%s" % book_node["technical_name"]] = generate_book_config(book_node)
  141. # Add the primary menu data to the whole config
  142. config_data_dict.update({"menu": {"primary": primary_menu}})
  143. #config_data_dict.update({"params": {"primary": primary_menu}})
  144. print("WHOLE CONFIG")
  145. print(config_data_dict)
  146. # Replace the config.toml content with the new params
  147. with open(config_path, 'w') as toml_file:
  148. toml.dump(config_data_dict, toml_file)
  149. parse_json_file("structure.json")