[#21338] $SAFE=4 での autoload — Hidetoshi NAGAI <nagai@...>

永井@知能.九工大です.

21 messages 2003/09/04
[#21346] Re: $SAFE=4 での autoload — nobu.nakada@... 2003/09/04

なかだです。

[#21359] Re: $SAFE=4 での autoload — Hidetoshi NAGAI <nagai@...> 2003/09/05

永井@知能.九工大です.

[#21419] Makefile.inのlex.c — Kazuhiro NISHIYAMA <zn@...>

西山和広です。

15 messages 2003/09/28

[ruby-dev:21336] temporary directory

From: nobu.nakada@...
Date: 2003-09-04 07:46:56 UTC
List: ruby-dev #21336
なかだです。

一時ファイルを使うときにはTempfileがありますが、時々一時ディレ
クトリの中でファイルを作りたい場合があります。

* lib/tempfile.rb (Tempfile.callback): support directory.

* lib/tempfile.rb (Tempfile::Dir): temporary directory class.

Index: lib/tempfile.rb
===================================================================
RCS file: /cvs/ruby/src/ruby/lib/tempfile.rb,v
retrieving revision 1.19
diff -u -2 -p -r1.19 tempfile.rb
--- lib/tempfile.rb	23 Jul 2003 16:37:35 -0000	1.19
+++ lib/tempfile.rb	4 Sep 2003 07:42:46 -0000
@@ -141,5 +141,11 @@ class Tempfile < SimpleDelegator
 
 	  # keep this order for thread safeness
-	  File.unlink(path) if File.exist?(path)
+	  if File.exist?(path)
+	    if File.lstat(path).directory?
+	      FileUtils.rm_rf(path)
+	    else
+	      File.unlink(path)
+	    end
+	  end
 	  cleanlist.delete(path) if cleanlist
 
@@ -168,4 +174,57 @@ class Tempfile < SimpleDelegator
 	tempfile
       end
+    end
+
+    def cleanlist
+      @@cleanlist
+    end
+  end
+
+  class Dir
+    @@cleanlist = []
+
+    def initialize(basename, tmpdir=Dir::tmpdir)
+      require 'fileutils'
+      n = failure = 0
+
+      begin
+	Thread.critical = true
+
+	begin
+	  tmpname = sprintf('%s/%s%d.%d', tmpdir, basename, $$, n)
+	  n += 1
+	end while @@cleanlist.include?(tmpname) or File.exist?(tmpname)
+
+	Dir.mkdir(tmpname, 0700)
+      rescue
+	failure += 1
+	retry if failure < MAX_TRY
+	raise "cannot generate tempdir `%s'" % tmpname
+      ensure
+	Thread.critical = false
+      end
+      @@cleanlist << tmpname
+      @tmpname = tmpname
+      @clean_proc = Tempfile.callback([tmpname, nil, @@cleanlist])
+      ObjectSpace.define_finalizer(self, @clean_proc)
+    end
+
+    # Returns the full path name of the temporary directory.
+    def path
+      @tmpname
+    end
+
+    def each(&block)
+      Dir.foreach(@tmpname, &block)
+    end
+
+    def open(basename, *modes, &block)
+      File.open(File.join(@tmpname, basename), *modes, &block)
+    end
+
+    def clear
+      FileUtils.rm_rf(@tmpname)
+      @clean_proc.call
+      ObjectSpace.undefine_finalizer(self)
     end
   end


-- 
--- 僕の前にBugはない。
--- 僕の後ろにBugはできる。
    中田 伸悦

In This Thread

Prev Next