Skip to content

Instantly share code, notes, and snippets.

@danivovich
Created October 27, 2017 12:05
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 danivovich/ed74593ad0a7c77f01a757ec85f8399f to your computer and use it in GitHub Desktop.
Save danivovich/ed74593ad0a7c77f01a757ec85f8399f to your computer and use it in GitHub Desktop.
Migrate from Ghost JSON into Jekyll Markdown Files
#!/usr/bin/env ruby
require 'fileutils'
require 'json'
require 'date'
require 'yaml'
FileUtils.mkdir_p("_posts")
FileUtils.mkdir_p("_drafts")
FileUtils.mkdir_p("_data")
$json = JSON.parse File.read(ARGV.pop), symbolize_names: true
unless $json[:data].nil?
posts = $json[:data][:posts]
else
posts = $json[:db].first[:data][:posts]
end
def there_are_tags?
@tags ||=
$json[:db] &&
$json[:db].first[:data][:posts_tags] &&
$json[:db].first[:data][:tags]
end
@imported = Hash.new(0)
class Post
# the source of the post
attr_reader :post
def initialize post
@post = post
end
def import
puts "Importing #{ filename }"
File.write filename, full_body
end
def draft?
post[:status] == 'draft'
end
private
def folder
draft? ? '_drafts' : '_posts'
end
def filename
File.join folder, basename
end
def date
case post[:published_at]
when String
DateTime.parse(post[:published_at])
when Integer
Time.at(post[:published_at] / 1000).utc.to_datetime
end
end
def front_matter
front_matter_hash = {
'layout' => 'single',
'title' => post[:title],
'header' => {
'image' => post[:image],
'caption' => "Photo credit: [**Unsplash**](https://unsplash.com)"
},
'meta_title' => post[:meta_title],
'meta_description' => post[:meta_description]
}
unless draft?
front_matter_hash['date'] = date.strftime('%Y-%m-%d %H:%M:%S') if date
end
front_matter_hash['tags'] = tags if tags && !tags.empty?
front_matter_hash
end
def slug
post[:slug]
end
def tags
if there_are_tags?
post_tags = $json[:db].first[:data][:posts_tags].select do |pt|
pt[:post_id] == post[:id]
end
tags_ids = post_tags.map { |pt| pt[:tag_id] }
tags = $json[:db].first[:data][:tags].select do |t|
tags_ids.include? t[:id]
end
tags.map { |t| t[:slug] }
end
end
def full_body
front_matter.to_yaml + "---\n\n" + post[:markdown]
end
def basename
if draft?
"#{ slug }.markdown"
else
"#{ date.strftime('%Y-%m-%d') }-#{ slug }.markdown"
end
end
end
posts.each do |post|
post = Post.new post
post.import
@imported[:posts] += 1
@imported[:drafts] += 1 if post.draft?
end
tags = $json[:db].first[:data][:tags].map do |tg|
{
'name': tg[:name],
'slug': tg[:slug],
'description': tg[:description],
'meta_title': tg[:meta_title],
'meta_description': tg[:meta_description],
'image': tg[:image]
}
end
puts "Importing tags"
File.write "_data/tags.yml", tags.to_yaml
puts "#{ @imported[:posts] } posts imported ( #{ @imported[:drafts] } draft )"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment