generate_rss.lua 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. local markdown = require "markdown"
  2. local lfs = require "lfs"
  3. local AMOUNT = 10
  4. local date = require "date"
  5. local function read_md(path)
  6. local f = io.open (path..".md", "rb")
  7. if f then
  8. local src = f:read("*all")
  9. f:close()
  10. return markdown(src)
  11. end
  12. return false
  13. end
  14. local function get_posts()
  15. local posts = require "posts.posts_meta"
  16. if #posts < AMOUNT then AMOUNT = #posts end
  17. local rss_posts = {}
  18. for i=1,AMOUNT do
  19. posts[i].date = date(posts[i].date):fmt("%a, %d %b %Y %T GMT")
  20. local category = posts[i].category or 'general'
  21. posts[i].body = read_md('posts/'..category..'/'..posts[i].short_url)
  22. posts[i].url = "http://lua.space/"..category..'/'..posts[i].short_url
  23. rss_posts[#rss_posts+1] = posts[i]
  24. end
  25. return rss_posts
  26. end
  27. local function build_rss()
  28. local rss = {
  29. [[<?xml version="1.0" encoding="utf-8"?>
  30. <rss version="2.0">
  31. <channel>
  32. <title>Lua.Space</title>
  33. <link>http://http://lua.space/</link>
  34. <description>The unofficial Lua blog</description>]]
  35. }
  36. local item_template = {
  37. [[
  38. <item>
  39. <title>]],
  40. "title",
  41. [[</title>
  42. <link>]],
  43. "url",
  44. [[</link>
  45. <guid>]],
  46. "url again",
  47. [[</guid>
  48. <pubDate>]],
  49. "date",
  50. [[</pubDate>
  51. <description><![CDATA[]],
  52. "content",
  53. [=[
  54. ]]></description>
  55. </item>]=]
  56. }
  57. for _,p in ipairs(get_posts()) do
  58. item_template[2] = p.page_title
  59. item_template[4] = p.url
  60. item_template[6] = p.url
  61. item_template[8] = p.date
  62. item_template[10] = p.body
  63. rss[#rss+1] = table.concat(item_template)
  64. end
  65. rss[#rss+1] = [[
  66. </channel>
  67. </rss>]]
  68. -- print(table.concat(rss))
  69. local file = io.output ("rss.xml")
  70. file:write(table.concat(rss))
  71. file:close()
  72. end
  73. build_rss()