tDiaryの過去ログをJekyllに移行したい
プラグインまわりが微妙すぎるけど、とりあえず……。
require 'fileutils'
require 'hiki2md'
require 'yaml'
INPUT_DIR = 'diary_log'
OUTPUT_DIR = '_posts'
def parse_td2_file(path)
entries = []
current = nil
skip_keys = ['Title:', 'Last-Modified:', 'Visible:', 'Format:']
File.read(path).split("\n").each do |line|
if line.strip == '.'
entries << current if current
current = nil
elsif line.start_with?('Date:')
current = { date: line.sub('Date: ', '').strip, lines: [] }
elsif current
unless skip_keys.any? { |k| line.start_with?(k) }
current[:lines] << line
end
end
end
entries << current if current
entries
end
def split_by_heading(lines)
sections = []
current = nil
lines.each do |line|
if line.strip.start_with?('!')
# ! で始まる見出しを新規セクションとする
if line.strip =~ /^![^!]/
sections << current if current
current = [line]
else
current << line if current
end
else
current << line if current
end
end
sections << current if current
sections
end
def write_markdown_sections(entry)
date_str = entry[:date]
y = date_str[0..3]
m = date_str[4..5]
d = date_str[6..7]
ymd = "#{y}-#{m}-#{d}"
sections = split_by_heading(entry[:lines])
sections.each_with_index do |section_lines, idx|
next if section_lines.nil? || section_lines.empty?
heading_line = section_lines.first
title_text = heading_line.sub(/^!+/, '').strip
content = section_lines.join("\n")
content = Hiki2md.new.convert(content)
markdown = convert_liquid_tags(content)
front_matter_hash = {
'title' => title_text
}
front_matter = YAML.dump(front_matter_hash) + "---\n"
output_dir = File.join(OUTPUT_DIR, y, m)
FileUtils.mkdir_p(output_dir)
filename = File.join(output_dir, "#{ymd}-#{idx + 1}.md")
File.write(filename, front_matter + "\n" + markdown)
puts "Wrote #{filename}"
end
end
def convert_liquid_tags(text)
# Jekyllでエラーが出ちゃったから、%は小文字に置き換えて
text.gsub(/\{\{\s*(\w+.*?)\s*\}\}/, "{% \1 %}")
end
Dir.glob("#{INPUT_DIR}/**/*.td2") do |file|
entries = parse_td2_file(file)
entries.each { |entry| write_markdown_sections(entry) }
end
プラグインはダミーのJekyllプラグインを作っておく。
# _plugins/tdiary.rb
module Jekyll
class IsbnTag < Liquid::Tag
def initialize(tag_name, text, tokens)
super
@isbn = text.strip
end
def render(context)
"<p>(ISBN: #{@isbn})</p>"
end
end
end
Liquid::Template.register_tag('isbn', Jekyll::IsbnTag)
「タイトルがリンク」みたいなのをどうにかしたい
# _plugins/render_title_generator.rb
class RenderTitleGenerator < Jekyll::Generator
def generate(site)
site.posts.docs.each do |post|
title_line = post.content.lines.first.to_s.strip
title_line.gsub!(/^#\s*/, "")
title_line.gsub!(/\[([^\[\]]+?(?:\[[^\]]+\])?[^\]]*?)\]\((https?:\/\/[^\s)]+)\)/, '\1')
context = Liquid::Context.new({ "page" => post.data }, {}, { site: site })
rendered = Liquid::Template.parse(title_line).render!(context)
post.data["title_rendered"] = rendered
end
end
end
↑これを入れておけば{{ post.title_rendered }}でタイトルを表示できる。