made it work, more or less, with ruby 1.9
[nyuron.git] / data / merge_commands_with_db.rb
blob33f648365109b3f6080450c3a5ca4110122a25d6
1 #!/usr/bin/env ruby
2 require 'pp'
3 $data = {}
5 $adr1 = nil
6 $adr2 = nil
8 ## some definitions {{{
9 def current() $data[$adr1] end
11 def get()  current[$adr2] end
13 def set(x) current[$adr2] = x end
15 def found(key)
16         return false if $cleared
17         !$db.get_first_row("SELECT * FROM nyu WHERE type='cmd' AND key=?;", key).nil?
18 end
20 def update(key, data)
21         $db.execute("UPDATE nyu SET mtime=?, value=?, descr=?, info1=? WHERE type='cmd' AND key=?;", Time.now.to_i, data['value'], data['descr'], data['tab'], key)
22 end
24 def create(key, data)
25         $db.execute("INSERT INTO nyu (key,type,ctime,mtime,value,descr,info1) VALUES (?, 'cmd', ?,?,?,?,?);", key, Time.now.to_i, Time.now.to_i, data['value'], data['descr'], data['tab'])
26 end
27 ## }}}
29 ## reading the data about commands from command.rb
30 print 'reading '
31 file = File.join(File.dirname(__FILE__), 'commands.rb')
32 File.read(file).each_line do |line|
33         if line =~ /^#\s*([\w\d]+)(?:\s*\.\s*([\w\d]+))?(?:\s*:\s*(.+))?/
34                 next if current and get.empty?
35                 $adr1 = $1
36                 $adr2 = $2 || 'value'
37                 print $adr2[0].chr
38                 $data[$adr1] ||= {}
39                 current['descr'] = $3 if $3
40                 set ''
41                 next
42         end
44         if current
45                 print '.'
46                 get << line
47         end
48 end
50 puts 'done!'
52 ## asking what to do
53 while true
54         puts
55         puts 'current path: ' + Dir.pwd + '/'
56         print 'write to which file? (leave free to print) '
57         gets
59         if $_.strip!.empty?
60                 pp $data
61                 exit
62         end
64         file = File.expand_path($_.strip)
66         while true
67                 puts "file = #{file.inspect}"
68                 print "is that correct? (yes/no) "
69                 gets
70                 break if %w[yes no].include? $_.strip!
71         end
73         break if $_ == 'yes'
74 end
76 ## if okay, write stuff to db
77 while true
78         print "clear old commands before applying new ones? (clear/no) "
79         break if %w[clear no].include? gets.strip!
80 end
82 require 'sqlite3'
83 $db = db = SQLite3::Database.new(file)
85 if $cleared = ($_ == 'clear')
86         db.execute "DELETE FROM nyu WHERE type='cmd'"
87 end
89 db.transaction
91 for key, val in $data
92         if found(key)
93                 puts " ) #{key} found. updating."
94                 update key, val
95         else
96                 puts "+) #{key} not found. creating."
97                 create key, val
98         end
99 end
100 db.commit
102 puts "done."