~ryanford/git-blog-tup

91df9295c272315c5fc949d5c7d9864fa1c03745 — Ryan Ford 3 years ago dada3bc
add posts json plugin
1 files changed, 78 insertions(+), 0 deletions(-)

A plugins/create_json
A plugins/create_json => plugins/create_json +78 -0
@@ 0,0 1,78 @@
#!/usr/bin/env lua

local json = require("dkjson")
local date = require("date")

local output = io.output()

local posts = {}

local function unslug(w)
   return w:sub(1, 1):upper() .. w:sub(2)
end

local function sort_by_published(a, b)
   return (a.published or math.huge) < (b.published or math.huge)
end

for fname in (arg[1]):gmatch("%S+") do
   local title do
      local f = fname:match("([%w-_%%]+).md")
      title = f:gsub("-", " "):gsub("%w+%s?", unslug)
   end

   local commits = {}
   do
      local git_log = assert( io.popen('git log --no-merges --date="iso-local" --format="%an%n%H%n%ad%n%s" ' .. fname), "failed to open file: " .. fname)
      local fields = { [0] = "author", "hash", "date", "message" }
      local i, field = 0
      local commit
      for line in git_log:lines() do
         field = fields[i % 4]
         i = i + 1
         commit = math.ceil(i/4)
         commits[commit] = commits[commit] or {}
         if field == "date" and commit > 0 then
            commits[commit].date = #line > 0 and date(line):fmt("%b %d, %Y - %H:%M %p") or false
         else
            commits[commit][field] = line
         end
      end
      git_log:close()
   end

   local body do
      local fd = io.open(fname)
      body = fd:read("*a")
      fd:close()
   end

   table.insert(posts, {
      path = fname,
      title = title,
      author = commits[1] and commits[1].author or false,
      published = #commits > 0  and commits[#commits].date or false,
      body = body,
      commits = commits,
    })
end

table.sort(posts, sort_by_published)

for i, post in ipairs(posts) do
   if post.published then
      if i > 1 then
         post.prev_post = i - 1
      end
      if i < #posts then
         post.next_post = i + 1
      end
   end
end

local post_json = assert(json.encode(posts))

output:write(post_json)
if arg[2] then output:close() end

os.exit(0)