parse.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #!/usr/bin/env python3
  2. import os
  3. import mistune
  4. from pygments import highlight
  5. from pygments.lexers import get_lexer_by_name
  6. from pygments.formatters import html
  7. base = """
  8. <html>
  9. <head>
  10. <meta charset="UTF-8">
  11. <title>-{title} | Ryozuki Blog</title>
  12. <meta name="description" content="-{about}">
  13. <meta name="keywords" content="-{tags}">
  14. <meta name="author" content="Ryozuki">
  15. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  16. <link rel="stylesheet" href="/css/code.css">
  17. <link rel="stylesheet" href="/css/style.css">
  18. <meta property="og:title" content="-{title} | Ryozuki Blog" />
  19. <meta property="og:description" content="-{about}" />
  20. <meta name='medium' content='blog'>
  21. </head>
  22. <body>
  23. <div class="container">
  24. <a href="/">cd /</a>
  25. -{body}
  26. </div>
  27. </body>
  28. </html>
  29. """
  30. class HighlightRenderer(mistune.Renderer):
  31. def block_code(self, code, lang):
  32. if not lang:
  33. return '\n<pre><code>%s</code></pre>\n' % \
  34. mistune.escape(code)
  35. lexer = get_lexer_by_name(lang, stripall=True)
  36. formatter = html.HtmlFormatter(linenos='inline')
  37. return highlight(code, lexer, formatter)
  38. if __name__ == "__main__":
  39. renderer = HighlightRenderer()
  40. markdown = mistune.Markdown(renderer=renderer)
  41. for x in os.listdir("blog"):
  42. with open(f"blog/{x}") as f:
  43. parsed = markdown(f.read())
  44. name, ext = os.path.splitext(x)
  45. if ext != ".md":
  46. continue
  47. info = open(f"blog/{name}.info", 'r')
  48. title = info.readline().replace("\n", "").strip()
  49. about = info.readline().replace("\n", "").strip()
  50. date = info.readline().replace("\n", "").strip()
  51. tags = info.readline().replace("\n", "").strip()
  52. info.close()
  53. _base = base.replace("-{title}", title)
  54. _base = _base.replace("-{about}", about)
  55. _base = _base.replace("-{tags}", tags)
  56. parsed = parsed.replace("-{title}", title)
  57. parsed = parsed.replace("-{date}", date)
  58. _base = _base.replace("-{body}", parsed)
  59. with open(f"public/blog/{name}.html", 'w') as out:
  60. out.write(_base)
  61. print(f"\033[94mGenerated file: \033[92m\033[1m{name}.html\033[0m")