Skip to content

Instantly share code, notes, and snippets.

@ashfurrow
Last active March 2, 2019 17:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ashfurrow/b10628a879236d85c262e5621e583f14 to your computer and use it in GitHub Desktop.
Save ashfurrow/b10628a879236d85c262e5621e583f14 to your computer and use it in GitHub Desktop.
Script to migrate blog from Middleman to Gatsby
#!/usr/bin/ruby
require 'rake'
require 'yaml'
require 'date'
OLD_ROOT_DIR = "/Users/ashfurrow/bin/blog/source"
OLD_MD_DIR = "/Users/ashfurrow/bin/blog/source/blog"
NEW_MD_DIR = "/Users/ashfurrow/bin/blog2/blog"
YAML_FRONT_MATTER_REGEXP = /\A(---\s*\n.*?\n?)^((---|\.\.\.)\s*$\n?)/m
IMAGE_REGEXP = %r{(\/img\/[^"\)]*)["\)]}
puts "Starting...\n#{Array.new(80).map { '-' }.join('')}\n\n\n"
old_posts = FileList.new("#{OLD_MD_DIR}/*").to_a
puts "Migrating #{old_posts.length} posts."
results = old_posts.map do |filename|
puts " Migrating #{filename}"
file = File.read(filename)
raise "Bad file: #{filename}" unless file =~ YAML_FRONT_MATTER_REGEXP
data, content = YAML.load($1), Regexp.last_match.post_match
stripped_filename = filename.split("/").last.match(%r{(\d\d\d\d-\d\d-\d\d)-.*.html.(markdown|slim)})[1]
new_post_dir = "#{NEW_MD_DIR}/#{stripped_filename}"
puts " Making new directory #{new_post_dir}"
output = `mkdir #{new_post_dir} 2>&1`
date = DateTime.parse(data["date"])
map = {
"title" => data["title"],
"createdDate" => date.strftime("%F"),
"updatedDate" => date.strftime("%F"),
"author" => "Ash Furrow"
}
background_image = data["background_image"]
if !background_image.nil?
map["image"] = background_image.split("/").last
old_filename = "#{OLD_ROOT_DIR}#{background_image}"
raise "File does not exist: #{old_filename}" unless File.exists?(old_filename)
`cp #{old_filename} #{new_post_dir}/#{map['image']}`
end
og_image = data["og_image"]
if !og_image.nil?
map["socialImage"] = og_image.split("/").last
old_filename = "#{OLD_ROOT_DIR}#{og_image}"
raise "File does not exist: #{old_filename}" unless File.exists?(old_filename)
`cp #{old_filename} #{new_post_dir}/#{map['socialImage']}`
end
# Look for any local images and move
content.scan(IMAGE_REGEXP).select { |m| m[0].start_with? "/" }.map(&:first).each do |match|
old_filename = "#{OLD_ROOT_DIR}#{match}"
raise "File does not exist: #{old_filename}" unless File.exists?(old_filename)
content.gsub!(match, match.split("/").last)
`cp #{old_filename} #{new_post_dir}/#{match.split("/").last}`
end
raise "Help! Reference old image dir! #{filename}, #{content}" if content.include? "/img/"
# TODO: Replace YOUTUBE
# map
# stripped_filename
new_file = <<~EOS
#{YAML.dump(map)}---
#{content}
EOS
File.open("#{new_post_dir}/index.md", "w") { |f| f.write(new_file) }
true
end
puts results.to_a.uniq
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment