Created
March 21, 2018 14:44
-
-
Save atog/005cca6a09df6cd290a955690060aece to your computer and use it in GitHub Desktop.
Migrate Ghost json export to Markdown files for static generation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'json' | |
require 'open-uri' | |
class GhostMigrate | |
attr_accessor :archive, :posts, :tags, :posts_tags, :template, :base_url | |
def run(filename, url) | |
@archive = JSON.parse(File.read(filename)) | |
@posts = archive["db"][0]["data"]["posts"] | |
@tags = archive["db"][0]["data"]["tags"] | |
@posts_tags = archive["db"][0]["data"]["posts_tags"] | |
@template = DATA.read | |
@base_url = url | |
posts.each_with_index do |p,i| | |
File.open("ghost-#{i}.md", "w") do |f| | |
f.write post(p) | |
end | |
end | |
end | |
def post(post_data) | |
title = post_data["title"] | |
uuid = post_data["uuid"] | |
id = post_data["id"] | |
permalink = post_data["slug"] | |
date = post_data["published_at"]#[0...10] | |
image = (download_image post_data["feature_image"], id) || "none" | |
markdown = JSON.parse(post_data["mobiledoc"])["cards"][0][1]["markdown"] | |
template % [id, title, permalink, date, formatted_tags(id), image, markdown] | |
end | |
def formatted_tags(post_id) | |
tag_ids = posts_tags.find_all { |pt| pt["post_id"] == post_id }.map { |pt| pt["tag_id"] } | |
selected_tags = tag_ids.inject([]) do |r,ti| | |
r << " - \"#{(tags.find { |t| t["id"] == ti })["name"]}\"" | |
end | |
selected_tags.join("\n") | |
end | |
def download_image(url, id) | |
return unless url | |
image_url = base_url + url | |
image_name = File.basename url | |
image_output = "img/#{id}-#{image_name}" | |
unless File.exist?(image_output) | |
image_data = open(image_url, &:read) | |
File.open(image_output, "w") do |f| | |
f.write(image_data) | |
end | |
end | |
image_output | |
end | |
end | |
if __FILE__ == $0 | |
puts "MIGRATE!" | |
GhostMigrate.new.run ARGV[0], ARGV[1] | |
end | |
__END__ | |
--- | |
id: %s | |
title: "%s" | |
permalink: %s/index.html | |
date: %s | |
tags: | |
%s | |
layout: layouts/post.njk | |
feature_image: %s | |
--- | |
%s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment