Martin Frost

Converting Hugo frontmatter to Zola

Published:

I recently converted this page to use Zola, and in doing so I had to migrate the frontmatter for the actual pages.

I did so using this small script I whipped up:

#!/usr/bin/env ruby

require 'yaml'

if ARGV.empty?
  STDERR.puts "Usage: hugo_to_zola.rb <FILE>"
  exit(-1)
end

filename = File.expand_path(ARGV.shift)

if !File.exist?(filename)
  STDERR.puts "No such file or directory: #{filename}"
  exit(-2)
end

STDERR.puts filename

contents = File.read(filename)

_, frontmatter, body = contents.split("---").map(&:strip)

frontmatter = YAML.load(frontmatter, permitted_classes: [Time])

def format_frontmatter(value)
  case value
  when Time
    %("#{value.strftime("%Y-%m-%d %H:%M:%S %Z")}")
  when Array
    value.to_s
  when true, false
    value
  else
    %("#{value}")
  end
end

puts "+++"
frontmatter.each do |key, value|
  puts %(#{key} = #{format_frontmatter(value)})
end
puts "+++"
puts ""
puts body

Yes, it's in Ruby. That's the language I came to think of that I know, have installed, and that has a built-in YAML library.

It's also not very pretty, but that's what a quick hack looks like, I guess.