-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtil.rb
executable file
·288 lines (245 loc) · 6.93 KB
/
til.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
#! /usr/bin/env ruby
require 'xdg'
require 'sqlite3'
require 'colorize'
require 'tempfile'
require 'json'
def db_file()
xdg = XDG::Environment.new
data_path = xdg.data_home.to_s
program_name = 'til'
File.join(data_path, program_name, "notes.db")
end
def normalize_word(s)
s.gsub(/[^[[:word:]]-]/,'').downcase
end
def normalize_spaces(s)
s.gsub(/[[:space:]]+/, ' ')
end
def edit_entry(start_title='', start_tags='', start_text='')
file = Tempfile.new('til')
file.puts(start_title)
file.puts(start_tags)
file.print(start_text)
file.close
system("vim #{file.path}")
arr = File.read(file.path).split("\n")
title = arr[0] || ''
tags = arr[1] || ''
text = (arr[2..-1] || '').join("\n")
file.unlink
[title, tags, text]
end
def add_keywords(db, nid, title, tagline)
def find_keywords(s)
normalize_spaces(s).split.map{|w| normalize_word(w) }
end
kws = (find_keywords(title) + find_keywords(tagline)).uniq
kws.each{|w|
res = db.get_first_row('SELECT tid,counter FROM tags WHERE tag = ?', w)
if res == nil
db.execute('INSERT INTO tags VALUES (NULL,?,?)', w, 0)
tid = db.last_insert_row_id
counter = 0
res = [tid, counter]
end
tid = res[0].to_i
counter = res[1].to_i
db.execute('INSERT INTO links (tid, nid) VALUES (?,?)', tid, nid)
db.execute('UPDATE tags SET counter = ? WHERE tid = ?', counter + 1, tid)
}
end
def remove_keywords(db, nid)
arr = db.execute('SELECT tid, COUNT(tid) FROM links WHERE nid = ? GROUP BY tid', nid)
arr.each{|row|
tid = row[0]
count = row[1]
counter = db.get_first_row('SELECT counter FROM tags WHERE tid = ?', tid)[0].to_i
new_counter = counter - count
if new_counter > 0
db.execute('UPDATE tags SET counter = ? WHERE tid = ?', new_counter, tid)
else
db.execute('DELETE FROM tags WHERE tid = ?', tid)
end
db.execute('DELETE FROM links WHERE nid = ?', nid)
}
end
def add(db, title, tagline, content)
db.execute('INSERT INTO notes VALUES (NULL,?,?,?)', title, tagline, content)
nid = db.last_insert_row_id
add_keywords(db, nid, title, tagline)
end
def update(db, nid, title, tagline, content)
remove_keywords(db, nid)
db.execute('UPDATE notes SET title = ?, tagline = ?, content = ? WHERE nid = ?', title, tagline, content, nid)
add_keywords(db, nid, title, tagline)
end
def init()
file = db_file()
dirname = File.dirname(file)
if not File.exist?(dirname)
Dir.mkdir(dirname)
end
begin
db = SQLite3::Database.open(file)
db.execute "CREATE TABLE IF NOT EXISTS notes(nid INTEGER PRIMARY KEY, title TEXT, tagline TEXT, content TEXT)"
db.execute "CREATE TABLE IF NOT EXISTS tags(tid INTEGER PRIMARY KEY, tag TEXT, counter INTEGER)"
db.execute "CREATE TABLE IF NOT EXISTS links(tid INTEGER, nid INTEGER)"
rescue SQLite3::Exception => e
puts "SQLite Exception"
puts e
ensure
db.close if db
end
end
def transaction(procedure)
begin
file = db_file()
db = SQLite3::Database.open(file)
db.transaction
procedure.call(db)
db.commit
rescue SQLite3::Exception => e
puts "SQLite Exception"
puts e
db.rollback
ensure
db.close if db
end
end
def vacuum()
file = db_file()
db = SQLite3::Database.open(file)
db.execute('VACUUM')
db.close if db
end
def run()
case ARGV[0]
when 'add'
title,tags,text = edit_entry()
transaction(Proc.new{|db|
add(db, title, tags, text)
})
when 'edit'
nid = ARGV[1].to_i
db = SQLite3::Database.open(db_file())
row = db.get_first_row('SELECT title,tagline,content FROM notes WHERE nid = ?', nid)
db.close if db
if row != nil
title = row[0]
tagline = row[1]
content = row[2]
new_title,new_tagline,new_content = edit_entry(title,tagline,content)
transaction(Proc.new{|db|
update(db, nid, new_title, new_tagline, new_content)
})
vacuum()
end
when 'del'
nid = ARGV[1].to_i
db = SQLite3::Database.open(db_file())
row = db.get_first_row('SELECT title,tagline,content FROM notes WHERE nid = ?', nid)
db.close if db
if row != nil
transaction(Proc.new{|db|
remove_keywords(db, nid)
db.execute('DELETE FROM notes WHERE nid = ?', nid)
})
vacuum()
end
when 'find'
tags = ARGV[1..-1].map{|t| normalize_word(t) }.uniq
db = SQLite3::Database.open(db_file())
tag_records = Array.new
tags.map{|t|
res = db.get_first_row('SELECT tid,counter FROM tags WHERE tag = ?', t)
if res != nil
tid = res[0]
counter = res[1]
nids = Array.new
db.execute('SELECT nid FROM links WHERE tid = ?', tid).each{|entry|
nids << entry[0]
}
tag_records << {:tid => res[0], :tag => t, :counter => counter, :nids => nids}
end
}
note_score = Hash.new(0)
note_tagcount = Hash.new(0)
tag_records.each{|r|
c = r[:counter]
score = 1.0/c
r[:nids].each{|nid|
note_score[nid] += score
note_tagcount[nid] += 1
}
}
max_tagcount = note_tagcount.values.max
notes = Array.new
note_tagcount.each_pair{|nid, tagcount|
if tagcount == max_tagcount
res = db.get_first_row('SELECT title,tagline,content FROM notes WHERE nid = ?', nid)
if res != nil
title = res[0]
tagline = res[1]
content = res[2]
score = note_score[nid]
notes << {:nid => nid, :title => title, :tagline => tagline, :content => content, :score => score}
end
end
}
db.close if db
notes.sort_by!{|note| -note[:score]}
notes.each{|note|
print "#{note[:nid]}. ".colorize(:blue)
print "#{note[:title].strip} ".colorize(:green)
print "(#{note[:tagline].strip})\n".colorize(:light_black)
print "#{note[:content]}"
puts ""
puts ""
}
when 'clear'
transaction(Proc.new{|db|
db.execute "DELETE FROM notes"
db.execute "DELETE FROM tags"
db.execute "DELETE FROM links"
})
vacuum()
when 'export'
def f(s)
s.gsub(/"/, '\"').gsub(/\n/, '\n')
end
transaction(Proc.new{|db|
print "["
first = true
db.execute("SELECT nid,title,tagline,content FROM notes").each{|rec|
if first
first = false
else
puts ","
end
#print "{\"title\":\"#{f(rec[1])}\", \"tagline\":\"#{f(rec[2])}\", \"content\":\"#{f(rec[3])}\"}"
print JSON.pretty_generate({'title' => rec[1], "tagline" => rec[2], "content" => rec[3]})
}
puts "]"
})
when 'import'
filename = ARGV[1]
data = []
if filename != nil
if File.exist?(filename)
file = File.open(filename)
data = JSON.load(file)
file.close
end
else
data = JSON.load(STDIN)
end
transaction(Proc.new{|db|
data.each{|entry|
add(db, entry['title'], entry['tagline'], entry['content'])
}
})
end
end
init()
run()