]> git.donarmstrong.com Git - biopieces.git/blobdiff - code_ruby/lib/maasha/filesys.rb
changed layout of ruby source
[biopieces.git] / code_ruby / lib / maasha / filesys.rb
diff --git a/code_ruby/lib/maasha/filesys.rb b/code_ruby/lib/maasha/filesys.rb
new file mode 100644 (file)
index 0000000..9024a58
--- /dev/null
@@ -0,0 +1,100 @@
+# Copyright (C) 2007-2011 Martin A. Hansen.
+
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+
+# http://www.gnu.org/copyleft/gpl.html
+
+# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+
+# This software is part of the Biopieces framework (www.biopieces.org).
+
+# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+
+require 'zlib'
+
+# Error class for all exceptions to do with Filesys.
+class FilesysError < StandardError; end
+
+class Filesys
+  include Enumerable
+
+  # Class method that returns a path to a unique temporary file.
+  # If no directory is specified reverts to the systems tmp directory.
+  def self.tmpfile(tmp_dir = ENV["TMPDIR"])
+    time = Time.now.to_i
+    user = ENV["USER"]
+    pid  = $$
+    path = tmp_dir + [user, time + pid, pid].join("_") + ".tmp"
+    path
+  end
+
+  # Class method allowing open to be used on (zipped) files.
+  # See File.open.
+  def self.open(*args)
+    args = *args
+    file = args.first
+
+    if file == "-"
+      ios = self.new(STDIN)
+    elsif File.pipe? file
+      ios = self.new(File.open(*args))
+    else
+      ios = self.zopen(*args)
+    end
+
+    if block_given?
+      begin
+        yield ios
+      ensure
+        ios.close
+      end
+    else
+      return ios
+    end
+  end
+
+  def initialize(io, type=nil)
+    @io   = io
+    @type = type
+  end
+
+  # Method to close ios.
+  def close
+    @io.close
+  end
+
+  # Iterator method for parsing entries.
+  def each
+    while entry = get_entry do
+      yield entry
+    end
+  end
+
+  private
+
+  # Helper method to return an ios to a file that may be zipped in which case
+  # the ios is unzipped on the fly. See File.open.
+  def self.zopen(*args)
+    ios = File.open(*args)
+
+    begin
+      ios = Zlib::GzipReader.new(ios)
+    rescue
+      ios.rewind
+    end
+
+    self.new(ios)
+  end
+end