Skip to content

Instantly share code, notes, and snippets.

@kunishi
Last active October 20, 2017 16:16
Show Gist options
  • Save kunishi/c28715b03fe91004376221a7621e5f60 to your computer and use it in GitHub Desktop.
Save kunishi/c28715b03fe91004376221a7621e5f60 to your computer and use it in GitHub Desktop.
Dayone importer from Hatena diary backup file
#!/usr/bin/env ruby
# coding: utf-8
require "tempfile"
article = ""
microseconds = ""
subject = ""
date = ""
in_day = in_article = false
while line = gets
line.gsub!(/\&/, '&')
line.gsub!(/\"/, '"')
line.gsub!(/\[(.*):title=(.*)\]/, '[\2](\1)')
if line =~ /^\<day date="([0-9-]+)" .*\>$/
date = $1
in_day = true
next
end
if in_day && (line =~ /^\*([0-9]+)\*(.*)$/)
if in_article
temp = Tempfile.new
begin
temp.puts article
temp.flush
system "dayone2 -d='#{Time.at(microseconds.to_i)}' -j=hatena new < #{temp.path}"
ensure
temp.close
temp.unlink
end
in_article = false
article = ""
end
microseconds = $1
subject = $2
article += "# #{subject}\n\n"
in_article = true
next
end
if in_article && (line !~ /^\<\//)
article += line
elsif in_article && (line =~ /^\<\//)
temp = Tempfile.new
begin
temp.puts article
temp.flush
system "dayone2 -d='#{Time.at(microseconds.to_i)}' -j=hatena new < #{temp.path}"
ensure
temp.close
temp.unlink
end
in_article = false
article = ""
end
end
@kunishi
Copy link
Author

kunishi commented Oct 20, 2017

temp.flush is required because it seems to be late to write the content into the temporary file until flush method is executed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment