-class Stream < IO
- # Open Biopieces output data stream for reading from stdin or a file
- # specified in options[:stream_in] OR writing to stdout or a file
- # specified in options[:stream_out] or options[:data_out].
- def self.open(options, mode, stdio)
- if mode == "r"
- if options[:data_in] and options[:data_in].first == "-"
- self.nread(["-"])
- else
- $stdin.tty? ? read(options[:stream_in]) : stdio
- end
- elsif mode == "w"
- options[:stream_out] ? self.write(options[:stream_out], options[:compress]) : stdio
- else
- raise "Bad mode #{mode}"
- end
- end
-
- private
-
- # Opens a reads stream to a list of files.
- def self.read(files)
- return if files.nil? #TODO case/when
- self.zipped?(files) ? self.zread(files) : self.nread(files)
- end
-
- # Opens a write stream to a file and returns a _io_ object.
- def self.write(file, zip=nil)
- zip ? self.zwrite(file) : self.nwrite(file)
- end
-
- # Opens a list of gzipped files for reading and return an _io_ object.
- def self.zread(files)
- stdin, stdout, stderr = Open3.popen3("zcat " + files.join(' '));
- stdin.close
- stderr.close
- stdout
- end
-
- # Opens a file for gzipped writing and return an _io_ object.
- def self.zwrite(file)
- stdin, stdout, stderr = Open3.popen3("gzip -f > #{file}")
- stderr.close
- stdout.close
- stdin
- end
-
- # Opens a list of files for reading and return an _io_ object.
- def self.nread(files)
- stdin, stdout, stderr = Open3.popen3("cat " + files.join(' '));
- stdin.close
- stderr.close
- stdout
- end
-
- # Opens a file for writing and return an _io_ object.
- def self.nwrite(file)
- File.open(file, mode="w")
- end
-
- # Test if a list of files are gzipped or not.
- # Raises if files are mixed zipped and unzipped.
- def self.zipped?(files)
- type_hash = {}
-
- files.each do |file|
- type = `file #{file}`
-
- if type =~ /gzip compressed/
- type_hash[:gzip] = true
- else
- type_hash[:ascii] = true
- end
- end
-
- raise "Mixture of zipped and unzipped files" if type_hash.size == 2
-
- type_hash[:gzip]
- end
-end
-