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.

81 lines
2.1 KiB

2 years ago
  1. import io
  2. import os
  3. import pypandoc
  4. import panflute
  5. import requests
  6. import ipdb
  7. parent_dir = "./content"
  8. def action(elem, doc):
  9. if isinstance(elem, panflute.Image):
  10. doc.images.append(elem)
  11. elif isinstance(elem, panflute.Link):
  12. doc.links.append(elem)
  13. def find_link(elem, doc):
  14. if type(elem) == panflute.elements.Link:
  15. doc.link.append(elem)
  16. print(panflute.stringify(elem))
  17. def create_folder_h3(elem, doc):
  18. if type(elem) == panflute.elements.Header and elem.level == 3:
  19. directory = panflute.stringify(elem)
  20. path = os.path.join(parent_dir, directory)
  21. print(path)
  22. def download(link):
  23. r = requests.get(link)
  24. return r.text
  25. def create_folder_h2(elem, doc):
  26. if type(elem) == panflute.elements.Header and elem.level == 2:
  27. doc.link = []
  28. directory = panflute.stringify(elem)
  29. path = os.path.join(parent_dir, directory)
  30. os.makedirs(path, exist_ok=True)
  31. elem.next.walk(find_link)
  32. for link in doc.link:
  33. if link.url[-1] == "#":
  34. md_content = download(link.url[:-1] + "/download")
  35. print(
  36. parent_dir
  37. + "/"
  38. + directory
  39. + "/"
  40. + panflute.stringify(link)
  41. + ".md"
  42. )
  43. with open(
  44. parent_dir
  45. + "/"
  46. + directory
  47. + "/"
  48. + panflute.stringify(link)
  49. + ".md",
  50. "w",
  51. ) as f:
  52. hugo_head = """
  53. ---
  54. title: %s
  55. date: 2022-10-29T15:59:37+02:00
  56. draft: false
  57. ---
  58. """ % (
  59. panflute.stringify(link)
  60. )
  61. f.write(hugo_head + md_content)
  62. if __name__ == "__main__":
  63. data = pypandoc.convert_file("content/posts/my-first-post.md", "json")
  64. doc = panflute.load(io.StringIO(data))
  65. doc.images = []
  66. doc.links = []
  67. doc = panflute.run_filter(create_folder_h2, doc=doc)