repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

skills/pandoc/scripts/pandoc-batch-convert.lua

Raw
File outline
-- pandoc-batch-convert.lua — Batch convert files between formats
-- Usage: pandoc lua scripts/pandoc-batch-convert.lua <input-ext> <output-ext> [pandoc-args...]
-- Example: pandoc lua scripts/pandoc-batch-convert.lua md html -s --toc
--          pandoc lua scripts/pandoc-batch-convert.lua md pdf --pdf-engine=xelatex
-- Cross-platform: works on Linux, macOS, Windows (requires pandoc 3.x)

local system = require 'pandoc.system'

local args = arg
if #args < 2 then
  io.stderr:write("Usage: pandoc lua " .. args[0]
    .. " <input-ext> <output-ext> [pandoc-args...]\n")
  io.stderr:write("Example: pandoc lua " .. args[0]
    .. " md html -s --toc\n")
  os.exit(1)
end

local in_ext  = args[1]
local out_ext = args[2]

-- Collect extra pandoc args
local extra = {}
for i = 3, #args do
  extra[#extra + 1] = args[i]
end

-- Portable directory listing via pandoc.system
local function list_matching_files(ext)
  local files = {}
  local pattern = "%." .. ext .. "$"
  for _, name in ipairs(system.list_directory(".")) do
    if name:match(pattern) then
      files[#files + 1] = name
    end
  end
  table.sort(files)
  return files
end

local files = list_matching_files(in_ext)

if #files == 0 then
  io.stderr:write("No *." .. in_ext
    .. " files found in current directory\n")
  os.exit(1)
end

local count = 0
local failed = 0

for _, f in ipairs(files) do
  local base = f:gsub("%." .. in_ext .. "$", "")
  local out = base .. "." .. out_ext

  local pandoc_args = {f, "-o", out}
  for _, a in ipairs(extra) do
    pandoc_args[#pandoc_args + 1] = a
  end

  io.stdout:write("Converting: " .. f .. " -> " .. out .. "\n")
  local ok, result = pcall(pandoc.pipe, "pandoc", pandoc_args, "")

  if ok then
    count = count + 1
  else
    io.stderr:write("  FAILED: " .. f .. "\n")
    io.stderr:write("  " .. tostring(result):match("([^\r\n]+)") .. "\n")
    failed = failed + 1
  end
end

io.stdout:write(string.format("Done: %d converted, %d failed.\n",
  count, failed))