-
Notifications
You must be signed in to change notification settings - Fork 332
Expand file tree
/
Copy pathghost.rb
More file actions
86 lines (73 loc) · 2.68 KB
/
Copy pathghost.rb
File metadata and controls
86 lines (73 loc) · 2.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# frozen_string_literal: true
module JekyllImport
module Importers
class Ghost < Importer
def self.specify_options(c)
c.option "dbfile", "--dbfile", "Database file (default: ghost.db)"
end
def self.require_deps
JekyllImport.require_with_fallback(%w(
rubygems
sequel
sqlite3
fileutils
safe_yaml
))
end
def self.process(options)
posts = fetch_posts(options.fetch("dbfile", "ghost.db"))
unless posts.empty?
FileUtils.mkdir_p("_posts")
FileUtils.mkdir_p("_drafts")
posts.each do |post|
write_post_to_file(post)
end
end
end
class << self
private
def fetch_posts(dbfile)
db = Sequel.sqlite(dbfile)
query = "SELECT `title`, `slug`, `markdown`, `created_at`, `published_at`, `status`, `page` FROM posts"
db[query]
end
def write_post_to_file(post)
# detect if the post is a draft
draft = post[:status].eql?("draft")
# detect if the post is considered a static page
page = post[:page]
# the publish date if the post has been published, creation date otherwise
# The database stores timestamps in milliseconds, so we need to divide by 1000
# to get time in seconds.
date = Time.at(post[draft ? :created_at : :published_at].to_i / 1000)
if page
# the filename under which the page is stored
filename = "#{post[:slug]}.markdown"
else
# the directory where the file will be saved to. either _drafts or _posts
directory = draft ? "_drafts" : "_posts"
# the filename under which the post is stored
filename = File.join(directory, "#{date.strftime("%Y-%m-%d")}-#{post[:slug]}.markdown")
end
# the YAML FrontMatter
frontmatter = {
"layout" => page ? "page" : "post",
"title" => post[:title],
}
frontmatter["date"] = date if !page && !draft # only add the date to the frontmatter when the post is published
frontmatter["published"] = false if page && draft # set published to false for draft pages
frontmatter.delete_if { |_k, v| v.nil? || v == "" } # removes empty fields
# write the posts to disk
write_file(filename, frontmatter.to_yaml, post[:markdown])
end
def write_file(filename, frontmatter, content)
File.open(filename, "w") do |f|
f.puts frontmatter
f.puts "---"
f.puts content
end
end
end
end
end
end