]> git.donarmstrong.com Git - biopieces.git/blob - code_ruby/lib/maasha/biopieces.rb
committing major ruby overhaul
[biopieces.git] / code_ruby / lib / maasha / biopieces.rb
1 raise "Ruby 1.9 or later required" if RUBY_VERSION < "1.9"
2
3 # Copyright (C) 2007-2011 Martin A. Hansen.
4
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
9
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18
19 # http://www.gnu.org/copyleft/gpl.html
20
21 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
22
23 # This software is part of the Biopieces framework (www.biopieces.org).
24
25 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
26
27 require 'date'
28 require 'fileutils'
29 require 'optparse'
30 require 'pp'
31 require 'stringio'
32 require 'zlib'
33
34 TEST = false
35
36 # Monkey patch (evil) changing the to_s method of the Hash class to
37 # return a Hash in Biopieces format; keys and value pairs on one line
38 # each seperated with ': ' and terminated by a line of '---'.
39 class Hash
40   def to_s
41     string = ""
42
43     self.each do |key, value|
44       string << "#{key.to_s}: #{value}\n"
45     end
46
47     string << "---\n"
48
49     string
50   end
51 end
52
53 # Error class for all exceptions to do with the Biopieces class.
54 class BiopiecesError < StandardError; end
55
56 # Biopieces are command line scripts and uses OptionParser to parse command line
57 # options according to a list of casts. Each cast prescribes the long and short
58 # name of the option, the type, if it is mandatory, the default value, and allowed
59 # and disallowed values. An optional list of extra casts can be supplied, and the
60 # integrity of the casts are checked. Following the command line parsing, the
61 # options are checked according to the casts. Methods are also included for handling
62 # the parsing and emitting of Biopiece records, which are ASCII text records consisting
63 # of lines with a key/value pair separated by a colon and a white space ': '.
64 # Each record is separated by a line with three dashes '---'.
65 class Biopieces
66   include Enumerable
67
68   # Class method to check the integrity of a list of casts, followed by parsing
69   # options from argv and finally checking the options according to the casts.
70   def self.options_parse(argv, cast_list=[], script_path=$0)
71     casts          = Casts.new(cast_list)
72     option_handler = OptionHandler.new(argv, casts, script_path)
73     options        = option_handler.options_parse
74
75     options
76   end
77
78   # Class method for opening data streams for reading and writing Biopiece
79   # records. Records are read from STDIN (default) or file (possibly gzipped)
80   # and written to STDOUT (default) or file.
81   def self.open(input = STDIN, output = STDOUT)
82     input  = self.open_input(input)
83     output = self.open_output(output)
84
85     if block_given?
86       begin
87         yield input, output
88       ensure
89         input.close
90         output.close
91       end
92     else
93       return input, output
94     end
95   end
96
97   # Class method to create a temporary directory inside the ENV["BP_TMP"] directory.
98   def self.mktmpdir
99     time = Time.now.to_i
100     user = ENV["USER"]
101     pid  = $$
102     path = File.join(ENV["BP_TMP"], [user, time + pid, pid, "bp_tmp"].join("_"))
103     Dir.mkdir(path)
104     Status.new.set_tmpdir(path)
105     path
106   end
107
108   # Initialize a Biopiece object for either reading or writing from _ios_.
109   def initialize(ios, stdio = nil)
110     @ios   = ios
111     @stdio = stdio
112   end
113
114   # Method to write a Biopiece record to _ios_.
115   def puts(foo)
116     @ios << foo.to_s
117   end
118
119   # Method to close _ios_.
120   def close
121     @ios.close unless @stdio
122   end
123
124   # Method to parse and yield a Biopiece record from _ios_.
125   def each_record
126     record = {}
127
128     @ios.each_line do |line|
129       case line
130       when /^([^:]+): (.*)$/
131         record[$1.to_sym] = $2
132       when /^---$/
133         yield record unless record.empty?
134         record = {}
135       else
136         raise BiopiecesError, "Bad record format: #{line}"
137       end
138     end
139
140     yield record unless record.empty?
141
142     self # conventionally
143   end
144
145   alias :each :each_record
146
147   private
148
149   # Class method for opening data stream for reading Biopiece records.
150   # Records are read from STDIN (default) or file (possibly gzipped).
151   def self.open_input(input)
152     if STDIN.tty?
153       if input.nil?
154         input = self.new(StringIO.new)
155       else
156         ios = File.open(input, mode='r')
157
158         begin
159             ios = Zlib::GzipReader.new(ios)
160         rescue
161             ios.rewind
162         end
163
164         input = self.new(ios)
165       end
166     else
167       input = self.new(STDIN, stdio = true)
168     end
169
170     input
171   end
172
173   # Class method for opening data stream for writing Biopiece records.
174   # Records are written to STDOU (default) or file.
175   def self.open_output(output)
176     if output.nil?
177       output = self.new(STDOUT, stdio = true)
178     elsif not output.is_a? IO
179       output = self.new(File.open(output, mode='w'))
180     end
181
182     output
183   end
184 end
185
186
187 # Error class for all exceptions to do with option casts.
188 class CastError < StandardError; end
189
190 # Class to handle casts of command line options. Each cast prescribes the long and
191 # short name of the option, the type, if it is mandatory, the default value, and
192 # allowed and disallowed values. An optional list of extra casts can be supplied,
193 # and the integrity of the casts are checked.
194 class Casts < Array
195   TYPES     = %w[flag string list int uint float file file! files files! dir dir! genome]
196   MANDATORY = %w[long short type mandatory default allowed disallowed]
197
198   # Initialize cast object with an optional options cast list to which
199   # ubiquitous casts are added after which all casts are checked.
200   def initialize(cast_list=[])
201     @cast_list = cast_list
202     ubiquitous
203     check
204     long_to_sym
205     self.push(*@cast_list)
206   end
207
208   private
209
210   # Add ubiquitous options casts.
211   def ubiquitous
212     @cast_list << {:long=>'help',       :short=>'?', :type=>'flag',   :mandatory=>false, :default=>nil, :allowed=>nil, :disallowed=>nil}
213     @cast_list << {:long=>'stream_in',  :short=>'I', :type=>'file!',  :mandatory=>false, :default=>nil, :allowed=>nil, :disallowed=>nil}
214     @cast_list << {:long=>'stream_out', :short=>'O', :type=>'file',   :mandatory=>false, :default=>nil, :allowed=>nil, :disallowed=>nil}
215     @cast_list << {:long=>'verbose',    :short=>'v', :type=>'flag',   :mandatory=>false, :default=>nil, :allowed=>nil, :disallowed=>nil}
216   end
217
218   # Check integrity of the casts.
219   def check
220     check_keys
221     check_values
222     check_duplicates
223   end
224   
225   # Check if all mandatory keys are present in casts and raise if not.
226   def check_keys
227     @cast_list.each do |cast|
228       MANDATORY.each do |mandatory|
229         raise CastError, "Missing symbol in cast: '#{mandatory.to_sym}'" unless cast.has_key? mandatory.to_sym
230       end
231     end
232   end
233
234   # Check if all values in casts are valid.
235   def check_values
236     @cast_list.each do |cast|
237       check_val_long(cast)
238       check_val_short(cast)
239       check_val_type(cast)
240       check_val_mandatory(cast)
241       check_val_default(cast)
242       check_val_allowed(cast)
243       check_val_disallowed(cast)
244     end
245   end
246
247   # Check if the values to long are legal and raise if not.
248   def check_val_long(cast)
249     unless cast[:long].is_a? String and cast[:long].length > 1
250       raise CastError, "Illegal cast of long: '#{cast[:long]}'"
251     end
252   end
253   
254   # Check if the values to short are legal and raise if not.
255   def check_val_short(cast)
256     unless cast[:short].is_a? String and cast[:short].length == 1
257       raise CastError, "Illegal cast of short: '#{cast[:short]}'"
258     end
259   end
260
261   # Check if values to type are legal and raise if not.
262   def check_val_type(cast)
263     type_hash = {}
264     TYPES.each do |type|
265       type_hash[type] = true
266     end
267
268     unless type_hash.has_key? cast[:type]
269       raise CastError, "Illegal cast of type: '#{cast[:type]}'"
270     end
271   end
272
273   # Check if values to mandatory are legal and raise if not.
274   def check_val_mandatory(cast)
275     unless cast[:mandatory] == true or cast[:mandatory] == false
276       raise CastError, "Illegal cast of mandatory: '#{cast[:mandatory]}'"
277     end
278   end
279
280   # Check if values to default are legal and raise if not.
281   def check_val_default(cast)
282     unless cast[:default].nil?          or
283            cast[:default].is_a? String  or
284            cast[:default].is_a? Integer or
285            cast[:default].is_a? Float
286       raise CastError, "Illegal cast of default: '#{cast[:default]}'"
287     end
288   end
289
290   # Check if values to allowed are legal and raise if not.
291   def check_val_allowed(cast)
292     unless cast[:allowed].is_a? String or cast[:allowed].nil?
293       raise CastError, "Illegal cast of allowed: '#{cast[:allowed]}'"
294     end
295   end
296
297   # Check if values to disallowed are legal and raise if not.
298   def check_val_disallowed(cast)
299     unless cast[:disallowed].is_a? String or cast[:disallowed].nil?
300       raise CastError, "Illegal cast of disallowed: '#{cast[:disallowed]}'"
301     end
302   end
303
304   # Check cast for duplicate long or short options names.
305   def check_duplicates
306     check_hash = {}
307     @cast_list.each do |cast|
308       raise CastError, "Duplicate argument: '--#{cast[:long]}'" if check_hash.has_key? cast[:long]
309       raise CastError, "Duplicate argument: '-#{cast[:short]}'" if check_hash.has_key? cast[:short]
310       check_hash[cast[:long]]  = true
311       check_hash[cast[:short]] = true
312     end
313   end
314
315   # Convert values to :long keys to symbols for all casts.
316   def long_to_sym
317     @cast_list.each do |cast|
318       cast[:long] = cast[:long].to_sym
319     end
320   end
321 end
322
323
324 # Class for parsing argv using OptionParser according to given casts.
325 # Default options are set, file glob expressions expanded, and options are
326 # checked according to the casts. Usage information is printed and exit called
327 # if required.
328 class OptionHandler
329   REGEX_LIST   = /^(list|files|files!)$/
330   REGEX_INT    = /^(int|uint)$/
331   REGEX_STRING = /^(file|file!|dir|dir!|genome)$/
332
333   def initialize(argv, casts, script_path)
334     @argv        = argv
335     @casts       = casts
336     @script_path = script_path
337   end
338
339   # Parse options from argv using OptionParser and casts denoting long and
340   # short option names. Usage information is printed and exit called.
341   # A hash with options is returned.
342   def options_parse
343     @options = {}
344
345     option_parser = OptionParser.new do |option|
346       @casts.each do |cast|
347         case cast[:type]
348         when 'flag'
349           option.on("-#{cast[:short]}", "--#{cast[:long]}") do |o|
350             @options[cast[:long]] = o
351           end
352         when 'float'
353           option.on("-#{cast[:short]}", "--#{cast[:long]} F", Float) do |f|
354             @options[cast[:long]] = f
355           end
356         when 'string'
357           option.on("-#{cast[:short]}", "--#{cast[:long]} S", String) do |s|
358             @options[cast[:long]] = s.to_sym  # TODO: this to_sym - is that needed?
359           end
360         when REGEX_LIST
361           option.on( "-#{cast[:short]}", "--#{cast[:long]} A", Array) do |a|
362             @options[cast[:long]] = a
363           end
364         when REGEX_INT
365           option.on("-#{cast[:short]}", "--#{cast[:long]} I", Integer) do |i|
366             @options[cast[:long]] = i
367           end
368         when REGEX_STRING
369           option.on("-#{cast[:short]}", "--#{cast[:long]} S", String) do |s|
370             @options[cast[:long]] = s
371           end
372         else
373           raise ArgumentError, "Unknown option type: '#{cast[:type]}'"
374         end
375       end
376     end
377
378     option_parser.parse!(@argv)
379
380     if print_usage_full?
381       print_usage_and_exit(full=true)
382     elsif print_usage_short?
383       print_usage_and_exit
384     end
385
386     options_default
387     options_glob
388     options_check
389
390     @options
391   end
392
393   # Given the script name determine the path of the wiki file with the usage info.
394   def wiki_path
395     path = File.join(ENV["BP_DIR"], "bp_usage", File.basename(@script_path)) + ".wiki"
396     raise "No such wiki file: #{path}" unless File.file? path
397     path
398   end
399
400   # Check if full "usage info" should be printed.
401   def print_usage_full?
402     @options[:help]
403   end
404
405   # Check if short "usage info" should be printed.
406   def print_usage_short?
407     if not STDIN.tty?
408       return false
409     elsif @options[:stream_in]
410       return false
411     elsif @options[:data_in]
412       return false
413     elsif wiki_path =~ /^(list_biopieces|list_genomes|list_mysql_databases|biostat)$/  # TODO get rid of this!
414       return false
415     else
416       return true
417     end
418   end
419
420   # Print usage info by Calling an external script 'print_wiki'
421   # using a system() call and exit. An optional 'full' flag
422   # outputs the full usage info.
423   def print_usage_and_exit(full=nil)
424     if TEST
425       return
426     else
427       if full
428         system("print_wiki --data_in #{wiki_path} --help")
429       else
430         system("print_wiki --data_in #{wiki_path}")
431       end
432
433       raise "Failed printing wiki: #{wiki_path}" unless $?.success?
434
435       exit
436     end
437   end
438
439   # Set default options value from cast unless a value is set.
440   def options_default
441     @casts.each do |cast|
442       if cast[:default]
443         unless @options.has_key? cast[:long]
444           if cast[:type] == 'list'
445             @options[cast[:long]] = cast[:default].split ','
446           else
447             @options[cast[:long]] = cast[:default]
448           end
449         end
450       end
451     end
452   end
453
454   # Expands glob expressions to a full list of paths.
455   # Examples: "*.fna" or "foo.fna,*.fna" or "foo.fna,/bar/*.fna"
456   def options_glob
457     @casts.each do |cast|
458       if cast[:type] == 'files' or cast[:type] == 'files!'
459         if @options.has_key? cast[:long]
460           files = []
461         
462           @options[cast[:long]].each do |path|
463             if path.include? "*"
464               Dir.glob(path).each do |file|
465                 files << file if File.file? file
466               end
467             else
468               files << path
469             end
470           end
471
472           @options[cast[:long]] = files
473         end
474       end
475     end
476   end
477
478   # Check all options according to casts.
479   def options_check
480     @casts.each do |cast|
481       options_check_mandatory(cast)
482       options_check_int(cast)
483       options_check_uint(cast)
484       options_check_file(cast)
485       options_check_files(cast)
486       options_check_dir(cast)
487       options_check_allowed(cast)
488       options_check_disallowed(cast)
489     end
490   end
491   
492   # Check if a mandatory option is set and raise if it isn't.
493   def options_check_mandatory(cast)
494     if cast[:mandatory]
495       raise ArgumentError, "Mandatory argument: --#{cast[:long]}" unless @options.has_key? cast[:long]
496     end
497   end
498
499   # Check int type option and raise if not an integer.
500   def options_check_int(cast)
501     if cast[:type] == 'int' and @options.has_key? cast[:long]
502       unless @options[cast[:long]].is_a? Integer
503         raise ArgumentError, "Argument to --#{cast[:long]} must be an integer, not '#{@options[cast[:long]]}'"
504       end
505     end
506   end
507   
508   # Check uint type option and raise if not an unsinged integer.
509   def options_check_uint(cast)
510     if cast[:type] == 'uint' and @options.has_key? cast[:long]
511       unless @options[cast[:long]].is_a? Integer and @options[cast[:long]] >= 0
512         raise ArgumentError, "Argument to --#{cast[:long]} must be an unsigned integer, not '#{@options[cast[:long]]}'"
513       end
514     end
515   end
516
517   # Check file! type argument and raise if file don't exists.
518   def options_check_file(cast)
519     if cast[:type] == 'file!' and @options.has_key? cast[:long]
520       raise ArgumentError, "No such file: '#{@options[cast[:long]]}'" unless File.file? @options[cast[:long]]
521     end
522   end
523
524   # Check files! type argument and raise if files don't exists.
525   def options_check_files(cast)
526     if cast[:type] == 'files!' and @options.has_key? cast[:long]
527       @options[cast[:long]].each do |path|
528         next if path == "-"
529         raise ArgumentError, "File not readable: '#{path}'" unless File.readable? path
530       end
531     end
532   end
533   
534   # Check dir! type argument and raise if directory don't exist.
535   def options_check_dir(cast)
536     if cast[:type] == 'dir!' and @options.has_key? cast[:long]
537       raise ArgumentError, "No such directory: '#{@options[cast[:long]]}'" unless File.directory? @options[cast[:long]]
538     end
539   end
540   
541   # Check options and raise unless allowed.
542   def options_check_allowed(cast)
543     if cast[:allowed] and @options.has_key? cast[:long]
544       allowed_hash = {}
545       cast[:allowed].split(',').each { |a| allowed_hash[a.to_s] = 1 }
546   
547       raise ArgumentError, "Argument '#{@options[cast[:long]]}' to --#{cast[:long]} not allowed" unless allowed_hash.has_key? @options[cast[:long]].to_s
548     end
549   end
550   
551   # Check disallowed argument values and raise if disallowed.
552   def options_check_disallowed(cast)
553     if cast[:disallowed] and @options.has_key? cast[:long]
554       cast[:disallowed].split(',').each do |val|
555         raise ArgumentError, "Argument '#{@options[cast[:long]]}' to --#{cast[:long]} is disallowed" if val.to_s == @options[cast[:long]].to_s
556       end
557     end
558   end
559 end
560
561 # Class for manipulating the execution status of Biopieces by setting a
562 # status file with a time stamp, process id, and command arguments. The
563 # status file is used for creating log entries and for displaying the
564 # runtime status of Biopieces.
565 class Status
566   # Write the status to a status file.
567   def set
568     time0  = Time.new.strftime("%Y-%m-%d %X")
569
570     File.open(path, mode="w") do |fh|
571       fh.puts [time0, ARGV.join(" ")].join(";")
572     end
573   end
574
575   # Append the a temporary directory path to the status file.
576   def set_tmpdir(tmpdir_path)
577     status = ""
578
579     File.open(path, mode="r") do |fh|
580       status = fh.read.chomp
581     end
582
583     status = "#{status};#{tmpdir_path}\n"
584
585     File.open(path, mode="w") do |fh|
586       fh << status
587     end
588   end
589
590   # Extract the temporary directory path from the status file,
591   # and return this or nil if not found.
592   def get_tmpdir
593     File.open(path, mode="r") do |fh|
594       tmpdir_path = fh.read.chomp.split(";").last
595       return tmpdir_path if File.directory?(tmpdir_path)
596     end
597
598     nil
599   end
600
601   # Write the Biopiece status to the log file.
602   def log(exit_status)
603     time1   = Time.new.strftime("%Y-%m-%d %X")
604     user    = ENV["USER"]
605     script  = File.basename($0)
606
607     stream = File.open(path)
608     time0, args, tmp_dir = stream.first.split(";")
609     stream.close
610
611     elap     = time_diff(time0, time1)
612     command  = [script, args].join(" ") 
613     log_file = File.join(ENV["BP_LOG"], "biopieces.log")
614
615     File.open(log_file, mode = "a") { |file| file.puts [time0, time1, elap, user, exit_status, command].join("\t") }
616   end
617
618   # Delete status file.
619   def delete
620     File.delete(path)
621   end
622   
623   private
624
625   # Path to status file
626   def path
627     user   = ENV["USER"]
628     script = File.basename($0)
629     pid    = $$
630     path   = File.join(ENV["BP_TMP"], [user, script, pid, "status"].join("."))
631   end
632
633   # Get the elapsed time from the difference between two time stamps.
634   def time_diff(t0, t1)
635     Time.at((DateTime.parse(t1).to_time - DateTime.parse(t0).to_time).to_i).gmtime.strftime('%X')
636   end
637 end
638
639
640 # Set status when 'biopieces' is required.
641 Status.new.set
642
643 # Clean up when 'biopieces' exists.
644 at_exit do
645   exit_status = $! ? $!.inspect : "OK"
646
647   case exit_status
648   when /error|errno/i
649     exit_status = "ERROR"
650   when "Interrupt"
651     exit_status = "INTERRUPTED"
652   when /SIGTERM/
653     exit_status = "TERMINATED"
654   when /SIGQUIT/
655     exit_status = "QUIT"
656   end
657
658   status = Status.new
659   tmpdir = status.get_tmpdir
660   FileUtils.remove_entry_secure(tmpdir) unless tmpdir.nil?
661   status.log(exit_status)
662   status.delete
663 end
664
665
666 __END__
667