forked from rhysd/notes-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
migrate-from-memolist.rb
executable file
·99 lines (83 loc) · 2.33 KB
/
migrate-from-memolist.rb
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
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/usr/bin/env ruby
require 'pathname'
require 'fileutils'
require 'date'
def help
puts "#{$PROGRAM_NAME} <memolist dir> <notes-cli home>"
end
Memo = Struct.new(:file, :title, :date, :category, :tags, :body)
TIMEZONE = Time.now.zone
def fail_read(path)
raise "Invalid memo at #{path}"
end
def read_memo(path)
puts "Reading memo #{path}"
File.basename(path) =~ /^\d+-\d+-\d+-(.*\.md)$/
file = $1
lines = File.readlines path
title = lines.shift.sub(/^title: /, '').chop
fail_read path unless lines.shift =~ /^=+$/
date = DateTime.parse "#{lines.shift.sub(/^date: /, '').chop} #{TIMEZONE}"
tags = lines.shift.gsub(/^tags: \[|\]$/, '').chop.split(',').reject{|s| s == "" }
categories = lines.shift.gsub(/^categories: \[|\]$/, '').chop.split(',').reject{|s| s == "" }
fail_read path unless lines.shift =~ /^\s{0,3}(?:-+\s*){3,}$/
body = lines.join.strip
if categories.length == 1
category = categories.first.downcase
else
category = "imported"
tags += categories
end
Memo.new(file, title, date, category, tags, body)
end
def migrate(memo, home_dir)
dir = home_dir.join(memo.category)
FileUtils.mkdir_p dir.to_s unless dir.exist?
file = dir.join(memo.file).to_s
puts "Generating note #{file}"
File.open(file, 'w') do |f|
f.write <<~EOS
#{memo.title}
#{'=' * memo.title.length}
- Category: #{memo.category}
- Tags: #{memo.tags.join(", ")}
- Created: #{memo.date.rfc3339}
---
#{memo.body}
EOS
end
end
def which(cmd)
exts = ENV['PATHEXT'] ? ENV['PATHEXT'].split(';') : ['']
ENV['PATH'].split(File::PATH_SEPARATOR).each do |path|
exts.each do |ext|
exe = File.join(path, "#{cmd}#{ext}")
return exe if File.executable?(exe) && !File.directory?(exe)
end
end
return nil
end
def main
if ARGV.length < 2
help
exit 1
end
memolist_dir = Pathname.new ARGV[0]
notes_home = Pathname.new(ARGV[1])
puts "Migrating from memolist '#{memolist_dir}' to notes-cli '#{notes_home}'"
unless memolist_dir.exist?
puts "memolist dir not exist"
exit 1
end
FileUtils.mkdir_p notes_home.to_s unless notes_home.exist?
Dir.glob("#{memolist_dir}/*.md").map{|p| read_memo p}.each do |path|
migrate(path, notes_home)
end
git = which('git')
if git
system(git, '-C', notes_home.to_s, 'init')
end
end
if __FILE__ == $PROGRAM_NAME
main
end