properly delete file in case of errors in StoredFile.create
[coquelicot.git] / lib / coquelicot / depot.rb
index 2acc9b1..eda3b6a 100644 (file)
@@ -25,19 +25,19 @@ module Coquelicot
       @path = path
     end
 
-    def add_file(src, pass, options)
+    def add_file(pass, options, &block)
       dst = nil
-      lockfile.lock do
+
+      # Ensure that the generated name is not already used
+      loop do
         dst = gen_random_file_name
-        File.open(full_path(dst), 'w').close
-      end
-      begin
-        File.open(full_path(dst), 'w') do |dest|
-          StoredFile.create(src, pass, options) { |data| dest.write data }
+        begin
+          StoredFile.create(full_path(dst), pass, options, &block)
+          break
+        rescue Errno::EEXIST => e
+          raise unless e.message =~ /(?:^|\s)#{Regexp.escape(full_path(dst))}(?:\s|$)/
+          next # let's try again
         end
-      rescue
-        File.unlink full_path(dst)
-        raise
       end
       link = gen_random_file_name
       add_link(link, dst)