2 # tmpdir - retrieve temporary directory path
15 CSIDL_LOCAL_APPDATA = 0x001c
17 windir = ' '*(max_pathlen+1)
19 getdir = Win32API.new('shell32', 'SHGetFolderPath', 'LLLLP', 'L')
20 raise RuntimeError if getdir.call(0, CSIDL_LOCAL_APPDATA, 0, 0, windir) != 0
21 windir = File.expand_path(windir.rstrip)
24 getdir = Win32API.new('kernel32', 'GetSystemWindowsDirectory', 'PL', 'L')
26 getdir = Win32API.new('kernel32', 'GetWindowsDirectory', 'PL', 'L')
28 len = getdir.call(windir, windir.size)
29 windir = File.expand_path(windir[0, len])
31 temp = File.join(windir.untaint, 'temp')
32 @@systmpdir = temp if File.directory?(temp) and File.writable?(temp)
37 # Returns the operating system's temporary file path.
44 for dir in [ENV['TMPDIR'], ENV['TMP'], ENV['TEMP'],
45 ENV['USERPROFILE'], @@systmpdir, '/tmp']
46 if dir and File.directory?(dir) and File.writable?(dir)
55 # Dir.mktmpdir creates a temporary directory.
57 # The directory is created with 0700 permission.
59 # The prefix and suffix of the name of the directory is specified by
60 # the optional first argument, <i>prefix_suffix</i>.
61 # - If it is not specified or nil, "d" is used as the prefix and no suffix is used.
62 # - If it is a string, it is used as the prefix and no suffix is used.
63 # - If it is an array, first element is used as the prefix and second element is used as a suffix.
65 # Dir.mktmpdir {|dir| dir is ".../d..." }
66 # Dir.mktmpdir("foo") {|dir| dir is ".../foo..." }
67 # Dir.mktmpdir(["foo", "bar"]) {|dir| dir is ".../foo...bar" }
69 # The directory is created under Dir.tmpdir or
70 # the optional second argument <i>tmpdir</i> if non-nil value is given.
72 # Dir.mktmpdir {|dir| dir is "#{Dir.tmpdir}/d..." }
73 # Dir.mktmpdir(nil, "/var/tmp") {|dir| dir is "/var/tmp/d..." }
75 # If a block is given,
76 # it is yielded with the path of the directory.
77 # The directory and its contents are removed
78 # using FileUtils.remove_entry_secure before Dir.mktmpdir returns.
79 # The value of the block is returned.
82 # # use the directory...
83 # open("#{dir}/foo", "w") { ... }
86 # If a block is not given,
87 # The path of the directory is returned.
88 # In this case, Dir.mktmpdir doesn't remove the directory.
92 # # use the directory...
93 # open("#{dir}/foo", "w") { ... }
95 # # remove the directory.
96 # FileUtils.remove_entry_secure dir
99 def Dir.mktmpdir(prefix_suffix=nil, tmpdir=nil)
105 prefix = prefix_suffix
108 prefix = prefix_suffix[0]
109 suffix = prefix_suffix[1]
111 raise ArgumentError, "unexpected prefix_suffix: #{prefix_suffix.inspect}"
113 tmpdir ||= Dir.tmpdir
114 t = Time.now.strftime("%Y%m%d")
117 path = "#{tmpdir}/#{prefix}#{t}-#{$$}-#{rand(0x100000000).to_s(36)}"
120 Dir.mkdir(path, 0700)
131 FileUtils.remove_entry_secure path