Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
memolist.vim のメモを Day One 2 に取り込むやつ / A script to import entries created with memolist.vim to Day One 2. requires rb-dayone.gem
require 'rb-dayone'
require 'optparse'
require 'json'
dry_run = true
journal_location = "#{ENV['HOME']}/Library/Group Containers/5U8NS4GX82.dayoneapp2/Data/Auto Import/Default Journal.dayone"
target_dir = "#{ENV['HOME']}/Dropbox/memolist/"
since = Date.today
exclude = nil
options = OptionParser.new
options.on('--execute') {|v|
dry_run = false
}
options.on('-j', '--journal VALUE') {|v|
journal_location = v if v != '' || !v.nil?
}
options.on('-t', '--target_dir VALUE') {|v|
if v != '' || !v.nil?
dir = File.expand_path(v)
target_dir = dir if File.exist?(dir)
end
}
options.on('-s', '--since VALUE') {|v|
if v != '' || !v.nil?
since = Date.parse(v)
end
}
options.on('--exclude VALUE') {|v|
if v != '' || !v.nil?
exclude = Regexp.new(v)
end
}
options.parse!(ARGV)
DayOne::journal_location = journal_location
files = Dir.glob(%{#{target_dir}/*\.{markdown,md}})
files = files.grep_v(exclude) if exclude
files = files.delete_if {|file| File.birthtime(file) < since.to_time }
puts "Begin Importing memolist"
puts "Dry run: #{dry_run}"
puts "Target dir: #{target_dir}"
puts "Target files count: #{files.count}"
puts "Journal location: #{journal_location}"
files.each do |file|
content = File.read(file)
if content.nil?
puts "Skip #{file} because content is blank"
next
end
if content.match(/==========/) # memolist defualt
content.sub!(/==========\n/, '')
meta_info, body = content.split('- - -').map {|item| item.strip }
elsif content.match(/\-{3}/) # yaml front-matter
_, meta_info, body = content.split('---').map {|item| item.strip }
else
meta_info = nil
body = content.strip
end
if body.nil? || body.length.zero?
puts "Skip #{file} because body is blank"
next
end
if !meta_info.nil?
meta_array = meta_info.split("\n")
title = meta_array[0].sub(/title: (.+)/, '\\1')
date = Time.parse(meta_array[1].sub(/date: (.+)/, '\\1'))
tags = begin
tags = meta_array[2]
matched = tags.match(/tags: (.*)/)[1]
JSON.parse(matched)
rescue JSON::ParserError
matched.sub(/^\[(.+)\]/, '\\1').split(/,\s/)
end
else
title = File.basename(file).sub(/\d{4}\-\d{2}\-\d{2}\-(.+)?\.(?:.+)$/) { $1 }.gsub(/\-/, ' ').upcase
date = File.birthtime(file)
tags = []
end
unified_body = if body.split("\n")[0].match(/^(?:#\s)?#{title}$/)
body
else
"# #{title}\n\n#{body}"
end
tags << 'from memolist'
entry = DayOne::Entry.new(unified_body, creation_date: date, tags: tags)
if dry_run
puts "#{date} #{title} #{tags}"
else
begin
entry.create!
puts "Successfully save #{date} #{title} #{tags}"
rescue => e
puts e.message
puts e.backtrace.join("\n")
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment